gopkg.in/ubuntu-core/snappy.v0@v0.0.0-20210902073436-25a8614f10a6/kernel/kernel.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2020 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package kernel 21 22 import ( 23 "fmt" 24 "io/ioutil" 25 "os" 26 "path/filepath" 27 "regexp" 28 29 "gopkg.in/yaml.v2" 30 ) 31 32 type Asset struct { 33 // TODO: we may make this an (optional) map at some point in 34 // the future to select what things should be updated. 35 // 36 // Update set to true indicates that assets shall be updated. 37 Update bool `yaml:"update,omitempty"` 38 Content []string `yaml:"content,omitempty"` 39 } 40 41 type Info struct { 42 Assets map[string]*Asset `yaml:"assets,omitempty"` 43 } 44 45 // ValidAssetName is a regular expression matching valid asset name. 46 var ValidAssetName = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9-]*$") 47 48 // InfoFromKernelYaml reads the provided kernel metadata. 49 func InfoFromKernelYaml(kernelYaml []byte) (*Info, error) { 50 var ki Info 51 52 if err := yaml.Unmarshal(kernelYaml, &ki); err != nil { 53 return nil, fmt.Errorf("cannot parse kernel metadata: %v", err) 54 } 55 56 for name := range ki.Assets { 57 if !ValidAssetName.MatchString(name) { 58 return nil, fmt.Errorf("invalid asset name %q, please use only alphanumeric characters and dashes", name) 59 } 60 } 61 62 return &ki, nil 63 } 64 65 // ReadInfo reads the kernel specific metadata from meta/kernel.yaml 66 // in the snap root directory if the file exists. 67 func ReadInfo(kernelSnapRootDir string) (*Info, error) { 68 p := filepath.Join(kernelSnapRootDir, "meta", "kernel.yaml") 69 content, err := ioutil.ReadFile(p) 70 // meta/kernel.yaml is optional so we should not error here if 71 // it is missing 72 if os.IsNotExist(err) { 73 return &Info{}, nil 74 } 75 if err != nil { 76 return nil, fmt.Errorf("cannot read kernel info: %v", err) 77 } 78 return InfoFromKernelYaml(content) 79 }