image.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // This file contains all image related functions for rkt runtime.
  14. package rkt
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "sort"
  23. "strings"
  24. appcschema "github.com/appc/spec/schema"
  25. rktapi "github.com/coreos/rkt/api/v1alpha"
  26. dockertypes "github.com/docker/engine-api/types"
  27. "github.com/golang/glog"
  28. "golang.org/x/net/context"
  29. "k8s.io/kubernetes/pkg/api"
  30. "k8s.io/kubernetes/pkg/credentialprovider"
  31. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  32. "k8s.io/kubernetes/pkg/util/parsers"
  33. )
  34. // PullImage invokes 'rkt fetch' to download an aci.
  35. // TODO(yifan): Now we only support docker images, this should be changed
  36. // once the format of image is landed, see:
  37. //
  38. // http://issue.k8s.io/7203
  39. //
  40. func (r *Runtime) PullImage(image kubecontainer.ImageSpec, pullSecrets []api.Secret) error {
  41. img := image.Image
  42. // TODO(yifan): The credential operation is a copy from dockertools package,
  43. // Need to resolve the code duplication.
  44. repoToPull, _, _, err := parsers.ParseImageName(img)
  45. if err != nil {
  46. return err
  47. }
  48. keyring, err := credentialprovider.MakeDockerKeyring(pullSecrets, r.dockerKeyring)
  49. if err != nil {
  50. return err
  51. }
  52. creds, ok := keyring.Lookup(repoToPull)
  53. if !ok {
  54. glog.V(1).Infof("Pulling image %s without credentials", img)
  55. }
  56. userConfigDir, err := ioutil.TempDir("", "rktnetes-user-config-dir-")
  57. if err != nil {
  58. return fmt.Errorf("rkt: Cannot create a temporary user-config directory: %v", err)
  59. }
  60. defer os.RemoveAll(userConfigDir)
  61. config := *r.config
  62. config.UserConfigDir = userConfigDir
  63. if err := r.writeDockerAuthConfig(img, creds, userConfigDir); err != nil {
  64. return err
  65. }
  66. // Today, `--no-store` will fetch the remote image regardless of whether the content of the image
  67. // has changed or not. This causes performance downgrades when the image tag is ':latest' and
  68. // the image pull policy is 'always'. The issue is tracked in https://github.com/coreos/rkt/issues/2937.
  69. if _, err := r.cli.RunCommand(&config, "fetch", "--no-store", dockerPrefix+img); err != nil {
  70. glog.Errorf("Failed to fetch: %v", err)
  71. return err
  72. }
  73. return nil
  74. }
  75. func (r *Runtime) IsImagePresent(image kubecontainer.ImageSpec) (bool, error) {
  76. images, err := r.listImages(image.Image, false)
  77. return len(images) > 0, err
  78. }
  79. // ListImages lists all the available appc images on the machine by invoking 'rkt image list'.
  80. func (r *Runtime) ListImages() ([]kubecontainer.Image, error) {
  81. ctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout)
  82. defer cancel()
  83. listResp, err := r.apisvc.ListImages(ctx, &rktapi.ListImagesRequest{})
  84. if err != nil {
  85. return nil, fmt.Errorf("couldn't list images: %v", err)
  86. }
  87. images := make([]kubecontainer.Image, len(listResp.Images))
  88. for i, image := range listResp.Images {
  89. images[i] = kubecontainer.Image{
  90. ID: image.Id,
  91. RepoTags: []string{buildImageName(image)},
  92. Size: image.Size,
  93. }
  94. }
  95. return images, nil
  96. }
  97. // RemoveImage removes an on-disk image using 'rkt image rm'.
  98. func (r *Runtime) RemoveImage(image kubecontainer.ImageSpec) error {
  99. imageID, err := r.getImageID(image.Image)
  100. if err != nil {
  101. return err
  102. }
  103. if _, err := r.cli.RunCommand(nil, "image", "rm", imageID); err != nil {
  104. return err
  105. }
  106. return nil
  107. }
  108. // buildImageName constructs the image name for kubecontainer.Image.
  109. func buildImageName(img *rktapi.Image) string {
  110. return fmt.Sprintf("%s:%s", img.Name, img.Version)
  111. }
  112. // getImageID tries to find the image ID for the given image name.
  113. // imageName should be in the form of 'name[:version]', e.g., 'example.com/app:latest'.
  114. // The name should matches the result of 'rkt image list'. If the version is empty,
  115. // then 'latest' is assumed.
  116. func (r *Runtime) getImageID(imageName string) (string, error) {
  117. images, err := r.listImages(imageName, false)
  118. if err != nil {
  119. return "", err
  120. }
  121. if len(images) == 0 {
  122. return "", fmt.Errorf("cannot find the image %q", imageName)
  123. }
  124. return images[0].Id, nil
  125. }
  126. type sortByImportTime []*rktapi.Image
  127. func (s sortByImportTime) Len() int { return len(s) }
  128. func (s sortByImportTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  129. func (s sortByImportTime) Less(i, j int) bool { return s[i].ImportTimestamp < s[j].ImportTimestamp }
  130. // listImages lists the images that have the given name. If detail is true,
  131. // then image manifest is also included in the result.
  132. // Note that there could be more than one images that have the given name, we
  133. // will return the result reversely sorted by the import time, so that the latest
  134. // image comes first.
  135. func (r *Runtime) listImages(image string, detail bool) ([]*rktapi.Image, error) {
  136. repoToPull, tag, _, err := parsers.ParseImageName(image)
  137. if err != nil {
  138. return nil, err
  139. }
  140. ctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout)
  141. defer cancel()
  142. listResp, err := r.apisvc.ListImages(ctx, &rktapi.ListImagesRequest{
  143. Detail: detail,
  144. Filters: []*rktapi.ImageFilter{
  145. {
  146. // TODO(yifan): Add a field in the ImageFilter to match the whole name,
  147. // not just keywords.
  148. // https://github.com/coreos/rkt/issues/1872#issuecomment-166456938
  149. Keywords: []string{repoToPull},
  150. Labels: []*rktapi.KeyValue{{Key: "version", Value: tag}},
  151. },
  152. },
  153. })
  154. if err != nil {
  155. return nil, fmt.Errorf("couldn't list images: %v", err)
  156. }
  157. // TODO(yifan): Let the API service to sort the result:
  158. // See https://github.com/coreos/rkt/issues/1911.
  159. sort.Sort(sort.Reverse(sortByImportTime(listResp.Images)))
  160. return listResp.Images, nil
  161. }
  162. // getImageManifest retrieves the image manifest for the given image.
  163. func (r *Runtime) getImageManifest(image string) (*appcschema.ImageManifest, error) {
  164. var manifest appcschema.ImageManifest
  165. images, err := r.listImages(image, true)
  166. if err != nil {
  167. return nil, err
  168. }
  169. if len(images) == 0 {
  170. return nil, fmt.Errorf("cannot find the image %q", image)
  171. }
  172. return &manifest, json.Unmarshal(images[0].Manifest, &manifest)
  173. }
  174. // TODO(yifan): This is very racy, inefficient, and unsafe, we need to provide
  175. // different namespaces. See: https://github.com/coreos/rkt/issues/836.
  176. func (r *Runtime) writeDockerAuthConfig(image string, credsSlice []credentialprovider.LazyAuthConfiguration, userConfigDir string) error {
  177. if len(credsSlice) == 0 {
  178. return nil
  179. }
  180. creds := dockertypes.AuthConfig{}
  181. // TODO handle multiple creds
  182. if len(credsSlice) >= 1 {
  183. creds = credentialprovider.LazyProvide(credsSlice[0])
  184. }
  185. registry := "index.docker.io"
  186. // Image spec: [<registry>/]<repository>/<image>[:<version]
  187. explicitRegistry := (strings.Count(image, "/") == 2)
  188. if explicitRegistry {
  189. registry = strings.Split(image, "/")[0]
  190. }
  191. authDir := filepath.Join(userConfigDir, "auth.d")
  192. if _, err := os.Stat(authDir); os.IsNotExist(err) {
  193. if err := os.MkdirAll(authDir, 0600); err != nil {
  194. glog.Errorf("rkt: Cannot create auth dir: %v", err)
  195. return err
  196. }
  197. }
  198. config := fmt.Sprintf(dockerAuthTemplate, registry, creds.Username, creds.Password)
  199. if err := ioutil.WriteFile(path.Join(authDir, registry+".json"), []byte(config), 0600); err != nil {
  200. glog.Errorf("rkt: Cannot write docker auth config file: %v", err)
  201. return err
  202. }
  203. return nil
  204. }
  205. // ImageStats returns the image stat (total storage bytes).
  206. func (r *Runtime) ImageStats() (*kubecontainer.ImageStats, error) {
  207. var imageStat kubecontainer.ImageStats
  208. ctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout)
  209. defer cancel()
  210. listResp, err := r.apisvc.ListImages(ctx, &rktapi.ListImagesRequest{})
  211. if err != nil {
  212. return nil, fmt.Errorf("couldn't list images: %v", err)
  213. }
  214. for _, image := range listResp.Images {
  215. imageStat.TotalStorageBytes = imageStat.TotalStorageBytes + uint64(image.Size)
  216. }
  217. return &imageStat, nil
  218. }