github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/state/dump.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package state
     5  
     6  import "github.com/juju/errors"
     7  
     8  // DumpAll returns a map of collection names to a slice of documents
     9  // in that collection. Every document that is related to the current
    10  // model is returned in the map.
    11  func (st *State) DumpAll() (map[string]interface{}, error) {
    12  	result := make(map[string]interface{})
    13  	// Add in the model document itself.
    14  	doc, err := getModelDoc(st)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	result[modelsC] = doc
    19  	for name, info := range allCollections() {
    20  		if !info.global {
    21  			docs, err := getAllModelDocs(st, name)
    22  			if err != nil {
    23  				return nil, errors.Trace(err)
    24  			}
    25  			if len(docs) > 0 {
    26  				result[name] = docs
    27  			}
    28  		}
    29  	}
    30  	return result, nil
    31  }
    32  
    33  func getModelDoc(st *State) (map[string]interface{}, error) {
    34  	coll, closer := st.getCollection(modelsC)
    35  	defer closer()
    36  
    37  	var doc map[string]interface{}
    38  	if err := coll.FindId(st.ModelUUID()).One(&doc); err != nil {
    39  		return nil, errors.Annotatef(err, "reading model %q", st.ModelUUID())
    40  	}
    41  	return doc, nil
    42  
    43  }
    44  
    45  func getAllModelDocs(st *State, collectionName string) ([]map[string]interface{}, error) {
    46  	coll, closer := st.getCollection(collectionName)
    47  	defer closer()
    48  
    49  	var (
    50  		result []map[string]interface{}
    51  		doc    map[string]interface{}
    52  	)
    53  	// Always output in id order.
    54  	iter := coll.Find(nil).Sort("_id").Iter()
    55  	defer iter.Close()
    56  	for iter.Next(&doc) {
    57  		result = append(result, doc)
    58  		doc = nil
    59  	}
    60  
    61  	if err := iter.Err(); err != nil {
    62  		return nil, errors.Annotatef(err, "reading collection %q", collectionName)
    63  	}
    64  	return result, nil
    65  }