Skip to content

Commit

Permalink
feat: add initial equalized deploy command
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickMenoti committed Sep 2, 2024
1 parent ac64ff4 commit 3829a99
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 361 deletions.
26 changes: 26 additions & 0 deletions pkg/api/storage/credentials.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package storage

import (
"context"

"github.com/aziontech/azion-cli/pkg/logger"
"github.com/aziontech/azion-cli/utils"
sdk "github.com/aziontech/azionapi-go-sdk/storage"
"go.uber.org/zap"
)

type RequestCredentials struct {
sdk.S3CredentialCreate
}

func (c *Client) CreateCredentials(ctx context.Context, request RequestCredentials) (*sdk.ResponseS3Credential, error) {
logger.Debug("Creating s3 credentials ", zap.Any("name", request.Name))
req := c.apiClient.StorageAPI.StorageApiS3CredentialsCreate(ctx).S3CredentialCreate(request.S3CredentialCreate)
// req := c.apiClient.StorageAPI.StorageApiBucketsCreate(ctx).BucketCreate(request.BucketCreate)
resp, httpResp, err := req.Execute()
if err != nil {
logger.Debug("Error while creating the user's s3 credentials", zap.Error(err))
return nil, utils.ErrorPerStatusCode(httpResp, err)
}
return resp, nil
}
160 changes: 40 additions & 120 deletions pkg/cmd/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,20 @@ import (
"io/fs"
"os"
"path/filepath"
"strconv"
"time"

"github.com/MakeNowJust/heredoc"
msg "github.com/aziontech/azion-cli/messages/deploy"
apiEdgeApplications "github.com/aziontech/azion-cli/pkg/api/edge_applications"
"github.com/aziontech/azion-cli/pkg/api/storage"
"github.com/aziontech/azion-cli/pkg/cmd/build"
"github.com/aziontech/azion-cli/pkg/cmd/sync"
"github.com/aziontech/azion-cli/pkg/cmdutil"
"github.com/aziontech/azion-cli/pkg/contracts"
"github.com/aziontech/azion-cli/pkg/iostreams"
"github.com/aziontech/azion-cli/pkg/logger"
manifestInt "github.com/aziontech/azion-cli/pkg/manifest"
"github.com/aziontech/azion-cli/pkg/output"
"github.com/aziontech/azion-cli/pkg/token"
"github.com/aziontech/azion-cli/utils"
sdk "github.com/aziontech/azionapi-go-sdk/edgeapplications"
sdk "github.com/aziontech/azionapi-go-sdk/storage"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
Expand Down Expand Up @@ -114,157 +113,78 @@ func (cmd *DeployCmd) Run(f *cmdutil.Factory) error {
msgs = append(msgs, "Running deploy command")
ctx := context.Background()

err := checkToken(f)
settings, err := token.ReadSettings()
if err != nil {
return err
}

if Sync {
sync.ProjectConf = ProjectConf
syncCmd := sync.NewSyncCmd(f)
syncCmd.EnvPath = Env
if err := sync.Run(syncCmd); err != nil {
logger.Debug("Error while synchronizing local resources with remove resources", zap.Error(err))
return err
}
}

if !SkipBuild {
buildCmd := cmd.BuildCmd(f)
err = buildCmd.ExternalRun(&contracts.BuildInfo{}, ProjectConf, &msgs)
if err != nil {
logger.Debug("Error while running build command called by deploy command", zap.Error(err))
return err
}
}

conf, err := cmd.GetAzionJsonContent(ProjectConf)
if err != nil {
logger.Debug("Failed to get Azion JSON content", zap.Error(err))
return err
}

versionID := cmd.VersionID()

conf.Prefix = versionID

err = checkArgsJson(cmd, ProjectConf)
if err != nil {
return err
}

clients := NewClients(f)
interpreter := cmd.Interpreter()

pathManifest, err := interpreter.ManifestPath()
if err != nil {
return err
}

err = cmd.doApplication(clients.EdgeApplication, context.Background(), conf, &msgs)
if err != nil {
return err
}

singleOriginId, err := cmd.doOriginSingle(clients.Origin, ctx, conf, &msgs)
if err != nil {
return err
}

err = cmd.doBucket(clients.Bucket, ctx, conf, &msgs)
if err != nil {
return err
}

// Check if directory exists; if not, we skip uploading static files
if _, err := os.Stat(PathStatic); os.IsNotExist(err) {
logger.Debug(msg.SkipUpload)
} else {
err = cmd.uploadFiles(f, conf, &msgs)
//create credentials if they are not found on settings file
if settings.S3AccessKey == "" || settings.S3SecreKey == "" {
nameBucket := fmt.Sprintf("%s-%s", conf.Name, cmd.VersionID())
storageClient := storage.NewClient(f.HttpClient, f.Config.GetString("storage_url"), f.Config.GetString("token"))
err := storageClient.CreateBucket(ctx, storage.RequestBucket{BucketCreate: sdk.BucketCreate{Name: nameBucket, EdgeAccess: sdk.READ_WRITE}})
if err != nil {
return err
}
}

conf.Function.File = ".edge/worker.js"
err = cmd.doFunction(clients, ctx, conf, &msgs)
if err != nil {
return err
}
// Get the current time
now := time.Now()

if !conf.NotFirstRun {
ruleDefaultID, err := clients.EdgeApplication.GetRulesDefault(ctx, conf.Application.ID, "request")
if err != nil {
logger.Debug("Error while getting default rules engine", zap.Error(err))
return err
}
behaviors := make([]sdk.RulesEngineBehaviorEntry, 0)

var behString sdk.RulesEngineBehaviorString
behString.SetName("set_origin")
// Add one year to the current time
oneYearLater := now.AddDate(1, 0, 0)

behString.SetTarget(strconv.Itoa(int(singleOriginId)))
request := new(storage.RequestCredentials)
request.Name = &nameBucket
request.Capabilities = []string{"listAllBucketNames", "listBuckets", "listFiles", "readFiles", "writeFiles", "deleteFiles"}
request.Bucket = &nameBucket
request.ExpirationDate = &oneYearLater

behaviors = append(behaviors, sdk.RulesEngineBehaviorEntry{
RulesEngineBehaviorString: &behString,
})

reqUpdateRulesEngine := apiEdgeApplications.UpdateRulesEngineRequest{
IdApplication: conf.Application.ID,
Phase: "request",
Id: ruleDefaultID,
creds, err := storageClient.CreateCredentials(ctx, *request)
if err != nil {
return err
}
settings.S3AccessKey = creds.Data.GetAccessKey()
settings.S3SecreKey = creds.Data.GetSecretKey()
settings.S3Bucket = nameBucket

reqUpdateRulesEngine.SetBehaviors(behaviors)

_, err = clients.EdgeApplication.UpdateRulesEngine(ctx, &reqUpdateRulesEngine)
err = token.WriteSettings(settings)
if err != nil {
logger.Debug("Error while updating default rules engine", zap.Error(err))
return err
}
}

manifestStructure, err := interpreter.ReadManifest(pathManifest, f, &msgs)
localDir, err := cmd.GetWorkDir()
if err != nil {
return err
}

if len(conf.RulesEngine.Rules) == 0 {
err = cmd.doRulesDeploy(ctx, conf, clients.EdgeApplication, &msgs)
if err != nil {
return err
}
}
conf.Prefix = cmd.VersionID()

err = interpreter.CreateResources(conf, manifestStructure, f, ProjectConf, &msgs)
err = cmd.uploadFiles(f, conf, &msgs, localDir)
if err != nil {
return err
}

if manifestStructure.Domain.Name == "" {
err = cmd.doDomain(clients.Domain, ctx, conf, &msgs)
if err != nil {
return err
}
id, err := callScript("azion3c6bad99a7f30a2491e5423e227050aa72a", settings.S3AccessKey, settings.S3SecreKey, conf.Prefix, settings.S3Bucket)
if err != nil {
return err
}
fmt.Println(id)

logger.FInfoFlags(cmd.F.IOStreams.Out, msg.DeploySuccessful, f.Format, f.Out)
msgs = append(msgs, msg.DeploySuccessful)

msgfOutputDomainSuccess := fmt.Sprintf(msg.DeployOutputDomainSuccess, conf.Domain.Url)
logger.FInfoFlags(cmd.F.IOStreams.Out, msgfOutputDomainSuccess, f.Format, f.Out)
msgs = append(msgs, msgfOutputDomainSuccess)
fmt.Println("5")

logger.FInfoFlags(cmd.F.IOStreams.Out, msg.DeployPropagation, f.Format, f.Out)
msgs = append(msgs, msg.DeployPropagation)

outSlice := output.SliceOutput{
Messages: msgs,
GeneralOutput: output.GeneralOutput{
Out: cmd.F.IOStreams.Out,
Flags: cmd.F.Flags,
},
err = openBrowser(f, fmt.Sprintf("https://stage-console.azion.com/create/deploy/%s", id))
if err != nil {
return err
}

return output.Print(&outSlice)
fmt.Println("6")

return nil
}
Loading

0 comments on commit 3829a99

Please sign in to comment.