2020-07-05 23:21:03 +00:00
package stacks
import (
2021-09-07 00:37:26 +00:00
"fmt"
2020-07-05 23:21:03 +00:00
"net/http"
2021-09-29 23:58:10 +00:00
"os"
2021-06-16 21:47:32 +00:00
"strconv"
"time"
2020-07-05 23:21:03 +00:00
2021-09-02 05:28:51 +00:00
"github.com/pkg/errors"
2020-07-05 23:21:03 +00:00
2021-09-07 00:37:26 +00:00
"github.com/asaskevich/govalidator"
2020-07-05 23:21:03 +00:00
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
"github.com/portainer/libhttp/response"
portainer "github.com/portainer/portainer/api"
2021-06-16 21:47:32 +00:00
"github.com/portainer/portainer/api/filesystem"
2021-09-07 00:37:26 +00:00
gittypes "github.com/portainer/portainer/api/git/types"
2021-09-03 05:37:34 +00:00
"github.com/portainer/portainer/api/http/client"
2021-09-29 23:58:10 +00:00
"github.com/portainer/portainer/api/internal/stackutils"
2021-09-07 00:37:26 +00:00
k "github.com/portainer/portainer/api/kubernetes"
2020-07-05 23:21:03 +00:00
)
2021-06-16 21:47:32 +00:00
type kubernetesStringDeploymentPayload struct {
2021-09-29 23:58:10 +00:00
StackName string
2020-07-05 23:21:03 +00:00
ComposeFormat bool
Namespace string
StackFileContent string
}
2021-06-16 21:47:32 +00:00
type kubernetesGitDeploymentPayload struct {
2021-09-29 23:58:10 +00:00
StackName string
2021-06-16 21:47:32 +00:00
ComposeFormat bool
Namespace string
RepositoryURL string
RepositoryReferenceName string
RepositoryAuthentication bool
RepositoryUsername string
RepositoryPassword string
2021-09-29 23:58:10 +00:00
ManifestFile string
AdditionalFiles [ ] string
AutoUpdate * portainer . StackAutoUpdate
2021-06-16 21:47:32 +00:00
}
2021-09-03 05:37:34 +00:00
type kubernetesManifestURLDeploymentPayload struct {
2021-09-29 23:58:10 +00:00
StackName string
2021-09-07 00:37:26 +00:00
Namespace string
ComposeFormat bool
ManifestURL string
2021-09-03 05:37:34 +00:00
}
2021-06-16 21:47:32 +00:00
func ( payload * kubernetesStringDeploymentPayload ) Validate ( r * http . Request ) error {
2020-07-05 23:21:03 +00:00
if govalidator . IsNull ( payload . StackFileContent ) {
2020-07-07 21:57:52 +00:00
return errors . New ( "Invalid stack file content" )
2020-07-05 23:21:03 +00:00
}
if govalidator . IsNull ( payload . Namespace ) {
2020-07-07 21:57:52 +00:00
return errors . New ( "Invalid namespace" )
2020-07-05 23:21:03 +00:00
}
2021-09-29 23:58:10 +00:00
if govalidator . IsNull ( payload . StackName ) {
return errors . New ( "Invalid stack name" )
}
2020-07-05 23:21:03 +00:00
return nil
}
2021-06-16 21:47:32 +00:00
func ( payload * kubernetesGitDeploymentPayload ) Validate ( r * http . Request ) error {
if govalidator . IsNull ( payload . Namespace ) {
return errors . New ( "Invalid namespace" )
}
if govalidator . IsNull ( payload . RepositoryURL ) || ! govalidator . IsURL ( payload . RepositoryURL ) {
return errors . New ( "Invalid repository URL. Must correspond to a valid URL format" )
}
if payload . RepositoryAuthentication && govalidator . IsNull ( payload . RepositoryPassword ) {
return errors . New ( "Invalid repository credentials. Password must be specified when authentication is enabled" )
}
2021-09-29 23:58:10 +00:00
if govalidator . IsNull ( payload . ManifestFile ) {
return errors . New ( "Invalid manifest file in repository" )
2021-06-16 21:47:32 +00:00
}
if govalidator . IsNull ( payload . RepositoryReferenceName ) {
2021-09-07 00:37:26 +00:00
payload . RepositoryReferenceName = defaultGitReferenceName
2021-06-16 21:47:32 +00:00
}
2021-09-29 23:58:10 +00:00
if err := validateStackAutoUpdate ( payload . AutoUpdate ) ; err != nil {
return err
}
if govalidator . IsNull ( payload . StackName ) {
return errors . New ( "Invalid stack name" )
}
2021-06-16 21:47:32 +00:00
return nil
}
2021-09-03 05:37:34 +00:00
func ( payload * kubernetesManifestURLDeploymentPayload ) Validate ( r * http . Request ) error {
if govalidator . IsNull ( payload . ManifestURL ) || ! govalidator . IsURL ( payload . ManifestURL ) {
return errors . New ( "Invalid manifest URL" )
}
2021-09-29 23:58:10 +00:00
if govalidator . IsNull ( payload . StackName ) {
return errors . New ( "Invalid stack name" )
}
2021-09-03 05:37:34 +00:00
return nil
}
2020-07-05 23:21:03 +00:00
type createKubernetesStackResponse struct {
Output string ` json:"Output" `
}
2021-09-07 00:37:26 +00:00
func ( handler * Handler ) createKubernetesStackFromFileContent ( w http . ResponseWriter , r * http . Request , endpoint * portainer . Endpoint , userID portainer . UserID ) * httperror . HandlerError {
2021-06-16 21:47:32 +00:00
var payload kubernetesStringDeploymentPayload
if err := request . DecodeAndValidateJSONPayload ( r , & payload ) ; err != nil {
return & httperror . HandlerError { StatusCode : http . StatusBadRequest , Message : "Invalid request payload" , Err : err }
}
2021-09-07 00:37:26 +00:00
user , err := handler . DataStore . User ( ) . User ( userID )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to load user information from the database" , Err : err }
}
2021-09-29 23:58:10 +00:00
isUnique , err := handler . checkUniqueStackName ( endpoint , payload . StackName , 0 )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to check for name collision" , Err : err }
}
if ! isUnique {
return & httperror . HandlerError { StatusCode : http . StatusConflict , Message : fmt . Sprintf ( "A stack with the name '%s' already exists" , payload . StackName ) , Err : errStackAlreadyExists }
}
2021-09-07 00:37:26 +00:00
2021-06-16 21:47:32 +00:00
stackID := handler . DataStore . Stack ( ) . GetNextIdentifier ( )
stack := & portainer . Stack {
2021-09-07 00:37:26 +00:00
ID : portainer . StackID ( stackID ) ,
Type : portainer . KubernetesStack ,
EndpointID : endpoint . ID ,
EntryPoint : filesystem . ManifestFileDefaultName ,
2021-09-29 23:58:10 +00:00
Name : payload . StackName ,
2021-09-07 00:37:26 +00:00
Namespace : payload . Namespace ,
Status : portainer . StackStatusActive ,
CreationDate : time . Now ( ) . Unix ( ) ,
CreatedBy : user . Username ,
IsComposeFormat : payload . ComposeFormat ,
2021-06-08 23:55:17 +00:00
}
2021-06-16 21:47:32 +00:00
stackFolder := strconv . Itoa ( int ( stack . ID ) )
projectPath , err := handler . FileService . StoreStackFileFromBytes ( stackFolder , stack . EntryPoint , [ ] byte ( payload . StackFileContent ) )
2020-07-05 23:21:03 +00:00
if err != nil {
2021-09-07 00:37:26 +00:00
fileType := "Manifest"
if stack . IsComposeFormat {
fileType = "Compose"
}
errMsg := fmt . Sprintf ( "Unable to persist Kubernetes %s file on disk" , fileType )
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : errMsg , Err : err }
2020-07-05 23:21:03 +00:00
}
2021-06-16 21:47:32 +00:00
stack . ProjectPath = projectPath
doCleanUp := true
defer handler . cleanUp ( stack , & doCleanUp )
2020-07-05 23:21:03 +00:00
2021-09-29 23:58:10 +00:00
output , err := handler . deployKubernetesStack ( user . ID , endpoint , stack , k . KubeAppLabels {
StackID : stackID ,
StackName : stack . Name ,
Owner : stack . CreatedBy ,
Kind : "content" ,
2021-09-02 05:28:51 +00:00
} )
2021-09-07 00:37:26 +00:00
2020-07-05 23:21:03 +00:00
if err != nil {
2021-06-16 21:47:32 +00:00
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to deploy Kubernetes stack" , Err : err }
}
err = handler . DataStore . Stack ( ) . CreateStack ( stack )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to persist the Kubernetes stack inside the database" , Err : err }
2020-07-05 23:21:03 +00:00
}
resp := & createKubernetesStackResponse {
2021-06-08 23:55:17 +00:00
Output : output ,
2020-07-05 23:21:03 +00:00
}
2021-09-29 23:58:10 +00:00
doCleanUp = false
2020-07-05 23:21:03 +00:00
return response . JSON ( w , resp )
}
2021-09-07 00:37:26 +00:00
func ( handler * Handler ) createKubernetesStackFromGitRepository ( w http . ResponseWriter , r * http . Request , endpoint * portainer . Endpoint , userID portainer . UserID ) * httperror . HandlerError {
2021-06-16 21:47:32 +00:00
var payload kubernetesGitDeploymentPayload
if err := request . DecodeAndValidateJSONPayload ( r , & payload ) ; err != nil {
return & httperror . HandlerError { StatusCode : http . StatusBadRequest , Message : "Invalid request payload" , Err : err }
}
2021-09-07 00:37:26 +00:00
user , err := handler . DataStore . User ( ) . User ( userID )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to load user information from the database" , Err : err }
}
2021-09-29 23:58:10 +00:00
isUnique , err := handler . checkUniqueStackName ( endpoint , payload . StackName , 0 )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to check for name collision" , Err : err }
}
if ! isUnique {
return & httperror . HandlerError { StatusCode : http . StatusConflict , Message : fmt . Sprintf ( "A stack with the name '%s' already exists" , payload . StackName ) , Err : errStackAlreadyExists }
}
//make sure the webhook ID is unique
if payload . AutoUpdate != nil && payload . AutoUpdate . Webhook != "" {
isUnique , err := handler . checkUniqueWebhookID ( payload . AutoUpdate . Webhook )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to check for webhook ID collision" , Err : err }
}
if ! isUnique {
return & httperror . HandlerError { StatusCode : http . StatusConflict , Message : fmt . Sprintf ( "Webhook ID: %s already exists" , payload . AutoUpdate . Webhook ) , Err : errWebhookIDAlreadyExists }
}
}
2021-09-07 00:37:26 +00:00
2021-06-16 21:47:32 +00:00
stackID := handler . DataStore . Stack ( ) . GetNextIdentifier ( )
stack := & portainer . Stack {
2021-09-07 00:37:26 +00:00
ID : portainer . StackID ( stackID ) ,
Type : portainer . KubernetesStack ,
EndpointID : endpoint . ID ,
2021-09-29 23:58:10 +00:00
EntryPoint : payload . ManifestFile ,
2021-09-07 00:37:26 +00:00
GitConfig : & gittypes . RepoConfig {
URL : payload . RepositoryURL ,
ReferenceName : payload . RepositoryReferenceName ,
2021-09-29 23:58:10 +00:00
ConfigFilePath : payload . ManifestFile ,
2021-09-07 00:37:26 +00:00
} ,
Namespace : payload . Namespace ,
2021-09-29 23:58:10 +00:00
Name : payload . StackName ,
2021-09-07 00:37:26 +00:00
Status : portainer . StackStatusActive ,
CreationDate : time . Now ( ) . Unix ( ) ,
CreatedBy : user . Username ,
IsComposeFormat : payload . ComposeFormat ,
2021-09-29 23:58:10 +00:00
AutoUpdate : payload . AutoUpdate ,
AdditionalFiles : payload . AdditionalFiles ,
2021-09-07 00:37:26 +00:00
}
if payload . RepositoryAuthentication {
stack . GitConfig . Authentication = & gittypes . GitAuthentication {
Username : payload . RepositoryUsername ,
Password : payload . RepositoryPassword ,
}
2021-06-16 21:47:32 +00:00
}
projectPath := handler . FileService . GetStackProjectPath ( strconv . Itoa ( int ( stack . ID ) ) )
stack . ProjectPath = projectPath
doCleanUp := true
defer handler . cleanUp ( stack , & doCleanUp )
2021-09-10 01:35:37 +00:00
commitID , err := handler . latestCommitID ( payload . RepositoryURL , payload . RepositoryReferenceName , payload . RepositoryAuthentication , payload . RepositoryUsername , payload . RepositoryPassword )
2021-09-07 00:37:26 +00:00
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to fetch git repository id" , Err : err }
}
2021-09-10 01:35:37 +00:00
stack . GitConfig . ConfigHash = commitID
2021-09-07 00:37:26 +00:00
2021-09-29 23:58:10 +00:00
repositoryUsername := payload . RepositoryUsername
repositoryPassword := payload . RepositoryPassword
if ! payload . RepositoryAuthentication {
repositoryUsername = ""
repositoryPassword = ""
}
err = handler . GitService . CloneRepository ( projectPath , payload . RepositoryURL , payload . RepositoryReferenceName , repositoryUsername , repositoryPassword )
2021-06-16 21:47:32 +00:00
if err != nil {
2021-09-29 23:58:10 +00:00
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Failed to clone git repository" , Err : err }
2021-06-16 21:47:32 +00:00
}
2021-09-29 23:58:10 +00:00
output , err := handler . deployKubernetesStack ( user . ID , endpoint , stack , k . KubeAppLabels {
StackID : stackID ,
StackName : stack . Name ,
Owner : stack . CreatedBy ,
Kind : "git" ,
2021-09-02 05:28:51 +00:00
} )
2021-09-07 00:37:26 +00:00
2021-06-16 21:47:32 +00:00
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to deploy Kubernetes stack" , Err : err }
}
2021-09-29 23:58:10 +00:00
if payload . AutoUpdate != nil && payload . AutoUpdate . Interval != "" {
jobID , e := startAutoupdate ( stack . ID , stack . AutoUpdate . Interval , handler . Scheduler , handler . StackDeployer , handler . DataStore , handler . GitService )
if e != nil {
return e
}
stack . AutoUpdate . JobID = jobID
}
2021-06-16 21:47:32 +00:00
err = handler . DataStore . Stack ( ) . CreateStack ( stack )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to persist the stack inside the database" , Err : err }
}
resp := & createKubernetesStackResponse {
Output : output ,
}
2021-09-02 05:28:51 +00:00
2021-09-29 23:58:10 +00:00
doCleanUp = false
2021-06-16 21:47:32 +00:00
return response . JSON ( w , resp )
}
2021-09-07 00:37:26 +00:00
func ( handler * Handler ) createKubernetesStackFromManifestURL ( w http . ResponseWriter , r * http . Request , endpoint * portainer . Endpoint , userID portainer . UserID ) * httperror . HandlerError {
2021-09-03 05:37:34 +00:00
var payload kubernetesManifestURLDeploymentPayload
if err := request . DecodeAndValidateJSONPayload ( r , & payload ) ; err != nil {
return & httperror . HandlerError { StatusCode : http . StatusBadRequest , Message : "Invalid request payload" , Err : err }
}
2021-09-07 00:37:26 +00:00
user , err := handler . DataStore . User ( ) . User ( userID )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to load user information from the database" , Err : err }
}
2021-09-29 23:58:10 +00:00
isUnique , err := handler . checkUniqueStackName ( endpoint , payload . StackName , 0 )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to check for name collision" , Err : err }
}
if ! isUnique {
return & httperror . HandlerError { StatusCode : http . StatusConflict , Message : fmt . Sprintf ( "A stack with the name '%s' already exists" , payload . StackName ) , Err : errStackAlreadyExists }
}
2021-09-07 00:37:26 +00:00
2021-09-03 05:37:34 +00:00
stackID := handler . DataStore . Stack ( ) . GetNextIdentifier ( )
stack := & portainer . Stack {
2021-09-07 00:37:26 +00:00
ID : portainer . StackID ( stackID ) ,
Type : portainer . KubernetesStack ,
EndpointID : endpoint . ID ,
EntryPoint : filesystem . ManifestFileDefaultName ,
2021-09-10 01:35:37 +00:00
Namespace : payload . Namespace ,
2021-09-29 23:58:10 +00:00
Name : payload . StackName ,
2021-09-07 00:37:26 +00:00
Status : portainer . StackStatusActive ,
CreationDate : time . Now ( ) . Unix ( ) ,
CreatedBy : user . Username ,
IsComposeFormat : payload . ComposeFormat ,
2021-09-03 05:37:34 +00:00
}
var manifestContent [ ] byte
2021-09-07 00:37:26 +00:00
manifestContent , err = client . Get ( payload . ManifestURL , 30 )
2021-09-03 05:37:34 +00:00
if err != nil {
2021-09-07 00:37:26 +00:00
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to retrieve manifest from URL" , Err : err }
2021-09-03 05:37:34 +00:00
}
stackFolder := strconv . Itoa ( int ( stack . ID ) )
projectPath , err := handler . FileService . StoreStackFileFromBytes ( stackFolder , stack . EntryPoint , manifestContent )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to persist Kubernetes manifest file on disk" , Err : err }
}
stack . ProjectPath = projectPath
doCleanUp := true
defer handler . cleanUp ( stack , & doCleanUp )
2021-09-29 23:58:10 +00:00
output , err := handler . deployKubernetesStack ( user . ID , endpoint , stack , k . KubeAppLabels {
StackID : stackID ,
StackName : stack . Name ,
Owner : stack . CreatedBy ,
Kind : "url" ,
2021-09-03 05:37:34 +00:00
} )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to deploy Kubernetes stack" , Err : err }
}
err = handler . DataStore . Stack ( ) . CreateStack ( stack )
if err != nil {
return & httperror . HandlerError { StatusCode : http . StatusInternalServerError , Message : "Unable to persist the Kubernetes stack inside the database" , Err : err }
}
2021-09-10 01:35:37 +00:00
doCleanUp = false
2021-09-03 05:37:34 +00:00
resp := & createKubernetesStackResponse {
Output : output ,
}
return response . JSON ( w , resp )
}
2021-09-29 23:58:10 +00:00
func ( handler * Handler ) deployKubernetesStack ( userID portainer . UserID , endpoint * portainer . Endpoint , stack * portainer . Stack , appLabels k . KubeAppLabels ) ( string , error ) {
2020-07-05 23:21:03 +00:00
handler . stackCreationMutex . Lock ( )
defer handler . stackCreationMutex . Unlock ( )
2021-09-29 23:58:10 +00:00
manifestFilePaths , tempDir , err := stackutils . CreateTempK8SDeploymentFiles ( stack , handler . KubernetesDeployer , appLabels )
2021-06-16 21:47:32 +00:00
if err != nil {
2021-09-29 23:58:10 +00:00
return "" , errors . Wrap ( err , "failed to create temp kub deployment files" )
2021-06-16 21:47:32 +00:00
}
2021-09-29 23:58:10 +00:00
defer os . RemoveAll ( tempDir )
return handler . KubernetesDeployer . Deploy ( userID , endpoint , manifestFilePaths , stack . Namespace )
2021-06-16 21:47:32 +00:00
}