// Export writes the contents of the container's filesystem as a tar archive to outfile.
423509
func (c *Container) Export(outfile *os.File) error {
	dc, err := getDockerClient()
	if err != nil {
		return err
	}
	return dc.ExportContainer(dockerclient.ExportContainerOptions{c.ID, outfile})
}
501485
func (s *Block) Export(precision int) string {
	var k string
	if s.BlockDelete {
		return ""
	}
	for _, c := range s.Nodes {
		k += c.Export(precision)
	}
	return k
}
1127333
func (m *RTMetrics) Export() *RTMetrics {
	m.statusCodesLock.RLock()
	defer m.statusCodesLock.RUnlock()
	m.histogramLock.RLock()
	defer m.histogramLock.RUnlock()

	export := &RTMetrics{}
	export.statusCodesLock = sync.RWMutex{}
	export.histogramLock = sync.RWMutex{}
	export.total = m.total.Clone()
	export.netErrors = m.netErrors.Clone()
	exportStatusCodes := map[int]*RollingCounter{}
	for code, rollingCounter := range m.statusCodes {
		exportStatusCodes[code] = rollingCounter.Clone()
	}
	export.statusCodes = exportStatusCodes
	if m.histogram != nil {
		export.histogram = m.histogram.Export()
	}
	export.newCounter = m.newCounter
	export.newHist = m.newHist
	export.clock = m.clock

	return export
}
536699
func ExportEnv(env []string) string {
	if len(env) == 0 {
		return ""
	}
	out := "export"
	for _, e := range env {
		if len(e) == 0 {
			continue
		}
		out += " " + BashQuote(e)
	}
	return out + "; "
}
546083
func (api *API) Export() (params.SerializedModel, error) {
	var serialized params.SerializedModel

	model, err := api.backend.Export()
	if err != nil {
		return serialized, err
	}

	bytes, err := description.Serialize(model)
	if err != nil {
		return serialized, err
	}
	serialized.Bytes = bytes
	serialized.Charms = getUsedCharms(model)
	serialized.Resources = getUsedResources(model)
	if model.Type() == string(coremodel.IAAS) {
		serialized.Tools = getUsedTools(model)
	}
	return serialized, nil
}
1336603
func (b *BadgeState) Export() (keybase1.BadgeState, error) {
	b.Lock()
	defer b.Unlock()

	b.state.Conversations = []keybase1.BadgeConversationInfo{}
	for _, info := range b.chatUnreadMap {
		b.state.Conversations = append(b.state.Conversations, info)
	}
	b.state.InboxVers = int(b.inboxVers)

	b.state.UnreadWalletAccounts = []keybase1.WalletAccountInfo{}
	for accountID, count := range b.walletUnreadMap {
		info := keybase1.WalletAccountInfo{AccountID: string(accountID), NumUnread: count}
		b.state.UnreadWalletAccounts = append(b.state.UnreadWalletAccounts, info)
	}

	return b.state, nil
}
1169398
func (t *Tar) Extract(source, target, destination string) error {
	// target refers to a path inside the archive, which should be clean also
	target = path.Clean(target)

	// if the target ends up being a directory, then
	// we will continue walking and extracting files
	// until we are no longer within that directory
	var targetDirPath string

	return t.Walk(source, func(f File) error {
		th, ok := f.Header.(*tar.Header)
		if !ok {
			return fmt.Errorf("expected header to be *tar.Header but was %T", f.Header)
		}

		// importantly, cleaning the path strips tailing slash,
		// which must be appended to folders within the archive
		name := path.Clean(th.Name)
		if f.IsDir() && target == name {
			targetDirPath = path.Dir(name)
		}

		if within(target, th.Name) {
			// either this is the exact file we want, or is
			// in the directory we want to extract

			// build the filename we will extract to
			end, err := filepath.Rel(targetDirPath, th.Name)
			if err != nil {
				return fmt.Errorf("relativizing paths: %v", err)
			}
			joined := filepath.Join(destination, end)

			err = t.untarFile(f, joined)
			if err != nil {
				return fmt.Errorf("extracting file %s: %v", th.Name, err)
			}

			// if our target was not a directory, stop walk
			if targetDirPath == "" {
				return ErrStopWalk
			}
		} else if targetDirPath != "" {
			// finished walking the entire directory
			return ErrStopWalk
		}

		return nil
	})
}
50119
func (v *BtrfsVolume) Export(label, parent string, writer io.Writer, excludes []string) error {
	if len(excludes) > 0 {
		glog.Warning("btrfs backups do not support excluding directories")
	}
	if label = strings.TrimSpace(label); label == "" {
		glog.Errorf("%s: label cannot be empty", volume.DriverTypeBtrFS)
		return ErrBtrfsInvalidLabel
	} else if exists, err := v.snapshotExists(label); err != nil {
		return err
	} else if !exists {
		return volume.ErrSnapshotDoesNotExist
	}
	// TODO: add to tarfile and include metadata
	if err := runBtrfsSend(writer, v.sudoer, parent, v.snapshotPath(label)); err != nil {
		glog.Errorf("Could not export snapshot %s: %s", label, err)
		return err
	}
	return nil
}
491185
func (dfs *DistributedFilesystem) Backup(data BackupInfo, w io.Writer) error {

	backupLogger := plog.WithFields(log.Fields{
		"backupversion": data.BackupVersion,
		"timestamp":     data.Timestamp,
	})

	progress := NewProgressCounter(300)
	progress.Log = func() { plog.Infof("Written %v bytes to archive for backup", progress.Total) }

	tarOut := tar.NewWriter(io.MultiWriter(w, progress))

	// write the backup metadata
	if err := dfs.writeBackupMetadata(data, tarOut); err != nil {
		plog.WithError(err).Error("Unable to write metadata for backup")
		return err
	}

	var images []string

	baseImageLogger := backupLogger.WithField("total", len(data.BaseImages))
	baseImageLogger.Info("Preparing docker images for backup")

	// download the base images
	for i, image := range data.BaseImages {
		baseImageLogger = baseImageLogger.WithFields(log.Fields{
			"image":          image,
			"numbercomplete": i + 1,
		})

		if _, err := dfs.docker.FindImage(image); docker.IsImageNotFound(err) {
			if err := dfs.docker.PullImage(image); docker.IsImageNotFound(err) {
				baseImageLogger.Warn("Could not pull base image for backup, skipping")
				continue
			} else if err != nil {
				baseImageLogger.WithError(err).Error("Could not pull image for backup")
				return err
			}
		} else if err != nil {
			baseImageLogger.WithError(err).Error("Could not find image for backup")
			return err
		}

		baseImageLogger.Info("Prepared Docker image for backup")

		images = append(images, image)
	}

	numberOfSnapshots := len(data.Snapshots)

	backupLogger.WithField("total", numberOfSnapshots).Info("Preparing snapshots for backup")

	// export the snapshots
	for i, snapshot := range data.Snapshots {
		vol, info, err := dfs.getSnapshotVolumeAndInfo(snapshot)
		if err != nil {
			return err
		}

		// load the images from this snapshot
		tenantLogger := backupLogger.WithField("tenant", info.TenantID)
		tenantLogger.Info("Preparing images for tenant")

		r, err := vol.ReadMetadata(info.Label, ImagesMetadataFile)
		if err != nil {
			tenantLogger.WithError(err).Error("Could not receive images metadata for tenant")
			return err
		}

		var imgs []string
		if err := importJSON(r, &imgs); err != nil {
			tenantLogger.WithError(err).Error("Could not interpret images metadata for tenant")
			return err
		}

		timer := time.NewTimer(0)
		for _, img := range imgs {
			tenantImageLogger := tenantLogger.WithField("image", img)

			timer.Reset(dfs.timeout)
			if err := dfs.reg.PullImage(timer.C, img); err != nil {
				tenantImageLogger.WithError(err).Error("Could not pull image from registry")
				return err
			}

			image, err := dfs.reg.ImagePath(img)
			if err != nil {
				tenantImageLogger.WithError(err).Error("Could not get the image path from registry")
				return err
			}

			plog.WithField("image", image).Info("Prepared Docker image for backup")

			images = append(images, image)
		}

		timer.Stop()

		snapshotLogger := backupLogger.WithField("snapshot", snapshot)

		// dump the snapshot into the backup
		prefix := path.Join(SnapshotsMetadataDir, info.TenantID, info.Label)
		snapReader, errchan := dfs.snapshotSavePipe(vol, info.Label, data.SnapshotExcludes[snapshot])
		if err := rewriteTar(prefix, tarOut, snapReader); err != nil {
			// be a good citizen and clean up any running threads
			<-errchan
			snapshotLogger.WithError(err).Error("Could not write snapshot to backup")
			return err
		} else if err := <-errchan; err != nil {
			snapshotLogger.WithError(err).Error("Could not export snapshot for backup")
			return err
		}

		snapshotLogger.WithFields(log.Fields{
			"numbercomplete": i + 1,
			"total":          numberOfSnapshots,
		}).Info("Exported snapshot to backup")
	}

	// dump the images from all the snapshots into the backup
	imageReader, errchan := dfs.dockerSavePipe(images...)
	imageLogger := backupLogger.WithField("images", images)
	imageLogger.Info("Starting export of images to backup")
	if err := rewriteTar(DockerImagesFile, tarOut, imageReader); err != nil {
		// be a good citizen and clean up any running threads
		<-errchan
		imageLogger.WithError(err).Error("Could not write images to backup")
		return err
	} else if err := <-errchan; err != nil {
		imageLogger.WithError(err).Error("Could not export images for backup")
		return err
	}
	tarOut.Close()

	imageLogger.Info("Exported images to backup")

	return nil
}
693181
func (exporter *logExporter) cleanup() {
	// Close all of the temporary files
	for _, outputFile := range exporter.outputFiles {
		if e := outputFile.File.Close(); e != nil {
			log.WithFields(logrus.Fields{
				"outputfile": outputFile.Name,
			}).WithError(e).Error("Failed to close file cleanly")
		}
	}

	if exporter.parseWarningsFile != nil {
		if e := exporter.parseWarningsFile.Close(); e != nil {
			log.WithFields(logrus.Fields{
				"warningsfile": exporter.parseWarningsFilename,
			}).WithError(e).Error("Failed to close file cleanly")
		}
	}

	// close the tar file
	if exporter.outFile != nil {
		exporter.outFile.Close()
	}

	if exporter.tempdir != "" {
		os.RemoveAll(exporter.tempdir)
	}
}
337516
func (res *Resource) Export(container Container, context *qor.Context, callbacks ...func(Progress) error) error {
	var (
		total   uint
		results = res.NewSlice()
		err     = context.GetDB().Find(results).Count(&total).Error
	)

	if err == nil {
		reflectValue := reflect.Indirect(reflect.ValueOf(results))

		writer, err := container.NewWriter(res, context)

		if err == nil {
			writer.WriteHeader()

			for i := 0; i < reflectValue.Len(); i++ {
				var result = reflectValue.Index(i).Interface()
				var metaValues *resource.MetaValues
				if metaValues, err = writer.WriteRow(result); err != nil {
					return err
				}

				var progress = Progress{
					Current: uint(i + 1),
					Total:   total,
					Value:   result,
				}

				for _, metaValue := range metaValues.Values {
					progress.Cells = append(progress.Cells, Cell{
						Header: metaValue.Name,
						Value:  metaValue.Value,
					})
				}

				for _, callback := range callbacks {
					if err := callback(progress); err != nil {
						return err
					}
				}
			}
			err = writer.Flush()
		}

		return err
	}

	return err
}
1231146
func ExportCreate(
	ctx context.Context,
	client api.Client,
	export *Export) (int, error) {

	if export.Paths != nil && len(*export.Paths) == 0 {
		return 0, errors.New("no path set")
	}

	var resp Export

	if err := client.Post(
		ctx,
		exportsPath,
		"",
		nil,
		nil,
		export,
		&resp); err != nil {

		return 0, err
	}

	return resp.ID, nil
}
606448
func (n *Name) Export() (b *Buffer, err error) {
	b, err = n.MakeBuffer(allocGSSAPI)
	if err != nil {
		return nil, err
	}

	var min C.OM_uint32
	maj := C.wrap_gss_export_name(n.Fp_gss_export_name, &min,
		n.C_gss_name_t, b.C_gss_buffer_t)
	err = n.stashLastStatus(maj, min)
	if err != nil {
		b.Release()
		return nil, err
	}

	return b, nil
}
424988
func (e *ganeshaExporter) Export(path string) error {
	// Call AddExport using dbus
	conn, err := dbus.SystemBus()
	if err != nil {
		return fmt.Errorf("error getting dbus session bus: %v", err)
	}
	obj := conn.Object("org.ganesha.nfsd", "/org/ganesha/nfsd/ExportMgr")
	call := obj.Call("org.ganesha.nfsd.exportmgr.AddExport", 0, e.config, fmt.Sprintf("export(path = %s)", path))
	if call.Err != nil {
		return fmt.Errorf("error calling org.ganesha.nfsd.exportmgr.AddExport: %v", call.Err)
	}

	return nil
}
244155
func (c *Cluster) Export() ([]byte, error) {
	var config bytes.Buffer

	namespaces, err := c.getAllowedAndExistingNamespaces()
	if err != nil {
		return nil, errors.Wrap(err, "getting namespaces")
	}

	encoder := yaml.NewEncoder(&config)
	defer encoder.Close()

	for _, ns := range namespaces {
		// kind & apiVersion must be set, since TypeMeta is not populated
		ns.Kind = "Namespace"
		ns.APIVersion = "v1"
		err := encoder.Encode(yamlThroughJSON{ns})
		if err != nil {
			return nil, errors.Wrap(err, "marshalling namespace to YAML")
		}

		for _, resourceKind := range resourceKinds {
			workloads, err := resourceKind.getWorkloads(c, ns.Name)
			if err != nil {
				switch {
				case apierrors.IsNotFound(err):
					// Kind not supported by API server, skip
					continue
				case apierrors.IsForbidden(err):
					// K8s can return forbidden instead of not found for non super admins
					c.logger.Log("warning", "not allowed to list resources", "err", err)
					continue
				default:
					return nil, err
				}
			}

			for _, pc := range workloads {
				if !isAddon(pc) {
					if err := encoder.Encode(yamlThroughJSON{pc.k8sObject}); err != nil {
						return nil, err
					}
				}
			}
		}
	}
	return config.Bytes(), nil
}
725452
func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error {

	_, err := os.Stat(dirname)
	fmt.Println(dirname, err, os.IsNotExist(err))
	if err != nil {

		if !os.IsNotExist(err) {
			return err
		}

		if err = os.MkdirAll(dirname, 0744); err != nil {
			return err
		}
	}

	// build up translations
	var trans []translation
	var b []byte
	var ext string

	for _, locale := range t.translators {

		for k, v := range locale.(*translator).translations {
			trans = append(trans, translation{
				Locale:      locale.Locale(),
				Key:         k,
				Translation: v.text,
			})
		}

		for k, pluralTrans := range locale.(*translator).cardinalTanslations {

			for i, plural := range pluralTrans {

				// leave enough for all plural rules
				// but not all are set for all languages.
				if plural == nil {
					continue
				}

				trans = append(trans, translation{
					Locale:      locale.Locale(),
					Key:         k.(string),
					Translation: plural.text,
					PluralType:  cardinalType,
					PluralRule:  locales.PluralRule(i).String(),
				})
			}
		}

		for k, pluralTrans := range locale.(*translator).ordinalTanslations {

			for i, plural := range pluralTrans {

				// leave enough for all plural rules
				// but not all are set for all languages.
				if plural == nil {
					continue
				}

				trans = append(trans, translation{
					Locale:      locale.Locale(),
					Key:         k.(string),
					Translation: plural.text,
					PluralType:  ordinalType,
					PluralRule:  locales.PluralRule(i).String(),
				})
			}
		}

		for k, pluralTrans := range locale.(*translator).rangeTanslations {

			for i, plural := range pluralTrans {

				// leave enough for all plural rules
				// but not all are set for all languages.
				if plural == nil {
					continue
				}

				trans = append(trans, translation{
					Locale:      locale.Locale(),
					Key:         k.(string),
					Translation: plural.text,
					PluralType:  rangeType,
					PluralRule:  locales.PluralRule(i).String(),
				})
			}
		}

		switch format {
		case FormatJSON:
			b, err = json.MarshalIndent(trans, "", "    ")
			ext = ".json"
		}

		if err != nil {
			return err
		}

		err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644)
		if err != nil {
			return err
		}

		trans = trans[0:0]
	}

	return nil
}
258394
func (c *Cluster) ExportContainer(opts docker.ExportContainerOptions) error {
	node, err := c.getNodeForContainer(opts.ID)
	if err != nil {
		return err
	}
	return wrapError(node, node.ExportContainer(opts))
}