text
stringlengths 76
10.6k
|
---|
// SubQuery allows you to run another query in the same transaction for each
// record in a parent query
func (r *RecordAccess) SubQuery(result interface{}, query *Query) error {
return findQuery(r.tx, result, query)
} |
// SubAggregateQuery allows you to run another aggregate query in the same transaction for each
// record in a parent query
func (r *RecordAccess) SubAggregateQuery(query *Query, groupBy...string) ([]*AggregateResult, error) {
return aggregateQuery(r.tx, r.record, query, groupBy...)
} |
// MatchFunc will test if a field matches the passed in function
func (c *Criterion) MatchFunc(match MatchFunc) *Query {
if c.query.currentField == Key {
panic("Match func cannot be used against Keys, as the Key type is unknown at runtime, and there is no value compare against")
}
return c.op(fn, match)
} |
// runQuerySort runs the query without sort, skip, or limit, then applies them to the entire result set
func runQuerySort(tx *bolt.Tx, dataType interface{}, query *Query, action func(r *record) error) error {
// Validate sort fields
for _, field := range query.sort {
fields := strings.Split(field, ".")
current := query.dataType
for i := range fields {
var structField reflect.StructField
found := false
if current.Kind() == reflect.Ptr {
structField, found = current.Elem().FieldByName(fields[i])
} else {
structField, found = current.FieldByName(fields[i])
}
if!found {
return fmt.Errorf("The field %s does not exist in the type %s", field, query.dataType)
}
current = structField.Type
}
}
// Run query without sort, skip or limit
// apply sort, skip and limit to entire dataset
qCopy := *query
qCopy.sort = nil
qCopy.limit = 0
qCopy.skip = 0
var records []*record
err := runQuery(tx, dataType, &qCopy, nil, 0,
func(r *record) error {
records = append(records, r)
return nil
})
if err!= nil {
return err
}
sort.Slice(records, func(i, j int) bool {
for _, field := range query.sort {
val, err := fieldValue(records[i].value.Elem(), field)
if err!= nil {
panic(err.Error()) // shouldn't happen due to field check above
}
value := val.Interface()
val, err = fieldValue(records[j].value.Elem(), field)
if err!= nil {
panic(err.Error()) // shouldn't happen due to field check above
}
other := val.Interface()
if query.reverse {
value, other = other, value
}
cmp, cerr := compare(value, other)
if cerr!= nil {
// if for some reason there is an error on compare, fallback to a lexicographic compare
valS := fmt.Sprintf("%s", value)
otherS := fmt.Sprintf("%s", other)
if valS < otherS {
return true
} else if valS == otherS {
continue
}
return false
}
if cmp == -1 {
return true
} else if cmp == 0 {
continue
}
return false
}
return false
})
// apply skip and limit
limit := query.limit
skip := query.skip
if skip > len(records) {
records = records[0:0]
} else {
records = records[skip:]
}
if limit > 0 && limit <= len(records) {
records = records[:limit]
}
for i := range records {
err = action(records[i])
if err!= nil {
return err
}
}
return nil
} |
// Group returns the field grouped by in the query
func (a *AggregateResult) Group(result...interface{}) {
for i := range result {
resultVal := reflect.ValueOf(result[i])
if resultVal.Kind()!= reflect.Ptr {
panic("result argument must be an address")
}
if i >= len(a.group) {
panic(fmt.Sprintf("There is not %d elements in the grouping", i))
}
resultVal.Elem().Set(a.group[i])
}
} |
// Reduction is the collection of records that are part of the AggregateResult Group
func (a *AggregateResult) Reduction(result interface{}) {
resultVal := reflect.ValueOf(result)
if resultVal.Kind()!= reflect.Ptr || resultVal.Elem().Kind()!= reflect.Slice {
panic("result argument must be a slice address")
}
sliceVal := resultVal.Elem()
elType := sliceVal.Type().Elem()
for i := range a.reduction {
if elType.Kind() == reflect.Ptr {
sliceVal = reflect.Append(sliceVal, a.reduction[i])
} else {
sliceVal = reflect.Append(sliceVal, a.reduction[i].Elem())
}
}
resultVal.Elem().Set(sliceVal.Slice(0, sliceVal.Len()))
} |
// Sort sorts the aggregate reduction by the passed in field in ascending order
// Sort is called automatically by calls to Min / Max to get the min and max values
func (a *AggregateResult) Sort(field string) {
if!startsUpper(field) {
panic("The first letter of a field must be upper-case")
}
if a.sortby == field {
// already sorted
return
}
a.sortby = field
sort.Sort((*aggregateResultSort)(a))
} |
// Max Returns the maxiumum value of the Aggregate Grouping, uses the Comparer interface
func (a *AggregateResult) Max(field string, result interface{}) {
a.Sort(field)
resultVal := reflect.ValueOf(result)
if resultVal.Kind()!= reflect.Ptr {
panic("result argument must be an address")
}
if resultVal.IsNil() {
panic("result argument must not be nil")
}
resultVal.Elem().Set(a.reduction[len(a.reduction)-1].Elem())
} |
// Avg returns the average float value of the aggregate grouping
// panics if the field cannot be converted to an float64
func (a *AggregateResult) Avg(field string) float64 {
sum := a.Sum(field)
return sum / float64(len(a.reduction))
} |
// Sum returns the sum value of the aggregate grouping
// panics if the field cannot be converted to an float64
func (a *AggregateResult) Sum(field string) float64 {
var sum float64
for i := range a.reduction {
fVal := a.reduction[i].Elem().FieldByName(field)
if!fVal.IsValid() {
panic(fmt.Sprintf("The field %s does not exist in the type %s", field, a.reduction[i].Type()))
}
sum += tryFloat(fVal)
}
return sum
} |
// FindAggregate returns an aggregate grouping for the passed in query
// groupBy is optional
func (s *Store) FindAggregate(dataType interface{}, query *Query, groupBy...string) ([]*AggregateResult, error) {
var result []*AggregateResult
var err error
err = s.Bolt().View(func(tx *bolt.Tx) error {
result, err = s.TxFindAggregate(tx, dataType, query, groupBy...)
return err
})
if err!= nil {
return nil, err
}
return result, nil
} |
// TxFindAggregate is the same as FindAggregate, but you specify your own transaction
// groupBy is optional
func (s *Store) TxFindAggregate(tx *bolt.Tx, dataType interface{}, query *Query, groupBy...string) ([]*AggregateResult, error) {
return aggregateQuery(tx, dataType, query, groupBy...)
} |
// DefaultEncode is the default encoding func for bolthold (Gob)
func DefaultEncode(value interface{}) ([]byte, error) {
var buff bytes.Buffer
en := gob.NewEncoder(&buff)
err := en.Encode(value)
if err!= nil {
return nil, err
}
return buff.Bytes(), nil
} |
// DefaultDecode is the default decoding func for bolthold (Gob)
func DefaultDecode(data []byte, value interface{}) error {
var buff bytes.Buffer
de := gob.NewDecoder(&buff)
_, err := buff.Write(data)
if err!= nil {
return err
}
return de.Decode(value)
} |
// GetConf aggregates all the JSON and enviornment variable values
// and puts them into the passed interface.
func GetConf(filename string, configuration interface{}) (err error) {
configValue := reflect.ValueOf(configuration)
if typ := configValue.Type(); typ.Kind()!= reflect.Ptr || typ.Elem().Kind()!= reflect.Struct {
return fmt.Errorf("configuration should be a pointer to a struct type")
}
err = getFromYAML(filename, configuration)
if err == nil {
getFromEnvVariables(configuration)
}
return
} |
// NewSemVer generates a new SemVer from a string. If the given string does
// not represent a valid SemVer, nil and an error are returned.
func NewSemVer(s string) (*SemVer, error) {
nsv, err := semver.NewVersion(s)
if err!= nil {
return nil, ErrBadSemVer
}
v := SemVer(*nsv)
if v.Empty() {
return nil, ErrNoZeroSemVer
}
return &v, nil
} |
// UnmarshalJSON implements the json.Unmarshaler interface
func (sv *SemVer) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err!= nil {
return err
}
v, err := NewSemVer(s)
if err!= nil {
return err
}
*sv = *v
return nil
} |
// MarshalJSON implements the json.Marshaler interface
func (sv SemVer) MarshalJSON() ([]byte, error) {
if sv.Empty() {
return nil, ErrNoZeroSemVer
}
return json.Marshal(sv.String())
} |
// parseSeccompArgs parses seccomp mode and set CLI flags, preparing an
// appropriate seccomp isolator.
func parseSeccompArgs(patchSeccompMode string, patchSeccompSet string) (*types.Isolator, error) {
// Parse mode flag and additional keyed arguments.
var errno, mode string
args := strings.Split(patchSeccompMode, ",")
for _, a := range args {
kv := strings.Split(a, "=")
switch len(kv) {
case 1:
// mode, either "remove" or "retain"
mode = kv[0]
case 2:
// k=v argument, only "errno" allowed for now
if kv[0] == "errno" {
errno = kv[1]
} else {
return nil, fmt.Errorf("invalid seccomp-mode optional argument: %s", a)
}
default:
return nil, fmt.Errorf("cannot parse seccomp-mode argument: %s", a)
}
}
// Instantiate an Isolator with the content specified by the --seccomp-set parameter.
var err error
var seccomp types.AsIsolator
switch mode {
case "remove":
seccomp, err = types.NewLinuxSeccompRemoveSet(errno, strings.Split(patchSeccompSet, ",")...)
case "retain":
seccomp, err = types.NewLinuxSeccompRetainSet(errno, strings.Split(patchSeccompSet, ",")...)
default:
err = fmt.Errorf("unknown seccomp mode %s", mode)
}
if err!= nil {
return nil, fmt.Errorf("cannot parse seccomp isolator: %s", err)
}
seccompIsolator, err := seccomp.AsIsolator()
if err!= nil {
return nil, err
}
return seccompIsolator, nil
} |
// extractManifest iterates over the tar reader and locate the manifest. Once
// located, the manifest can be printed, replaced or patched.
func extractManifest(tr *tar.Reader, tw *tar.Writer, printManifest bool, newManifest []byte) error {
Tar:
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
break Tar
case nil:
if filepath.Clean(hdr.Name) == aci.ManifestFile {
var new_bytes []byte
bytes, err := ioutil.ReadAll(tr)
if err!= nil {
return err
}
if printManifest &&!catPrettyPrint {
fmt.Println(string(bytes))
}
im := &schema.ImageManifest{}
err = im.UnmarshalJSON(bytes)
if err!= nil {
return err
}
if printManifest && catPrettyPrint {
output, err := json.MarshalIndent(im, "", " ")
if err!= nil {
return err
}
fmt.Println(string(output))
}
if tw == nil {
return nil
}
if len(newManifest) == 0 {
err = patchManifest(im)
if err!= nil {
return err
}
new_bytes, err = im.MarshalJSON()
if err!= nil {
return err
}
} else {
new_bytes = newManifest
}
hdr.Size = int64(len(new_bytes))
err = tw.WriteHeader(hdr)
if err!= nil {
return err
}
_, err = tw.Write(new_bytes)
if err!= nil {
return err
}
} else if tw!= nil {
err := tw.WriteHeader(hdr)
if err!= nil {
return err
}
_, err = io.Copy(tw, tr)
if err!= nil {
return err
}
}
default:
return fmt.Errorf("error reading tarball: %v", err)
}
}
return nil
} |
// main outputs diagnostic information to stderr and exits 1 if validation fails
func main() {
if len(os.Args)!= 2 {
stderr("usage: %s [main|sidekick|preStart|postStop]", os.Args[0])
os.Exit(64)
}
mode := os.Args[1]
var res results
switch strings.ToLower(mode) {
case "main":
res = validateMain()
case "sidekick":
res = validateSidekick()
case "prestart":
res = validatePrestart()
case "poststop":
res = validatePoststop()
default:
stderr("unrecognized mode: %s", mode)
os.Exit(64)
}
if len(res) == 0 {
fmt.Printf("%s OK\n", mode)
os.Exit(0)
}
fmt.Printf("%s FAIL\n", mode)
for _, err := range res {
fmt.Fprintln(os.Stderr, "==>", err)
}
os.Exit(1)
} |
// ValidatePath ensures that the PATH has been set up correctly within the
// environment in which this process is being run
func ValidatePath(wp string) results {
r := results{}
gp := os.Getenv("PATH")
if wp!= gp {
r = append(r, fmt.Errorf("PATH not set appropriately (need %q, got %q)", wp, gp))
}
return r
} |
// ValidateWorkingDirectory ensures that the process working directory is set
// to the desired path.
func ValidateWorkingDirectory(wwd string) (r results) {
gwd, err := os.Getwd()
if err!= nil {
r = append(r, fmt.Errorf("error getting working directory: %v", err))
return
}
if gwd!= wwd {
r = append(r, fmt.Errorf("working directory not set appropriately (need %q, got %v)", wwd, gwd))
}
return
} |
// ValidateEnvironment ensures that the given environment contains the
// necessary/expected environment variables.
func ValidateEnvironment(wenv map[string]string) (r results) {
for wkey, wval := range wenv {
gval := os.Getenv(wkey)
if gval!= wval {
err := fmt.Errorf("environment variable %q not set appropriately (need %q, got %q)", wkey, wval, gval)
r = append(r, err)
}
}
return
} |
// ValidateAppNameEnv ensures that the environment variable specifying the
// entrypoint of this process is set correctly.
func ValidateAppNameEnv(want string) (r results) {
if got := os.Getenv(appNameEnv); got!= want {
r = append(r, fmt.Errorf("%s not set appropriately (need %q, got %q)", appNameEnv, want, got))
}
return
} |
// ValidateMountpoints ensures that the given mount points are present in the
// environment in which this process is running
func ValidateMountpoints(wmp map[string]types.MountPoint) results {
r := results{}
// TODO(jonboulle): verify actual source
for _, mp := range wmp {
if err := checkMount(mp.Path, mp.ReadOnly); err!= nil {
r = append(r, err)
}
}
return r
} |
// parseMountinfo parses a Reader representing a /proc/PID/mountinfo file and
// returns whether dir is mounted and if so, whether it is read-only or not
func parseMountinfo(mountinfo io.Reader, dir string) (isMounted bool, readOnly bool, err error) {
sc := bufio.NewScanner(mountinfo)
for sc.Scan() {
var (
mountID int
parentID int
majorMinor string
root string
mountPoint string
mountOptions string
)
_, err := fmt.Sscanf(sc.Text(), "%d %d %s %s %s %s",
&mountID, &parentID, &majorMinor, &root, &mountPoint, &mountOptions)
if err!= nil {
return false, false, err
}
if mountPoint == dir {
isMounted = true
optionsParts := strings.Split(mountOptions, ",")
for _, o := range optionsParts {
switch o {
case "ro":
readOnly = true
case "rw":
readOnly = false
}
}
}
}
return
} |
// assertNotExistsAndCreate asserts that a file at the given path does not
// exist, and then proceeds to create (touch) the file. It returns any errors
// encountered at either of these steps.
func assertNotExistsAndCreate(p string) []error {
var errs []error
errs = append(errs, assertNotExists(p)...)
if err := touchFile(p); err!= nil {
errs = append(errs, fmt.Errorf("error touching file %q: %v", p, err))
}
return errs
} |
// assertNotExists asserts that a file at the given path does not exist. A
// non-empty list of errors is returned if the file exists or any error is
// encountered while checking.
func assertNotExists(p string) []error {
var errs []error
e, err := fileExists(p)
if err!= nil {
errs = append(errs, fmt.Errorf("error checking %q exists: %v", p, err))
}
if e {
errs = append(errs, fmt.Errorf("file %q exists unexpectedly", p))
}
return errs
} |
// touchFile creates an empty file, returning any error encountered
func touchFile(p string) error {
_, err := os.Create(p)
return err
} |
// waitForFile waits for the file at the given path to appear
func waitForFile(p string, to time.Duration) []error {
done := time.After(to)
for {
select {
case <-done:
return []error{
fmt.Errorf("timed out waiting for %s", p),
}
case <-time.After(1):
if ok, _ := fileExists(p); ok {
return nil
}
}
}
} |
// NewAppFromString takes a command line app parameter and returns a map of labels.
//
// Example app parameters:
// example.com/reduce-worker:1.0.0
// example.com/reduce-worker,channel=alpha,label=value
// example.com/reduce-worker:1.0.0,label=value
//
// As can be seen in above examples - colon, comma and equal sign have
// special meaning. If any of them has to be a part of a label's value
// then consider writing your own string to App parser.
func NewAppFromString(app string) (*App, error) {
var (
name string
labels map[types.ACIdentifier]string
)
preparedApp, err := prepareAppString(app)
if err!= nil {
return nil, err
}
v, err := url.ParseQuery(preparedApp)
if err!= nil {
return nil, err
}
labels = make(map[types.ACIdentifier]string, 0)
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
if key == "name" {
name = val[0]
continue
}
labelName, err := types.NewACIdentifier(key)
if err!= nil {
return nil, err
}
labels[*labelName] = val[0]
}
a, err := NewApp(name, labels)
if err!= nil {
return nil, err
}
return a, nil
} |
// String returns the URL-like image name
func (a *App) String() string {
img := a.Name.String()
for n, v := range a.Labels {
img += fmt.Sprintf(",%s=%s", n, v)
}
return img
} |
// GetRenderedACIWithImageID, given an imageID, starts with the matching image
// available in the store, creates the dependencies list and returns the
// RenderedACI list.
func GetRenderedACIWithImageID(imageID types.Hash, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromImageID(imageID, ap)
if err!= nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} |
// GetRenderedACI, given an image app name and optional labels, starts with the
// best matching image available in the store, creates the dependencies list
// and returns the RenderedACI list.
func GetRenderedACI(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromNameLabels(name, labels, ap)
if err!= nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} |
// GetRenderedACIFromList returns the RenderedACI list. All file outside rootfs
// are excluded (at the moment only "manifest").
func GetRenderedACIFromList(imgs Images, ap ACIProvider) (RenderedACI, error) {
if len(imgs) == 0 {
return nil, fmt.Errorf("image list empty")
}
allFiles := make(map[string]byte)
renderedACI := RenderedACI{}
first := true
for i, img := range imgs {
pwlm := getUpperPWLM(imgs, i)
ra, err := getACIFiles(img, ap, allFiles, pwlm)
if err!= nil {
return nil, err
}
// Use the manifest from the upper ACI
if first {
ra.FileMap["manifest"] = struct{}{}
first = false
}
renderedACI = append(renderedACI, ra)
}
return renderedACI, nil
} |
// getUpperPWLM returns the pwl at the lower level for the branch where
// img[pos] lives.
func getUpperPWLM(imgs Images, pos int) map[string]struct{} {
var pwlm map[string]struct{}
curlevel := imgs[pos].Level
// Start from our position and go back ignoring the other leafs.
for i := pos; i >= 0; i-- {
img := imgs[i]
if img.Level < curlevel && len(img.Im.PathWhitelist) > 0 {
pwlm = pwlToMap(img.Im.PathWhitelist)
}
curlevel = img.Level
}
return pwlm
} |
// getACIFiles returns the ACIFiles struct for the given image. All files
// outside rootfs are excluded (at the moment only "manifest").
func getACIFiles(img Image, ap ACIProvider, allFiles map[string]byte, pwlm map[string]struct{}) (*ACIFiles, error) {
rs, err := ap.ReadStream(img.Key)
if err!= nil {
return nil, err
}
defer rs.Close()
hash := sha512.New()
r := io.TeeReader(rs, hash)
thispwlm := pwlToMap(img.Im.PathWhitelist)
ra := &ACIFiles{FileMap: make(map[string]struct{})}
if err = Walk(tar.NewReader(r), func(hdr *tar.Header) error {
name := hdr.Name
cleanName := filepath.Clean(name)
// Add the rootfs directory.
if cleanName == "rootfs" && hdr.Typeflag == tar.TypeDir {
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}
// Ignore files outside /rootfs/ (at the moment only "manifest").
if!strings.HasPrefix(cleanName, "rootfs/") {
return nil
}
// Is the file in our PathWhiteList?
// If the file is a directory continue also if not in PathWhiteList
if hdr.Typeflag!= tar.TypeDir {
if len(img.Im.PathWhitelist) > 0 {
if _, ok := thispwlm[cleanName];!ok {
return nil
}
}
}
// Is the file in the lower level PathWhiteList of this img branch?
if pwlm!= nil {
if _, ok := pwlm[cleanName];!ok {
return nil
}
}
// Is the file already provided by a previous image?
if _, ok := allFiles[cleanName]; ok {
return nil
}
// Check that the parent dirs are also of type dir in the upper
// images
parentDir := filepath.Dir(cleanName)
for parentDir!= "." && parentDir!= "/" {
if ft, ok := allFiles[parentDir]; ok && ft!= tar.TypeDir {
return nil
}
parentDir = filepath.Dir(parentDir)
}
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}); err!= nil {
return nil, err
}
// Tar does not necessarily read the complete file, so ensure we read the entirety into the hash
if _, err := io.Copy(ioutil.Discard, r); err!= nil {
return nil, fmt.Errorf("error reading ACI: %v", err)
}
if g := ap.HashToKey(hash); g!= img.Key {
return nil, fmt.Errorf("image hash does not match expected (%s!= %s)", g, img.Key)
}
ra.Key = img.Key
return ra, nil
} |
// pwlToMap converts a pathWhiteList slice to a map for faster search
// It will also prepend "rootfs/" to the provided paths and they will be
// relative to "/" so they can be easily compared with the tar.Header.Name
// If pwl length is 0, a nil map is returned
func pwlToMap(pwl []string) map[string]struct{} {
if len(pwl) == 0 {
return nil
}
m := make(map[string]struct{}, len(pwl))
for _, name := range pwl {
relpath := filepath.Join("rootfs", name)
m[relpath] = struct{}{}
}
return m
} |
// Retrieve the value of an annotation by the given name from Annotations, if
// it exists.
func (a Annotations) Get(name string) (val string, ok bool) {
for _, anno := range a {
if anno.Name.String() == name {
return anno.Value, true
}
}
return "", false
} |
// Set sets the value of an annotation by the given name, overwriting if one already exists.
func (a *Annotations) Set(name ACIdentifier, value string) {
for i, anno := range *a {
if anno.Name.Equals(name) {
(*a)[i] = Annotation{
Name: name,
Value: value,
}
return
}
}
anno := Annotation{
Name: name,
Value: value,
}
*a = append(*a, anno)
} |
// DiscoverWalk will make HTTPS requests to find discovery meta tags and
// optionally will use HTTP if insecure is set. hostHeaders specifies the
// header to apply depending on the host (e.g. authentication). Based on the
// response of the discoverFn it will continue to recurse up the tree. If port
// is 0, the default port will be used.
func DiscoverWalk(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint, discoverFn DiscoverWalkFunc) (dd *discoveryData, err error) {
parts := strings.Split(string(app.Name), "/")
for i := range parts {
end := len(parts) - i
pre := strings.Join(parts[:end], "/")
dd, err = doDiscover(pre, hostHeaders, app, insecure, port)
if derr := discoverFn(pre, dd, err); derr!= nil {
return dd, derr
}
}
return nil, fmt.Errorf("discovery failed")
} |
// DiscoverACIEndpoints will make HTTPS requests to find the ac-discovery meta
// tags and optionally will use HTTP if insecure is set. hostHeaders
// specifies the header to apply depending on the host (e.g. authentication).
// It will not give up until it has exhausted the path or found an image
// discovery. If port is 0, the default port will be used.
func DiscoverACIEndpoints(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint) (ACIEndpoints, []FailedAttempt, error) {
testFn := func(pre string, dd *discoveryData, err error) error {
if len(dd.ACIEndpoints)!= 0 {
return errEnough
}
return nil
}
attempts := []FailedAttempt{}
dd, err := DiscoverWalk(app, hostHeaders, insecure, port, walker(&attempts, testFn))
if err!= nil && err!= errEnough {
return nil, attempts, err
}
return dd.ACIEndpoints, attempts, nil
} |
// DetectFileType attempts to detect the type of file that the given reader
// represents by comparing it against known file signatures (magic numbers)
func DetectFileType(r io.Reader) (FileType, error) {
var b bytes.Buffer
n, err := io.CopyN(&b, r, readLen)
if err!= nil && err!= io.EOF {
return TypeUnknown, err
}
bs := b.Bytes()
switch {
case bytes.HasPrefix(bs, hdrGzip):
return TypeGzip, nil
case bytes.HasPrefix(bs, hdrBzip2):
return TypeBzip2, nil
case bytes.HasPrefix(bs, hdrXz):
return TypeXz, nil
case n > int64(tarEnd) && bytes.Equal(bs[tarOffset:tarEnd], sigTar):
return TypeTar, nil
case http.DetectContentType(bs) == textMime:
return TypeText, nil
default:
return TypeUnknown, nil
}
} |
// NewXzReader shells out to a command line xz executable (if
// available) to decompress the given io.Reader using the xz
// compression format and returns an *XzReader.
// It is the caller's responsibility to call Close on the XzReader when done.
func NewXzReader(r io.Reader) (*XzReader, error) {
rpipe, wpipe := io.Pipe()
ex, err := exec.LookPath("xz")
if err!= nil {
log.Fatalf("couldn't find xz executable: %v", err)
}
cmd := exec.Command(ex, "--decompress", "--stdout")
closech := make(chan error)
cmd.Stdin = r
cmd.Stdout = wpipe
go func() {
err := cmd.Run()
wpipe.CloseWithError(err)
closech <- err
}()
return &XzReader{rpipe, cmd, closech}, nil
} |
// ManifestFromImage extracts a new schema.ImageManifest from the given ACI image.
func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
var im schema.ImageManifest
tr, err := NewCompressedTarReader(rs)
if err!= nil {
return nil, err
}
defer tr.Close()
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
return nil, errors.New("missing manifest")
case nil:
if filepath.Clean(hdr.Name) == ManifestFile {
data, err := ioutil.ReadAll(tr)
if err!= nil {
return nil, err
}
if err := im.UnmarshalJSON(data); err!= nil {
return nil, err
}
return &im, nil
}
default:
return nil, fmt.Errorf("error extracting tarball: %v", err)
}
}
} |
// NewCompressedTarReader creates a new TarReadCloser reading from the
// given ACI image.
// It is the caller's responsibility to call Close on the TarReadCloser
// when done.
func NewCompressedTarReader(rs io.ReadSeeker) (*TarReadCloser, error) {
cr, err := NewCompressedReader(rs)
if err!= nil {
return nil, err
}
return &TarReadCloser{tar.NewReader(cr), cr}, nil
} |
// NewCompressedReader creates a new io.ReaderCloser from the given ACI image.
// It is the caller's responsibility to call Close on the Reader when done.
func NewCompressedReader(rs io.ReadSeeker) (io.ReadCloser, error) {
var (
dr io.ReadCloser
err error
)
_, err = rs.Seek(0, 0)
if err!= nil {
return nil, err
}
ftype, err := DetectFileType(rs)
if err!= nil {
return nil, err
}
_, err = rs.Seek(0, 0)
if err!= nil {
return nil, err
}
switch ftype {
case TypeGzip:
dr, err = gzip.NewReader(rs)
if err!= nil {
return nil, err
}
case TypeBzip2:
dr = ioutil.NopCloser(bzip2.NewReader(rs))
case TypeXz:
dr, err = NewXzReader(rs)
if err!= nil {
return nil, err
}
case TypeTar:
dr = ioutil.NopCloser(rs)
case TypeUnknown:
return nil, errors.New("error: unknown image filetype")
default:
return nil, errors.New("no type returned from DetectFileType?")
}
return dr, nil
} |
// powInt64 raises a to the bth power. Is not overflow aware.
func powInt64(a, b int64) int64 {
p := int64(1)
for b > 0 {
if b&1!= 0 {
p *= a
}
b >>= 1
a *= a
}
return p
} |
// PortFromString takes a command line port parameter and returns a port
//
// It is useful for actool patch-manifest --ports
//
// Example port parameters:
// health-check,protocol=udp,port=8000
// query,protocol=tcp,port=8080,count=1,socketActivated=true
func PortFromString(pt string) (*Port, error) {
var port Port
pt = "name=" + pt
ptQuery, err := common.MakeQueryString(pt)
if err!= nil {
return nil, err
}
v, err := url.ParseQuery(ptQuery)
if err!= nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err!= nil {
return nil, err
}
port.Name = *acn
case "protocol":
port.Protocol = val[0]
case "port":
p, err := strconv.ParseUint(val[0], 10, 16)
if err!= nil {
return nil, err
}
port.Port = uint(p)
case "count":
cnt, err := strconv.ParseUint(val[0], 10, 16)
if err!= nil {
return nil, err
}
port.Count = uint(cnt)
case "socketActivated":
sa, err := strconv.ParseBool(val[0])
if err!= nil {
return nil, err
}
port.SocketActivated = sa
default:
return nil, fmt.Errorf("unknown port parameter %q", key)
}
}
err = port.assertValid()
if err!= nil {
return nil, err
}
return &port, nil
} |
// MountPointFromString takes a command line mountpoint parameter and returns a mountpoint
//
// It is useful for actool patch-manifest --mounts
//
// Example mountpoint parameters:
// database,path=/tmp,readOnly=true
func MountPointFromString(mp string) (*MountPoint, error) {
var mount MountPoint
mp = "name=" + mp
mpQuery, err := common.MakeQueryString(mp)
if err!= nil {
return nil, err
}
v, err := url.ParseQuery(mpQuery)
if err!= nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err!= nil {
return nil, err
}
mount.Name = *acn
case "path":
mount.Path = val[0]
case "readOnly":
ro, err := strconv.ParseBool(val[0])
if err!= nil {
return nil, err
}
mount.ReadOnly = ro
default:
return nil, fmt.Errorf("unknown mountpoint parameter %q", key)
}
}
err = mount.assertValid()
if err!= nil {
return nil, err
}
return &mount, nil
} |
// assertValid checks that every single isolator is valid and that
// the whole set is well built
func (isolators Isolators) assertValid() error {
typesMap := make(map[ACIdentifier]bool)
for _, i := range isolators {
v := i.Value()
if v == nil {
return ErrInvalidIsolator
}
if err := v.AssertValid(); err!= nil {
return err
}
if _, ok := typesMap[i.Name]; ok {
if!v.multipleAllowed() {
return fmt.Errorf(`isolators set contains too many instances of type %s"`, i.Name)
}
}
for _, c := range v.Conflicts() {
if _, found := typesMap[c]; found {
return ErrIncompatibleIsolator
}
}
typesMap[i.Name] = true
}
return nil
} |
// GetByName returns the last isolator in the list by the given name.
func (is *Isolators) GetByName(name ACIdentifier) *Isolator {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
if i.Name == name {
return &i
}
}
return nil
} |
// ReplaceIsolatorsByName overrides matching isolator types with a new
// isolator, deleting them all and appending the new one instead
func (is *Isolators) ReplaceIsolatorsByName(newIs Isolator, oldNames []ACIdentifier) {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
for _, name := range oldNames {
if i.Name == name {
*is = append((*is)[:j], (*is)[j+1:]...)
}
}
}
*is = append((*is)[:], newIs)
return
} |
// Unrecognized returns a set of isolators that are not recognized.
// An isolator is not recognized if it has not had an associated
// constructor registered with AddIsolatorValueConstructor.
func (is *Isolators) Unrecognized() Isolators {
u := Isolators{}
for _, i := range *is {
if i.value == nil {
u = append(u, i)
}
}
return u
} |
// UnmarshalJSON populates this Isolator from a JSON-encoded representation. To
// unmarshal the Value of the Isolator, it will use the appropriate constructor
// as registered by AddIsolatorValueConstructor.
func (i *Isolator) UnmarshalJSON(b []byte) error {
var ii isolator
err := json.Unmarshal(b, &ii)
if err!= nil {
return err
}
var dst IsolatorValue
con, ok := isolatorMap[ii.Name]
if ok {
dst = con()
err = dst.UnmarshalJSON(*ii.ValueRaw)
if err!= nil {
return err
}
err = dst.AssertValid()
if err!= nil {
return err
}
}
i.value = dst
i.ValueRaw = ii.ValueRaw
i.Name = ii.Name
return nil
} |
// assertValid performs extra assertions on an ImageManifest to ensure that
// fields are set appropriately, etc. It is used exclusively when marshalling
// and unmarshalling an ImageManifest. Most field-specific validation is
// performed through the individual types being marshalled; assertValid()
// should only deal with higher-level validation.
func (im *ImageManifest) assertValid() error {
if im.ACKind!= ImageManifestKind {
return imKindError
}
if im.ACVersion.Empty() {
return errors.New(`acVersion must be set`)
}
if im.Name.Empty() {
return errors.New(`name must be set`)
}
return nil
} |
// IsValidOsArch checks if a OS-architecture combination is valid given a map
// of valid OS-architectures
func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error {
if os, ok := labels["os"]; ok {
if validArchs, ok := validOSArch[os];!ok {
// Not a whitelisted OS. TODO: how to warn rather than fail?
validOses := make([]string, 0, len(validOSArch))
for validOs := range validOSArch {
validOses = append(validOses, validOs)
}
sort.Strings(validOses)
return fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses)
} else {
// Whitelisted OS. We check arch here, as arch makes sense only
// when os is defined.
if arch, ok := labels["arch"]; ok {
found := false
for _, validArch := range validArchs {
if arch == validArch {
found = true
break
}
}
if!found {
return fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs)
}
}
}
}
return nil
} |
// Get retrieves the value of the label by the given name from Labels, if it exists
func (l Labels) Get(name string) (val string, ok bool) {
for _, lbl := range l {
if lbl.Name.String() == name {
return lbl.Value, true
}
}
return "", false
} |
// ToMap creates a map[ACIdentifier]string.
func (l Labels) ToMap() map[ACIdentifier]string {
labelsMap := make(map[ACIdentifier]string)
for _, lbl := range l {
labelsMap[lbl.Name] = lbl.Value
}
return labelsMap
} |
// LabelsFromMap creates Labels from a map[ACIdentifier]string
func LabelsFromMap(labelsMap map[ACIdentifier]string) (Labels, error) {
labels := Labels{}
for n, v := range labelsMap {
labels = append(labels, Label{Name: n, Value: v})
}
if err := labels.assertValid(); err!= nil {
return nil, err
}
sort.Sort(labelsSlice(labels))
return labels, nil
} |
// ToAppcOSArch translates a Golang arch tuple (OS, architecture, flavor) into
// an appc arch tuple (OS, architecture)
func ToAppcOSArch(goOs string, goArch string, goArchFlavor string) (appcOs string, appcArch string, e error) {
tabularAppcToGo := map[goArchTuple]appcArchTuple{
{"linux", "amd64", ""}: {"linux", "amd64"},
{"linux", "386", ""}: {"linux", "i386"},
{"linux", "arm64", ""}: {"linux", "aarch64"},
{"linux", "arm", ""}: {"linux", "armv6l"},
{"linux", "arm", "6"}: {"linux", "armv6l"},
{"linux", "arm", "7"}: {"linux", "armv7l"},
{"linux", "ppc64", ""}: {"linux", "ppc64"},
{"linux", "ppc64le", ""}: {"linux", "ppc64le"},
{"linux", "s390x", ""}: {"linux", "s390x"},
{"freebsd", "amd64", ""}: {"freebsd", "amd64"},
{"freebsd", "386", ""}: {"freebsd", "i386"},
{"freebsd", "arm", ""}: {"freebsd", "arm"},
{"freebsd", "arm", "5"}: {"freebsd", "arm"},
{"freebsd", "arm", "6"}: {"freebsd", "arm"},
{"freebsd", "arm", "7"}: {"freebsd", "arm"},
{"darwin", "amd64", ""}: {"darwin", "x86_64"},
{"darwin", "386", ""}: {"darwin", "i386"},
}
archTuple, ok := tabularAppcToGo[goArchTuple{goOs, goArch, goArchFlavor}]
if!ok {
return "", "", fmt.Errorf("unknown arch tuple: %q - %q - %q", goOs, goArch, goArchFlavor)
}
return archTuple.appcOs, archTuple.appcArch, nil
} |
// ToGoOSArch translates an appc arch tuple (OS, architecture) into
// a Golang arch tuple (OS, architecture, flavor)
func ToGoOSArch(appcOs string, appcArch string) (goOs string, goArch string, goArchFlavor string, e error) {
tabularGoToAppc := map[appcArchTuple]goArchTuple{
// {"linux", "aarch64_be"}: nil,
// {"linux", "armv7b"}: nil,
{"linux", "aarch64"}: {"linux", "arm64", ""},
{"linux", "amd64"}: {"linux", "amd64", ""},
{"linux", "armv6l"}: {"linux", "arm", "6"},
{"linux", "armv7l"}: {"linux", "arm", "7"},
{"linux", "i386"}: {"linux", "386", ""},
{"linux", "ppc64"}: {"linux", "ppc64", ""},
{"linux", "ppc64le"}: {"linux", "ppc64le", ""},
{"linux", "s390x"}: {"linux", "s390x", ""},
{"freebsd", "amd64"}: {"freebsd", "amd64", ""},
{"freebsd", "arm"}: {"freebsd", "arm", "6"},
{"freebsd", "386"}: {"freebsd", "i386", ""},
{"darwin", "amd64"}: {"darwin", "x86_64", ""},
{"darwin", "386"}: {"darwin", "i386", ""},
}
archTuple, ok := tabularGoToAppc[appcArchTuple{appcOs, appcArch}]
if!ok {
return "", "", "", fmt.Errorf("unknown arch tuple: %q - %q", appcOs, appcArch)
}
return archTuple.goOs, archTuple.goArch, archTuple.goArchFlavor, nil
} |
// assertValid performs extra assertions on an PodManifest to
// ensure that fields are set appropriately, etc. It is used exclusively when
// marshalling and unmarshalling an PodManifest. Most
// field-specific validation is performed through the individual types being
// marshalled; assertValid() should only deal with higher-level validation.
func (pm *PodManifest) assertValid() error {
if pm.ACKind!= PodManifestKind {
return pmKindError
}
// ensure volumes names are unique (unique key)
volNames := make(map[types.ACName]bool, len(pm.Volumes))
for _, vol := range pm.Volumes {
if volNames[vol.Name] {
return fmt.Errorf("duplicate volume name %q", vol.Name)
}
volNames[vol.Name] = true
}
return nil
} |
// Get retrieves an app by the specified name from the AppList; if there is
// no such app, nil is returned. The returned *RuntimeApp MUST be considered
// read-only.
func (al AppList) Get(name types.ACName) *RuntimeApp {
for _, a := range al {
if name.Equals(a.Name) {
aa := a
return &aa
}
}
return nil
} |
// Retrieve the value of an environment variable by the given name from
// Environment, if it exists.
func (e Environment) Get(name string) (value string, ok bool) {
for _, env := range e {
if env.Name == name {
return env.Value, true
}
}
return "", false
} |
// Set sets the value of an environment variable by the given name,
// overwriting if one already exists.
func (e *Environment) Set(name string, value string) {
for i, env := range *e {
if env.Name == name {
(*e)[i] = EnvironmentVariable{
Name: name,
Value: value,
}
return
}
}
env := EnvironmentVariable{
Name: name,
Value: value,
}
*e = append(*e, env)
} |
// NewUUID generates a new UUID from the given string. If the string does not
// represent a valid UUID, nil and an error are returned.
func NewUUID(s string) (*UUID, error) {
s = strings.Replace(s, "-", "", -1)
if len(s)!= 32 {
return nil, errors.New("bad UUID length!= 32")
}
dec, err := hex.DecodeString(s)
if err!= nil {
return nil, err
}
var u UUID
for i, b := range dec {
u[i] = b
}
return &u, nil
} |
// Set sets the ACIdentifier to the given value, if it is valid; if not,
// an error is returned.
func (n *ACIdentifier) Set(s string) error {
nn, err := NewACIdentifier(s)
if err == nil {
*n = *nn
}
return err
} |
// Equals checks whether a given ACIdentifier is equal to this one.
func (n ACIdentifier) Equals(o ACIdentifier) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} |
// NewACIdentifier generates a new ACIdentifier from a string. If the given string is
// not a valid ACIdentifier, nil and an error are returned.
func NewACIdentifier(s string) (*ACIdentifier, error) {
n := ACIdentifier(s)
if err := n.assertValid(); err!= nil {
return nil, err
}
return &n, nil
} |
// MustACIdentifier generates a new ACIdentifier from a string, If the given string is
// not a valid ACIdentifier, it panics.
func MustACIdentifier(s string) *ACIdentifier {
n, err := NewACIdentifier(s)
if err!= nil {
panic(err)
}
return n
} |
// UnmarshalJSON implements the json.Unmarshaler interface
func (n *ACIdentifier) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err!= nil {
return err
}
nn, err := NewACIdentifier(s)
if err!= nil {
return err
}
*n = *nn
return nil
} |
// SanitizeACIdentifier replaces every invalid ACIdentifier character in s with an underscore
// making it a legal ACIdentifier string. If the character is an upper case letter it
// replaces it with its lower case. It also removes illegal edge characters
// (hyphens, period, underscore, tilde and slash).
//
// This is a helper function and its algorithm is not part of the spec. It
// should not be called without the user explicitly asking for a suggestion.
func SanitizeACIdentifier(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACIdentifierChars.ReplaceAllString(s, "_")
s = invalidACIdentifierEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} |
// VolumeFromString takes a command line volume parameter and returns a volume
//
// Example volume parameters:
// database,kind=host,source=/tmp,readOnly=true,recursive=true
func VolumeFromString(vp string) (*Volume, error) {
vp = "name=" + vp
vpQuery, err := common.MakeQueryString(vp)
if err!= nil {
return nil, err
}
v, err := url.ParseQuery(vpQuery)
if err!= nil {
return nil, err
}
return VolumeFromParams(v)
} |
// maybeSetDefaults sets the correct default values for certain fields on a
// Volume if they are not already been set. These fields are not
// pre-populated on all Volumes as the Volume type is polymorphic.
func maybeSetDefaults(vol *Volume) {
if vol.Kind == "empty" {
if vol.Mode == nil {
m := emptyVolumeDefaultMode
vol.Mode = &m
}
if vol.UID == nil {
u := emptyVolumeDefaultUID
vol.UID = &u
}
if vol.GID == nil {
g := emptyVolumeDefaultGID
vol.GID = &g
}
}
} |
// Set sets the ACName to the given value, if it is valid; if not,
// an error is returned.
func (n *ACName) Set(s string) error {
nn, err := NewACName(s)
if err == nil {
*n = *nn
}
return err
} |
// Equals checks whether a given ACName is equal to this one.
func (n ACName) Equals(o ACName) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} |
// NewACName generates a new ACName from a string. If the given string is
// not a valid ACName, nil and an error are returned.
func NewACName(s string) (*ACName, error) {
n := ACName(s)
if err := n.assertValid(); err!= nil {
return nil, err
}
return &n, nil
} |
// MustACName generates a new ACName from a string, If the given string is
// not a valid ACName, it panics.
func MustACName(s string) *ACName {
n, err := NewACName(s)
if err!= nil {
panic(err)
}
return n
} |
// UnmarshalJSON implements the json.Unmarshaler interface
func (n *ACName) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err!= nil {
return err
}
nn, err := NewACName(s)
if err!= nil {
return err
}
*n = *nn
return nil
} |
// MarshalJSON implements the json.Marshaler interface
func (n ACName) MarshalJSON() ([]byte, error) {
if err := n.assertValid(); err!= nil {
return nil, err
}
return json.Marshal(n.String())
} |
// SanitizeACName replaces every invalid ACName character in s with a dash
// making it a legal ACName string. If the character is an upper case letter it
// replaces it with its lower case. It also removes illegal edge characters
// (hyphens).
//
// This is a helper function and its algorithm is not part of the spec. It
// should not be called without the user explicitly asking for a suggestion.
func SanitizeACName(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACNameChars.ReplaceAllString(s, "-")
s = invalidACNameEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} |
// ValidateLayout takes a directory and validates that the layout of the directory
// matches that expected by the Application Container Image format.
// If any errors are encountered during the validation, it will abort and
// return the first one.
func ValidateLayout(dir string) error {
fi, err := os.Stat(dir)
if err!= nil {
return fmt.Errorf("error accessing layout: %v", err)
}
if!fi.IsDir() {
return fmt.Errorf("given path %q is not a directory", dir)
}
var flist []string
var imOK, rfsOK bool
var im io.Reader
walkLayout := func(fpath string, fi os.FileInfo, err error) error {
rpath, err := filepath.Rel(dir, fpath)
if err!= nil {
return err
}
switch rpath {
case ".":
case ManifestFile:
im, err = os.Open(fpath)
if err!= nil {
return err
}
imOK = true
case RootfsDir:
if!fi.IsDir() {
return errors.New("rootfs is not a directory")
}
rfsOK = true
default:
flist = append(flist, rpath)
}
return nil
}
if err := filepath.Walk(dir, walkLayout); err!= nil {
return err
}
return validate(imOK, im, rfsOK, flist)
} |
// ValidateArchive takes a *tar.Reader and validates that the layout of the
// filesystem the reader encapsulates matches that expected by the
// Application Container Image format. If any errors are encountered during
// the validation, it will abort and return the first one.
func ValidateArchive(tr *tar.Reader) error {
var fseen map[string]bool = make(map[string]bool)
var imOK, rfsOK bool
var im bytes.Buffer
Tar:
for {
hdr, err := tr.Next()
switch {
case err == nil:
case err == io.EOF:
break Tar
default:
return err
}
name := filepath.Clean(hdr.Name)
switch name {
case ".":
case ManifestFile:
_, err := io.Copy(&im, tr)
if err!= nil {
return err
}
imOK = true
case RootfsDir:
if!hdr.FileInfo().IsDir() {
return fmt.Errorf("rootfs is not a directory")
}
rfsOK = true
default:
if _, seen := fseen[name]; seen {
return fmt.Errorf("duplicate file entry in archive: %s", name)
}
fseen[name] = true
}
}
var flist []string
for key := range fseen {
flist = append(flist, key)
}
return validate(imOK, &im, rfsOK, flist)
} |
// CreateDepListFromImageID returns the flat dependency tree of the image with
// the provided imageID
func CreateDepListFromImageID(imageID types.Hash, ap ACIRegistry) (Images, error) {
key, err := ap.ResolveKey(imageID.String())
if err!= nil {
return nil, err
}
return createDepList(key, ap)
} |
// CreateDepListFromNameLabels returns the flat dependency tree of the image
// with the provided app name and optional labels.
func CreateDepListFromNameLabels(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (Images, error) {
key, err := ap.GetACI(name, labels)
if err!= nil {
return nil, err
}
return createDepList(key, ap)
} |
// createDepList returns the flat dependency tree as a list of Image type
func createDepList(key string, ap ACIRegistry) (Images, error) {
imgsl := list.New()
im, err := ap.GetImageManifest(key)
if err!= nil {
return nil, err
}
img := Image{Im: im, Key: key, Level: 0}
imgsl.PushFront(img)
// Create a flat dependency tree. Use a LinkedList to be able to
// insert elements in the list while working on it.
for el := imgsl.Front(); el!= nil; el = el.Next() {
img := el.Value.(Image)
dependencies := img.Im.Dependencies
for _, d := range dependencies {
var depimg Image
var depKey string
if d.ImageID!= nil &&!d.ImageID.Empty() {
depKey, err = ap.ResolveKey(d.ImageID.String())
if err!= nil {
return nil, err
}
} else {
var err error
depKey, err = ap.GetACI(d.ImageName, d.Labels)
if err!= nil {
return nil, err
}
}
im, err := ap.GetImageManifest(depKey)
if err!= nil {
return nil, err
}
depimg = Image{Im: im, Key: depKey, Level: img.Level + 1}
imgsl.InsertAfter(depimg, el)
}
}
imgs := Images{}
for el := imgsl.Front(); el!= nil; el = el.Next() {
imgs = append(imgs, el.Value.(Image))
}
return imgs, nil
} |
// StaticMiddleware is the same as StaticMiddlewareFromDir, but accepts a
// path string for backwards compatibility.
func StaticMiddleware(path string, option...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
return StaticMiddlewareFromDir(http.Dir(path), option...)
} |
// StaticMiddlewareFromDir returns a middleware that serves static files from the specified http.FileSystem.
// This middleware is great for development because each file is read from disk each time and no
// special caching or cache headers are sent.
//
// If a path is requested which maps to a folder with an index.html folder on your filesystem,
// then that index.html file will be served.
func StaticMiddlewareFromDir(dir http.FileSystem, options...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
var option StaticOption
if len(options) > 0 {
option = options[0]
}
return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) {
if req.Method!= "GET" && req.Method!= "HEAD" {
next(w, req)
return
}
file := req.URL.Path
if option.Prefix!= "" {
if!strings.HasPrefix(file, option.Prefix) {
next(w, req)
return
}
file = file[len(option.Prefix):]
}
f, err := dir.Open(file)
if err!= nil {
next(w, req)
return
}
defer f.Close()
fi, err := f.Stat()
if err!= nil {
next(w, req)
return
}
// If the file is a directory, try to serve an index file.
// If no index is available, DO NOT serve the directory to avoid
// Content-Length issues. Simply skip to the next middleware, and return
// a 404 if no route with the same name is handled.
if fi.IsDir() {
if option.IndexFile!= "" {
file = filepath.Join(file, option.IndexFile)
f, err = dir.Open(file)
if err!= nil {
next(w, req)
return
}
defer f.Close()
fi, err = f.Stat()
if err!= nil || fi.IsDir() {
next(w, req)
return
}
} else {
next(w, req)
return
}
}
http.ServeContent(w, req.Request, file, fi.ModTime(), f)
}
} |
// New returns a new router with context type ctx. ctx should be a struct instance,
// whose purpose is to communicate type information. On each request, an instance of this
// context type will be automatically allocated and sent to handlers.
func New(ctx interface{}) *Router {
validateContext(ctx, nil)
r := &Router{}
r.contextType = reflect.TypeOf(ctx)
r.pathPrefix = "/"
r.maxChildrenDepth = 1
r.root = make(map[httpMethod]*pathNode)
for _, method := range httpMethods {
r.root[method] = newPathNode()
}
return r
} |
// NewWithPrefix returns a new router (see New) but each route will have an implicit prefix.
// For instance, with pathPrefix = "/api/v2", all routes under this router will begin with "/api/v2".
func NewWithPrefix(ctx interface{}, pathPrefix string) *Router {
r := New(ctx)
r.pathPrefix = pathPrefix
return r
} |
// Subrouter attaches a new subrouter to the specified router and returns it.
// You can use the same context or pass a new one. If you pass a new one, it must
// embed a pointer to the previous context in the first slot. You can also pass
// a pathPrefix that each route will have. If "" is passed, then no path prefix is applied.
func (r *Router) Subrouter(ctx interface{}, pathPrefix string) *Router {
validateContext(ctx, r.contextType)
// Create new router, link up hierarchy
newRouter := &Router{parent: r}
r.children = append(r.children, newRouter)
// Increment maxChildrenDepth if this is the first child of the router
if len(r.children) == 1 {
curParent := r
for curParent!= nil {
curParent.maxChildrenDepth = curParent.depth()
curParent = curParent.parent
}
}
newRouter.contextType = reflect.TypeOf(ctx)
newRouter.pathPrefix = appendPath(r.pathPrefix, pathPrefix)
newRouter.root = r.root
return newRouter
} |
// Middleware adds the specified middleware tot he router and returns the router.
func (r *Router) Middleware(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateMiddleware(vfn, r.contextType)
if vfn.Type().NumIn() == 3 {
r.middleware = append(r.middleware, &middlewareHandler{Generic: true, GenericMiddleware: fn.(func(ResponseWriter, *Request, NextMiddlewareFunc))})
} else {
r.middleware = append(r.middleware, &middlewareHandler{Generic: false, DynamicMiddleware: vfn})
}
return r
} |
// Error sets the specified function as the error handler (when panics happen) and returns the router.
func (r *Router) Error(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateErrorHandler(vfn, r.contextType)
r.errorHandler = vfn
return r
} |
// NotFound sets the specified function as the not-found handler (when no route matches) and returns the router.
// Note that only the root router can have a NotFound handler.
func (r *Router) NotFound(fn interface{}) *Router {
if r.parent!= nil {
panic("You can only set a NotFoundHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateNotFoundHandler(vfn, r.contextType)
r.notFoundHandler = vfn
return r
} |
// OptionsHandler sets the specified function as the options handler and returns the router.
// Note that only the root router can have a OptionsHandler handler.
func (r *Router) OptionsHandler(fn interface{}) *Router {
if r.parent!= nil {
panic("You can only set an OptionsHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateOptionsHandler(vfn, r.contextType)
r.optionsHandler = vfn
return r
} |
// Get will add a route to the router that matches on GET requests and the specified path.
func (r *Router) Get(path string, fn interface{}) *Router {
return r.addRoute(httpMethodGet, path, fn)
} |
// Post will add a route to the router that matches on POST requests and the specified path.
func (r *Router) Post(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPost, path, fn)
} |
// Put will add a route to the router that matches on PUT requests and the specified path.
func (r *Router) Put(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPut, path, fn)
} |