// readBundle reads an Bundle from reader.
338599
func readBundle(reader *bufio.Reader, start *int, end int) (*Bundle, error) {
	// Read the '#bundle' OSC string
	startTag, n, err := readPaddedString(reader)
	if err != nil {
		return nil, err
	}
	*start += n

	if startTag != bundleTagString {
		return nil, fmt.Errorf("Invalid bundle start tag: %s", startTag)
	}

	// Read the timetag
	var timeTag uint64
	if err := binary.Read(reader, binary.BigEndian, &timeTag); err != nil {
		return nil, err
	}
	*start += 8

	// Create a new bundle
	bundle := NewBundle(timetagToTime(timeTag))

	// Read until the end of the buffer
	for *start < end {
		// Read the size of the bundle element
		var length int32
		if err := binary.Read(reader, binary.BigEndian, &length); err != nil {
			return nil, err
		}
		*start += 4

		p, err := readPacket(reader, start, end)
		if err != nil {
			return nil, err
		}
		if err = bundle.Append(p); err != nil {
			return nil, err
		}
	}

	return bundle, nil
}
1045167
func parseBundle(data []byte, sender net.Addr, limit int32) (Bundle, error) {
	b := Bundle{}

	// If 0 <= limit < 16 this is an error.
	// We have to be able to read at least the bundle tag and a timetag.
	if (limit >= 0) && (limit < int32(len(BundleTag)+1+TimetagSize)) {
		return b, errors.New("limit must be >= 16 or < 0")
	}

	data, err := sliceBundleTag(data)
	if err != nil {
		return b, errors.Wrap(err, "slice bundle tag")
	}

	tt, err := ReadTimetag(data)
	if err != nil {
		return b, errors.Wrap(err, "read timetag")
	}
	b.Timetag = tt
	data = data[8:]

	// We are limited to only reading the bundle tag and the timetag.
	if limit == 16 {
		return b, nil
	}

	// We take away 16 from limit so that readPackets doesn't have to know we have already read 16 bytes.
	packets, err := readPackets(data, sender, limit-16)
	if err != nil {
		return b, errors.Wrap(err, "read packets")
	}
	b.Packets = packets

	return b, nil
}
751037
func (s *S3Location) SetBundleType(v string) *S3Location {
	s.BundleType = &v
	return s
}
191011
func (c *bundles) Create(bundle *v1.Bundle) (result *v1.Bundle, err error) {
	result = &v1.Bundle{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("bundles").
		Body(bundle).
		Do().
		Into(result)
	return
}
130986
func (ovsif *ovsExec) bundle(flows []string) error {
	if len(flows) == 0 {
		return nil
	}

	_, err := ovsif.execWithStdin(OVS_OFCTL, flows, "bundle", ovsif.bridge, "-")
	return err
}
1113899
func (c *Controller) ProcessBundle(logger *zap.Logger, bundle *smith_v1.Bundle) (bool /*external*/, bool /*retriable*/, error) {
	st := bundleSyncTask{
		logger:                          logger,
		bundleClient:                    c.BundleClient,
		smartClient:                     c.SmartClient,
		checker:                         c.Rc,
		store:                           c.Store,
		specChecker:                     c.SpecChecker,
		bundle:                          bundle,
		pluginContainers:                c.PluginContainers,
		scheme:                          c.Scheme,
		catalog:                         c.Catalog,
		bundleTransitionCounter:         c.BundleTransitionCounter,
		bundleResourceTransitionCounter: c.BundleResourceTransitionCounter,
		recorder:                        c.Recorder,
	}

	var external bool
	var retriable bool
	var err error
	if st.bundle.DeletionTimestamp != nil {
		external, retriable, err = st.processDeleted()
	} else {
		external, retriable, err = st.processNormal()
	}
	if err != nil {
		cause := errors.Cause(err)
		// short circuit on conflicts
		if api_errors.IsConflict(cause) {
			return external, retriable, err
		}
		// proceed to handleProcessResult() for all other errors
	}

	// Updates bundle status
	handleProcessRetriable, handleProcessErr := st.handleProcessResult(retriable, err)

	// Inspect the resources for failures. They can fail for many different reasons.
	// The priority of errors to bubble up to the ctrl layer are:
	//  1. processDeleted/processNormal errors
	//  2. Internal resource processing errors are raised first
	//  3. External resource processing errors are raised last
	//  4. handleProcessResult errors of any sort.

	// Handle the errors from processDeleted/processNormal, taking precedence
	// over the handleProcessErr if any.
	if err != nil {
		if handleProcessErr != nil {
			st.logger.Error("Error processing Bundle", zap.Error(handleProcessErr))
		}

		return external, retriable || handleProcessRetriable, err
	}

	// Inspect resources, returning an error if necessary
	allExternalErrors := true
	hasRetriableResourceErr := false
	var failedResources []string
	for resName, resInfo := range st.processedResources {
		resErr := resInfo.fetchError()

		if resErr != nil {
			allExternalErrors = allExternalErrors && resErr.isExternalError
			hasRetriableResourceErr = hasRetriableResourceErr || resErr.isRetriableError
			failedResources = append(failedResources, string(resName))
		}
	}
	if len(failedResources) > 0 {
		if handleProcessErr != nil {
			st.logger.Error("Error processing Bundle", zap.Error(handleProcessErr))
		}
		// stable output
		sort.Strings(failedResources)
		err := errors.Errorf("error processing resource(s): %q", failedResources)
		return allExternalErrors, hasRetriableResourceErr || handleProcessRetriable, err
	}

	// Otherwise, return the result from handleProcessResult
	return false, handleProcessRetriable, handleProcessErr
}
117471
func ValidBundle(bundle Bundle) error {
	var totalSum int64

	sigs := make(map[Hash][]Trytes)
	k := kerl.NewKerl()

	lastIndex := uint64(len(bundle) - 1)
	for i := range bundle {
		tx := &bundle[i]
		totalSum += tx.Value

		if tx.CurrentIndex != uint64(i) {
			return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have current index %d but got %d", i, i, tx.CurrentIndex)
		}
		if tx.LastIndex != lastIndex {
			return errors.Wrapf(ErrInvalidBundle, "expected tx at index %d to have last index %d but got %d", i, lastIndex, tx.LastIndex)
		}

		txTrits := MustTrytesToTrits(transaction.MustTransactionToTrytes(tx)[2187 : 2187+162])
		k.Absorb(txTrits)

		// continue if output or signature txbundle bundle
		if tx.Value >= 0 {
			continue
		}

		// here we have an input transaction (negative value)
		sigs[tx.Address] = append(sigs[tx.Address], tx.SignatureMessageFragment)

		// find the subsequent txs containing the remaining signature
		// message fragments for this input transaction
		for j := i; j < len(bundle)-1; j++ {
			tx2 := &bundle[j+1]

			// check if the tx is part of the input transaction
			if tx2.Address == tx.Address && tx2.Value == 0 {
				// append the signature message fragment
				sigs[tx.Address] = append(sigs[tx.Address], tx2.SignatureMessageFragment)
			}
		}
	}

	// sum of all transaction must be 0
	if totalSum != 0 {
		return errors.Wrapf(ErrInvalidBundle, "bundle total sum should be 0 but got %d", totalSum)
	}

	bundleHashTrits, err := k.Squeeze(HashTrinarySize)
	if err != nil {
		return err
	}

	bundleHash := MustTritsToTrytes(bundleHashTrits)

	if bundleHash != bundle[0].Bundle {
		return ErrInvalidBundleHash
	}

	// validate the signatures
	valid, err := ValidateBundleSignatures(bundle)
	if err != nil {
		return err
	}

	if !valid {
		return ErrInvalidSignature
	}

	return nil
}
1183279
func (s *BundleStore) GetBundlesByObject(gk schema.GroupKind, namespace, name string) ([]*smith_v1.Bundle, error) {
	return s.getBundles(byObjectIndexName, byObjectIndexKey(gk, namespace, name))
}
885355
func DeployBundle(ctx context.Context, dockerCli command.Cli, opts options.Deploy) error {
	bundle, err := loadBundlefile(dockerCli.Err(), opts.Namespace, opts.Bundlefile)
	if err != nil {
		return err
	}

	if err := checkDaemonIsSwarmManager(ctx, dockerCli); err != nil {
		return err
	}

	namespace := convert.NewNamespace(opts.Namespace)

	if opts.Prune {
		services := map[string]struct{}{}
		for service := range bundle.Services {
			services[service] = struct{}{}
		}
		pruneServices(ctx, dockerCli, namespace, services)
	}

	networks := make(map[string]types.NetworkCreate)
	for _, service := range bundle.Services {
		for _, networkName := range service.Networks {
			networks[namespace.Scope(networkName)] = types.NetworkCreate{
				Labels: convert.AddStackLabel(namespace, nil),
			}
		}
	}

	services := make(map[string]swarm.ServiceSpec)
	for internalName, service := range bundle.Services {
		name := namespace.Scope(internalName)

		var ports []swarm.PortConfig
		for _, portSpec := range service.Ports {
			ports = append(ports, swarm.PortConfig{
				Protocol:   swarm.PortConfigProtocol(portSpec.Protocol),
				TargetPort: portSpec.Port,
			})
		}

		nets := []swarm.NetworkAttachmentConfig{}
		for _, networkName := range service.Networks {
			nets = append(nets, swarm.NetworkAttachmentConfig{
				Target:  namespace.Scope(networkName),
				Aliases: []string{internalName},
			})
		}

		serviceSpec := swarm.ServiceSpec{
			Annotations: swarm.Annotations{
				Name:   name,
				Labels: convert.AddStackLabel(namespace, service.Labels),
			},
			TaskTemplate: swarm.TaskSpec{
				ContainerSpec: &swarm.ContainerSpec{
					Image:   service.Image,
					Command: service.Command,
					Args:    service.Args,
					Env:     service.Env,
					// Service Labels will not be copied to Containers
					// automatically during the deployment so we apply
					// it here.
					Labels: convert.AddStackLabel(namespace, nil),
				},
			},
			EndpointSpec: &swarm.EndpointSpec{
				Ports: ports,
			},
			Networks: nets,
		}

		services[internalName] = serviceSpec
	}

	if err := createNetworks(ctx, dockerCli, namespace, networks); err != nil {
		return err
	}
	return deployServices(ctx, dockerCli, services, namespace, opts.SendRegistryAuth, opts.ResolveImage)
}
307128
func (cg *CertGeneratorHandler) SetBundler(caBundleFile, intBundleFile string) (err error) {
	cg.bundler, err = bundler.NewBundler(caBundleFile, intBundleFile)
	return err
}
1300548
func (c *Client) ExportBundle() (string, error) {
	var result params.StringResult
	if bestVer := c.BestAPIVersion(); bestVer < 2 {
		return "", errors.Errorf("this controller version does not support bundle export feature.")
	}

	if err := c.facade.FacadeCall("ExportBundle", nil, &result); err != nil {
		return "", errors.Trace(err)
	}

	if result.Error != nil {
		return "", errors.Trace(result.Error)
	}

	return result.Result, nil
}
1065834
func (b *Bundle) Get(name string) (*template.Template, error) {
	if b.err != nil {
		return nil, b.err
	}
	if templ := b.templates[name]; templ != nil {
		return templ, nil
	}
	return nil, fmt.Errorf("template: no such template %q in the bundle", name)
}
1246734
func newBundles(c *SmithV1Client, namespace string) *bundles {
	return &bundles{
		client: c.RESTClient(),
		ns:     namespace,
	}
}
641114
func newBundle(id, path, workDir string, spec []byte) (b *bundle, err error) {
	if err := os.MkdirAll(path, 0711); err != nil {
		return nil, err
	}
	path = filepath.Join(path, id)
	if err := os.Mkdir(path, 0711); err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			os.RemoveAll(path)
		}
	}()
	workDir = filepath.Join(workDir, id)
	if err := os.MkdirAll(workDir, 0711); err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			os.RemoveAll(workDir)
		}
	}()
	if err := os.Mkdir(filepath.Join(path, "rootfs"), 0711); err != nil {
		return nil, err
	}
	err = ioutil.WriteFile(filepath.Join(path, configFilename), spec, 0666)
	return &bundle{
		id:      id,
		path:    path,
		workDir: workDir,
	}, err
}
342635
func NormalizedBundleHash(bundleHash Hash) []int8 {
	normalizedBundle := make([]int8, HashTrytesSize)
	for i := 0; i < MaxSecurityLevel; i++ {
		sum := 0
		for j := 0; j < 27; j++ {
			normalizedBundle[i*27+j] = int8(TritsToInt(MustTrytesToTrits(string(bundleHash[i*27+j]))))
			sum += int(normalizedBundle[i*27+j])
		}

		if sum >= 0 {
			for ; sum > 0; sum-- {
				for j := 0; j < 27; j++ {
					if normalizedBundle[i*27+j] > MinTryteValue {
						normalizedBundle[i*27+j]--
						break
					}
				}
			}
		} else {
			for ; sum < 0; sum++ {
				for j := 0; j < 27; j++ {
					if normalizedBundle[i*27+j] < MaxTryteValue {
						normalizedBundle[i*27+j]++
						break
					}
				}
			}
		}
	}
	return normalizedBundle
}
900966
func (ws *ArchiveWorkspace) OpenBundledFile(filename string) (io.Reader, error) {
	if filepath.IsAbs(filename) {
		return nil, errors.Errorf("filename must be relative, got %q", filename)
	}

	tarFile, err := os.Open(ws.FilesBundle)
	if err != nil {
		return nil, errors.Trace(err)
	}

	_, file, err := tar.FindFile(tarFile, filename)
	if err != nil {
		tarFile.Close()
		return nil, errors.Trace(err)
	}
	return file, nil
}
1115945
func (in *Bundle) DeepCopy() *Bundle {
	if in == nil {
		return nil
	}
	out := new(Bundle)
	in.DeepCopyInto(out)
	return out
}