2022-03-07 11:40:54 -06:00
package coderd
import (
2025-07-03 14:35:44 -05:00
"bytes"
2022-11-09 11:01:34 -06:00
"context"
2022-12-09 14:29:50 -05:00
"crypto/sha256"
2022-03-07 11:40:54 -06:00
"database/sql"
2022-12-09 14:29:50 -05:00
"encoding/hex"
2022-06-02 00:44:53 +10:00
"encoding/json"
2022-03-07 11:40:54 -06:00
"errors"
"fmt"
2025-07-03 14:35:44 -05:00
"io/fs"
stdslog "log/slog"
2022-03-07 11:40:54 -06:00
"net/http"
2024-11-25 11:19:14 +00:00
"os"
2022-03-07 11:40:54 -06:00
2022-05-16 14:36:27 -05:00
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
2023-07-15 09:07:19 +03:00
"github.com/sqlc-dev/pqtype"
2025-07-21 13:02:31 -05:00
"github.com/zclconf/go-cty/cty"
2022-05-16 14:36:27 -05:00
"golang.org/x/xerrors"
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
2025-07-03 14:35:44 -05:00
archivefs "github.com/coder/coder/v2/archive/fs"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
2024-12-02 20:54:32 +00:00
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2023-09-01 19:50:12 +03:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-09-19 10:25:57 +04:00
"github.com/coder/coder/v2/coderd/database/provisionerjobs"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/dynamicparameters"
2023-09-30 14:30:01 -05:00
"github.com/coder/coder/v2/coderd/externalauth"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/provisionerdserver"
"github.com/coder/coder/v2/coderd/rbac"
2024-07-08 15:38:50 +02:00
"github.com/coder/coder/v2/coderd/rbac/policy"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/tracing"
2026-01-09 15:40:26 -07:00
"github.com/coder/coder/v2/coderd/util/namesgenerator"
2024-12-02 20:54:32 +00:00
"github.com/coder/coder/v2/coderd/util/ptr"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/examples"
2024-11-25 11:19:14 +00:00
"github.com/coder/coder/v2/provisioner/terraform/tfparse"
2023-12-08 12:10:25 +00:00
"github.com/coder/coder/v2/provisionersdk"
2026-01-08 15:24:11 +04:00
"github.com/coder/preview"
2022-03-07 11:40:54 -06:00
)
2023-01-11 12:16:09 +01:00
// @Summary Get template version by ID
// @ID get-template-version-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {object} codersdk.TemplateVersion
// @Router /templateversions/{templateversion} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateVersion ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2023-03-21 09:10:22 -05:00
templateVersion := httpmw . TemplateVersionParam ( r )
2022-05-25 11:00:59 -05:00
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { templateVersion . JobID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-07 11:40:54 -06:00
})
return
}
2022-04-12 10:17:33 -05:00
2024-12-02 20:54:32 +00:00
var matchedProvisioners * codersdk . MatchedProvisioners
if jobs [ 0 ]. ProvisionerJob . JobStatus == database . ProvisionerJobStatusPending {
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
provisioners , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : jobs [ 0 ]. ProvisionerJob . OrganizationID ,
WantTags : jobs [ 0 ]. ProvisionerJob . Tags ,
})
if err != nil {
api . Logger . Error ( ctx , "failed to fetch provisioners for job id" , slog . F ( "job_id" , jobs [ 0 ]. ProvisionerJob . ID ), slog . Error ( err ))
} else {
matchedProvisioners = ptr . Ref ( db2sdk . MatchedProvisioners ( provisioners , dbtime . Now (), provisionerdserver . StaleInterval ))
}
}
2023-06-20 15:07:18 -05:00
schemas , err := api . Database . GetParameterSchemasByJobID ( ctx , jobs [ 0 ]. ProvisionerJob . ID )
2023-05-12 11:21:49 +02:00
if errors . Is ( err , sql . ErrNoRows ) {
err = nil
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error listing parameter schemas." ,
Detail : err . Error (),
})
return
}
2023-06-02 11:16:46 +02:00
var warnings [] codersdk . TemplateVersionWarning
if len ( schemas ) > 0 {
warnings = append ( warnings , codersdk . TemplateVersionWarningUnsupportedWorkspaces )
}
2024-12-02 20:54:32 +00:00
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersion ( templateVersion , convertProvisionerJob ( jobs [ 0 ]), matchedProvisioners , warnings ))
2022-03-07 11:40:54 -06:00
}
2023-03-23 13:26:50 -03:00
// @Summary Patch template version by ID
// @ID patch-template-version-by-id
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Param request body codersdk.PatchTemplateVersionRequest true "Patch template version request"
// @Success 200 {object} codersdk.TemplateVersion
// @Router /templateversions/{templateversion} [patch]
func ( api * API ) patchTemplateVersion ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
templateVersion := httpmw . TemplateVersionParam ( r )
var params codersdk . PatchTemplateVersionRequest
if ! httpapi . Read ( ctx , rw , r , & params ) {
return
}
updateParams := database . UpdateTemplateVersionByIDParams {
ID : templateVersion . ID ,
TemplateID : templateVersion . TemplateID ,
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2023-03-23 13:26:50 -03:00
Name : templateVersion . Name ,
2023-07-13 10:36:10 -03:00
Message : templateVersion . Message ,
2023-03-23 13:26:50 -03:00
}
if params . Name != "" {
updateParams . Name = params . Name
}
2023-03-27 13:54:01 +02:00
2023-07-13 10:36:10 -03:00
if params . Message != nil {
updateParams . Message = * params . Message
}
2023-03-27 13:54:01 +02:00
errTemplateVersionNameConflict := xerrors . New ( "template version name must be unique for a template" )
var updatedTemplateVersion database . TemplateVersion
err := api . Database . InTx ( func ( tx database . Store ) error {
if templateVersion . TemplateID . Valid && templateVersion . Name != updateParams . Name {
// User wants to rename the template version
_ , err := tx . GetTemplateVersionByTemplateIDAndName ( ctx , database . GetTemplateVersionByTemplateIDAndNameParams {
TemplateID : templateVersion . TemplateID ,
Name : updateParams . Name ,
})
if err != nil && ! xerrors . Is ( err , sql . ErrNoRows ) {
return xerrors . Errorf ( "error on retrieving conflicting template version: %v" , err )
}
if err == nil {
return errTemplateVersionNameConflict
}
}
// It is not allowed to "patch" the template ID, and reassign it.
var err error
2023-07-25 09:14:38 -04:00
err = tx . UpdateTemplateVersionByID ( ctx , updateParams )
2023-03-27 13:54:01 +02:00
if err != nil {
return xerrors . Errorf ( "error on patching template version: %v" , err )
}
2023-07-25 09:14:38 -04:00
updatedTemplateVersion , err = tx . GetTemplateVersionByID ( ctx , updateParams . ID )
if err != nil {
return xerrors . Errorf ( "error on fetching patched template version: %v" , err )
}
2023-03-27 13:54:01 +02:00
return nil
}, nil )
if errors . Is ( err , errTemplateVersionNameConflict ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : err . Error (),
2023-03-27 14:26:57 -03:00
Validations : [] codersdk . ValidationError {
{ Field : "name" , Detail : "Name is already used" },
},
2023-03-27 13:54:01 +02:00
})
return
}
2023-03-23 13:26:50 -03:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2023-03-27 13:54:01 +02:00
Message : err . Error (),
2023-03-23 13:26:50 -03:00
})
return
}
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { templateVersion . JobID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2023-03-23 13:26:50 -03:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
2024-12-02 20:54:32 +00:00
var matchedProvisioners * codersdk . MatchedProvisioners
if jobs [ 0 ]. ProvisionerJob . JobStatus == database . ProvisionerJobStatusPending {
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
provisioners , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : jobs [ 0 ]. ProvisionerJob . OrganizationID ,
WantTags : jobs [ 0 ]. ProvisionerJob . Tags ,
})
if err != nil {
api . Logger . Error ( ctx , "failed to fetch provisioners for job id" , slog . F ( "job_id" , jobs [ 0 ]. ProvisionerJob . ID ), slog . Error ( err ))
} else {
matchedProvisioners = ptr . Ref ( db2sdk . MatchedProvisioners ( provisioners , dbtime . Now (), provisionerdserver . StaleInterval ))
}
}
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersion ( updatedTemplateVersion , convertProvisionerJob ( jobs [ 0 ]), matchedProvisioners , nil ))
2023-03-23 13:26:50 -03:00
}
2023-01-11 12:16:09 +01:00
// @Summary Cancel template version by ID
// @ID cancel-template-version-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {object} codersdk.Response
// @Router /templateversions/{templateversion}/cancel [patch]
2022-05-25 22:14:08 -05:00
func ( api * API ) patchCancelTemplateVersion ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2023-03-21 09:10:22 -05:00
templateVersion := httpmw . TemplateVersionParam ( r )
2022-05-25 11:00:59 -05:00
2022-09-21 17:07:00 -05:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
2022-03-22 13:17:50 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-22 13:17:50 -06:00
})
return
}
if job . CompletedAt . Valid {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-03-22 13:17:50 -06:00
Message : "Job has already completed!" ,
})
return
}
if job . CanceledAt . Valid {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-03-22 13:17:50 -06:00
Message : "Job has already been marked as canceled!" ,
})
return
}
2022-09-21 17:07:00 -05:00
err = api . Database . UpdateProvisionerJobWithCancelByID ( ctx , database . UpdateProvisionerJobWithCancelByIDParams {
2022-03-22 13:17:50 -06:00
ID : job . ID ,
CanceledAt : sql . NullTime {
2023-09-01 19:50:12 +03:00
Time : dbtime . Now (),
2022-03-22 13:17:50 -06:00
Valid : true ,
},
2022-10-03 11:43:11 -05:00
CompletedAt : sql . NullTime {
2023-09-01 19:50:12 +03:00
Time : dbtime . Now (),
2022-10-03 11:43:11 -05:00
// If the job is running, don't mark it completed!
Valid : ! job . WorkerID . Valid ,
},
2022-03-22 13:17:50 -06:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error updating provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-22 13:17:50 -06:00
})
return
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . Response {
2022-03-22 13:17:50 -06:00
Message : "Job has been marked as canceled..." ,
})
}
2023-01-17 11:22:11 +01:00
// @Summary Get rich parameters by template version
// @ID get-rich-parameters-by-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-02-07 09:36:13 +01:00
// @Success 200 {array} codersdk.TemplateVersionParameter
2023-01-17 11:22:11 +01:00
// @Router /templateversions/{templateversion}/rich-parameters [get]
func ( api * API ) templateVersionRichParameters ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
templateVersion := httpmw . TemplateVersionParam ( r )
2023-03-21 09:10:22 -05:00
2023-01-17 11:22:11 +01:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
if ! job . CompletedAt . Valid {
2025-04-10 13:08:50 -07:00
httpapi . Write ( ctx , rw , http . StatusTooEarly , codersdk . Response {
Message : "Template version job has not finished" ,
2023-01-17 11:22:11 +01:00
})
return
}
2023-01-24 14:22:00 +01:00
dbTemplateVersionParameters , err := api . Database . GetTemplateVersionParameters ( ctx , templateVersion . ID )
2023-01-17 11:22:11 +01:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version parameters." ,
Detail : err . Error (),
})
return
}
2023-01-24 14:22:00 +01:00
2025-05-29 08:55:19 -05:00
templateVersionParameters , err := db2sdk . TemplateVersionParameters ( dbTemplateVersionParameters )
2023-01-24 14:22:00 +01:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error converting template version parameter." ,
Detail : err . Error (),
})
return
2023-01-17 11:22:11 +01:00
}
2023-01-24 14:22:00 +01:00
httpapi . Write ( ctx , rw , http . StatusOK , templateVersionParameters )
2023-01-17 11:22:11 +01:00
}
2023-09-30 14:30:01 -05:00
// @Summary Get external auth by template version
// @ID get-external-auth-by-template-version
2023-02-27 10:18:19 -06:00
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-09-29 14:13:20 -05:00
// @Success 200 {array} codersdk.TemplateVersionExternalAuth
2023-10-03 09:04:39 -05:00
// @Router /templateversions/{templateversion}/external-auth [get]
2023-09-30 14:30:01 -05:00
func ( api * API ) templateVersionExternalAuth ( rw http . ResponseWriter , r * http . Request ) {
2023-02-27 10:18:19 -06:00
ctx := r . Context ()
var (
apiKey = httpmw . APIKey ( r )
templateVersion = httpmw . TemplateVersionParam ( r )
)
2024-02-21 11:18:38 -07:00
var rawProviders [] database . ExternalAuthProvider
err := json . Unmarshal ( templateVersion . ExternalAuthProviders , & rawProviders )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error reading auth config from database" ,
Detail : err . Error (),
})
return
}
2023-09-29 14:13:20 -05:00
providers := make ([] codersdk . TemplateVersionExternalAuth , 0 )
2023-02-27 10:18:19 -06:00
for _ , rawProvider := range rawProviders {
2023-09-30 14:30:01 -05:00
var config * externalauth . Config
2023-09-29 14:13:20 -05:00
for _ , provider := range api . ExternalAuthConfigs {
2024-02-21 11:18:38 -07:00
if provider . ID == rawProvider . ID {
2023-02-27 10:18:19 -06:00
config = provider
break
}
}
if config == nil {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2024-02-21 11:18:38 -07:00
Message : fmt . Sprintf ( "The template version references a Git auth provider %q that no longer exists." , rawProvider . ID ),
2023-02-27 10:18:19 -06:00
Detail : "You'll need to update the template version to use a different provider." ,
})
return
}
// This is the URL that will redirect the user with a state token.
2023-10-03 09:04:39 -05:00
redirectURL , err := api . AccessURL . Parse ( fmt . Sprintf ( "/external-auth/%s" , config . ID ))
2023-02-27 10:18:19 -06:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to parse access URL." ,
Detail : err . Error (),
})
return
}
2023-09-29 14:13:20 -05:00
provider := codersdk . TemplateVersionExternalAuth {
2023-02-27 10:18:19 -06:00
ID : config . ID ,
Type : config . Type ,
AuthenticateURL : redirectURL . String (),
2023-10-03 09:04:39 -05:00
DisplayName : config . DisplayName ,
DisplayIcon : config . DisplayIcon ,
2024-02-21 11:18:38 -07:00
Optional : rawProvider . Optional ,
2023-02-27 10:18:19 -06:00
}
2023-09-29 14:13:20 -05:00
authLink , err := api . Database . GetExternalAuthLink ( ctx , database . GetExternalAuthLinkParams {
2023-02-27 10:18:19 -06:00
ProviderID : config . ID ,
UserID : apiKey . UserID ,
})
// If there isn't an auth link, then the user just isn't authenticated.
if errors . Is ( err , sql . ErrNoRows ) {
providers = append ( providers , provider )
continue
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2023-09-30 14:30:01 -05:00
Message : "Internal error fetching external auth link." ,
2023-02-27 10:18:19 -06:00
Detail : err . Error (),
})
return
}
2024-06-03 09:33:49 -05:00
_ , err = config . RefreshToken ( ctx , api . Database , authLink )
if err != nil && ! externalauth . IsInvalidTokenError ( err ) {
2023-02-27 10:18:19 -06:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2023-09-30 14:30:01 -05:00
Message : "Failed to refresh external auth token." ,
2023-02-27 10:18:19 -06:00
Detail : err . Error (),
})
return
}
2024-06-03 09:33:49 -05:00
provider . Authenticated = err == nil
2023-02-27 10:18:19 -06:00
providers = append ( providers , provider )
}
httpapi . Write ( ctx , rw , http . StatusOK , providers )
}
2023-02-15 18:24:15 +01:00
// @Summary Get template variables by template version
// @ID get-template-variables-by-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {array} codersdk.TemplateVersionVariable
// @Router /templateversions/{templateversion}/variables [get]
func ( api * API ) templateVersionVariables ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
templateVersion := httpmw . TemplateVersionParam ( r )
2023-03-21 09:10:22 -05:00
2023-02-15 18:24:15 +01:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
if ! job . CompletedAt . Valid {
2023-10-05 10:49:25 -06:00
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
2025-04-10 13:08:50 -07:00
Message : "Template version job has not finished" ,
2023-02-15 18:24:15 +01:00
})
return
}
dbTemplateVersionVariables , err := api . Database . GetTemplateVersionVariables ( ctx , templateVersion . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version variables." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersionVariables ( dbTemplateVersionVariables ))
}
2023-01-11 12:16:09 +01:00
// @Summary Create template version dry-run
// @ID create-template-version-dry-run
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Param request body codersdk.CreateTemplateVersionDryRunRequest true "Dry-run request"
// @Success 201 {object} codersdk.ProvisionerJob
// @Router /templateversions/{templateversion}/dry-run [post]
2022-06-02 00:44:53 +10:00
func ( api * API ) postTemplateVersionDryRun ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-10-10 15:37:06 -05:00
var (
apiKey = httpmw . APIKey ( r )
templateVersion = httpmw . TemplateVersionParam ( r )
)
2023-03-21 09:10:22 -05:00
2022-06-02 00:44:53 +10:00
// We use the workspace RBAC check since we don't want to allow dry runs if
// the user can't create workspaces.
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionCreate ,
2022-06-02 00:44:53 +10:00
rbac . ResourceWorkspace . InOrg ( templateVersion . OrganizationID ). WithOwner ( apiKey . UserID . String ())) {
2022-06-14 10:14:05 -05:00
httpapi . ResourceNotFound ( rw )
2022-06-02 00:44:53 +10:00
return
}
var req codersdk . CreateTemplateVersionDryRunRequest
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-06-02 00:44:53 +10:00
return
}
2022-09-21 17:07:00 -05:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
2022-06-02 00:44:53 +10:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error updating provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
return
}
if ! job . CompletedAt . Valid {
2025-04-10 13:08:50 -07:00
httpapi . Write ( ctx , rw , http . StatusTooEarly , codersdk . Response {
2022-06-02 00:44:53 +10:00
Message : "Template version import job hasn't completed!" ,
})
return
}
2023-01-23 15:01:22 +01:00
richParameterValues := make ([] database . WorkspaceBuildParameter , len ( req . RichParameterValues ))
for i , v := range req . RichParameterValues {
richParameterValues [ i ] = database . WorkspaceBuildParameter {
WorkspaceBuildID : uuid . Nil ,
Name : v . Name ,
Value : v . Value ,
}
}
2022-06-02 00:44:53 +10:00
// Marshal template version dry-run job with the parameters from the
// request.
2022-11-07 19:10:49 -06:00
input , err := json . Marshal ( provisionerdserver . TemplateVersionDryRunJob {
2023-01-23 15:01:22 +01:00
TemplateVersionID : templateVersion . ID ,
WorkspaceName : req . WorkspaceName ,
RichParameterValues : richParameterValues ,
2022-06-02 00:44:53 +10:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error unmarshalling provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
return
}
2023-05-03 18:02:35 -05:00
metadataRaw , err := json . Marshal ( tracing . MetadataFromContext ( ctx ))
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error unmarshalling metadata." ,
Detail : err . Error (),
})
return
}
2022-06-02 00:44:53 +10:00
// Create a dry-run job
jobID := uuid . New ()
2022-09-21 17:07:00 -05:00
provisionerJob , err := api . Database . InsertProvisionerJob ( ctx , database . InsertProvisionerJobParams {
2022-06-02 00:44:53 +10:00
ID : jobID ,
2023-09-01 19:50:12 +03:00
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
2022-06-02 00:44:53 +10:00
OrganizationID : templateVersion . OrganizationID ,
InitiatorID : apiKey . UserID ,
Provisioner : job . Provisioner ,
StorageMethod : job . StorageMethod ,
2022-10-13 18:02:52 -05:00
FileID : job . FileID ,
2022-06-02 00:44:53 +10:00
Type : database . ProvisionerJobTypeTemplateVersionDryRun ,
Input : input ,
2022-11-16 16:34:06 -06:00
// Copy tags from the previous run.
Tags : job . Tags ,
2023-05-03 18:02:35 -05:00
TraceMetadata : pqtype . NullRawMessage {
Valid : true ,
RawMessage : metadataRaw ,
},
2025-07-30 19:09:53 -05:00
LogsOverflowed : false ,
2022-06-02 00:44:53 +10:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error inserting provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
return
}
2023-09-19 10:25:57 +04:00
err = provisionerjobs . PostJob ( api . Pubsub , provisionerJob )
if err != nil {
// Client probably doesn't care about this error, so just log it.
api . Logger . Error ( ctx , "failed to post provisioner job to pubsub" , slog . Error ( err ))
}
2022-06-02 00:44:53 +10:00
2023-06-20 15:07:18 -05:00
httpapi . Write ( ctx , rw , http . StatusCreated , convertProvisionerJob ( database . GetProvisionerJobsByIDsWithQueuePositionRow {
ProvisionerJob : provisionerJob ,
QueuePosition : 0 ,
}))
2022-06-02 00:44:53 +10:00
}
2023-01-11 12:16:09 +01:00
// @Summary Get template version dry-run by job ID
// @ID get-template-version-dry-run-by-job-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-01-13 12:27:21 +01:00
// @Param jobID path string true "Job ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Success 200 {object} codersdk.ProvisionerJob
2023-01-13 12:27:21 +01:00
// @Router /templateversions/{templateversion}/dry-run/{jobID} [get]
2022-06-02 00:44:53 +10:00
func ( api * API ) templateVersionDryRun ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-06-02 00:44:53 +10:00
job , ok := api . fetchTemplateVersionDryRunJob ( rw , r )
if ! ok {
return
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , convertProvisionerJob ( job ))
2022-06-02 00:44:53 +10:00
}
2024-12-02 20:54:32 +00:00
// @Summary Get template version dry-run matched provisioners
// @ID get-template-version-dry-run-matched-provisioners
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Param jobID path string true "Job ID" format(uuid)
// @Success 200 {object} codersdk.MatchedProvisioners
// @Router /templateversions/{templateversion}/dry-run/{jobID}/matched-provisioners [get]
func ( api * API ) templateVersionDryRunMatchedProvisioners ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
job , ok := api . fetchTemplateVersionDryRunJob ( rw , r )
if ! ok {
return
}
// nolint:gocritic // The user may not have permissions to read all
// provisioner daemons in the org.
daemons , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : job . ProvisionerJob . OrganizationID ,
WantTags : job . ProvisionerJob . Tags ,
})
if err != nil {
if ! errors . Is ( err , sql . ErrNoRows ) {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner daemons by organization." ,
Detail : err . Error (),
})
return
}
daemons = [] database . ProvisionerDaemon {}
}
matchedProvisioners := db2sdk . MatchedProvisioners ( daemons , dbtime . Now (), provisionerdserver . StaleInterval )
httpapi . Write ( ctx , rw , http . StatusOK , matchedProvisioners )
}
2023-01-11 12:16:09 +01:00
// @Summary Get template version dry-run resources by job ID
// @ID get-template-version-dry-run-resources-by-job-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-01-13 12:27:21 +01:00
// @Param jobID path string true "Job ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Success 200 {array} codersdk.WorkspaceResource
2023-01-13 12:27:21 +01:00
// @Router /templateversions/{templateversion}/dry-run/{jobID}/resources [get]
2022-06-02 00:44:53 +10:00
func ( api * API ) templateVersionDryRunResources ( rw http . ResponseWriter , r * http . Request ) {
job , ok := api . fetchTemplateVersionDryRunJob ( rw , r )
if ! ok {
return
}
2023-06-20 15:07:18 -05:00
api . provisionerJobResources ( rw , r , job . ProvisionerJob )
2022-06-02 00:44:53 +10:00
}
2023-01-11 12:16:09 +01:00
// @Summary Get template version dry-run logs by job ID
// @ID get-template-version-dry-run-logs-by-job-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-01-13 12:27:21 +01:00
// @Param jobID path string true "Job ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Param before query int false "Before Unix timestamp"
// @Param after query int false "After Unix timestamp"
// @Param follow query bool false "Follow log stream"
2026-02-03 09:45:23 +00:00
// @Param format query string false "Log output format. Accepted: 'json' (default), 'text' (plain text with RFC3339 timestamps and ANSI colors). Not supported with follow=true." Enums(json,text)
2023-01-11 12:16:09 +01:00
// @Success 200 {array} codersdk.ProvisionerJobLog
2023-01-13 12:27:21 +01:00
// @Router /templateversions/{templateversion}/dry-run/{jobID}/logs [get]
2022-06-02 00:44:53 +10:00
func ( api * API ) templateVersionDryRunLogs ( rw http . ResponseWriter , r * http . Request ) {
job , ok := api . fetchTemplateVersionDryRunJob ( rw , r )
if ! ok {
return
}
2023-06-20 15:07:18 -05:00
api . provisionerJobLogs ( rw , r , job . ProvisionerJob )
2022-06-02 00:44:53 +10:00
}
2023-01-11 12:16:09 +01:00
// @Summary Cancel template version dry-run by job ID
// @ID cancel-template-version-dry-run-by-job-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param jobID path string true "Job ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {object} codersdk.Response
2023-01-13 12:27:21 +01:00
// @Router /templateversions/{templateversion}/dry-run/{jobID}/cancel [patch]
2022-06-02 00:44:53 +10:00
func ( api * API ) patchTemplateVersionDryRunCancel ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-06-02 00:44:53 +10:00
templateVersion := httpmw . TemplateVersionParam ( r )
job , ok := api . fetchTemplateVersionDryRunJob ( rw , r )
if ! ok {
return
}
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionUpdate ,
2023-06-20 15:07:18 -05:00
rbac . ResourceWorkspace . InOrg ( templateVersion . OrganizationID ). WithOwner ( job . ProvisionerJob . InitiatorID . String ())) {
2022-06-14 10:14:05 -05:00
httpapi . ResourceNotFound ( rw )
2022-06-02 00:44:53 +10:00
return
}
2023-06-20 15:07:18 -05:00
if job . ProvisionerJob . CompletedAt . Valid {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Job has already completed." ,
2022-06-02 00:44:53 +10:00
})
return
}
2023-06-20 15:07:18 -05:00
if job . ProvisionerJob . CanceledAt . Valid {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Job has already been marked as canceled." ,
2022-06-02 00:44:53 +10:00
})
return
}
2022-09-21 17:07:00 -05:00
err := api . Database . UpdateProvisionerJobWithCancelByID ( ctx , database . UpdateProvisionerJobWithCancelByIDParams {
2023-06-20 15:07:18 -05:00
ID : job . ProvisionerJob . ID ,
2022-06-02 00:44:53 +10:00
CanceledAt : sql . NullTime {
2023-09-01 19:50:12 +03:00
Time : dbtime . Now (),
2022-06-02 00:44:53 +10:00
Valid : true ,
},
2022-10-03 11:43:11 -05:00
CompletedAt : sql . NullTime {
2023-09-01 19:50:12 +03:00
Time : dbtime . Now (),
2022-10-03 11:43:11 -05:00
// If the job is running, don't mark it completed!
2023-06-20 15:07:18 -05:00
Valid : ! job . ProvisionerJob . WorkerID . Valid ,
2022-10-03 11:43:11 -05:00
},
2022-06-02 00:44:53 +10:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error updating provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
return
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Job has been marked as canceled." ,
2022-06-02 00:44:53 +10:00
})
}
2023-06-20 15:07:18 -05:00
func ( api * API ) fetchTemplateVersionDryRunJob ( rw http . ResponseWriter , r * http . Request ) ( database . GetProvisionerJobsByIDsWithQueuePositionRow , bool ) {
2022-06-02 00:44:53 +10:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-06-02 00:44:53 +10:00
templateVersion = httpmw . TemplateVersionParam ( r )
jobID = chi . URLParam ( r , "jobID" )
)
2022-10-10 15:37:06 -05:00
2022-06-02 00:44:53 +10:00
jobUUID , err := uuid . Parse ( jobID )
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Job ID %q must be a valid UUID." , jobID ),
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { jobUUID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2022-06-14 10:14:05 -05:00
Message : fmt . Sprintf ( "Provisioner job %q not found." , jobUUID ),
})
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
2023-06-20 15:07:18 -05:00
job := jobs [ 0 ]
if job . ProvisionerJob . Type != database . ProvisionerJobTypeTemplateVersionDryRun {
2022-06-02 00:44:53 +10:00
httpapi . Forbidden ( rw )
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
2022-10-12 14:33:21 -05:00
2022-10-22 09:36:31 +10:00
// Do a workspace resource check since it's basically a workspace dry-run.
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionRead ,
2023-06-20 15:07:18 -05:00
rbac . ResourceWorkspace . InOrg ( templateVersion . OrganizationID ). WithOwner ( job . ProvisionerJob . InitiatorID . String ())) {
2022-06-14 10:14:05 -05:00
httpapi . Forbidden ( rw )
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
// Verify that the template version is the one used in the request.
2022-11-07 19:10:49 -06:00
var input provisionerdserver . TemplateVersionDryRunJob
2023-06-20 15:07:18 -05:00
err = json . Unmarshal ( job . ProvisionerJob . Input , & input )
2022-06-02 00:44:53 +10:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-12-06 11:50:33 +00:00
Message : "Internal error unmarshalling job metadata." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 00:44:53 +10:00
})
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
if input . TemplateVersionID != templateVersion . ID {
httpapi . Forbidden ( rw )
2023-06-20 15:07:18 -05:00
return database . GetProvisionerJobsByIDsWithQueuePositionRow {}, false
2022-06-02 00:44:53 +10:00
}
return job , true
}
2023-01-11 12:16:09 +01:00
// @Summary List template versions by template ID
2023-01-13 12:27:21 +01:00
// @ID list-template-versions-by-template-id
2023-01-11 12:16:09 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2023-01-11 14:08:04 +01:00
// @Param after_id query string false "After ID" format(uuid)
2023-10-11 10:06:10 -05:00
// @Param include_archived query bool false "Include archived versions in the list"
2023-01-11 14:08:04 +01:00
// @Param limit query int false "Page limit"
// @Param offset query int false "Page offset"
2023-01-11 12:16:09 +01:00
// @Success 200 {array} codersdk.TemplateVersion
2023-01-13 12:27:21 +01:00
// @Router /templates/{template}/versions [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateVersionsByTemplate ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-16 14:36:27 -05:00
template := httpmw . TemplateParam ( r )
2025-07-15 14:55:34 +10:00
paginationParams , ok := ParsePagination ( rw , r )
2022-05-16 14:36:27 -05:00
if ! ok {
return
}
2023-10-11 09:26:22 -05:00
// If this throws an error, the boolean is false. Which is the default we want.
parser := httpapi . NewQueryParamParser ()
includeArchived := parser . Boolean ( r . URL . Query (), false , "include_archived" )
if len ( parser . Errors ) > 0 {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid query parameters." ,
Validations : parser . Errors ,
})
return
}
2022-06-02 09:01:45 -05:00
var err error
apiVersions := [] codersdk . TemplateVersion {}
err = api . Database . InTx ( func ( store database . Store ) error {
if paginationParams . AfterID != uuid . Nil {
// See if the record exists first. If the record does not exist, the pagination
// query will not work.
2022-09-21 17:07:00 -05:00
_ , err := store . GetTemplateVersionByID ( ctx , paginationParams . AfterID )
2022-06-02 09:01:45 -05:00
if err != nil && xerrors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Record at \"after_id\" (%q) does not exists." , paginationParams . AfterID . String ()),
2022-06-02 09:01:45 -05:00
})
return err
} else if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template version at after_id." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 09:01:45 -05:00
})
return err
}
2022-05-16 14:36:27 -05:00
}
2022-06-02 09:01:45 -05:00
2023-10-11 09:26:22 -05:00
// Exclude archived templates versions
archiveFilter := sql . NullBool {
Bool : false ,
Valid : true ,
}
if includeArchived {
archiveFilter = sql . NullBool { Valid : false }
}
2022-09-21 17:07:00 -05:00
versions , err := store . GetTemplateVersionsByTemplateID ( ctx , database . GetTemplateVersionsByTemplateIDParams {
2022-06-02 09:01:45 -05:00
TemplateID : template . ID ,
AfterID : paginationParams . AfterID ,
2025-03-26 01:56:39 -05:00
// #nosec G115 - Pagination limits are small and fit in int32
LimitOpt : int32 ( paginationParams . Limit ),
// #nosec G115 - Pagination offsets are small and fit in int32
OffsetOpt : int32 ( paginationParams . Offset ),
Archived : archiveFilter ,
2022-06-02 09:01:45 -05:00
})
if errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , apiVersions )
2022-06-02 09:01:45 -05:00
return err
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template versions." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 09:01:45 -05:00
})
return err
}
jobIDs := make ([] uuid . UUID , 0 , len ( versions ))
for _ , version := range versions {
jobIDs = append ( jobIDs , version . JobID )
}
2025-05-28 08:21:16 -04:00
jobs , err := store . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : jobIDs ,
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2022-06-02 09:01:45 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-06-02 09:01:45 -05:00
})
return err
}
2023-06-20 15:07:18 -05:00
jobByID := map [ string ] database . GetProvisionerJobsByIDsWithQueuePositionRow {}
2022-06-02 09:01:45 -05:00
for _ , job := range jobs {
2023-06-20 15:07:18 -05:00
jobByID [ job . ProvisionerJob . ID . String ()] = job
2022-06-02 09:01:45 -05:00
}
for _ , version := range versions {
job , exists := jobByID [ version . JobID . String ()]
if ! exists {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Job %q doesn't exist for version %q." , version . JobID , version . ID ),
2022-06-02 09:01:45 -05:00
})
return err
}
2023-07-25 09:14:38 -04:00
2024-11-29 19:45:58 +00:00
apiVersions = append ( apiVersions , convertTemplateVersion ( version , convertProvisionerJob ( job ), nil , nil ))
2022-06-02 09:01:45 -05:00
}
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-06-02 09:01:45 -05:00
if err != nil {
return
2022-05-16 14:36:27 -05:00
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , apiVersions )
2022-05-16 14:36:27 -05:00
}
2023-01-11 12:16:09 +01:00
// @Summary Get template version by template ID and name
// @ID get-template-version-by-template-id-and-name
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Param templateversionname path string true "Template version name"
// @Success 200 {array} codersdk.TemplateVersion
2023-01-13 12:27:21 +01:00
// @Router /templates/{template}/versions/{templateversionname} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateVersionByName ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-16 14:36:27 -05:00
template := httpmw . TemplateParam ( r )
2022-05-25 11:00:59 -05:00
2022-05-16 14:36:27 -05:00
templateVersionName := chi . URLParam ( r , "templateversionname" )
2022-09-21 17:07:00 -05:00
templateVersion , err := api . Database . GetTemplateVersionByTemplateIDAndName ( ctx , database . GetTemplateVersionByTemplateIDAndNameParams {
2022-05-16 14:36:27 -05:00
TemplateID : uuid . NullUUID {
UUID : template . ID ,
Valid : true ,
},
Name : templateVersionName ,
})
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "No template version found by name %q." , templateVersionName ),
2022-05-16 14:36:27 -05:00
})
return
}
2022-11-15 13:24:13 -03:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return
}
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { templateVersion . JobID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2022-11-15 13:24:13 -03:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
2024-12-02 20:54:32 +00:00
var matchedProvisioners * codersdk . MatchedProvisioners
if jobs [ 0 ]. ProvisionerJob . JobStatus == database . ProvisionerJobStatusPending {
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
provisioners , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : jobs [ 0 ]. ProvisionerJob . OrganizationID ,
WantTags : jobs [ 0 ]. ProvisionerJob . Tags ,
})
if err != nil {
api . Logger . Error ( ctx , "failed to fetch provisioners for job id" , slog . F ( "job_id" , jobs [ 0 ]. ProvisionerJob . ID ), slog . Error ( err ))
} else {
matchedProvisioners = ptr . Ref ( db2sdk . MatchedProvisioners ( provisioners , dbtime . Now (), provisionerdserver . StaleInterval ))
}
}
2022-11-15 13:24:13 -03:00
2024-12-02 20:54:32 +00:00
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersion ( templateVersion , convertProvisionerJob ( jobs [ 0 ]), matchedProvisioners , nil ))
2022-11-15 13:24:13 -03:00
}
2023-02-02 15:47:53 -06:00
// @Summary Get template version by organization, template, and name
// @ID get-template-version-by-organization-template-and-name
2023-01-11 12:16:09 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
2023-02-02 15:47:53 -06:00
// @Param templatename path string true "Template name"
2023-01-11 12:16:09 +01:00
// @Param templateversionname path string true "Template version name"
// @Success 200 {object} codersdk.TemplateVersion
2023-02-02 15:47:53 -06:00
// @Router /organizations/{organization}/templates/{templatename}/versions/{templateversionname} [get]
func ( api * API ) templateVersionByOrganizationTemplateAndName ( rw http . ResponseWriter , r * http . Request ) {
2022-11-15 13:24:13 -03:00
ctx := r . Context ()
organization := httpmw . OrganizationParam ( r )
2023-02-02 15:47:53 -06:00
templateName := chi . URLParam ( r , "templatename" )
template , err := api . Database . GetTemplateByOrganizationAndName ( ctx , database . GetTemplateByOrganizationAndNameParams {
2022-11-15 13:24:13 -03:00
OrganizationID : organization . ID ,
2023-02-02 15:47:53 -06:00
Name : templateName ,
})
if err != nil {
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2023-02-02 15:47:53 -06:00
httpapi . ResourceNotFound ( rw )
return
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template." ,
Detail : err . Error (),
})
return
}
templateVersionName := chi . URLParam ( r , "templateversionname" )
templateVersion , err := api . Database . GetTemplateVersionByTemplateIDAndName ( ctx , database . GetTemplateVersionByTemplateIDAndNameParams {
TemplateID : uuid . NullUUID {
UUID : template . ID ,
Valid : true ,
},
Name : templateVersionName ,
2022-11-15 13:24:13 -03:00
})
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-11-15 13:24:13 -03:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "No template version found by name %q." , templateVersionName ),
})
return
}
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template version." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { templateVersion . JobID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2024-12-02 20:54:32 +00:00
var matchedProvisioners * codersdk . MatchedProvisioners
if jobs [ 0 ]. ProvisionerJob . JobStatus == database . ProvisionerJobStatusPending {
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
provisioners , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : jobs [ 0 ]. ProvisionerJob . OrganizationID ,
WantTags : jobs [ 0 ]. ProvisionerJob . Tags ,
})
if err != nil {
api . Logger . Error ( ctx , "failed to fetch provisioners for job id" , slog . F ( "job_id" , jobs [ 0 ]. ProvisionerJob . ID ), slog . Error ( err ))
} else {
matchedProvisioners = ptr . Ref ( db2sdk . MatchedProvisioners ( provisioners , dbtime . Now (), provisionerdserver . StaleInterval ))
}
}
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersion ( templateVersion , convertProvisionerJob ( jobs [ 0 ]), matchedProvisioners , nil ))
2022-05-16 14:36:27 -05:00
}
2023-02-02 15:47:53 -06:00
// @Summary Get previous template version by organization, template, and name
// @ID get-previous-template-version-by-organization-template-and-name
2023-01-11 12:16:09 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
2023-02-02 15:47:53 -06:00
// @Param templatename path string true "Template name"
2023-01-11 12:16:09 +01:00
// @Param templateversionname path string true "Template version name"
// @Success 200 {object} codersdk.TemplateVersion
2023-02-02 15:47:53 -06:00
// @Router /organizations/{organization}/templates/{templatename}/versions/{templateversionname}/previous [get]
func ( api * API ) previousTemplateVersionByOrganizationTemplateAndName ( rw http . ResponseWriter , r * http . Request ) {
2022-12-06 11:15:03 -03:00
ctx := r . Context ()
organization := httpmw . OrganizationParam ( r )
2023-02-02 15:47:53 -06:00
templateName := chi . URLParam ( r , "templatename" )
template , err := api . Database . GetTemplateByOrganizationAndName ( ctx , database . GetTemplateByOrganizationAndNameParams {
2022-12-06 11:15:03 -03:00
OrganizationID : organization . ID ,
2023-02-02 15:47:53 -06:00
Name : templateName ,
})
if err != nil {
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2023-02-02 15:47:53 -06:00
httpapi . ResourceNotFound ( rw )
return
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template." ,
Detail : err . Error (),
})
return
}
templateVersionName := chi . URLParam ( r , "templateversionname" )
templateVersion , err := api . Database . GetTemplateVersionByTemplateIDAndName ( ctx , database . GetTemplateVersionByTemplateIDAndNameParams {
TemplateID : uuid . NullUUID {
UUID : template . ID ,
Valid : true ,
},
Name : templateVersionName ,
2022-12-06 11:15:03 -03:00
})
if err != nil {
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-12-06 11:15:03 -03:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "No template version found by name %q." , templateVersionName ),
})
return
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return
}
previousTemplateVersion , err := api . Database . GetPreviousTemplateVersion ( ctx , database . GetPreviousTemplateVersionParams {
OrganizationID : organization . ID ,
Name : templateVersionName ,
TemplateID : templateVersion . TemplateID ,
})
if err != nil {
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-12-06 11:15:03 -03:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : fmt . Sprintf ( "No previous template version found for %q." , templateVersionName ),
})
return
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching the previous template version." ,
Detail : err . Error (),
})
return
}
2025-05-28 08:21:16 -04:00
jobs , err := api . Database . GetProvisionerJobsByIDsWithQueuePosition ( ctx , database . GetProvisionerJobsByIDsWithQueuePositionParams {
IDs : [] uuid . UUID { previousTemplateVersion . JobID },
StaleIntervalMS : provisionerdserver . StaleInterval . Milliseconds (),
})
2023-06-20 15:07:18 -05:00
if err != nil || len ( jobs ) == 0 {
2022-12-06 11:15:03 -03:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching provisioner job." ,
Detail : err . Error (),
})
return
}
2024-12-02 20:54:32 +00:00
var matchedProvisioners * codersdk . MatchedProvisioners
if jobs [ 0 ]. ProvisionerJob . JobStatus == database . ProvisionerJobStatusPending {
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
provisioners , err := api . Database . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : jobs [ 0 ]. ProvisionerJob . OrganizationID ,
WantTags : jobs [ 0 ]. ProvisionerJob . Tags ,
})
if err != nil {
api . Logger . Error ( ctx , "failed to fetch provisioners for job id" , slog . F ( "job_id" , jobs [ 0 ]. ProvisionerJob . ID ), slog . Error ( err ))
} else {
matchedProvisioners = ptr . Ref ( db2sdk . MatchedProvisioners ( provisioners , dbtime . Now (), provisionerdserver . StaleInterval ))
}
}
httpapi . Write ( ctx , rw , http . StatusOK , convertTemplateVersion ( previousTemplateVersion , convertProvisionerJob ( jobs [ 0 ]), matchedProvisioners , nil ))
2022-12-06 11:15:03 -03:00
}
2023-10-11 09:26:22 -05:00
// @Summary Archive template unused versions by template id
// @ID archive-template-unused-versions-by-template-id
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Templates
// @Param template path string true "Template ID" format(uuid)
// @Param request body codersdk.ArchiveTemplateVersionsRequest true "Archive request"
// @Success 200 {object} codersdk.Response
// @Router /templates/{template}/versions/archive [post]
func ( api * API ) postArchiveTemplateVersions ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
template = httpmw . TemplateParam ( r )
auditor = * api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . Template ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : template . OrganizationID ,
2023-10-11 09:26:22 -05:00
})
)
defer commitAudit ()
aReq . Old = template
var req codersdk . ArchiveTemplateVersionsRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
status := database . NullProvisionerJobStatus {
ProvisionerJobStatus : database . ProvisionerJobStatusFailed ,
Valid : true ,
}
if req . All {
status = database . NullProvisionerJobStatus {}
}
archived , err := api . Database . ArchiveUnusedTemplateVersions ( ctx , database . ArchiveUnusedTemplateVersionsParams {
UpdatedAt : dbtime . Now (),
TemplateID : template . ID ,
JobStatus : status ,
// Archive all versions that match
TemplateVersionID : uuid . Nil ,
})
if httpapi . Is404Error ( err ) {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : "Template or template versions not found." ,
})
return
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . ArchiveTemplateVersionsResponse {
TemplateID : template . ID ,
ArchivedIDs : archived ,
})
}
// @Summary Archive template version
// @ID archive-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {object} codersdk.Response
// @Router /templateversions/{templateversion}/archive [post]
func ( api * API ) postArchiveTemplateVersion () func ( rw http . ResponseWriter , r * http . Request ) {
return api . setArchiveTemplateVersion ( true )
}
// @Summary Unarchive template version
// @ID unarchive-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {object} codersdk.Response
// @Router /templateversions/{templateversion}/unarchive [post]
func ( api * API ) postUnarchiveTemplateVersion () func ( rw http . ResponseWriter , r * http . Request ) {
return api . setArchiveTemplateVersion ( false )
}
//nolint:revive
func ( api * API ) setArchiveTemplateVersion ( archive bool ) func ( rw http . ResponseWriter , r * http . Request ) {
return func ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
templateVersion = httpmw . TemplateVersionParam ( r )
auditor = * api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . TemplateVersion ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : templateVersion . OrganizationID ,
2023-10-11 09:26:22 -05:00
})
)
defer commitAudit ()
aReq . Old = templateVersion
verb := "archived"
if ! archive {
verb = "unarchived"
}
if templateVersion . Archived == archive {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template version already %s" , verb ),
})
return
}
if ! templateVersion . TemplateID . Valid {
// Maybe we should allow this?
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Cannot archive template versions not associate with a template." ,
})
return
}
var err error
if archive {
archived , archiveError := api . Database . ArchiveUnusedTemplateVersions ( ctx , database . ArchiveUnusedTemplateVersionsParams {
UpdatedAt : dbtime . Now (),
TemplateID : templateVersion . TemplateID . UUID ,
TemplateVersionID : templateVersion . ID ,
JobStatus : database . NullProvisionerJobStatus {},
})
if archiveError != nil {
err = archiveError
2025-03-26 01:56:39 -05:00
} else if len ( archived ) == 0 {
err = xerrors . New ( "Unable to archive specified version, the version is likely in use by a workspace or currently set to the active version" )
2023-10-11 09:26:22 -05:00
}
} else {
err = api . Database . UnarchiveTemplateVersion ( ctx , database . UnarchiveTemplateVersionParams {
UpdatedAt : dbtime . Now (),
TemplateVersionID : templateVersion . ID ,
})
}
if httpapi . Is404Error ( err ) {
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : "Template or template versions not found." ,
})
return
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , fmt . Sprintf ( "template version %q %s" , templateVersion . ID . String (), verb ))
}
}
2023-01-11 12:16:09 +01:00
// @Summary Update active template version by template ID
2023-01-13 12:27:21 +01:00
// @ID update-active-template-version-by-template-id
2023-01-11 12:16:09 +01:00
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Templates
// @Param request body codersdk.UpdateActiveTemplateVersion true "Modified template version"
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Success 200 {object} codersdk.Response
2023-01-13 12:27:21 +01:00
// @Router /templates/{template}/versions [patch]
2022-05-25 22:14:08 -05:00
func ( api * API ) patchActiveTemplateVersion ( rw http . ResponseWriter , r * http . Request ) {
2022-09-09 11:34:23 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-09 11:34:23 -05:00
template = httpmw . TemplateParam ( r )
2022-09-19 23:11:01 -05:00
auditor = * api . Auditor . Load ()
2022-09-09 11:34:23 -05:00
aReq , commitAudit = audit . InitRequest [ database . Template ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : template . OrganizationID ,
2022-09-09 11:34:23 -05:00
})
)
defer commitAudit ()
aReq . Old = template
2022-05-16 14:36:27 -05:00
var req codersdk . UpdateActiveTemplateVersion
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-05-16 14:36:27 -05:00
return
}
2022-09-21 17:07:00 -05:00
version , err := api . Database . GetTemplateVersionByID ( ctx , req . ID )
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Template version not found." ,
2022-05-16 14:36:27 -05:00
})
return
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template version." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
if version . TemplateID . UUID . String () != template . ID . String () {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-05-16 14:36:27 -05:00
Message : "The provided template version doesn't belong to the specified template." ,
})
return
}
2023-10-05 10:49:25 -06:00
job , err := api . Database . GetProvisionerJobByID ( ctx , version . JobID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template version job status." ,
Detail : err . Error (),
})
return
}
2023-10-05 13:25:06 -05:00
if job . JobStatus != database . ProvisionerJobStatusSucceeded {
2023-10-05 10:49:25 -06:00
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "Only versions that have been built successfully can be promoted." ,
2023-10-05 13:25:06 -05:00
Detail : fmt . Sprintf ( "Attempted to promote a version with a %s build" , job . JobStatus ),
2023-10-05 10:49:25 -06:00
})
return
}
2023-10-11 09:26:22 -05:00
if version . Archived {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "The provided template version is archived." ,
})
return
}
2022-06-17 12:22:28 -05:00
err = api . Database . InTx ( func ( store database . Store ) error {
2022-09-21 17:07:00 -05:00
err = store . UpdateTemplateActiveVersionByID ( ctx , database . UpdateTemplateActiveVersionByIDParams {
2022-06-17 12:22:28 -05:00
ID : template . ID ,
ActiveVersionID : req . ID ,
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2022-06-17 12:22:28 -05:00
})
if err != nil {
return xerrors . Errorf ( "update active version: %w" , err )
}
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error updating active template version." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2022-09-09 11:34:23 -05:00
newTemplate := template
newTemplate . ActiveVersionID = req . ID
aReq . New = newTemplate
2022-11-09 11:01:34 -06:00
api . publishTemplateUpdate ( ctx , template . ID )
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . Response {
2022-05-16 14:36:27 -05:00
Message : "Updated the active template version!" ,
})
}
2023-01-13 12:27:21 +01:00
// postTemplateVersionsByOrganization creates a new version of a template. An import job is queued to parse the storage method provided.
//
2023-01-11 12:16:09 +01:00
// @Summary Create template version by organization
// @ID create-template-version-by-organization
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
2023-03-02 14:11:16 +01:00
// @Param request body codersdk.CreateTemplateVersionRequest true "Create template version request"
2023-01-11 12:16:09 +01:00
// @Success 201 {object} codersdk.TemplateVersion
// @Router /organizations/{organization}/templateversions [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postTemplateVersionsByOrganization ( rw http . ResponseWriter , r * http . Request ) {
2022-09-09 11:34:23 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-09 11:34:23 -05:00
apiKey = httpmw . APIKey ( r )
organization = httpmw . OrganizationParam ( r )
2022-09-19 23:11:01 -05:00
auditor = * api . Auditor . Load ()
2022-09-09 11:34:23 -05:00
aReq , commitAudit = audit . InitRequest [ database . TemplateVersion ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
OrganizationID : organization . ID ,
2022-09-09 11:34:23 -05:00
})
req codersdk . CreateTemplateVersionRequest
)
defer commitAudit ()
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-05-16 14:36:27 -05:00
return
}
2022-05-27 11:19:13 -05:00
2025-07-29 03:41:49 +02:00
dynamicTemplate := true // Default to using dynamic templates
2022-05-16 14:36:27 -05:00
if req . TemplateID != uuid . Nil {
2025-07-03 14:35:44 -05:00
tpl , err := api . Database . GetTemplateByID ( ctx , req . TemplateID )
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Template does not exist." ,
2022-05-16 14:36:27 -05:00
})
return
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2025-07-03 14:35:44 -05:00
dynamicTemplate = ! tpl . UseClassicParameterFlow
2022-05-16 14:36:27 -05:00
}
2022-12-09 14:29:50 -05:00
if req . ExampleID != "" && req . FileID != uuid . Nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "You cannot specify both an example_id and a file_id." ,
2022-05-16 14:36:27 -05:00
})
return
}
2022-12-09 14:29:50 -05:00
var file database . File
var err error
// if example id is specified we need to copy the embedded tar into a new file in the database
if req . ExampleID != "" {
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionCreate , rbac . ResourceFile . WithOwner ( apiKey . UserID . String ())) {
2022-12-09 14:29:50 -05:00
httpapi . Forbidden ( rw )
return
}
// ensure we can read the file that either already exists or will be created
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionRead , rbac . ResourceFile . WithOwner ( apiKey . UserID . String ())) {
2022-12-09 14:29:50 -05:00
httpapi . Forbidden ( rw )
return
}
// lookup template tar from embedded examples
tar , err := examples . Archive ( req . ExampleID )
if err != nil {
if xerrors . Is ( err , examples . ErrNotFound ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Example not found." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching example." ,
Detail : err . Error (),
})
return
}
// upload a copy of the template tar as a file in the database
hashBytes := sha256 . Sum256 ( tar )
hash := hex . EncodeToString ( hashBytes [:])
2022-12-13 11:27:37 -05:00
// Check if the file already exists.
file , err := api . Database . GetFileByHashAndCreator ( ctx , database . GetFileByHashAndCreatorParams {
2022-12-09 14:29:50 -05:00
Hash : hash ,
CreatedBy : apiKey . UserID ,
2022-05-16 14:36:27 -05:00
})
2022-12-09 14:29:50 -05:00
if err != nil {
2022-12-13 11:27:37 -05:00
if ! errors . Is ( err , sql . ErrNoRows ) {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching file." ,
Detail : err . Error (),
})
return
}
// If the example tar file doesn't exist, create it.
file , err = api . Database . InsertFile ( ctx , database . InsertFileParams {
ID : uuid . New (),
Hash : hash ,
CreatedBy : apiKey . UserID ,
2023-09-01 19:50:12 +03:00
CreatedAt : dbtime . Now (),
2022-12-13 11:27:37 -05:00
Mimetype : tarMimeType ,
Data : tar ,
2022-12-09 14:29:50 -05:00
})
2022-12-13 11:27:37 -05:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating file." ,
Detail : err . Error (),
})
return
}
2022-12-09 14:29:50 -05:00
}
2022-12-13 11:27:37 -05:00
req . FileID = file . ID
2022-12-09 14:29:50 -05:00
}
if req . FileID != uuid . Nil {
file , err = api . Database . GetFileByID ( ctx , req . FileID )
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-12-09 14:29:50 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
Message : "File not found." ,
})
return
}
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching file." ,
Detail : err . Error (),
})
return
}
2022-05-16 14:36:27 -05:00
}
2025-07-03 14:35:44 -05:00
var parsedTags map [ string ] string
var ok bool
if dynamicTemplate {
2025-07-21 13:02:31 -05:00
parsedTags , ok = api . dynamicTemplateVersionTags ( ctx , rw , organization . ID , apiKey . UserID , file , req . UserVariableValues )
2025-07-03 14:35:44 -05:00
if ! ok {
return
}
} else {
parsedTags , ok = api . classicTemplateVersionTags ( ctx , rw , file )
if ! ok {
return
2024-11-25 11:19:14 +00:00
}
}
// Ensure the "owner" tag is properly applied in addition to request tags and coder_workspace_tags.
2025-01-14 16:43:42 +00:00
// User-specified tags in the request will take precedence over tags parsed from `coder_workspace_tags`
// data sources defined in the template file.
tags := provisionersdk . MutateTags ( apiKey . UserID , parsedTags , req . ProvisionerTags )
2024-11-25 11:19:14 +00:00
2022-05-16 14:36:27 -05:00
var templateVersion database . TemplateVersion
var provisionerJob database . ProvisionerJob
2024-11-25 11:19:14 +00:00
var warnings [] codersdk . TemplateVersionWarning
var matchedProvisioners codersdk . MatchedProvisioners
2022-10-10 15:37:06 -05:00
err = api . Database . InTx ( func ( tx database . Store ) error {
2022-05-16 14:36:27 -05:00
jobID := uuid . New ()
2023-01-17 11:22:11 +01:00
templateVersionID := uuid . New ()
2025-11-12 12:46:39 -06:00
2023-01-17 11:22:11 +01:00
jobInput , err := json . Marshal ( provisionerdserver . TemplateVersionImportJob {
2025-11-12 12:46:39 -06:00
TemplateID : uuid . NullUUID {
UUID : req . TemplateID ,
Valid : req . TemplateID != uuid . Nil ,
},
2023-02-15 18:24:15 +01:00
TemplateVersionID : templateVersionID ,
UserVariableValues : req . UserVariableValues ,
2023-01-17 11:22:11 +01:00
})
if err != nil {
2024-09-06 16:13:34 +10:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating template version." ,
Detail : xerrors . Errorf ( "marshal job input: %w" , err ). Error (),
})
return err
2023-01-17 11:22:11 +01:00
}
2023-05-03 18:02:35 -05:00
traceMetadataRaw , err := json . Marshal ( tracing . MetadataFromContext ( ctx ))
if err != nil {
2024-09-06 16:13:34 +10:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating template version." ,
Detail : xerrors . Errorf ( "marshal job metadata: %w" , err ). Error (),
})
return err
2023-05-03 18:02:35 -05:00
}
2023-01-17 11:22:11 +01:00
2022-10-10 15:37:06 -05:00
provisionerJob , err = tx . InsertProvisionerJob ( ctx , database . InsertProvisionerJobParams {
2022-05-16 14:36:27 -05:00
ID : jobID ,
2023-09-01 19:50:12 +03:00
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
2022-05-16 14:36:27 -05:00
OrganizationID : organization . ID ,
InitiatorID : apiKey . UserID ,
2022-05-19 13:04:44 -05:00
Provisioner : database . ProvisionerType ( req . Provisioner ),
2022-05-16 14:36:27 -05:00
StorageMethod : database . ProvisionerStorageMethodFile ,
2022-10-13 18:02:52 -05:00
FileID : file . ID ,
2022-05-16 14:36:27 -05:00
Type : database . ProvisionerJobTypeTemplateVersionImport ,
2023-01-17 11:22:11 +01:00
Input : jobInput ,
2022-11-16 16:34:06 -06:00
Tags : tags ,
2023-05-03 18:02:35 -05:00
TraceMetadata : pqtype . NullRawMessage {
Valid : true ,
RawMessage : traceMetadataRaw ,
},
2025-07-30 19:09:53 -05:00
LogsOverflowed : false ,
2022-05-16 14:36:27 -05:00
})
if err != nil {
2024-09-06 16:13:34 +10:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating template version." ,
Detail : xerrors . Errorf ( "insert provisioner job: %w" , err ). Error (),
})
return err
2022-05-16 14:36:27 -05:00
}
2024-12-02 20:54:32 +00:00
// Check for eligible provisioners. This allows us to return a warning to the user if they
// submit a job for which no provisioner is available.
// nolint: gocritic // The user hitting this endpoint may not have
// permission to read provisioner daemons, but we want to show them
// information about the provisioner daemons that are available.
eligibleProvisioners , err := tx . GetProvisionerDaemonsByOrganization ( dbauthz . AsSystemReadProvisionerDaemons ( ctx ), database . GetProvisionerDaemonsByOrganizationParams {
OrganizationID : organization . ID ,
WantTags : provisionerJob . Tags ,
})
if err != nil {
// Log the error but do not return any warnings. This is purely advisory and we should not block.
api . Logger . Error ( ctx , "failed to check eligible provisioner daemons for job" , slog . Error ( err ))
}
matchedProvisioners = db2sdk . MatchedProvisioners ( eligibleProvisioners , provisionerJob . CreatedAt , provisionerdserver . StaleInterval )
if matchedProvisioners . Count == 0 {
api . Logger . Warn ( ctx , "no matching provisioners found for job" ,
slog . F ( "user_id" , apiKey . UserID ),
slog . F ( "job_id" , jobID ),
slog . F ( "job_type" , database . ProvisionerJobTypeTemplateVersionImport ),
slog . F ( "tags" , tags ),
)
} else if matchedProvisioners . Available == 0 {
api . Logger . Warn ( ctx , "no active provisioners found for job" ,
slog . F ( "user_id" , apiKey . UserID ),
slog . F ( "job_id" , jobID ),
slog . F ( "job_type" , database . ProvisionerJobTypeTemplateVersionImport ),
slog . F ( "tags" , tags ),
)
}
2022-05-16 14:36:27 -05:00
var templateID uuid . NullUUID
if req . TemplateID != uuid . Nil {
templateID = uuid . NullUUID {
UUID : req . TemplateID ,
Valid : true ,
}
}
2022-09-23 20:17:36 -05:00
if req . Name == "" {
2026-01-09 15:40:26 -07:00
req . Name = namesgenerator . NameDigitWith ( "_" )
2022-09-23 20:17:36 -05:00
}
2023-07-25 09:14:38 -04:00
err = tx . InsertTemplateVersion ( ctx , database . InsertTemplateVersionParams {
2023-01-17 11:22:11 +01:00
ID : templateVersionID ,
2022-05-16 14:36:27 -05:00
TemplateID : templateID ,
OrganizationID : organization . ID ,
2023-09-01 19:50:12 +03:00
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
2022-09-23 20:17:36 -05:00
Name : req . Name ,
2023-07-11 13:11:08 +03:00
Message : req . Message ,
2022-05-17 15:00:48 -05:00
Readme : "" ,
2022-05-16 14:36:27 -05:00
JobID : provisionerJob . ID ,
2022-10-31 13:38:07 -03:00
CreatedBy : apiKey . UserID ,
2024-11-27 20:01:08 +01:00
SourceExampleID : sql . NullString {
String : req . ExampleID ,
Valid : req . ExampleID != "" ,
},
2022-05-16 14:36:27 -05:00
})
if err != nil {
2024-09-06 16:13:34 +10:00
if database . IsUniqueViolation ( err , database . UniqueTemplateVersionsTemplateIDNameKey ) {
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
Message : fmt . Sprintf ( "A template version with name %q already exists for this template." , req . Name ),
Validations : [] codersdk . ValidationError {{
Field : "name" ,
Detail : "This value is already in use and should be unique." ,
}},
})
return err
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating template version." ,
Detail : xerrors . Errorf ( "insert template version: %w" , err ). Error (),
})
return err
2022-05-16 14:36:27 -05:00
}
2023-07-25 09:14:38 -04:00
templateVersion , err = tx . GetTemplateVersionByID ( ctx , templateVersionID )
if err != nil {
2024-09-06 16:13:34 +10:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error creating template version." ,
Detail : xerrors . Errorf ( "fetched inserted template version: %w" , err ). Error (),
})
return err
2023-07-25 09:14:38 -04:00
}
2022-05-16 14:36:27 -05:00
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-05-16 14:36:27 -05:00
if err != nil {
2024-09-06 16:13:34 +10:00
// Each failure case in the tx should have already written a response.
2022-05-16 14:36:27 -05:00
return
}
2022-09-09 11:34:23 -05:00
aReq . New = templateVersion
2023-09-19 10:25:57 +04:00
err = provisionerjobs . PostJob ( api . Pubsub , provisionerJob )
if err != nil {
// Client probably doesn't care about this error, so just log it.
api . Logger . Error ( ctx , "failed to post provisioner job to pubsub" , slog . Error ( err ))
}
2022-05-16 14:36:27 -05:00
2024-11-25 11:19:14 +00:00
httpapi . Write ( ctx , rw , http . StatusCreated , convertTemplateVersion (
templateVersion ,
convertProvisionerJob ( database . GetProvisionerJobsByIDsWithQueuePositionRow {
ProvisionerJob : provisionerJob ,
QueuePosition : 0 ,
}),
2024-11-29 19:45:58 +00:00
& matchedProvisioners ,
2024-11-25 11:19:14 +00:00
warnings ))
2022-05-16 14:36:27 -05:00
}
2025-07-21 13:02:31 -05:00
func ( api * API ) dynamicTemplateVersionTags ( ctx context . Context , rw http . ResponseWriter , orgID uuid . UUID , owner uuid . UUID , file database . File , templateVariables [] codersdk . VariableValue ) ( map [ string ] string , bool ) {
2025-07-03 14:35:44 -05:00
ownerData , err := dynamicparameters . WorkspaceOwner ( ctx , api . Database , orgID , owner )
if err != nil {
if httpapi . Is404Error ( err ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : fmt . Sprintf ( "Owner not found, uuid=%s" , owner . String ()),
})
return nil , false
}
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "fetch owner data: " + err . Error (),
})
return nil , false
}
var files fs . FS
switch file . Mimetype {
case "application/x-tar" :
files = archivefs . FromTarReader ( bytes . NewBuffer ( file . Data ))
case "application/zip" :
files , err = archivefs . FromZipReader ( bytes . NewReader ( file . Data ), int64 ( len ( file . Data )))
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "extract zip archive: " + err . Error (),
})
return nil , false
}
default :
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Unsupported file type for dynamic template version tags" ,
Detail : fmt . Sprintf ( "Mimetype %q is not supported for dynamic template version tags" , file . Mimetype ),
})
return nil , false
}
2025-07-21 13:02:31 -05:00
// Pass in any manually specified template variables as TFVars.
// TODO: Does this break if the type is not a string?
tfVarValues := make ( map [ string ] cty . Value )
for _ , variable := range templateVariables {
tfVarValues [ variable . Name ] = cty . StringVal ( variable . Value )
}
2026-03-03 10:50:18 -06:00
input := preview . Input {
2025-07-03 14:35:44 -05:00
PlanJSON : nil , // Template versions are before `terraform plan`
ParameterValues : nil , // No user-specified parameters
Owner : * ownerData ,
Logger : stdslog . New ( stdslog . DiscardHandler ),
2025-07-21 13:02:31 -05:00
TFVars : tfVarValues ,
2026-03-03 10:50:18 -06:00
}
output , diags := preview . Preview ( ctx , input , files )
if output != nil {
// ValidatePrebuilds iterates through the presets and validate their values. This
// ensures the prebuild can actually succeed in a workspace build. The failure
// diagnostics are added to the existing presets, and checked by
// 'dynamicparameters.CheckPresets'
preview . ValidatePrebuilds ( ctx , input , output . Presets , files )
}
2025-07-03 14:35:44 -05:00
tagErr := dynamicparameters . CheckTags ( output , diags )
if tagErr != nil {
code , resp := tagErr . Response ()
httpapi . Write ( ctx , rw , code , resp )
return nil , false
}
2025-07-30 15:28:56 +02:00
// Fails early if presets are invalid to prevent downstream workspace creation errors
presetErr := dynamicparameters . CheckPresets ( output , nil )
if presetErr != nil {
code , resp := presetErr . Response ()
httpapi . Write ( ctx , rw , code , resp )
return nil , false
}
2025-07-03 14:35:44 -05:00
return output . WorkspaceTags . Tags (), true
}
func ( api * API ) classicTemplateVersionTags ( ctx context . Context , rw http . ResponseWriter , file database . File ) ( map [ string ] string , bool ) {
// Try to parse template tags from the given file.
tempDir , err := os . MkdirTemp ( api . Options . CacheDir , "tfparse-*" )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "create tempdir: " + err . Error (),
})
return nil , false
}
defer func () {
if err := os . RemoveAll ( tempDir ); err != nil {
api . Logger . Error ( ctx , "failed to remove temporary tfparse dir" , slog . Error ( err ))
}
}()
if err := tfparse . WriteArchive ( file . Data , file . Mimetype , tempDir ); err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "extract archive to tempdir: " + err . Error (),
})
return nil , false
}
parser , diags := tfparse . New ( tempDir , tfparse . WithLogger ( api . Logger . Named ( "tfparse" )))
if diags . HasErrors () {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "parse module: " + diags . Error (),
})
return nil , false
}
parsedTags , err := parser . WorkspaceTagDefaults ( ctx )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error checking workspace tags" ,
Detail : "evaluate default values of workspace tags: " + err . Error (),
})
return nil , false
}
return parsedTags , true
}
2023-01-13 12:27:21 +01:00
// templateVersionResources returns the workspace agent resources associated
// with a template version. A template can specify more than one resource to be
// provisioned, each resource can have an agent that dials back to coderd. The
// agents returned are informative of the template version, and do not return
// agents associated with any particular workspace.
//
2023-01-11 12:16:09 +01:00
// @Summary Get resources by template version
// @ID get-resources-by-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
// @Success 200 {array} codersdk.WorkspaceResource
// @Router /templateversions/{templateversion}/resources [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateVersionResources ( rw http . ResponseWriter , r * http . Request ) {
2022-10-10 15:37:06 -05:00
var (
2022-12-21 13:48:49 -05:00
ctx = r . Context ()
2022-10-10 15:37:06 -05:00
templateVersion = httpmw . TemplateVersionParam ( r )
)
2022-09-21 17:07:00 -05:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
2022-03-07 11:40:54 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-07 11:40:54 -06:00
})
return
}
api . provisionerJobResources ( rw , r , job )
}
2023-01-13 12:27:21 +01:00
// templateVersionLogs returns the logs returned by the provisioner for the given
// template version. These logs are only associated with the template version,
// and not any build logs for a workspace.
// Eg: Logs returned from 'terraform plan' when uploading a new terraform file.
//
2023-01-11 12:16:09 +01:00
// @Summary Get logs by template version
// @ID get-logs-by-template-version
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param templateversion path string true "Template version ID" format(uuid)
2023-03-23 14:09:13 -05:00
// @Param before query int false "Before log id"
// @Param after query int false "After log id"
2023-01-11 12:16:09 +01:00
// @Param follow query bool false "Follow log stream"
2026-02-03 09:45:23 +00:00
// @Param format query string false "Log output format. Accepted: 'json' (default), 'text' (plain text with RFC3339 timestamps and ANSI colors). Not supported with follow=true." Enums(json,text)
2023-01-11 12:16:09 +01:00
// @Success 200 {array} codersdk.ProvisionerJobLog
// @Router /templateversions/{templateversion}/logs [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateVersionLogs ( rw http . ResponseWriter , r * http . Request ) {
2022-10-10 15:37:06 -05:00
var (
2022-12-21 13:48:49 -05:00
ctx = r . Context ()
2022-10-10 15:37:06 -05:00
templateVersion = httpmw . TemplateVersionParam ( r )
)
2022-09-21 17:07:00 -05:00
job , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
2022-03-07 11:40:54 -06:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-03-07 11:40:54 -06:00
})
return
}
api . provisionerJobLogs ( rw , r , job )
}
2024-11-29 19:45:58 +00:00
func convertTemplateVersion ( version database . TemplateVersion , job codersdk . ProvisionerJob , matchedProvisioners * codersdk . MatchedProvisioners , warnings [] codersdk . TemplateVersionWarning ) codersdk . TemplateVersion {
2022-04-06 12:42:40 -05:00
return codersdk . TemplateVersion {
2022-06-02 00:44:53 +10:00
ID : version . ID ,
TemplateID : & version . TemplateID . UUID ,
OrganizationID : version . OrganizationID ,
CreatedAt : version . CreatedAt ,
UpdatedAt : version . UpdatedAt ,
Name : version . Name ,
2023-07-11 13:11:08 +03:00
Message : version . Message ,
2022-06-02 00:44:53 +10:00
Job : job ,
Readme : version . Readme ,
2023-07-25 09:14:38 -04:00
CreatedBy : codersdk . MinimalUser {
ID : version . CreatedBy ,
Username : version . CreatedByUsername ,
2025-10-22 16:18:31 +11:00
Name : version . CreatedByName ,
2023-12-11 10:09:51 -07:00
AvatarURL : version . CreatedByAvatarURL ,
2023-07-25 09:14:38 -04:00
},
2024-11-25 11:19:14 +00:00
Archived : version . Archived ,
Warnings : warnings ,
MatchedProvisioners : matchedProvisioners ,
2025-08-19 10:41:33 +02:00
HasExternalAgent : version . HasExternalAgent . Bool ,
2022-03-07 11:40:54 -06:00
}
}
2022-11-09 11:01:34 -06:00
2023-02-15 18:24:15 +01:00
func convertTemplateVersionVariables ( dbVariables [] database . TemplateVersionVariable ) [] codersdk . TemplateVersionVariable {
variables := make ([] codersdk . TemplateVersionVariable , 0 )
for _ , dbVariable := range dbVariables {
variables = append ( variables , convertTemplateVersionVariable ( dbVariable ))
}
return variables
}
2023-02-17 09:07:45 +01:00
const redacted = "*redacted*"
2023-02-15 18:24:15 +01:00
func convertTemplateVersionVariable ( variable database . TemplateVersionVariable ) codersdk . TemplateVersionVariable {
2023-02-17 09:07:45 +01:00
templateVariable := codersdk . TemplateVersionVariable {
2023-02-15 18:24:15 +01:00
Name : variable . Name ,
Description : variable . Description ,
Type : variable . Type ,
Value : variable . Value ,
DefaultValue : variable . DefaultValue ,
Required : variable . Required ,
Sensitive : variable . Sensitive ,
}
2023-02-17 09:07:45 +01:00
if templateVariable . Sensitive {
templateVariable . Value = redacted
templateVariable . DefaultValue = redacted
}
return templateVariable
2023-02-15 18:24:15 +01:00
}
2022-11-09 11:01:34 -06:00
func watchTemplateChannel ( id uuid . UUID ) string {
return fmt . Sprintf ( "template:%s" , id )
}
func ( api * API ) publishTemplateUpdate ( ctx context . Context , templateID uuid . UUID ) {
err := api . Pubsub . Publish ( watchTemplateChannel ( templateID ), [] byte {})
if err != nil {
api . Logger . Warn ( ctx , "failed to publish template update" ,
slog . F ( "template_id" , templateID ), slog . Error ( err ))
}
}