aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/cmd/deploy.go
blob: bfd3837cd5a1ee0b2851f2ec7844a586780dbd28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// vespa deploy command
// Author: bratseth

package cmd

import (
    "archive/zip"
    "errors"
    "github.com/spf13/cobra"
    "github.com/vespa-engine/vespa/util"
    "io"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
    "path/filepath"
    "strings"
    "time"
)

func init() {
    rootCmd.AddCommand(deployCmd)
    deployCmd.AddCommand(deployPrepareCmd)
    deployCmd.AddCommand(deployActivateCmd)
}

var deployCmd = &cobra.Command{
    Use:   "deploy",
    Short: "Deploys an application package",
    Long:  `TODO: Use prepare or deploy activate`,
    Run: func(cmd *cobra.Command, args []string) {
        util.Error("Use either deploy prepare or deploy activate")
    },
}

var deployPrepareCmd = &cobra.Command{
    Use:   "prepare",
    Short: "Prepares an application for activation",
    Long:  `TODO:  prepare application-package-dir OR application.zip`,
    Args: func(cmd *cobra.Command, args []string) error {
        if len(args) > 1 {
          return errors.New("Expected an application package as the only argument")
        }
        return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        if len(args) == 0 {
            deploy(true, "src/main/application")
        } else {
            deploy(true, args[0])
        }
    },
}

var deployActivateCmd = &cobra.Command{
    Use:   "activate",
    Short: "Activates an application package. If no package argument, the previously prepared package is activated.",
    Long:  `TODO: activate  [application-package-dir OR application.zip]`,
    Args: func(cmd *cobra.Command, args []string) error {
        if len(args) > 1 {
          return errors.New("Expected an application package as the only argument")
        }
        return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        if len(args) == 0 {
            deploy(false, "")
        } else {
            deploy(false, args[0])
        }
    },
}

func deploy(prepare bool, application string) {
    // TODO: Support no application (activate)
    // TODO: Support application home as argument instead of src/main and
    //       - if target exists, use target/application.zip
    //       - else if src/main/application exists, use that
    //       - else if current dir has services.xml use that
    if filepath.Ext(application) != ".zip" {
        tempZip, error := ioutil.TempFile("", "application.zip")
        if error != nil {
            util.Error("Could not create a temporary zip file for the application package")
            util.Detail(error.Error())
            return
        }

        error = zipDir(application, tempZip.Name())
        if (error != nil) {
            util.Error(error.Error())
            return
        }
        defer os.Remove(tempZip.Name())
        application = tempZip.Name()
    }

    zipFileReader, zipFileError := os.Open(application)
    if zipFileError != nil {
        util.Error("Could not open application package at " + application)
        util.Detail(zipFileError.Error())
        return
    }

    var deployUrl *url.URL
    if prepare {
        deployUrl, _ = url.Parse(getTarget(deployContext).deploy + "/application/v2/tenant/default/prepare")
    } else if application == "" {
        deployUrl, _ = url.Parse(getTarget(deployContext).deploy + "/application/v2/tenant/default/activate")
    } else {
        deployUrl, _ = url.Parse(getTarget(deployContext).deploy + "/application/v2/tenant/default/prepareandactivate")
    }

    header := http.Header{}
    header.Add("Content-Type", "application/zip")
    request := &http.Request{
        URL: deployUrl,
        Method: "POST",
        Header: header,
        Body: ioutil.NopCloser(zipFileReader),
    }
    serviceDescription := "Deploy service"
    response := util.HttpDo(request, time.Minute * 10, serviceDescription)
    if (response == nil) {
        return
    }

    defer response.Body.Close()
    if response.StatusCode == 200 {
        util.Success("Success")
    } else if response.StatusCode / 100 == 4 {
        util.Error("Invalid application package", "(" + response.Status + "):")
        util.PrintReader(response.Body)
    } else {
        util.Error("Error from", strings.ToLower(serviceDescription), "at", request.URL.Host, "(" + response.Status + "):")
        util.PrintReader(response.Body)
    }
}

func zipDir(dir string, destination string) error {
    if filepath.IsAbs(dir) {
        message := "Path must be relative, but '" + dir + "'"
        return errors.New(message)
    }
    if ! util.PathExists(dir) {
        message := "'" + dir + "' should be an application package zip or dir, but does not exist"
        return errors.New(message)
    }
    if ! util.IsDirectory(dir) {
        message := "'" + dir + "' should be an application package dir, but is a (non-zip) file"
        return errors.New(message)
    }

    file, err := os.Create(destination)
    if err != nil {
        message := "Could not create a temporary zip file for the application package: " + err.Error()
        return errors.New(message)
    }
    defer file.Close()

    w := zip.NewWriter(file)
    defer w.Close()

    walker := func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if info.IsDir() {
            return nil
        }
        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()

        zippath := strings.TrimPrefix(path, dir)
        zipfile, err := w.Create(zippath)
        if err != nil {
            return err
        }

        _, err = io.Copy(zipfile, file)
        if err != nil {
            return err
        }
        return nil
    }
    return filepath.Walk(dir, walker)
}