Skip to content

Commit

Permalink
feat: support deploy
Browse files Browse the repository at this point in the history
  • Loading branch information
fredliang44 committed Jan 9, 2021
1 parent 59cff09 commit 2924f6b
Show file tree
Hide file tree
Showing 3 changed files with 213 additions and 7 deletions.
30 changes: 26 additions & 4 deletions cmd/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
package cmd

import (
"encoding/json"
"github.com/let-sh/cli/log"
"github.com/let-sh/cli/requests"
"github.com/let-sh/cli/types"
Expand Down Expand Up @@ -124,18 +125,37 @@ var deployCmd = &cobra.Command{

// remove if not clean
os.Remove(dir + "/" + deploymentConfig.Name + "-" + hashID + ".tar.gz")
err = archiver.Archive([]string{dir + "/" + deploymentConfig.Name + "-" + hashID}, dir+"/"+deploymentConfig.Name+"-"+hashID+".tar.gz")
err = archiver.Archive([]string{"."}, dir+"/"+deploymentConfig.Name+"-"+hashID+".tar.gz")
if err != nil {
log.Error(err)
return
}

oss.UploadFileToCodeSource(dir+"/"+deploymentConfig.Name+"-"+hashID+".tar.gz", deploymentConfig.Name+"-"+hashID+".tar.gz", deploymentConfig.Name)
}

// awaiting deployment result
configBytes, _ := json.Marshal(deploymentConfig)
deployment, err := requests.Deploy(deploymentConfig.Type, deploymentConfig.Name, string(configBytes), inputCN)
if err != nil {
log.Error(err)
return
}
// awaiting deployment result

time.Sleep(time.Second * 4)
for {
currentStatus, err := requests.GetDeploymentStatus(deployment.ID)
if err != nil {
log.Error(err)
}

log.BUpdate(" NetworkStage: " + currentStatus.NetworkStage + ", PackerStage: " + currentStatus.PackerStage + ", Status: " + currentStatus.Status)

time.Sleep(time.Second * 2)
if currentStatus.Done {
break
}
}
}
log.Success("deploy succeed")
log.BStop()
return
},
Expand All @@ -144,6 +164,7 @@ var deployCmd = &cobra.Command{
var deploymentConfig types.LetConfig
var inputProjectName string
var inputProjectType string
var inputCN bool

func init() {
rootCmd.AddCommand(deployCmd)
Expand All @@ -152,4 +173,5 @@ func init() {
// is called directly, e.g.:
deployCmd.Flags().StringVarP(&inputProjectName, "project", "p", "", "current project name")
deployCmd.Flags().StringVarP(&inputProjectType, "type", "t", "", "current project type, e.g. react")
deployCmd.Flags().BoolVarP(&inputCN, "cn", "", true, "deploy in mainland of china")
}
79 changes: 79 additions & 0 deletions requests/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,82 @@ query($type: String!, $name: String!) {

return respData.StsToken, nil
}

func Deploy(projectType, projectName, config string, cn bool) (deployment struct {
ID string `json:"id"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
}, err error) {
req := graphql.NewRequest(`
mutation($type: String!, $name: String!, $config: String, $cn: Boolean) {
deploy(input:{type:$type, projectName:$name, config:$config, cn:$cn}) {
id
networkStage
packerStage
status
}
}
`)

req.Var("type", projectType)
req.Var("name", projectName)
req.Var("config", config)
req.Var("cn", cn)
req.Header.Set("Authorization", "Bearer "+utils.Credentials.Token)

// run it and capture the response
var respData struct {
Deploy struct {
ID string `json:"id"`
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
} `json:"deploy,omitempty"`
}
if err := Graphql.Run(context.Background(), req, &respData); err != nil {
//if len(respData.Error.Errors) > 0 {
// return "", false, errors.New(respData.Error.Errors[0].Message)
//}

return deployment, err
}

return respData.Deploy, nil
}

func GetDeploymentStatus(id string) (deployment struct {
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Done bool `json:"done"`
}, err error) {
req := graphql.NewRequest(`
query($id: UUID!) {
deployment(id:$id) {
networkStage
packerStage
status
done
}
}
`)
req.Var("id", id)
req.Header.Set("Authorization", "Bearer "+utils.Credentials.Token)

// run it and capture the response
var respData struct {
Deployment struct {
NetworkStage string `json:"networkStage"`
PackerStage string `json:"packerStage"`
Status string `json:"status"`
Done bool `json:"done"`
} `json:"deployment,omitempty"`
}
if err := Graphql.Run(context.Background(), req, &respData); err != nil {

return deployment, err
}

return respData.Deployment, nil
}
111 changes: 108 additions & 3 deletions utils/oss/oss.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/vbauerster/mpb/v5"
"github.com/vbauerster/mpb/v5/decor"
"os"
"path/filepath"
"strings"
"time"
)
Expand Down Expand Up @@ -48,7 +49,7 @@ func UploadFileToCodeSource(filepath, filename, projectName string) {

// 创建OSSClient实例
endpoint := strings.Join(strings.Split(stsToken.Host, ".")[1:], ".")
client, err := oss.New(endpoint, stsToken.AccessKeyID, stsToken.AccessKeySecret)
client, err := oss.New(endpoint, stsToken.AccessKeyID, stsToken.AccessKeySecret, oss.SecurityToken(stsToken.SecurityToken))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
Expand All @@ -67,12 +68,116 @@ func UploadFileToCodeSource(filepath, filename, projectName string) {
proxyReader := bar.ProxyReader(r)
defer proxyReader.Close()

bucket.PutObject(filename, proxyReader, oss.Progress(&OssProgressListener{}))
err = bucket.PutObject(filename, proxyReader, oss.Progress(&OssProgressListener{}))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
//bar.Abort(true)

log.S.Suffix(" deploying ")
log.BUnpause()
}

func UploadDirToStaticSource(dirPath, projectName, bundleID string) error {
log.BPause()
stsToken, err := requests.GetStsToken("static", projectName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 创建OSSClient实例
endpoint := strings.Join(strings.Split(stsToken.Host, ".")[1:], ".")
client, err := oss.New(endpoint, stsToken.AccessKeyID, stsToken.AccessKeySecret, oss.SecurityToken(stsToken.SecurityToken))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucketName := strings.Replace(strings.Split(stsToken.Host, ".")[0], "https://", "", 1)

// 获取存储空间。
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}

// Read directory and close.

dir, err := os.Open(dirPath)
if err != nil {
return err
}
names, err := dir.Readdirnames(-1)
if err != nil {
return err
}
dir.Close()

// Copy names to a channel for workers to consume. Close the
// channel so that workers stop when all work is complete.

namesChan := make(chan string, len(names))
for _, name := range names {
namesChan <- name
}
close(namesChan)

// Create a maximum of 8 workers

bar.Abort(true)
workers := 8
if len(names) < workers {
workers = len(names)
}

errChan := make(chan error, 1)
resChan := make(chan *error, len(names))

// Run workers

for i := 0; i < workers; i++ {
go func() {
// Consume work from namesChan. Loop will end when no more work.
for name := range namesChan {
if err != nil {
select {
case errChan <- err:
// will break parent goroutine out of loop
default:
// don't care, first error wins
}
return
}
err = bucket.PutObjectFromFile(projectName+"-"+bundleID, filepath.Join(dirPath, name))

if err != nil {
select {
case errChan <- err:
// will break parent goroutine out of loop
default:
// don't care, first error wins
}
return
}
resChan <- &err
}
}()
}

// Collect results from workers

for i := 0; i < len(names); i++ {
select {
case res := <-resChan:
fmt.Println(res)
case err := <-errChan:
return err
}
}
log.S.Suffix(" deploying ")
log.BUnpause()
return nil

}

type OssProgressListener struct {
Expand Down

0 comments on commit 2924f6b

Please sign in to comment.