github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/orderer/sbft/persist/persist.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package persist
    18  
    19  import (
    20  	"io/ioutil"
    21  	"os"
    22  	"strings"
    23  )
    24  
    25  type Persist struct {
    26  	dir string
    27  }
    28  
    29  func New(dir string) *Persist {
    30  	p := &Persist{
    31  		dir: dir,
    32  	}
    33  	os.MkdirAll(dir, 0755)
    34  	return p
    35  }
    36  
    37  func (p *Persist) path(key string) string {
    38  	return p.dir + "/" + key
    39  }
    40  
    41  //
    42  func (p *Persist) StoreState(key string, value []byte) error {
    43  	return ioutil.WriteFile(p.path(key), value, 0640)
    44  }
    45  
    46  func (p *Persist) ReadState(key string) ([]byte, error) {
    47  	return ioutil.ReadFile(p.path(key))
    48  }
    49  
    50  func (p *Persist) ReadStateSet(prefix string) (map[string][]byte, error) {
    51  	files, err := ioutil.ReadDir(p.dir)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	r := make(map[string][]byte)
    56  	for _, fi := range files {
    57  		if fi.Mode()&os.ModeType != 0 {
    58  			continue
    59  		}
    60  		if strings.Index(fi.Name(), prefix) != 0 {
    61  			continue
    62  		}
    63  		data, err := ioutil.ReadFile(p.path(fi.Name()))
    64  		if err != nil {
    65  			return nil, err
    66  		}
    67  		r[fi.Name()] = data
    68  	}
    69  	return r, nil
    70  }
    71  
    72  func (p *Persist) DelState(key string) {
    73  	os.Remove(p.path(key))
    74  }