aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/admin/deploy/fetch.go
blob: 47eeb8631c6e3636cdced9f4becdac569d1ef614 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// vespa-deploy command
// Author: arnej

package deploy

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/vespa-engine/vespa/client/go/internal/util"
)

// main entry point for vespa-deploy fetch

func RunFetch(opts *Options, args []string) error {
	dirName := "."
	if len(args) > 0 {
		dirName = args[0]
	}
	src := makeConfigsourceUrl(opts)
	url := src +
		"/application/v2" +
		"/tenant/" + opts.Tenant +
		"/application/" + opts.Application +
		"/environment/" + opts.Environment +
		"/region/" + opts.Region +
		"/instance/" + opts.Instance +
		"/content/"

	url = addUrlPropertyFromOption(url, strconv.Itoa(opts.Timeout), "timeout")
	fmt.Printf("Writing active application to %s\n(using %s)\n", dirName, urlWithoutQuery(url))
	var out bytes.Buffer
	err := curlGet(url, &out)
	if err != nil {
		return err
	}
	fetchDirectory(dirName, &out)
	return err
}

func fetchDirectory(name string, input *bytes.Buffer) {
	err := os.MkdirAll(name, 0755)
	if err != nil {
		fmt.Printf("ERROR: %v\n", err)
		return
	}
	codec := json.NewDecoder(input)
	var result []string
	err = codec.Decode(&result)
	if err != nil {
		fmt.Printf("ERROR: %v [%v] <<< %s\n", result, err, input.String())
		return
	}
	for _, entry := range result {
		fmt.Println("GET", entry)
		fn := name + "/" + getPartAfterSlash(entry)
		if strings.HasSuffix(entry, "/") {
			var out bytes.Buffer
			err := curlGet(entry, &out)
			if err != nil {
				fmt.Println("FAILED", err)
				return
			}
			fetchDirectory(fn, &out)
		} else {
			f, err := os.Create(fn)
			if err != nil {
				fmt.Println("FAILED", err)
				return
			}
			defer f.Close()
			err = curlGet(entry, f)
			if err != nil {
				fmt.Println("FAILED", err)
				return
			}
		}
	}
}

func getPartAfterSlash(path string) string {
	parts := strings.Split(path, "/")
	idx := len(parts) - 1
	if idx > 1 && parts[idx] == "" {
		return parts[idx-1]
	}
	if idx == 0 {
		util.JustExitMsg("cannot find part after slash: " + path)
	}
	return parts[idx]
}