code
stringlengths
11
335k
docstring
stringlengths
20
11.8k
func_name
stringlengths
1
100
language
stringclasses
1 value
repo
stringclasses
245 values
path
stringlengths
4
144
url
stringlengths
43
214
license
stringclasses
4 values
func containerdSysProcAttr() *syscall.SysProcAttr { return &syscall.SysProcAttr{ Setsid: true, Pdeathsig: syscall.SIGKILL, } }
containerdSysProcAttr returns the SysProcAttr to use when exec'ing containerd
containerdSysProcAttr
go
balena-os/balena-engine
libcontainerd/supervisor/utils_linux.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/utils_linux.go
Apache-2.0
func Start(ctx context.Context, rootDir, stateDir string, opts ...DaemonOpt) (Daemon, error) { r := &remote{ rootDir: rootDir, stateDir: stateDir, Config: config.Config{ Root: filepath.Join(rootDir, "daemon"), State: filepath.Join(stateDir, "daemon"), }, pluginConfs: pluginConfigs{make(map[string]interface{})}, daemonPid: -1, logger: logrus.WithField("module", "libcontainerd"), daemonStartCh: make(chan error, 1), daemonStopCh: make(chan struct{}), } for _, opt := range opts { if err := opt(r); err != nil { return nil, err } } r.setDefaults() if err := system.MkdirAll(stateDir, 0700); err != nil { return nil, err } go r.monitorDaemon(ctx) timeout := time.NewTimer(startupTimeout) defer timeout.Stop() select { case <-timeout.C: return nil, errors.New("timeout waiting for containerd to start") case err := <-r.daemonStartCh: if err != nil { return nil, err } } return r, nil }
Start starts a containerd daemon and monitors it
Start
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon.go
Apache-2.0
func containerdSysProcAttr() *syscall.SysProcAttr { return nil }
containerdSysProcAttr returns the SysProcAttr to use when exec'ing containerd
containerdSysProcAttr
go
balena-os/balena-engine
libcontainerd/supervisor/utils_windows.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/utils_windows.go
Apache-2.0
func WithRemoteAddr(addr string) DaemonOpt { return func(r *remote) error { r.GRPC.Address = addr return nil } }
WithRemoteAddr sets the external containerd socket to connect to.
WithRemoteAddr
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithRemoteAddrUser(uid, gid int) DaemonOpt { return func(r *remote) error { r.GRPC.UID = uid r.GRPC.GID = gid return nil } }
WithRemoteAddrUser sets the uid and gid to create the RPC address with
WithRemoteAddrUser
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithLogLevel(lvl string) DaemonOpt { return func(r *remote) error { r.Debug.Level = lvl return nil } }
WithLogLevel defines which log level to starts containerd with. This only makes sense if WithStartDaemon() was set to true.
WithLogLevel
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithDebugAddress(addr string) DaemonOpt { return func(r *remote) error { r.Debug.Address = addr return nil } }
WithDebugAddress defines at which location the debug GRPC connection should be made
WithDebugAddress
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithMetricsAddress(addr string) DaemonOpt { return func(r *remote) error { r.Metrics.Address = addr return nil } }
WithMetricsAddress defines at which location the debug GRPC connection should be made
WithMetricsAddress
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithPlugin(name string, conf interface{}) DaemonOpt { return func(r *remote) error { r.pluginConfs.Plugins[name] = conf return nil } }
WithPlugin allow configuring a containerd plugin configuration values passed needs to be quoted if quotes are needed in the toml format.
WithPlugin
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options.go
Apache-2.0
func WithOOMScore(score int) DaemonOpt { return func(r *remote) error { r.OOMScore = score return nil } }
WithOOMScore defines the oom_score_adj to set for the containerd process.
WithOOMScore
go
balena-os/balena-engine
libcontainerd/supervisor/remote_daemon_options_linux.go
https://github.com/balena-os/balena-engine/blob/master/libcontainerd/supervisor/remote_daemon_options_linux.go
Apache-2.0
func RemoveNamespace(s *specs.Spec, nsType specs.LinuxNamespaceType) { for i, n := range s.Linux.Namespaces { if n.Type == nsType { s.Linux.Namespaces = append(s.Linux.Namespaces[:i], s.Linux.Namespaces[i+1:]...) return } } }
RemoveNamespace removes the `nsType` namespace from OCI spec `s`
RemoveNamespace
go
balena-os/balena-engine
oci/namespaces.go
https://github.com/balena-os/balena-engine/blob/master/oci/namespaces.go
Apache-2.0
func Device(d *configs.Device) specs.LinuxDevice { return specs.LinuxDevice{} }
Device transforms a libcontainer configs.Device to a specs.Device object. Not implemented
Device
go
balena-os/balena-engine
oci/devices_unsupported.go
https://github.com/balena-os/balena-engine/blob/master/oci/devices_unsupported.go
Apache-2.0
func DevicesFromPath(pathOnHost, pathInContainer, cgroupPermissions string) (devs []specs.LinuxDevice, devPermissions []specs.LinuxDeviceCgroup, err error) { return nil, nil, errors.New("oci/devices: unsupported platform") }
DevicesFromPath computes a list of devices and device permissions from paths (pathOnHost and pathInContainer) and cgroup permissions. Not implemented
DevicesFromPath
go
balena-os/balena-engine
oci/devices_unsupported.go
https://github.com/balena-os/balena-engine/blob/master/oci/devices_unsupported.go
Apache-2.0
func DefaultSpec() specs.Spec { return DefaultOSSpec(runtime.GOOS) }
DefaultSpec returns the default spec used by docker for the current Platform
DefaultSpec
go
balena-os/balena-engine
oci/defaults.go
https://github.com/balena-os/balena-engine/blob/master/oci/defaults.go
Apache-2.0
func DefaultOSSpec(osName string) specs.Spec { if osName == "windows" { return DefaultWindowsSpec() } return DefaultLinuxSpec() }
DefaultOSSpec returns the spec for a given OS
DefaultOSSpec
go
balena-os/balena-engine
oci/defaults.go
https://github.com/balena-os/balena-engine/blob/master/oci/defaults.go
Apache-2.0
func DefaultWindowsSpec() specs.Spec { return specs.Spec{ Version: specs.Version, Windows: &specs.Windows{}, Process: &specs.Process{}, Root: &specs.Root{}, } }
DefaultWindowsSpec create a default spec for running Windows containers
DefaultWindowsSpec
go
balena-os/balena-engine
oci/defaults.go
https://github.com/balena-os/balena-engine/blob/master/oci/defaults.go
Apache-2.0
func DefaultLinuxSpec() specs.Spec { s := specs.Spec{ Version: specs.Version, Process: &specs.Process{ Capabilities: &specs.LinuxCapabilities{ Bounding: caps.DefaultCapabilities(), Permitted: caps.DefaultCapabilities(), Effective: caps.DefaultCapabilities(), }, }, Root: &specs.Root{}, } s.Mounts = []specs.Mount{ { Destination: "/proc", Type: "proc", Source: "proc", Options: []string{"nosuid", "noexec", "nodev"}, }, { Destination: "/dev", Type: "tmpfs", Source: "tmpfs", Options: []string{"nosuid", "strictatime", "mode=755", "size=65536k"}, }, { Destination: "/dev/pts", Type: "devpts", Source: "devpts", Options: []string{"nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"}, }, { Destination: "/sys", Type: "sysfs", Source: "sysfs", Options: []string{"nosuid", "noexec", "nodev", "ro"}, }, { Destination: "/sys/fs/cgroup", Type: "cgroup", Source: "cgroup", Options: []string{"ro", "nosuid", "noexec", "nodev"}, }, { Destination: "/dev/mqueue", Type: "mqueue", Source: "mqueue", Options: []string{"nosuid", "noexec", "nodev"}, }, { Destination: "/dev/shm", Type: "tmpfs", Source: "shm", Options: []string{"nosuid", "noexec", "nodev", "mode=1777"}, }, } s.Linux = &specs.Linux{ MaskedPaths: []string{ "/proc/asound", "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/proc/scsi", "/sys/firmware", }, ReadonlyPaths: []string{ "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger", }, Namespaces: []specs.LinuxNamespace{ {Type: "mount"}, {Type: "network"}, {Type: "uts"}, {Type: "pid"}, {Type: "ipc"}, }, // Devices implicitly contains the following devices: // null, zero, full, random, urandom, tty, console, and ptmx. // ptmx is a bind mount or symlink of the container's ptmx. // See also: https://github.com/opencontainers/runtime-spec/blob/master/config-linux.md#default-devices Devices: []specs.LinuxDevice{}, Resources: &specs.LinuxResources{ Devices: []specs.LinuxDeviceCgroup{ { Allow: false, Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(1), Minor: iPtr(5), Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(1), Minor: iPtr(3), Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(1), Minor: iPtr(9), Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(1), Minor: iPtr(8), Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(5), Minor: iPtr(0), Access: "rwm", }, { Allow: true, Type: "c", Major: iPtr(5), Minor: iPtr(1), Access: "rwm", }, { Allow: false, Type: "c", Major: iPtr(10), Minor: iPtr(229), Access: "rwm", }, }, }, } // For LCOW support, populate a blank Windows spec if runtime.GOOS == "windows" { s.Windows = &specs.Windows{} } return s }
DefaultLinuxSpec create a default spec for running Linux containers
DefaultLinuxSpec
go
balena-os/balena-engine
oci/defaults.go
https://github.com/balena-os/balena-engine/blob/master/oci/defaults.go
Apache-2.0
func Device(d *devices.Device) specs.LinuxDevice { return specs.LinuxDevice{ Type: string(d.Type), Path: d.Path, Major: d.Major, Minor: d.Minor, FileMode: fmPtr(int64(d.FileMode)), UID: u32Ptr(int64(d.Uid)), GID: u32Ptr(int64(d.Gid)), } }
Device transforms a libcontainer configs.Device to a specs.LinuxDevice object.
Device
go
balena-os/balena-engine
oci/devices_linux.go
https://github.com/balena-os/balena-engine/blob/master/oci/devices_linux.go
Apache-2.0
func DevicesFromPath(pathOnHost, pathInContainer, cgroupPermissions string) (devs []specs.LinuxDevice, devPermissions []specs.LinuxDeviceCgroup, err error) { resolvedPathOnHost := pathOnHost // check if it is a symbolic link if src, e := os.Lstat(pathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink { if linkedPathOnHost, e := filepath.EvalSymlinks(pathOnHost); e == nil { resolvedPathOnHost = linkedPathOnHost } } device, err := devices.DeviceFromPath(resolvedPathOnHost, cgroupPermissions) // if there was no error, return the device if err == nil { device.Path = pathInContainer return append(devs, Device(device)), append(devPermissions, deviceCgroup(device)), nil } // if the device is not a device node // try to see if it's a directory holding many devices if err == devices.ErrNotADevice { // check if it is a directory if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() { // mount the internal devices recursively // TODO check if additional errors should be handled or logged _ = filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, _ error) error { childDevice, e := devices.DeviceFromPath(dpath, cgroupPermissions) if e != nil { // ignore the device return nil } // add the device to userSpecified devices childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, pathInContainer, 1) devs = append(devs, Device(childDevice)) devPermissions = append(devPermissions, deviceCgroup(childDevice)) return nil }) } } if len(devs) > 0 { return devs, devPermissions, nil } return devs, devPermissions, fmt.Errorf("error gathering device information while adding custom device %q: %s", pathOnHost, err) }
DevicesFromPath computes a list of devices and device permissions from paths (pathOnHost and pathInContainer) and cgroup permissions.
DevicesFromPath
go
balena-os/balena-engine
oci/devices_linux.go
https://github.com/balena-os/balena-engine/blob/master/oci/devices_linux.go
Apache-2.0
func SetCapabilities(s *specs.Spec, caplist []string) error { // setUser has already been executed here if s.Process.User.UID == 0 { s.Process.Capabilities = &specs.LinuxCapabilities{ Effective: caplist, Bounding: caplist, Permitted: caplist, } } else { // Do not set Effective and Permitted capabilities for non-root users, // to match what execve does. s.Process.Capabilities = &specs.LinuxCapabilities{ Bounding: caplist, } } return nil }
SetCapabilities sets the provided capabilities on the spec All capabilities are added if privileged is true.
SetCapabilities
go
balena-os/balena-engine
oci/oci.go
https://github.com/balena-os/balena-engine/blob/master/oci/oci.go
Apache-2.0
func AppendDevicePermissionsFromCgroupRules(devPermissions []specs.LinuxDeviceCgroup, rules []string) ([]specs.LinuxDeviceCgroup, error) { for _, deviceCgroupRule := range rules { ss := deviceCgroupRuleRegex.FindAllStringSubmatch(deviceCgroupRule, -1) if len(ss) == 0 || len(ss[0]) != 5 { return nil, fmt.Errorf("invalid device cgroup rule format: '%s'", deviceCgroupRule) } matches := ss[0] dPermissions := specs.LinuxDeviceCgroup{ Allow: true, Type: matches[1], Access: matches[4], } if matches[2] == "*" { major := int64(-1) dPermissions.Major = &major } else { major, err := strconv.ParseInt(matches[2], 10, 64) if err != nil { return nil, fmt.Errorf("invalid major value in device cgroup rule format: '%s'", deviceCgroupRule) } dPermissions.Major = &major } if matches[3] == "*" { minor := int64(-1) dPermissions.Minor = &minor } else { minor, err := strconv.ParseInt(matches[3], 10, 64) if err != nil { return nil, fmt.Errorf("invalid minor value in device cgroup rule format: '%s'", deviceCgroupRule) } dPermissions.Minor = &minor } devPermissions = append(devPermissions, dPermissions) } return devPermissions, nil }
AppendDevicePermissionsFromCgroupRules takes rules for the devices cgroup to append to the default set
AppendDevicePermissionsFromCgroupRules
go
balena-os/balena-engine
oci/oci.go
https://github.com/balena-os/balena-engine/blob/master/oci/oci.go
Apache-2.0
func DefaultCapabilities() []string { return []string{ "CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FSETID", "CAP_FOWNER", "CAP_MKNOD", "CAP_NET_RAW", "CAP_SETGID", "CAP_SETUID", "CAP_SETFCAP", "CAP_SETPCAP", "CAP_NET_BIND_SERVICE", "CAP_SYS_CHROOT", "CAP_KILL", "CAP_AUDIT_WRITE", } }
DefaultCapabilities returns a Linux kernel default capabilities
DefaultCapabilities
go
balena-os/balena-engine
oci/caps/defaults.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/defaults.go
Apache-2.0
func (c *CapabilityMapping) String() string { return c.Key }
String returns <key> of CapabilityMapping
String
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func GetCapability(key string) *CapabilityMapping { for _, capp := range capabilityList { if capp.Key == key { cpy := *capp return &cpy } } return nil }
GetCapability returns CapabilityMapping which contains specific key
GetCapability
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func GetAllCapabilities() []string { output := make([]string, len(capabilityList)) for i, capability := range capabilityList { output[i] = capability.String() } return output }
GetAllCapabilities returns all of the capabilities
GetAllCapabilities
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func inSlice(slice []string, s string) bool { for _, ss := range slice { if s == ss { return true } } return false }
inSlice tests whether a string is contained in a slice of strings or not.
inSlice
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func NormalizeLegacyCapabilities(caps []string) ([]string, error) { var normalized []string valids := GetAllCapabilities() for _, c := range caps { c = strings.ToUpper(c) if c == allCapabilities { normalized = append(normalized, c) continue } if !strings.HasPrefix(c, "CAP_") { c = "CAP_" + c } if !inSlice(valids, c) { return nil, errdefs.InvalidParameter(fmt.Errorf("unknown capability: %q", c)) } normalized = append(normalized, c) } return normalized, nil }
NormalizeLegacyCapabilities normalizes, and validates CapAdd/CapDrop capabilities by upper-casing them, and adding a CAP_ prefix (if not yet present). This function also accepts the "ALL" magic-value, that's used by CapAdd/CapDrop.
NormalizeLegacyCapabilities
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func ValidateCapabilities(caps []string) error { valids := GetAllCapabilities() for _, c := range caps { if !inSlice(valids, c) { return errdefs.InvalidParameter(fmt.Errorf("unknown capability: %q", c)) } } return nil }
ValidateCapabilities validates if caps only contains valid capabilities
ValidateCapabilities
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func TweakCapabilities(basics, adds, drops []string, privileged bool) ([]string, error) { switch { case privileged: // Privileged containers get all capabilities return GetAllCapabilities(), nil case len(adds) == 0 && len(drops) == 0: // Nothing to tweak; we're done return basics, nil } capDrop, err := NormalizeLegacyCapabilities(drops) if err != nil { return nil, err } capAdd, err := NormalizeLegacyCapabilities(adds) if err != nil { return nil, err } var caps []string switch { case inSlice(capAdd, allCapabilities): // Add all capabilities except ones on capDrop for _, c := range GetAllCapabilities() { if !inSlice(capDrop, c) { caps = append(caps, c) } } case inSlice(capDrop, allCapabilities): // "Drop" all capabilities; use what's in capAdd instead caps = capAdd default: // First drop some capabilities for _, c := range basics { if !inSlice(capDrop, c) { caps = append(caps, c) } } // Then add the list of capabilities from capAdd caps = append(caps, capAdd...) } return caps, nil }
TweakCapabilities tweaks capabilities by adding, dropping, or overriding capabilities in the basics capabilities list.
TweakCapabilities
go
balena-os/balena-engine
oci/caps/utils.go
https://github.com/balena-os/balena-engine/blob/master/oci/caps/utils.go
Apache-2.0
func newPuller(endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePullConfig *ImagePullConfig, local ContentStore) (Puller, error) { switch endpoint.Version { case registry.APIVersion2: return &v2Puller{ V2MetadataService: metadata.NewV2MetadataService(imagePullConfig.MetadataStore), endpoint: endpoint, config: imagePullConfig, repoInfo: repoInfo, manifestStore: &manifestStore{ local: local, }, }, nil case registry.APIVersion1: return nil, fmt.Errorf("protocol version %d no longer supported. Please contact admins of registry %s", endpoint.Version, endpoint.URL) } return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL) }
newPuller returns a Puller interface that will pull from either a v1 or v2 registry. The endpoint argument contains a Version field that determines whether a v1 or v2 puller will be created. The other parameters are passed through to the underlying puller implementation for use during the actual pull operation.
newPuller
go
balena-os/balena-engine
distribution/pull.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull.go
Apache-2.0
func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullConfig, local ContentStore) error { // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := imagePullConfig.RegistryService.ResolveRepository(ref) if err != nil { return err } // makes sure name is not `scratch` if err := ValidateRepoName(repoInfo.Name); err != nil { return err } endpoints, err := imagePullConfig.RegistryService.LookupPullEndpoints(reference.Domain(repoInfo.Name)) if err != nil { return err } var ( lastErr error // discardNoSupportErrors is used to track whether an endpoint encountered an error of type registry.ErrNoSupport // By default it is false, which means that if an ErrNoSupport error is encountered, it will be saved in lastErr. // As soon as another kind of error is encountered, discardNoSupportErrors is set to true, avoiding the saving of // any subsequent ErrNoSupport errors in lastErr. // It's needed for pull-by-digest on v1 endpoints: if there are only v1 endpoints configured, the error should be // returned and displayed, but if there was a v2 endpoint which supports pull-by-digest, then the last relevant // error is the ones from v2 endpoints not v1. discardNoSupportErrors bool // confirmedV2 is set to true if a pull attempt managed to // confirm that it was talking to a v2 registry. This will // prevent fallback to the v1 protocol. confirmedV2 bool // confirmedTLSRegistries is a map indicating which registries // are known to be using TLS. There should never be a plaintext // retry for any of these. confirmedTLSRegistries = make(map[string]struct{}) ) for _, endpoint := range endpoints { if imagePullConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 { continue } if confirmedV2 && endpoint.Version == registry.APIVersion1 { logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL) continue } if endpoint.URL.Scheme != "https" { if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS { logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL) continue } } logrus.Debugf("Trying to pull %s from %s %s", reference.FamiliarName(repoInfo.Name), endpoint.URL, endpoint.Version) puller, err := newPuller(endpoint, repoInfo, imagePullConfig, local) if err != nil { lastErr = err continue } if err := puller.Pull(ctx, ref, imagePullConfig.Platform); err != nil { // Was this pull cancelled? If so, don't try to fall // back. fallback := false select { case <-ctx.Done(): default: if fallbackErr, ok := err.(fallbackError); ok { fallback = true confirmedV2 = confirmedV2 || fallbackErr.confirmedV2 if fallbackErr.transportOK && endpoint.URL.Scheme == "https" { confirmedTLSRegistries[endpoint.URL.Host] = struct{}{} } err = fallbackErr.err } } if fallback { if _, ok := err.(ErrNoSupport); !ok { // Because we found an error that's not ErrNoSupport, discard all subsequent ErrNoSupport errors. discardNoSupportErrors = true // append subsequent errors lastErr = err } else if !discardNoSupportErrors { // Save the ErrNoSupport error, because it's either the first error or all encountered errors // were also ErrNoSupport errors. // append subsequent errors lastErr = err } logrus.Infof("Attempting next endpoint for pull after error: %v", err) continue } logrus.Errorf("Not continuing with pull after error: %v", err) return TranslatePullError(err, ref) } imagePullConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "pull") return nil } if lastErr == nil { lastErr = fmt.Errorf("no endpoints found for %s", reference.FamiliarString(ref)) } return TranslatePullError(lastErr, ref) }
Pull initiates a pull operation. image is the repository name to pull, and tag may be either empty, or indicate a specific tag to pull.
Pull
go
balena-os/balena-engine
distribution/pull.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull.go
Apache-2.0
func writeStatus(requestedTag string, out progress.Output, layersDownloaded bool) { if layersDownloaded { progress.Message(out, "", "Status: Downloaded newer image for "+requestedTag) } else { progress.Message(out, "", "Status: Image is up to date for "+requestedTag) } }
writeStatus writes a status message to out. If layersDownloaded is true, the status message indicates that a newer image was downloaded. Otherwise, it indicates that the image is up to date. requestedTag is the tag the message will refer to.
writeStatus
go
balena-os/balena-engine
distribution/pull.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull.go
Apache-2.0
func ValidateRepoName(name reference.Named) error { if reference.FamiliarName(name) == api.NoBaseImageSpecifier { return errors.WithStack(reservedNameError(api.NoBaseImageSpecifier)) } return nil }
ValidateRepoName validates the name of a repository.
ValidateRepoName
go
balena-os/balena-engine
distribution/pull.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull.go
Apache-2.0
func (s *memoryLabelStore) Get(dgst digest.Digest) (map[string]string, error) { s.mu.Lock() labels := s.labels[dgst] s.mu.Unlock() return labels, nil }
Get returns all the labels for the given digest
Get
go
balena-os/balena-engine
distribution/manifest_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/manifest_test.go
Apache-2.0
func (s *memoryLabelStore) Set(dgst digest.Digest, labels map[string]string) error { s.mu.Lock() if s.labels == nil { s.labels = make(map[digest.Digest]map[string]string) } s.labels[dgst] = labels s.mu.Unlock() return nil }
Set sets all the labels for a given digest
Set
go
balena-os/balena-engine
distribution/manifest_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/manifest_test.go
Apache-2.0
func (s *memoryLabelStore) Update(dgst digest.Digest, update map[string]string) (map[string]string, error) { s.mu.Lock() defer s.mu.Unlock() labels, ok := s.labels[dgst] if !ok { labels = map[string]string{} } for k, v := range update { labels[k] = v } s.labels[dgst] = labels return labels, nil }
Update replaces the given labels for a digest, a key with an empty value removes a label.
Update
go
balena-os/balena-engine
distribution/manifest_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/manifest_test.go
Apache-2.0
func NewV2Repository( ctx context.Context, repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *types.AuthConfig, actions ...string, ) (repo distribution.Repository, foundVersion bool, err error) { repoName := repoInfo.Name.Name() // If endpoint does not support CanonicalName, use the RemoteName instead if endpoint.TrimHostname { repoName = reference.Path(repoInfo.Name) } direct := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, } // TODO(dmcgowan): Call close idle connections when complete, use keep alive base := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: direct.DialContext, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: endpoint.TLSConfig, // TODO(dmcgowan): Call close idle connections when complete and use keep alive DisableKeepAlives: true, } modifiers := registry.Headers(dockerversion.DockerUserAgent(ctx), metaHeaders) authTransport := transport.NewTransport(base, modifiers...) challengeManager, foundVersion, err := registry.PingV2Registry(endpoint.URL, authTransport) if err != nil { transportOK := false if responseErr, ok := err.(registry.PingResponseError); ok { transportOK = true err = responseErr.Err } return nil, foundVersion, fallbackError{ err: err, confirmedV2: foundVersion, transportOK: transportOK, } } if authConfig.RegistryToken != "" { passThruTokenHandler := &existingTokenHandler{token: authConfig.RegistryToken} modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler)) } else { scope := auth.RepositoryScope{ Repository: repoName, Actions: actions, Class: repoInfo.Class, } creds := registry.NewStaticCredentialStore(authConfig) tokenHandlerOptions := auth.TokenHandlerOptions{ Transport: authTransport, Credentials: creds, Scopes: []auth.Scope{scope}, ClientID: registry.AuthClientID, } tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) basicHandler := auth.NewBasicHandler(creds) modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) } tr := transport.NewTransport(base, modifiers...) repoNameRef, err := reference.WithName(repoName) if err != nil { return nil, foundVersion, fallbackError{ err: err, confirmedV2: foundVersion, transportOK: true, } } repo, err = client.NewRepository(repoNameRef, endpoint.URL.String(), tr) if err != nil { err = fallbackError{ err: err, confirmedV2: foundVersion, transportOK: true, } } return }
NewV2Repository returns a repository (v2 only). It creates an HTTP transport providing timeout settings and authentication support, and also verifies the remote API version.
NewV2Repository
go
balena-os/balena-engine
distribution/registry.go
https://github.com/balena-os/balena-engine/blob/master/distribution/registry.go
Apache-2.0
func NewImageConfigStoreFromStore(is, deltaImageStore image.Store) ImageConfigStore { return &imageConfigStore{ Store: is, deltaStore: deltaImageStore, } }
NewImageConfigStoreFromStore returns an ImageConfigStore backed by an image.Store for container images.
NewImageConfigStoreFromStore
go
balena-os/balena-engine
distribution/config.go
https://github.com/balena-os/balena-engine/blob/master/distribution/config.go
Apache-2.0
func NewLayerProvidersFromStores(lss map[string]layer.Store) map[string]PushLayerProvider { plps := make(map[string]PushLayerProvider) for os, ls := range lss { plps[os] = &storeLayerProvider{ls: ls} } return plps }
NewLayerProvidersFromStores returns layer providers backed by an instance of LayerStore. Only getting layers as gzipped tars is supported.
NewLayerProvidersFromStores
go
balena-os/balena-engine
distribution/config.go
https://github.com/balena-os/balena-engine/blob/master/distribution/config.go
Apache-2.0
func checkImageCompatibility(imageOS, imageOSVersion string) error { if imageOS == "windows" { hostOSV := osversion.Get() splitImageOSVersion := strings.Split(imageOSVersion, ".") // eg 10.0.16299.nnnn if len(splitImageOSVersion) >= 3 { if imageOSBuild, err := strconv.Atoi(splitImageOSVersion[2]); err == nil { if imageOSBuild > int(hostOSV.Build) { errMsg := fmt.Sprintf("a Windows version %s.%s.%s-based image is incompatible with a %s host", splitImageOSVersion[0], splitImageOSVersion[1], splitImageOSVersion[2], hostOSV.ToString()) logrus.Debugf(errMsg) return errors.New(errMsg) } } } } return nil }
checkImageCompatibility blocks pulling incompatible images based on a later OS build Fixes https://github.com/moby/moby/issues/36184.
checkImageCompatibility
go
balena-os/balena-engine
distribution/pull_v2_windows.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull_v2_windows.go
Apache-2.0
func checkImageCompatibility(imageOS, imageOSVersion string) error { return nil }
checkImageCompatibility is a Windows-specific function. No-op on Linux
checkImageCompatibility
go
balena-os/balena-engine
distribution/pull_v2_unix.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull_v2_unix.go
Apache-2.0
func NewPusher(ref reference.Named, endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePushConfig *ImagePushConfig) (Pusher, error) { switch endpoint.Version { case registry.APIVersion2: return &v2Pusher{ v2MetadataService: metadata.NewV2MetadataService(imagePushConfig.MetadataStore), ref: ref, endpoint: endpoint, repoInfo: repoInfo, config: imagePushConfig, }, nil case registry.APIVersion1: return nil, fmt.Errorf("protocol version %d no longer supported. Please contact admins of registry %s", endpoint.Version, endpoint.URL) } return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL) }
NewPusher creates a new Pusher interface that will push to either a v1 or v2 registry. The endpoint argument contains a Version field that determines whether a v1 or v2 pusher will be created. The other parameters are passed through to the underlying pusher implementation for use during the actual push operation.
NewPusher
go
balena-os/balena-engine
distribution/push.go
https://github.com/balena-os/balena-engine/blob/master/distribution/push.go
Apache-2.0
func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushConfig) error { // FIXME: Allow to interrupt current push when new push of same image is done. // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := imagePushConfig.RegistryService.ResolveRepository(ref) if err != nil { return err } endpoints, err := imagePushConfig.RegistryService.LookupPushEndpoints(reference.Domain(repoInfo.Name)) if err != nil { return err } progress.Messagef(imagePushConfig.ProgressOutput, "", "The push refers to repository [%s]", repoInfo.Name.Name()) associations := imagePushConfig.ReferenceStore.ReferencesByName(repoInfo.Name) if len(associations) == 0 { return fmt.Errorf("An image does not exist locally with the tag: %s", reference.FamiliarName(repoInfo.Name)) } var ( lastErr error // confirmedV2 is set to true if a push attempt managed to // confirm that it was talking to a v2 registry. This will // prevent fallback to the v1 protocol. confirmedV2 bool // confirmedTLSRegistries is a map indicating which registries // are known to be using TLS. There should never be a plaintext // retry for any of these. confirmedTLSRegistries = make(map[string]struct{}) ) for _, endpoint := range endpoints { if imagePushConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 { continue } if confirmedV2 && endpoint.Version == registry.APIVersion1 { logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL) continue } if endpoint.URL.Scheme != "https" { if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS { logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL) continue } } logrus.Debugf("Trying to push %s to %s %s", repoInfo.Name.Name(), endpoint.URL, endpoint.Version) pusher, err := NewPusher(ref, endpoint, repoInfo, imagePushConfig) if err != nil { lastErr = err continue } if err := pusher.Push(ctx); err != nil { // Was this push cancelled? If so, don't try to fall // back. select { case <-ctx.Done(): default: if fallbackErr, ok := err.(fallbackError); ok { confirmedV2 = confirmedV2 || fallbackErr.confirmedV2 if fallbackErr.transportOK && endpoint.URL.Scheme == "https" { confirmedTLSRegistries[endpoint.URL.Host] = struct{}{} } err = fallbackErr.err lastErr = err logrus.Infof("Attempting next endpoint for push after error: %v", err) continue } } logrus.Errorf("Not continuing with push after error: %v", err) return err } imagePushConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "push") return nil } if lastErr == nil { lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.Name.Name()) } return lastErr }
Push initiates a push operation on ref. ref is the specific variant of the image to be pushed. If no tag is provided, all tags will be pushed.
Push
go
balena-os/balena-engine
distribution/push.go
https://github.com/balena-os/balena-engine/blob/master/distribution/push.go
Apache-2.0
func (f fallbackError) Error() string { return f.Cause().Error() }
Error renders the FallbackError as a string.
Error
go
balena-os/balena-engine
distribution/errors.go
https://github.com/balena-os/balena-engine/blob/master/distribution/errors.go
Apache-2.0
func shouldV2Fallback(err errcode.Error) bool { switch err.Code { case errcode.ErrorCodeUnauthorized, v2.ErrorCodeManifestUnknown, v2.ErrorCodeNameUnknown: return true } return false }
shouldV2Fallback returns true if this error is a reason to fall back to v1.
shouldV2Fallback
go
balena-os/balena-engine
distribution/errors.go
https://github.com/balena-os/balena-engine/blob/master/distribution/errors.go
Apache-2.0
func TranslatePullError(err error, ref reference.Named) error { switch v := err.(type) { case errcode.Errors: if len(v) != 0 { for _, extra := range v[1:] { logrus.Infof("Ignoring extra error returned from registry: %v", extra) } return TranslatePullError(v[0], ref) } case errcode.Error: switch v.Code { case errcode.ErrorCodeDenied, v2.ErrorCodeManifestUnknown, v2.ErrorCodeNameUnknown: return notFoundError{v, ref} } case xfer.DoNotRetry: return TranslatePullError(v.Err, ref) }
TranslatePullError is used to convert an error from a registry pull operation to an error representing the entire pull operation. Any error information which is not used by the returned error gets output to log at info level.
TranslatePullError
go
balena-os/balena-engine
distribution/errors.go
https://github.com/balena-os/balena-engine/blob/master/distribution/errors.go
Apache-2.0
func continueOnError(err error, mirrorEndpoint bool) bool { switch v := err.(type) { case errcode.Errors: if len(v) == 0 { return true } return continueOnError(v[0], mirrorEndpoint) case ErrNoSupport: return continueOnError(v.Err, mirrorEndpoint) case errcode.Error: return mirrorEndpoint || shouldV2Fallback(v) case *client.UnexpectedHTTPResponseError: return true case ImageConfigPullError: // ImageConfigPullError only happens with v2 images, v1 fallback is // unnecessary. // Failures from a mirror endpoint should result in fallback to the // canonical repo. return mirrorEndpoint case error: return !strings.Contains(err.Error(), strings.ToLower(syscall.ESRCH.Error())) }
continueOnError returns true if we should fallback to the next endpoint as a result of this error.
continueOnError
go
balena-os/balena-engine
distribution/errors.go
https://github.com/balena-os/balena-engine/blob/master/distribution/errors.go
Apache-2.0
func retryOnError(err error) error { switch v := err.(type) { case errcode.Errors: if len(v) != 0 { return retryOnError(v[0]) } case errcode.Error: switch v.Code { case errcode.ErrorCodeUnauthorized, errcode.ErrorCodeUnsupported, errcode.ErrorCodeDenied, errcode.ErrorCodeTooManyRequests, v2.ErrorCodeNameUnknown: return xfer.DoNotRetry{Err: err} } case *url.Error: switch v.Err { case auth.ErrNoBasicAuthCredentials, auth.ErrNoToken: return xfer.DoNotRetry{Err: v.Err} } return retryOnError(v.Err) case *client.UnexpectedHTTPResponseError: return xfer.DoNotRetry{Err: err} case error: if err == distribution.ErrBlobUnknown { return xfer.DoNotRetry{Err: err} } if strings.Contains(err.Error(), strings.ToLower(syscall.ENOSPC.Error())) { return xfer.DoNotRetry{Err: err} } }
retryOnError wraps the error in xfer.DoNotRetry if we should not retry the operation after this error.
retryOnError
go
balena-os/balena-engine
distribution/errors.go
https://github.com/balena-os/balena-engine/blob/master/distribution/errors.go
Apache-2.0
func detectManifestBlobMediaType(dt []byte) (string, error) { var mfst struct { MediaType string `json:"mediaType"` Manifests json.RawMessage `json:"manifests"` // oci index, manifest list Config json.RawMessage `json:"config"` // schema2 Manifest Layers json.RawMessage `json:"layers"` // schema2 Manifest FSLayers json.RawMessage `json:"fsLayers"` // schema1 Manifest } if err := json.Unmarshal(dt, &mfst); err != nil { return "", err } // We may have a media type specified in the json, in which case that should be used. // Docker types should generally have a media type set. // OCI (golang) types do not have a `mediaType` defined, and it is optional in the spec. // // `distribution.UnmarshalManifest`, which is used to unmarshal this for real, checks these media type values. // If the specified media type does not match it will error, and in some cases (docker media types) it is required. // So pretty much if we don't have a media type we can fall back to OCI. // This does have a special fallback for schema1 manifests just because it is easy to detect. switch mfst.MediaType { case schema2.MediaTypeManifest, specs.MediaTypeImageManifest: if mfst.Manifests != nil || mfst.FSLayers != nil { return "", fmt.Errorf(`media-type: %q should not have "manifests" or "fsLayers"`, mfst.MediaType) } return mfst.MediaType, nil case manifestlist.MediaTypeManifestList, specs.MediaTypeImageIndex: if mfst.Config != nil || mfst.Layers != nil || mfst.FSLayers != nil { return "", fmt.Errorf(`media-type: %q should not have "config", "layers", or "fsLayers"`, mfst.MediaType) } return mfst.MediaType, nil case schema1.MediaTypeManifest: if mfst.Manifests != nil || mfst.Layers != nil { return "", fmt.Errorf(`media-type: %q should not have "manifests" or "layers"`, mfst.MediaType) } return mfst.MediaType, nil default: if mfst.MediaType != "" { return mfst.MediaType, nil } } switch { case mfst.FSLayers != nil && mfst.Manifests == nil && mfst.Layers == nil && mfst.Config == nil: return schema1.MediaTypeManifest, nil case mfst.Config != nil && mfst.Manifests == nil && mfst.FSLayers == nil, mfst.Layers != nil && mfst.Manifests == nil && mfst.FSLayers == nil: return specs.MediaTypeImageManifest, nil case mfst.Config == nil && mfst.Layers == nil && mfst.FSLayers == nil: // fallback to index return specs.MediaTypeImageIndex, nil } return "", errors.New("media-type: cannot determine") }
This is used when the manifest store does not know the media type of a sha it was told to get. This would currently only happen when pulling by digest. The media type is needed so the blob can be unmarshalled properly.
detectManifestBlobMediaType
go
balena-os/balena-engine
distribution/manifest.go
https://github.com/balena-os/balena-engine/blob/master/distribution/manifest.go
Apache-2.0
func (e ImageConfigPullError) Error() string { return "error pulling image configuration: " + e.Err.Error() }
Error returns the error string for ImageConfigPullError.
Error
go
balena-os/balena-engine
distribution/pull_v2.go
https://github.com/balena-os/balena-engine/blob/master/distribution/pull_v2.go
Apache-2.0
func (lum *LayerUploadManager) SetConcurrency(concurrency int) { lum.tm.SetConcurrency(concurrency) }
SetConcurrency sets the max concurrent uploads for each push
SetConcurrency
go
balena-os/balena-engine
distribution/xfer/upload.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload.go
Apache-2.0
func NewLayerUploadManager(concurrencyLimit int, options ...func(*LayerUploadManager)) *LayerUploadManager { manager := LayerUploadManager{ tm: NewTransferManager(concurrencyLimit), waitDuration: time.Second, maxUploadAttempts: maxUploadAttempts, } for _, option := range options { option(&manager) } return &manager }
NewLayerUploadManager returns a new LayerUploadManager.
NewLayerUploadManager
go
balena-os/balena-engine
distribution/xfer/upload.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload.go
Apache-2.0
func WithMaxUploadAttempts(max int) func(*LayerUploadManager) { return func(dlm *LayerUploadManager) { dlm.maxUploadAttempts = max } }
WithMaxUploadAttempts configures the maximum number of upload attempts for a upload manager.
WithMaxUploadAttempts
go
balena-os/balena-engine
distribution/xfer/upload.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload.go
Apache-2.0
func (lum *LayerUploadManager) Upload(ctx context.Context, layers []UploadDescriptor, progressOutput progress.Output) error { var ( uploads []*uploadTransfer dedupDescriptors = make(map[string]*uploadTransfer) ) for _, descriptor := range layers { progress.Update(progressOutput, descriptor.ID(), "Preparing") key := descriptor.Key() if _, present := dedupDescriptors[key]; present { continue } xferFunc := lum.makeUploadFunc(descriptor) upload, watcher := lum.tm.Transfer(descriptor.Key(), xferFunc, progressOutput) defer upload.Release(watcher) uploads = append(uploads, upload.(*uploadTransfer)) dedupDescriptors[key] = upload.(*uploadTransfer) } for _, upload := range uploads { select { case <-ctx.Done(): return ctx.Err() case <-upload.Transfer.Done(): if upload.err != nil { return upload.err } } } for _, l := range layers { l.SetRemoteDescriptor(dedupDescriptors[l.Key()].remoteDescriptor) } return nil }
Upload is a blocking function which ensures the listed layers are present on the remote registry. It uses the string returned by the Key method to deduplicate uploads.
Upload
go
balena-os/balena-engine
distribution/xfer/upload.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload.go
Apache-2.0
func (e DoNotRetry) Error() string { return e.Err.Error() }
Error returns the stringified representation of the encapsulated error.
Error
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func IsDoNotRetryError(err error) bool { var dnr DoNotRetry return errors.As(err, &dnr) }
IsDoNotRetryError returns true if the error is caused by DoNotRetry error, and the transfer should not be retried.
IsDoNotRetryError
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func NewTransfer() Transfer { t := &transfer{ watchers: make(map[chan struct{}]*Watcher), running: make(chan struct{}), released: make(chan struct{}), broadcastSyncChan: make(chan struct{}), } // This uses context.Background instead of a caller-supplied context // so that a transfer won't be cancelled automatically if the client // which requested it is ^C'd (there could be other viewers). t.ctx, t.cancel = context.WithCancel(context.Background()) return t }
NewTransfer creates a new transfer.
NewTransfer
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (t *transfer) Broadcast(mainProgressChan <-chan progress.Progress) { for { var ( p progress.Progress ok bool ) select { case p, ok = <-mainProgressChan: default: // We've depleted the channel, so now we can handle // reads on broadcastSyncChan to let detaching watchers // know we're caught up. select { case <-t.broadcastSyncChan: continue case p, ok = <-mainProgressChan: } } t.mu.Lock() if ok { t.lastProgress = p t.hasLastProgress = true for _, w := range t.watchers { select { case w.signalChan <- struct{}{}: default: } } } else { t.broadcastDone = true } t.mu.Unlock() if !ok { close(t.running) return } } }
Broadcast copies the progress and error output to all viewers.
Broadcast
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (t *transfer) Watch(progressOutput progress.Output) *Watcher { t.mu.Lock() defer t.mu.Unlock() w := &Watcher{ releaseChan: make(chan struct{}), signalChan: make(chan struct{}), running: make(chan struct{}), } t.watchers[w.releaseChan] = w if t.broadcastDone { close(w.running) return w } go func() { defer func() { close(w.running) }() var ( done bool lastWritten progress.Progress hasLastWritten bool ) for { t.mu.Lock() hasLastProgress := t.hasLastProgress lastProgress := t.lastProgress t.mu.Unlock() // Make sure we don't write the last progress item // twice. if hasLastProgress && (!done || !hasLastWritten || lastProgress != lastWritten) { progressOutput.WriteProgress(lastProgress) lastWritten = lastProgress hasLastWritten = true } if done { return } select { case <-w.signalChan: case <-w.releaseChan: done = true // Since the watcher is going to detach, make // sure the broadcaster is caught up so we // don't miss anything. select { case t.broadcastSyncChan <- struct{}{}: case <-t.running: } case <-t.running: done = true } } }() return w }
Watch adds a watcher to the transfer. The supplied channel gets progress updates and is closed when the transfer finishes.
Watch
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (t *transfer) Release(watcher *Watcher) { t.mu.Lock() delete(t.watchers, watcher.releaseChan) if len(t.watchers) == 0 { if t.closed { // released may have been closed already if all // watchers were released, then another one was added // while waiting for a previous watcher goroutine to // finish. select { case <-t.released: default: close(t.released) } } else { t.cancel() } } t.mu.Unlock() close(watcher.releaseChan) // Block until the watcher goroutine completes <-watcher.running }
Release is the inverse of Watch; indicating that the watcher no longer wants to be notified about the progress of the transfer. All calls to Watch must be paired with later calls to Release so that the lifecycle of the transfer is properly managed.
Release
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (t *transfer) Context() context.Context { return t.ctx }
Context returns the context associated with the transfer.
Context
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (t *transfer) Close() { t.mu.Lock() t.closed = true if len(t.watchers) == 0 { close(t.released) } t.mu.Unlock() }
Close is called by the transfer manager when the transfer is no longer being tracked.
Close
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func NewTransferManager(concurrencyLimit int) TransferManager { return &transferManager{ concurrencyLimit: concurrencyLimit, transfers: make(map[string]Transfer), } }
NewTransferManager returns a new TransferManager.
NewTransferManager
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (tm *transferManager) SetConcurrency(concurrency int) { tm.mu.Lock() tm.concurrencyLimit = concurrency tm.mu.Unlock() }
SetConcurrency sets the concurrencyLimit
SetConcurrency
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (tm *transferManager) Transfer(key string, xferFunc DoFunc, progressOutput progress.Output) (Transfer, *Watcher) { tm.mu.Lock() defer tm.mu.Unlock() for { xfer, present := tm.transfers[key] if !present { break } // Transfer is already in progress. watcher := xfer.Watch(progressOutput) select { case <-xfer.Context().Done(): // We don't want to watch a transfer that has been cancelled. // Wait for it to be removed from the map and try again. xfer.Release(watcher) tm.mu.Unlock() // The goroutine that removes this transfer from the // map is also waiting for xfer.Done(), so yield to it. // This could be avoided by adding a Closed method // to Transfer to allow explicitly waiting for it to be // removed the map, but forcing a scheduling round in // this very rare case seems better than bloating the // interface definition. runtime.Gosched() <-xfer.Done() tm.mu.Lock() default: return xfer, watcher } } start := make(chan struct{}) inactive := make(chan struct{}) if tm.concurrencyLimit == 0 || tm.activeTransfers < tm.concurrencyLimit { close(start) tm.activeTransfers++ } else { tm.waitingTransfers = append(tm.waitingTransfers, start) } mainProgressChan := make(chan progress.Progress) xfer := xferFunc(mainProgressChan, start, inactive) watcher := xfer.Watch(progressOutput) go xfer.Broadcast(mainProgressChan) tm.transfers[key] = xfer // When the transfer is finished, remove from the map. go func() { for { select { case <-inactive: tm.mu.Lock() tm.inactivate(start) tm.mu.Unlock() inactive = nil case <-xfer.Done(): tm.mu.Lock() if inactive != nil { tm.inactivate(start) } delete(tm.transfers, key) tm.mu.Unlock() xfer.Close() return } } }() return xfer, watcher }
Transfer checks if a transfer matching the given key is in progress. If not, it starts one by calling xferFunc. The caller supplies a channel which receives progress output from the transfer.
Transfer
go
balena-os/balena-engine
distribution/xfer/transfer.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/transfer.go
Apache-2.0
func (d *mockDownloadDescriptor) Key() string { return d.id }
Key returns the key used to deduplicate downloads.
Key
go
balena-os/balena-engine
distribution/xfer/download_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download_test.go
Apache-2.0
func (d *mockDownloadDescriptor) ID() string { return d.id }
ID returns the ID for display purposes.
ID
go
balena-os/balena-engine
distribution/xfer/download_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download_test.go
Apache-2.0
func (d *mockDownloadDescriptor) DiffID() (layer.DiffID, error) { if d.diffID != "" { return d.diffID, nil } return "", errors.New("no diffID available") }
DiffID should return the DiffID for this layer, or an error if it is unknown (for example, if it has not been downloaded before).
DiffID
go
balena-os/balena-engine
distribution/xfer/download_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download_test.go
Apache-2.0
func (d *mockDownloadDescriptor) Download(ctx context.Context, progressOutput progress.Output) (io.ReadCloser, int64, error) { if d.currentDownloads != nil { defer atomic.AddInt32(d.currentDownloads, -1) if atomic.AddInt32(d.currentDownloads, 1) > maxDownloadConcurrency { return nil, 0, errors.New("concurrency limit exceeded") } } // Sleep a bit to simulate a time-consuming download. for i := int64(0); i <= 10; i++ { select { case <-ctx.Done(): return nil, 0, ctx.Err() case <-time.After(10 * time.Millisecond): progressOutput.WriteProgress(progress.Progress{ID: d.ID(), Action: "Downloading", Current: i, Total: 10}) } } if d.retries < d.simulateRetries { d.retries++ return nil, 0, fmt.Errorf("simulating download attempt %d/%d", d.retries, d.simulateRetries) } return d.mockTarStream(), 0, nil }
Download is called to perform the download.
Download
go
balena-os/balena-engine
distribution/xfer/download_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download_test.go
Apache-2.0
func (u *mockUploadDescriptor) Key() string { return u.diffID.String() }
Key returns the key used to deduplicate downloads.
Key
go
balena-os/balena-engine
distribution/xfer/upload_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload_test.go
Apache-2.0
func (u *mockUploadDescriptor) ID() string { return u.diffID.String() }
ID returns the ID for display purposes.
ID
go
balena-os/balena-engine
distribution/xfer/upload_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload_test.go
Apache-2.0
func (u *mockUploadDescriptor) DiffID() layer.DiffID { return u.diffID }
DiffID should return the DiffID for this layer.
DiffID
go
balena-os/balena-engine
distribution/xfer/upload_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload_test.go
Apache-2.0
func (u *mockUploadDescriptor) SetRemoteDescriptor(remoteDescriptor distribution.Descriptor) { }
SetRemoteDescriptor is not used in the mock.
SetRemoteDescriptor
go
balena-os/balena-engine
distribution/xfer/upload_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload_test.go
Apache-2.0
func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) { if u.currentUploads != nil { defer atomic.AddInt32(u.currentUploads, -1) if atomic.AddInt32(u.currentUploads, 1) > maxUploadConcurrency { return distribution.Descriptor{}, errors.New("concurrency limit exceeded") } } // Sleep a bit to simulate a time-consuming upload. for i := int64(0); i <= 10; i++ { select { case <-ctx.Done(): return distribution.Descriptor{}, ctx.Err() case <-time.After(10 * time.Millisecond): progressOutput.WriteProgress(progress.Progress{ID: u.ID(), Current: i, Total: 10}) } } if u.simulateRetries != 0 { u.simulateRetries-- return distribution.Descriptor{}, errors.New("simulating retry") } return distribution.Descriptor{}, nil }
Upload is called to perform the upload.
Upload
go
balena-os/balena-engine
distribution/xfer/upload_test.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/upload_test.go
Apache-2.0
func (ldm *LayerDownloadManager) SetConcurrency(concurrency int) { ldm.tm.SetConcurrency(concurrency) }
SetConcurrency sets the max concurrent downloads for each pull
SetConcurrency
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func NewLayerDownloadManager(layerStores map[string]layer.Store, concurrencyLimit int, options ...func(*LayerDownloadManager)) *LayerDownloadManager { manager := LayerDownloadManager{ layerStores: layerStores, tm: NewTransferManager(concurrencyLimit), waitDuration: time.Second, maxDownloadAttempts: maxDownloadAttempts, } for _, option := range options { option(&manager) } return &manager }
NewLayerDownloadManager returns a new LayerDownloadManager.
NewLayerDownloadManager
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func WithMaxDownloadAttempts(max int) func(*LayerDownloadManager) { return func(dlm *LayerDownloadManager) { dlm.maxDownloadAttempts = max } }
WithMaxDownloadAttempts configures the maximum number of download attempts for a download manager.
WithMaxDownloadAttempts
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func (d *downloadTransfer) result() (layer.Layer, error) { return d.layer, d.err }
result returns the layer resulting from the download, if the download and registration were successful.
result
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func (ldm *LayerDownloadManager) Download(ctx context.Context, initialRootFS image.RootFS, os string, layers []DownloadDescriptor, progressOutput progress.Output) (image.RootFS, func(), error) { var ( topLayer layer.Layer topDownload *downloadTransfer watcher *Watcher missingLayer bool transferKey = "" downloadsByKey = make(map[string]*downloadTransfer) ) // Assume that the operating system is the host OS if blank, and validate it // to ensure we don't cause a panic by an invalid index into the layerstores. if os == "" { os = runtime.GOOS } if !system.IsOSSupported(os) { return image.RootFS{}, nil, system.ErrNotSupportedOperatingSystem } totalProgress := progress.NewProgressSink(progressOutput, 0, "Total", "") rootFS := initialRootFS for _, descriptor := range layers { key := descriptor.Key() transferKey += key if !missingLayer { missingLayer = true diffID, err := descriptor.DiffID() if err == nil { getRootFS := rootFS getRootFS.Append(diffID) l, err := ldm.layerStores[os].Get(getRootFS.ChainID()) if err == nil { // Layer already exists. logrus.Debugf("Layer already exists: %s", descriptor.ID()) progress.Update(progressOutput, descriptor.ID(), "Already exists") if topLayer != nil { layer.ReleaseAndLog(ldm.layerStores[os], topLayer) } topLayer = l missingLayer = false rootFS.Append(diffID) // Register this repository as a source of this layer. withRegistered, hasRegistered := descriptor.(DownloadDescriptorWithRegistered) if hasRegistered { // As layerstore may set the driver withRegistered.Registered(diffID) } continue } } } // Does this layer have the same data as a previous layer in // the stack? If so, avoid downloading it more than once. var topDownloadUncasted Transfer if existingDownload, ok := downloadsByKey[key]; ok { xferFunc := ldm.makeDownloadFuncFromDownload(descriptor, existingDownload, topDownload, os) defer topDownload.Transfer.Release(watcher) topDownloadUncasted, watcher = ldm.tm.Transfer(transferKey, xferFunc, progressOutput) topDownload = topDownloadUncasted.(*downloadTransfer) continue } // Layer is not known to exist - download and register it. progress.Update(progressOutput, descriptor.ID(), "Pulling fs layer") totalProgress.Size += descriptor.Size() var xferFunc DoFunc if topDownload != nil { xferFunc = ldm.makeDownloadFunc(descriptor, "", topDownload, os, totalProgress) defer topDownload.Transfer.Release(watcher) } else { xferFunc = ldm.makeDownloadFunc(descriptor, rootFS.ChainID(), nil, os, totalProgress) } topDownloadUncasted, watcher = ldm.tm.Transfer(transferKey, xferFunc, progressOutput) topDownload = topDownloadUncasted.(*downloadTransfer) downloadsByKey[key] = topDownload } if topDownload == nil { return rootFS, func() { if topLayer != nil { layer.ReleaseAndLog(ldm.layerStores[os], topLayer) } }, nil } // Won't be using the list built up so far - will generate it // from downloaded layers instead. rootFS.DiffIDs = []layer.DiffID{} defer func() { if topLayer != nil { layer.ReleaseAndLog(ldm.layerStores[os], topLayer) } }() select { case <-ctx.Done(): topDownload.Transfer.Release(watcher) return rootFS, func() {}, ctx.Err() case <-topDownload.Done(): break } l, err := topDownload.result() if err != nil { topDownload.Transfer.Release(watcher) return rootFS, func() {}, err } // Must do this exactly len(layers) times, so we don't include the // base layer on Windows. for range layers { if l == nil { topDownload.Transfer.Release(watcher) return rootFS, func() {}, errors.New("internal error: too few parent layers") } rootFS.DiffIDs = append([]layer.DiffID{l.DiffID()}, rootFS.DiffIDs...) l = l.Parent() } return rootFS, func() { topDownload.Transfer.Release(watcher) }, err }
Download is a blocking function which ensures the requested layers are present in the layer store. It uses the string returned by the Key method to deduplicate downloads. If a given layer is not already known to present in the layer store, and the key is not used by an in-progress download, the Download method is called to get the layer tar data. Layers are then registered in the appropriate order. The caller must call the returned release function once it is done with the returned RootFS object.
Download
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor, parentLayer layer.ChainID, parentDownload *downloadTransfer, os string, totalProgress io.Writer) DoFunc { return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { d := &downloadTransfer{ Transfer: NewTransfer(), layerStore: ldm.layerStores[os], } go func() { defer func() { close(progressChan) }() progressOutput := progress.ChanOutput(progressChan) select { case <-start: default: progress.Update(progressOutput, descriptor.ID(), "Waiting") <-start } if parentDownload != nil { // Did the parent download already fail or get // cancelled? select { case <-parentDownload.Done(): _, err := parentDownload.result() if err != nil { d.err = err return } default: } } var ( downloadReader io.ReadCloser size int64 err error retries int ) defer descriptor.Close() for { downloadReader, size, err = descriptor.Download(d.Transfer.Context(), progressOutput) if err == nil { break } // If an error was returned because the context // was cancelled, we shouldn't retry. select { case <-d.Transfer.Context().Done(): d.err = err return default: } retries++ if _, isDNR := err.(DoNotRetry); isDNR || retries > ldm.maxDownloadAttempts { logrus.Errorf("Download failed after %d attempts: %v", retries, err) d.err = err return } logrus.Infof("Download failed, retrying (%d/%d): %v", retries, ldm.maxDownloadAttempts, err) delay := retries * 5 ticker := time.NewTicker(ldm.waitDuration) selectLoop: for { progress.Updatef(progressOutput, descriptor.ID(), "Retrying in %d second%s", delay, (map[bool]string{true: "s"})[delay != 1]) select { case <-ticker.C: delay-- if delay == 0 { ticker.Stop() break selectLoop } case <-d.Transfer.Context().Done(): ticker.Stop() d.err = errors.New("download cancelled during retry delay") return } } } close(inactive) if parentDownload != nil { select { case <-d.Transfer.Context().Done(): d.err = errors.New("layer registration cancelled") downloadReader.Close() return case <-parentDownload.Done(): } l, err := parentDownload.result() if err != nil { d.err = err downloadReader.Close() return } parentLayer = l.ChainID() } reader := progress.NewProgressReader(ioutils.NewCancelReadCloser(d.Transfer.Context(), downloadReader), progressOutput, size, descriptor.ID(), "Extracting") defer reader.Close() inflatedLayerData, err := archive.DecompressStream(io.TeeReader(reader, totalProgress)) if err != nil { d.err = fmt.Errorf("could not get decompression stream: %v", err) return } defer inflatedLayerData.Close() deltaBase := descriptor.DeltaBase() layerData := DecorateWithDeltaPatcher(inflatedLayerData, deltaBase) var src distribution.Descriptor if fs, ok := descriptor.(distribution.Describable); ok { src = fs.Descriptor() } if ds, ok := d.layerStore.(layer.DescribableStore); ok { d.layer, err = ds.RegisterWithDescriptor(layerData, parentLayer, src) } else { d.layer, err = d.layerStore.Register(layerData, parentLayer) } if err != nil { select { case <-d.Transfer.Context().Done(): d.err = errors.New("layer registration cancelled") default: d.err = fmt.Errorf("failed to register layer: %v", err) } return } progress.Update(progressOutput, descriptor.ID(), "Pull complete") withRegistered, hasRegistered := descriptor.(DownloadDescriptorWithRegistered) if hasRegistered { withRegistered.Registered(d.layer.DiffID()) } // Doesn't actually need to be its own goroutine, but // done like this so we can defer close(c). go func() { <-d.Transfer.Released() if d.layer != nil { layer.ReleaseAndLog(d.layerStore, d.layer) } }() }() return d } }
makeDownloadFunc returns a function that performs the layer download and registration. If parentDownload is non-nil, it waits for that download to complete before the registration step, and registers the downloaded data on top of parentDownload's resulting layer. Otherwise, it registers the layer on top of the ChainID given by parentLayer.
makeDownloadFunc
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func (ldm *LayerDownloadManager) makeDownloadFuncFromDownload(descriptor DownloadDescriptor, sourceDownload *downloadTransfer, parentDownload *downloadTransfer, os string) DoFunc { return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { d := &downloadTransfer{ Transfer: NewTransfer(), layerStore: ldm.layerStores[os], } go func() { defer func() { close(progressChan) }() <-start close(inactive) select { case <-d.Transfer.Context().Done(): d.err = errors.New("layer registration cancelled") return case <-parentDownload.Done(): } l, err := parentDownload.result() if err != nil { d.err = err return } parentLayer := l.ChainID() // sourceDownload should have already finished if // parentDownload finished, but wait for it explicitly // to be sure. select { case <-d.Transfer.Context().Done(): d.err = errors.New("layer registration cancelled") return case <-sourceDownload.Done(): } l, err = sourceDownload.result() if err != nil { d.err = err return } layerReader, err := l.TarStream() if err != nil { d.err = err return } defer layerReader.Close() var src distribution.Descriptor if fs, ok := l.(distribution.Describable); ok { src = fs.Descriptor() } if ds, ok := d.layerStore.(layer.DescribableStore); ok { d.layer, err = ds.RegisterWithDescriptor(layerReader, parentLayer, src) } else { d.layer, err = d.layerStore.Register(layerReader, parentLayer) } if err != nil { d.err = fmt.Errorf("failed to register layer: %v", err) return } withRegistered, hasRegistered := descriptor.(DownloadDescriptorWithRegistered) if hasRegistered { withRegistered.Registered(d.layer.DiffID()) } // Doesn't actually need to be its own goroutine, but // done like this so we can defer close(c). go func() { <-d.Transfer.Released() if d.layer != nil { layer.ReleaseAndLog(d.layerStore, d.layer) } }() }() return d } }
makeDownloadFuncFromDownload returns a function that performs the layer registration when the layer data is coming from an existing download. It waits for sourceDownload and parentDownload to complete, and then reregisters the data from sourceDownload's top layer on top of parentDownload. This function does not log progress output because it would interfere with the progress reporting for sourceDownload, which has the same Key.
makeDownloadFuncFromDownload
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func DecorateWithDeltaPatcher(layerData io.ReadCloser, deltaBase io.ReadSeeker) io.ReadCloser { if deltaBase != nil { pR, pW := io.Pipe() go func() { tr := tar.NewReader(layerData) _, err := tr.Next() if err == io.EOF { err = errors.New("unexpected EOF, invalid delta tar archive") pW.CloseWithError(err) return } err = librsync.Patch(deltaBase, tr, pW) if err != nil { err = fmt.Errorf("applying delta: %w", err) pW.CloseWithError(err) } pW.Close() }() return pR } return layerData }
DecorateWithDeltaPatcher returns an io.ReadCloser that applies a delta. The delta itself is read from layerData. If deltaBase is nil, this returns layerData itself -- in other words, this transparently handles the case of being passed non-delta data. Errors while applying the delta are reported when reading the returned io.ReadCloser.
DecorateWithDeltaPatcher
go
balena-os/balena-engine
distribution/xfer/download.go
https://github.com/balena-os/balena-engine/blob/master/distribution/xfer/download.go
Apache-2.0
func WriteDistributionProgress(cancelFunc func(), outStream io.Writer, progressChan <-chan progress.Progress) { progressOutput := streamformatter.NewJSONProgressOutput(outStream, false) operationCancelled := false for prog := range progressChan { if err := progressOutput.WriteProgress(prog); err != nil && !operationCancelled { // don't log broken pipe errors as this is the normal case when a client aborts if isBrokenPipe(err) { logrus.Info("Pull session cancelled") } else { logrus.Errorf("error writing progress to client: %v", err) } cancelFunc() operationCancelled = true // Don't return, because we need to continue draining // progressChan until it's closed to avoid a deadlock. } } }
WriteDistributionProgress is a helper for writing progress from chan to JSON stream with an optional cancel function.
WriteDistributionProgress
go
balena-os/balena-engine
distribution/utils/progress.go
https://github.com/balena-os/balena-engine/blob/master/distribution/utils/progress.go
Apache-2.0
func CheckV2MetadataHMAC(meta *V2Metadata, key []byte) bool { if len(meta.HMAC) == 0 || len(key) == 0 { return len(meta.HMAC) == 0 && len(key) == 0 } mac := hmac.New(sha256.New, key) mac.Write([]byte(meta.Digest)) mac.Write([]byte(meta.SourceRepository)) expectedMac := mac.Sum(nil) storedMac, err := hex.DecodeString(meta.HMAC) if err != nil { return false } return hmac.Equal(storedMac, expectedMac) }
CheckV2MetadataHMAC returns true if the given "meta" is tagged with a hmac hashed by the given "key".
CheckV2MetadataHMAC
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func ComputeV2MetadataHMAC(key []byte, meta *V2Metadata) string { if len(key) == 0 || meta == nil { return "" } mac := hmac.New(sha256.New, key) mac.Write([]byte(meta.Digest)) mac.Write([]byte(meta.SourceRepository)) return hex.EncodeToString(mac.Sum(nil)) }
ComputeV2MetadataHMAC returns a hmac for the given "meta" hash by the given key.
ComputeV2MetadataHMAC
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func ComputeV2MetadataHMACKey(authConfig *types.AuthConfig) ([]byte, error) { if authConfig == nil { return nil, nil } key := authConfigKeyInput{ Username: authConfig.Username, Password: authConfig.Password, Auth: authConfig.Auth, IdentityToken: authConfig.IdentityToken, RegistryToken: authConfig.RegistryToken, } buf, err := json.Marshal(&key) if err != nil { return nil, err } return []byte(digest.FromBytes(buf)), nil }
ComputeV2MetadataHMACKey returns a key for the given "authConfig" that can be used to hash v2 metadata entries.
ComputeV2MetadataHMACKey
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func NewV2MetadataService(store Store) V2MetadataService { return &v2MetadataService{ store: store, } }
NewV2MetadataService creates a new diff ID to v2 metadata mapping service.
NewV2MetadataService
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func (serv *v2MetadataService) GetMetadata(diffID layer.DiffID) ([]V2Metadata, error) { if serv.store == nil { return nil, errors.New("no metadata storage") } jsonBytes, err := serv.store.Get(serv.diffIDNamespace(), serv.diffIDKey(diffID)) if err != nil { return nil, err } var metadata []V2Metadata if err := json.Unmarshal(jsonBytes, &metadata); err != nil { return nil, err } return metadata, nil }
GetMetadata finds the metadata associated with a layer DiffID.
GetMetadata
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func (serv *v2MetadataService) GetDiffID(dgst digest.Digest) (layer.DiffID, error) { if serv.store == nil { return layer.DiffID(""), errors.New("no metadata storage") } diffIDBytes, err := serv.store.Get(serv.digestNamespace(), serv.digestKey(dgst)) if err != nil { return layer.DiffID(""), err } return layer.DiffID(diffIDBytes), nil }
GetDiffID finds a layer DiffID from a digest.
GetDiffID
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func (serv *v2MetadataService) Add(diffID layer.DiffID, metadata V2Metadata) error { if serv.store == nil { // Support a service which has no backend storage, in this case // an add becomes a no-op. // TODO: implement in memory storage return nil } oldMetadata, err := serv.GetMetadata(diffID) if err != nil { oldMetadata = nil } newMetadata := make([]V2Metadata, 0, len(oldMetadata)+1) // Copy all other metadata to new slice for _, oldMeta := range oldMetadata { if oldMeta != metadata { newMetadata = append(newMetadata, oldMeta) } } newMetadata = append(newMetadata, metadata) if len(newMetadata) > maxMetadata { newMetadata = newMetadata[len(newMetadata)-maxMetadata:] } jsonBytes, err := json.Marshal(newMetadata) if err != nil { return err } err = serv.store.Set(serv.diffIDNamespace(), serv.diffIDKey(diffID), jsonBytes) if err != nil { return err } return serv.store.Set(serv.digestNamespace(), serv.digestKey(metadata.Digest), []byte(diffID)) }
Add associates metadata with a layer DiffID. If too many metadata entries are present, the oldest one is dropped.
Add
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func (serv *v2MetadataService) TagAndAdd(diffID layer.DiffID, hmacKey []byte, meta V2Metadata) error { meta.HMAC = ComputeV2MetadataHMAC(hmacKey, &meta) return serv.Add(diffID, meta) }
TagAndAdd amends the given "meta" for hmac hashed by the given "hmacKey" and associates it with a layer DiffID. If too many metadata entries are present, the oldest one is dropped.
TagAndAdd
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func (serv *v2MetadataService) Remove(metadata V2Metadata) error { if serv.store == nil { // Support a service which has no backend storage, in this case // an remove becomes a no-op. // TODO: implement in memory storage return nil } diffID, err := serv.GetDiffID(metadata.Digest) if err != nil { return err } oldMetadata, err := serv.GetMetadata(diffID) if err != nil { oldMetadata = nil } newMetadata := make([]V2Metadata, 0, len(oldMetadata)) // Copy all other metadata to new slice for _, oldMeta := range oldMetadata { if oldMeta != metadata { newMetadata = append(newMetadata, oldMeta) } } if len(newMetadata) == 0 { return serv.store.Delete(serv.diffIDNamespace(), serv.diffIDKey(diffID)) } jsonBytes, err := json.Marshal(newMetadata) if err != nil { return err } return serv.store.Set(serv.diffIDNamespace(), serv.diffIDKey(diffID), jsonBytes) }
Remove disassociates a metadata entry from a layer DiffID.
Remove
go
balena-os/balena-engine
distribution/metadata/v2_metadata_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v2_metadata_service.go
Apache-2.0
func NewV1IDService(store Store) *V1IDService { return &V1IDService{ store: store, } }
NewV1IDService creates a new V1 ID mapping service.
NewV1IDService
go
balena-os/balena-engine
distribution/metadata/v1_id_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v1_id_service.go
Apache-2.0
func (idserv *V1IDService) namespace() string { return "v1id" }
namespace returns the namespace used by this service.
namespace
go
balena-os/balena-engine
distribution/metadata/v1_id_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v1_id_service.go
Apache-2.0
func (idserv *V1IDService) Get(v1ID, registry string) (layer.DiffID, error) { if idserv.store == nil { return "", errors.New("no v1IDService storage") } if err := v1.ValidateID(v1ID); err != nil { return layer.DiffID(""), err } idBytes, err := idserv.store.Get(idserv.namespace(), registry+","+v1ID) if err != nil { return layer.DiffID(""), err } return layer.DiffID(idBytes), nil }
Get finds a layer by its V1 ID.
Get
go
balena-os/balena-engine
distribution/metadata/v1_id_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v1_id_service.go
Apache-2.0
func (idserv *V1IDService) Set(v1ID, registry string, id layer.DiffID) error { if idserv.store == nil { return nil } if err := v1.ValidateID(v1ID); err != nil { return err } return idserv.store.Set(idserv.namespace(), registry+","+v1ID, []byte(id)) }
Set associates an image with a V1 ID.
Set
go
balena-os/balena-engine
distribution/metadata/v1_id_service.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/v1_id_service.go
Apache-2.0
func NewFSMetadataStore(basePath string) (*FSMetadataStore, error) { if err := os.MkdirAll(basePath, 0700); err != nil { return nil, err } return &FSMetadataStore{ basePath: basePath, }, nil }
NewFSMetadataStore creates a new filesystem-based metadata store.
NewFSMetadataStore
go
balena-os/balena-engine
distribution/metadata/metadata.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/metadata.go
Apache-2.0
func (store *FSMetadataStore) Get(namespace string, key string) ([]byte, error) { store.RLock() defer store.RUnlock() return ioutil.ReadFile(store.path(namespace, key)) }
Get retrieves data by namespace and key. The data is read from a file named after the key, stored in the namespace's directory.
Get
go
balena-os/balena-engine
distribution/metadata/metadata.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/metadata.go
Apache-2.0
func (store *FSMetadataStore) Set(namespace, key string, value []byte) error { store.Lock() defer store.Unlock() path := store.path(namespace, key) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } return ioutils.AtomicWriteFile(path, value, 0644) }
Set writes data indexed by namespace and key. The data is written to a file named after the key, stored in the namespace's directory.
Set
go
balena-os/balena-engine
distribution/metadata/metadata.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/metadata.go
Apache-2.0
func (store *FSMetadataStore) Delete(namespace, key string) error { store.Lock() defer store.Unlock() path := store.path(namespace, key) return os.Remove(path) }
Delete removes data indexed by namespace and key. The data file named after the key, stored in the namespace's directory is deleted.
Delete
go
balena-os/balena-engine
distribution/metadata/metadata.go
https://github.com/balena-os/balena-engine/blob/master/distribution/metadata/metadata.go
Apache-2.0