-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
179 lines (157 loc) · 5.17 KB
/
common.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
174
175
176
177
178
179
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* This file is part of AMS SDK
* Copyright 2021 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the Lesser GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY
* QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the Lesser GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package packages
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/anbox-cloud/ams-sdk/internal/ams/shared"
errs "github.com/anbox-cloud/ams-sdk/internal/ams/shared/errors"
yaml "gopkg.in/yaml.v2"
)
const (
// MaxHookExecutionTimeout represents the maximum hook execution timeout
MaxHookExecutionTimeout = time.Minute * 15
)
// PackageType represents the file format for a pacakge
type PackageType int
const (
// PackageTypeUnknown represents an unknown addon or application package format
PackageTypeUnknown PackageType = iota - 1
// PackageTypeTarBZ2 represents an addon or application package as a tarball
PackageTypeTarBZ2
// PackageTypeZip represents an addon or application package as a zip archive
PackageTypeZip
)
// DetectPackageType is used to auto-determine the type of a package by looking
// at the magic bytes of a file
func DetectPackageType(filePath string) (PackageType, error) {
file, err := os.Open(filePath)
if err != nil {
return PackageTypeUnknown, err
}
defer file.Close()
buff := make([]byte, 512)
if _, err = file.Read(buff); err != nil {
return PackageTypeUnknown, err
}
mimeType := http.DetectContentType(buff)
switch mimeType {
case "application/zip":
return PackageTypeZip, nil
// TODO: Add the mimetype required to detect tarballs. This is currently not
// available in the standard functions in Go lib
default:
return PackageTypeUnknown, nil
}
}
// IsTarball detects if the given package is a valid tarball
func IsTarball(filePath string) bool {
return strings.HasSuffix(strings.ToLower(filePath), ".tar.bz2") ||
strings.HasSuffix(strings.ToLower(filePath), ".tbz2")
}
// IsZip detects if the given package is a valid zip archive
func IsZip(filePath string) bool {
return strings.HasSuffix(strings.ToLower(filePath), ".zip")
}
// ParseManifest parses the manifest structure from io reader
func ParseManifest(reader io.Reader, manifest interface{}) error {
byteBuf := new(bytes.Buffer)
if _, err := byteBuf.ReadFrom(reader); err != nil {
return err
}
return yaml.Unmarshal(byteBuf.Bytes(), manifest)
}
// CreateTempPackage creates a temporary package file with the given contents
func CreateTempPackage(sources []string, packageType PackageType) (string, error) {
srcDir, err := os.Getwd()
if err != nil {
return "", err
}
outputDir, err := ioutil.TempDir("", "app")
if err != nil {
return "", err
}
// The shared.DirCopy function that is used by this function to create a
// package tarball does a file copy recursively. Hence we just need to keep
// the top-level files and dirs for a tarball creation. Keeping the children
// of one directory in the sources fails the function due to file existence.
// it also results in performance degradation.
topLevelFiles := map[string]bool{}
for _, file := range sources {
parts := strings.Split(file, "/")
topLevelFiles[parts[0]] = true
}
// Copy all files to the output dir
for file := range topLevelFiles {
fi, err := os.Stat(file)
if err != nil {
return "", err
}
fileName := fi.Name()
srcFile := file
if !shared.PathExists(srcFile) {
srcFile = filepath.Join(srcDir, fileName)
}
destFile := filepath.Join(outputDir, fileName)
if fi.IsDir() {
if err := shared.DirCopy(srcFile, destFile); err != nil {
return "", fmt.Errorf("Failed to copy data %s to %s: %v",
srcFile, destFile, err)
}
} else {
if err := shared.FileCopy(srcFile, destFile); err != nil {
return "", fmt.Errorf("Failed to copy data %s to %s: %v",
srcFile, destFile, err)
}
}
}
var packagePath string
switch packageType {
case PackageTypeTarBZ2:
packagePath = filepath.Join(outputDir, "application.tar.bz2")
if err := shared.CreateBzip2Tarball(srcDir, packagePath, sources); err != nil {
return "", fmt.Errorf("Failed to create tarball file")
}
case PackageTypeZip:
fallthrough
default:
packagePath = filepath.Join(outputDir, "application.zip")
if err := shared.CreateZip(srcDir, packagePath, sources); err != nil {
return "", fmt.Errorf("Failed to create zip file")
}
}
return packagePath, nil
}
// ValidateHookTimeout validates the given timeout for hooks
func ValidateHookTimeout(timeout string) error {
d, err := time.ParseDuration(timeout)
if err != nil || d < 0 {
return errs.NewInvalidArgument("timeout")
}
if d > MaxHookExecutionTimeout {
return fmt.Errorf("timeout exceeds the allowed maximum(%d mins)", MaxHookExecutionTimeout/time.Minute)
}
return nil
}