-
Notifications
You must be signed in to change notification settings - Fork 21
/
observiq_downloadable_file_manager.go
173 lines (144 loc) · 5.32 KB
/
observiq_downloadable_file_manager.go
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
// Copyright observIQ, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package observiq
import (
"crypto/sha256"
"crypto/subtle"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
archiver "github.com/mholt/archiver/v3"
"github.com/observiq/bindplane-agent/opamp"
"github.com/open-telemetry/opamp-go/protobufs"
"go.uber.org/zap"
)
const extractFolder = "latest"
// Ensure interface is satisfied
var _ opamp.DownloadableFileManager = (*DownloadableFileManager)(nil)
// DownloadableFileManager handles DownloadableFile's from a PackagesAvailable message
type DownloadableFileManager struct {
tmpPath string
logger *zap.Logger
}
// newDownloadableFileManager creates a new OpAmp DownloadableFileManager
func newDownloadableFileManager(logger *zap.Logger, tmpPath string) *DownloadableFileManager {
return &DownloadableFileManager{
tmpPath: filepath.Clean(tmpPath),
logger: logger,
}
}
// FetchAndExtractArchive fetches the archive at the specified URL, placing it into dir.
// It then checks to see if it matches the "expectedHash", a hex-encoded string representing the expected sha256 sum of the file.
// If it matches, the archive is extracted into the $dir/latest directory.
// If the archive cannot be extracted, downloaded, or verified, then an error is returned.
func (m DownloadableFileManager) FetchAndExtractArchive(file *protobufs.DownloadableFile) error {
archiveFilePath, err := getOutputFilePath(m.tmpPath, file.GetDownloadUrl())
if err != nil {
return fmt.Errorf("failed to determine archive download path: %w", err)
}
if err := m.downloadFile(file.GetDownloadUrl(), archiveFilePath); err != nil {
return fmt.Errorf("failed to download file: %w", err)
}
extractPath := filepath.Join(m.tmpPath, extractFolder)
if err := m.verifyContentHash(archiveFilePath, file.GetContentHash()); err != nil {
return fmt.Errorf("content hash could not be verified: %w", err)
}
// Clean the "latest" dir before extraction
if err := os.RemoveAll(extractPath); err != nil {
return fmt.Errorf("error cleaning archive extraction target path: %w", err)
}
if err := archiver.Unarchive(archiveFilePath, extractPath); err != nil {
return fmt.Errorf("failed to extract file: %w", err)
}
return nil
}
// Downloads the file into the outPath, truncating the file if it already exists
func (m DownloadableFileManager) downloadFile(downloadURL string, outPath string) error {
//#nosec G107 HTTP request must be dynamic based on input
resp, err := http.Get(downloadURL)
if err != nil {
return fmt.Errorf("could not GET url: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
m.logger.Warn("Failed to close response body while downloading file", zap.String("URL", downloadURL), zap.Error(err))
}
}()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("got non-200 status code (%d)", resp.StatusCode)
}
outPathClean := filepath.Clean(outPath)
f, err := os.OpenFile(outPathClean, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer func() {
err := f.Close()
if err != nil {
m.logger.Warn("Failed to close file", zap.Error(err))
}
}()
if _, err = io.Copy(f, resp.Body); err != nil {
return fmt.Errorf("failed to copy request body to file: %w", err)
}
return nil
}
// getOutputFilePath gets the output path relative to the base dir for the archive from the given URL.
func getOutputFilePath(basePath, downloadURL string) (string, error) {
err := os.MkdirAll(basePath, 0700)
if err != nil {
return "", fmt.Errorf("problem with base url: %w", err)
}
url, err := url.Parse(downloadURL)
if err != nil {
return "", fmt.Errorf("cannot parse url: %w", err)
}
if url.Path == "" {
return "", errors.New("input url must have path")
}
return filepath.Join(basePath, filepath.Base(url.Path)), nil
}
func (m DownloadableFileManager) verifyContentHash(contentPath string, expectedFileHash []byte) error {
// Hash file at contentPath using sha256
fileHash := sha256.New()
contentPathClean := filepath.Clean(contentPath)
f, err := os.Open(contentPathClean)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer func() {
err := f.Close()
if err != nil {
m.logger.Warn("Failed to close file", zap.Error(err))
}
}()
if _, err = io.Copy(fileHash, f); err != nil {
return fmt.Errorf("failed to calculate file hash: %w", err)
}
actualContentHash := fileHash.Sum(nil)
if subtle.ConstantTimeCompare(expectedFileHash, actualContentHash) == 0 {
return errors.New("file hash did not match expected")
}
return nil
}
// CleanupArtifacts removes previous installation artifacts by removing the temporary directory.
func (m DownloadableFileManager) CleanupArtifacts() {
if err := os.RemoveAll(m.tmpPath); err != nil {
m.logger.Error("Failed to remove temporary directory", zap.Error(err))
}
}