github.com/sri09kanth/helm@v3.0.0-beta.3+incompatible/pkg/storage/driver/util.go (about)

     1  /*
     2  Copyright The Helm Authors.
     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 driver // import "helm.sh/helm/pkg/storage/driver"
    18  
    19  import (
    20  	"bytes"
    21  	"compress/gzip"
    22  	"encoding/base64"
    23  	"encoding/json"
    24  	"io/ioutil"
    25  
    26  	rspb "helm.sh/helm/pkg/release"
    27  )
    28  
    29  var b64 = base64.StdEncoding
    30  
    31  var magicGzip = []byte{0x1f, 0x8b, 0x08}
    32  
    33  // encodeRelease encodes a release returning a base64 encoded
    34  // gzipped binary protobuf encoding representation, or error.
    35  func encodeRelease(rls *rspb.Release) (string, error) {
    36  	b, err := json.Marshal(rls)
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  	var buf bytes.Buffer
    41  	w, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  	if _, err = w.Write(b); err != nil {
    46  		return "", err
    47  	}
    48  	w.Close()
    49  
    50  	return b64.EncodeToString(buf.Bytes()), nil
    51  }
    52  
    53  // decodeRelease decodes the bytes in data into a release
    54  // type. Data must contain a base64 encoded string of a
    55  // valid protobuf encoding of a release, otherwise
    56  // an error is returned.
    57  func decodeRelease(data string) (*rspb.Release, error) {
    58  	// base64 decode string
    59  	b, err := b64.DecodeString(data)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	// For backwards compatibility with releases that were stored before
    65  	// compression was introduced we skip decompression if the
    66  	// gzip magic header is not found
    67  	if bytes.Equal(b[0:3], magicGzip) {
    68  		r, err := gzip.NewReader(bytes.NewReader(b))
    69  		if err != nil {
    70  			return nil, err
    71  		}
    72  		b2, err := ioutil.ReadAll(r)
    73  		if err != nil {
    74  			return nil, err
    75  		}
    76  		b = b2
    77  	}
    78  
    79  	var rls rspb.Release
    80  	// unmarshal protobuf bytes
    81  	if err := json.Unmarshal(b, &rls); err != nil {
    82  		return nil, err
    83  	}
    84  	return &rls, nil
    85  }