// Adds backup image store.
197408
func (s *ImageStoreService) AddImageStore(p *AddImageStoreParams) (*AddImageStoreResponse, error) {
	resp, err := s.cs.newRequest("addImageStore", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r AddImageStoreResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
866004
func (c *memoryStore) Add(id string, cont *Container) {
	c.Lock()
	c.s[id] = cont
	c.Unlock()
}
786314
func addStorages(ctx context.Context, storages []*pb.Storage, s *sandbox) ([]string, error) {
	span, ctx := trace(ctx, "mount", "addStorages")
	span.SetTag("sandbox", s.id)
	defer span.Finish()

	var mountList []string

	for _, storage := range storages {
		if storage == nil {
			continue
		}

		devHandler, ok := storageHandlerList[storage.Driver]
		if !ok {
			return nil, grpcStatus.Errorf(codes.InvalidArgument,
				"Unknown storage driver %q", storage.Driver)
		}

		// Wrap the span around the handler call to avoid modifying
		// the handler interface but also to avoid having to add trace
		// code to each driver.
		handlerSpan, _ := trace(ctx, "mount", storage.Driver)
		mountPoint, err := devHandler(*storage, s)
		handlerSpan.Finish()

		if err != nil {
			return nil, err
		}

		if mountPoint != "" {
			// Prepend mount point to mount list.
			mountList = append([]string{mountPoint}, mountList...)
		}
	}

	return mountList, nil
}
1317400
func (t *fileTracker) AddBytes(bytes uint64, level int) {
	atomic.AddUint64(&t.diskBytes, bytes)

	labels := t.Labels()
	labels["level"] = fmt.Sprintf("%d", level)
	t.metrics.DiskSize.With(labels).Add(float64(bytes))
}
216973
func (sb *storageBackend) addStorageForUnitOps(
	u *Unit,
	storageName string,
	cons StorageConstraints,
) ([]names.StorageTag, []txn.Op, error) {
	if u.Life() != Alive {
		return nil, nil, unitNotAliveErr
	}

	// Storage addition is based on the charm metadata; u.charm()
	// returns txn.Ops that ensure the charm URL does not change
	// during the transaction.
	ch, err := u.charm()
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	charmMeta := ch.Meta()
	charmStorageMeta, ok := charmMeta.Storage[storageName]
	if !ok {
		return nil, nil, errors.NotFoundf("charm storage %q", storageName)
	}
	ops := u.assertCharmOps(ch)

	if cons.Pool == "" || cons.Size == 0 {
		// Either pool or size, or both, were not specified. Take the
		// values from the unit's recorded storage constraints.
		allCons, err := u.StorageConstraints()
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		if uCons, ok := allCons[storageName]; ok {
			if cons.Pool == "" {
				cons.Pool = uCons.Pool
			}
			if cons.Size == 0 {
				cons.Size = uCons.Size
			}
		}

		// Populate missing configuration parameters with defaults.
		if cons.Pool == "" || cons.Size == 0 {
			modelConfig, err := sb.config()
			if err != nil {
				return nil, nil, errors.Trace(err)
			}
			completeCons, err := storageConstraintsWithDefaults(
				sb.modelType,
				modelConfig,
				charmStorageMeta,
				storageName,
				cons,
			)
			if err != nil {
				return nil, nil, errors.Trace(err)
			}
			cons = completeCons
		}
	}

	// This can happen for charm stores that specify instances range from 0,
	// and no count was specified at deploy as storage constraints for this store,
	// and no count was specified to storage add as a contraint either.
	if cons.Count == 0 {
		return nil, nil, errors.NotValidf("adding storage where instance count is 0")
	}

	tags, addUnitStorageOps, err := sb.addUnitStorageOps(charmMeta, u, storageName, cons, -1)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	ops = append(ops, addUnitStorageOps...)
	return tags, ops, nil
}
557039
func (f *Facade) Backup(ctx datastore.Context, w io.Writer, excludes []string, snapshotSpacePercent int, backupFilename string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.Backup"))
	// Do not DFSLock here, ControlPlaneDao does that
	stime := time.Now()
	message := fmt.Sprintf("started backup at %s", stime.UTC())
	plog.WithField("excludes", excludes).Info("Started backup")
	alog := f.auditLogger.Message(ctx, "Started Backup").
		Action(audit.Backup).
		WithFields(logrus.Fields{
				"starttime": stime.UTC().Format("2006-01-02-150405"),
				"backupfile": backupFilename})
	alog.Succeeded()
	alog = f.auditLogger.Message(ctx, "Completed Backup").
		Action(audit.Backup)
	templates, images, err := f.GetServiceTemplatesAndImages(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get service templates and images")
		return alog.Error(err)
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded templates and their images")
	pools, err := f.GetResourcePools(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get resource pools")
		return alog.Error(err)
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded resource pools")
	tenants, err := f.GetTenantIDs(ctx)
	if err != nil {
		plog.WithError(err).Debug("Could not get tenants")
		return alog.Error(err)
	}
	snapshots := make([]string, len(tenants))
	snapshotExcludes := map[string][]string{}
	for i, tenant := range tenants {
		tenantLogger := plog.WithField("tenant", tenant)
		tag := fmt.Sprintf("backup-%s-%s", tenant, stime)
		snapshot, err := f.Snapshot(ctx, tenant, message, []string{tag}, snapshotSpacePercent)
		if err != nil {
			tenantLogger.WithError(err).Debug("Could not snapshot tenant")
			return alog.Error(err)
		}

		defer func(tenant, snapshot, tag string) {
			if err := f.DeleteSnapshot(ctx, snapshot); err != nil {
				tenantLogger.WithError(err).Warn("Could not delete snapshot; untagging for consumption by TTL")
				if _, err := f.RemoveSnapshotTag(ctx, tenant, tag); err != nil {
					tenantLogger.WithError(err).Error("Could not untag snapshot.  Snapshot must be deleted manually!")
				}
			}
		}(tenant, snapshot, tag)

		snapshots[i] = snapshot
		snapshotExcludes[snapshot] = append(excludes, f.getExcludedVolumes(ctx, tenant)...)
		tenantLogger.WithField("snapshot", snapshot).Info("Created a snapshot for tenant")
	}
	plog.WithField("elapsed", time.Since(stime)).Info("Loaded tenants")
	data := dfs.BackupInfo{
		Templates:        templates,
		BaseImages:       images,
		Pools:            pools,
		Snapshots:        snapshots,
		SnapshotExcludes: snapshotExcludes,
		Timestamp:        stime,
		BackupVersion:    1,
	}
	plog.WithField("data", data).Info("Calling dfs.Backup")
	if err := f.dfs.Backup(data, w); err != nil {
		plog.WithError(err).Debug("Could not backup")
		return alog.Error(err)
	}
	duration := time.Since(stime)
	plog.WithField("duration", duration).Info("Completed backup")
	alog.WithFields(logrus.Fields{
				"backupfile": backupFilename,
				"elasped": fmt.Sprintf("%fsec", duration.Seconds()),
			}).Succeeded()
	return nil
}
1338637
func (a *Attachments) Storage(tag names.StorageTag) (jujuc.ContextStorageAttachment, error) {
	if attachment, ok := a.storageAttachments[tag]; ok {
		return attachment, nil
	}
	return nil, errors.NotFoundf("storage")
}
1192370
func (s *backupBlobStorage) AddFile(id string, file io.Reader, size int64) error {
	return s.storeImpl.PutForBucket(s.modelUUID, s.path(id), file, size)
}
371083
func (_m *DFS) Backup(info dfs.BackupInfo, w io.Writer) error {
	ret := _m.Called(info, w)

	var r0 error
	if rf, ok := ret.Get(0).(func(dfs.BackupInfo, io.Writer) error); ok {
		r0 = rf(info, w)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
803189
func (st *State) GUIStorage() (binarystorage.StorageCloser, error) {
	return newBinaryStorageCloser(st.database, guimetadataC, st.ControllerModelUUID()), nil
}
923269
func NewBackupContext(targetDir string, env map[string]string, cryptKey string) (backupContext BackupContext) {
	backupContext = BackupContext{
		TargetDir: targetDir,
	}
	if useS3(env) {
		backupContext.StorageProvider = NewS3Provider(env[S3Domain], env[AccessKeyIDVarname], env[SecretAccessKeyVarname], env[BucketNameVarname])
		backupContext.IsS3 = true
	} else {
		backupContext.StorageProvider = NewDiskProvider()
	}

	if isValidCryptKey(cryptKey) {
		var err error

		if backupContext.StorageProvider, err = NewEncryptedStorageProvider(backupContext.StorageProvider, cryptKey); err != nil {
			lo.G.Error("something went wrong when applying encryption to storage provider: ", err)
			panic(err)
		}
	}
	return
}
1101376
func WithStorageBackendString(ctx context.Context, sb string) context.Context {
	return WithStorageBackend(ctx, storageBackendFromName(sb))
}
662899
func (b *backups) Add(archive io.Reader, meta *Metadata) (string, error) {
	// Store the archive.
	err := storeArchive(b.storage, meta, archive)
	if err != nil {
		return "", errors.Annotate(err, "while storing backup archive")
	}

	return meta.ID(), nil
}
1355756
func (i *ImageService) AddMetadata(imageID string, metadata *ImageMetadata, auth Authenticator) error {
	path := fmt.Sprintf("images/%s/json", imageID)
	req, err := i.client.newRequest("PUT", path, auth, metadata)
	if err != nil {
		return err
	}

	req.Header.Add("Content-Type", "application/json")

	_, err = i.client.do(req, nil)
	return err
}
1267649
func (c *fileStore) Store(authConfig types.AuthConfig) error {
	c.file.GetAuthConfigs()[authConfig.ServerAddress] = authConfig
	return c.file.Save()
}
839332
func restore(store string) {
	files, rderr := ioutil.ReadDir(store)
	chkerr(rderr)
	for _, f := range files {
		fname := f.Name()
		if len(fname) > 4 {
			if fname[len(fname)-4:] == bkpExt {
				key := fname[0 : len(fname)-4]
				fulp := fullpath(store, key)
				msg, cerr := os.Create(fulp)
				chkerr(cerr)
				bkpp := path.Join(store, fname)
				bkp, oerr := os.Open(bkpp)
				chkerr(oerr)
				n, cerr := io.Copy(msg, bkp)
				chkerr(cerr)
				chkcond(n > 0)
				clmerr := msg.Close()
				chkerr(clmerr)
				clberr := bkp.Close()
				chkerr(clberr)
				remerr := os.Remove(bkpp)
				chkerr(remerr)
			}
		}
	}
}
1370222
func (fbs *FileBackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {
	// Make sure the directory exists.
	p := path.Join(*FileBackupStorageRoot, dir)
	if err := os.MkdirAll(p, os.ModePerm); err != nil {
		return nil, err
	}

	// Create the subdirectory for this named backup.
	p = path.Join(p, name)
	if err := os.Mkdir(p, os.ModePerm); err != nil {
		return nil, err
	}

	return &FileBackupHandle{
		fbs:      fbs,
		dir:      dir,
		name:     name,
		readOnly: false,
	}, nil
}