github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io.go (about)

     1  /*
     2  Copyright 2015 The Kubernetes Authors 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 io
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  	"os"
    23  
    24  	"k8s.io/kubernetes/pkg/api"
    25  	"k8s.io/kubernetes/pkg/api/latest"
    26  )
    27  
    28  // LoadPodFromFile will read, decode, and return a Pod from a file.
    29  func LoadPodFromFile(filePath string) (*api.Pod, error) {
    30  	if filePath == "" {
    31  		return nil, fmt.Errorf("file path not specified")
    32  	}
    33  	podDef, err := ioutil.ReadFile(filePath)
    34  	if err != nil {
    35  		return nil, fmt.Errorf("failed to read file path %s: %+v", filePath, err)
    36  	}
    37  	if len(podDef) == 0 {
    38  		return nil, fmt.Errorf("file was empty: %s", filePath)
    39  	}
    40  	pod := &api.Pod{}
    41  
    42  	if err := latest.GroupOrDie("").Codec.DecodeInto(podDef, pod); err != nil {
    43  		return nil, fmt.Errorf("failed decoding file: %v", err)
    44  	}
    45  	return pod, nil
    46  }
    47  
    48  // SavePodToFile will encode and save a pod to a given path & permissions
    49  func SavePodToFile(pod *api.Pod, filePath string, perm os.FileMode) error {
    50  	if filePath == "" {
    51  		return fmt.Errorf("file path not specified")
    52  	}
    53  	data, err := latest.GroupOrDie("").Codec.Encode(pod)
    54  	if err != nil {
    55  		return fmt.Errorf("failed encoding pod: %v", err)
    56  	}
    57  	return ioutil.WriteFile(filePath, data, perm)
    58  }