forked from SUSE/zypper-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
163 lines (140 loc) · 4.47 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Copyright (c) 2015 SUSE LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
"strings"
)
const cacheName = "docker-zypper.json"
// The representation of cached data for this application.
type cachedData struct {
// The path to the original cache file.
Path string `json:"-"`
// Contains all the IDs that are known to be valid openSUSE/SLE images.
Suse []string `json:"suse"`
// Contains all the IDs that are known to be non-openSUSE/SLE images.
Other []string `json:"other"`
// Contains all the IDs of the images that have been either patched or
// upgraded or patched using zypper-docker
Outdated []string `json:"outdated"`
// Whether this data comes from a valid file or not.
Valid bool `json:"-"`
}
// Checks whether the given Id exists or not. It returns two booleans:
// - Whether it exists or not.
// - If it exists, whether it is a SUSE image or not.
func (cd *cachedData) idExists(id string) (bool, bool) {
suse := arrayIncludeString(cd.Suse, id)
other := arrayIncludeString(cd.Other, id)
return suse || other, suse
}
// Returns whether the given ID matches an image that has been
// updated via zypper-docker patch|update
func (cd *cachedData) isImageOutdated(id string) bool {
return arrayIncludeString(cd.Outdated, id)
}
// Returns whether the given ID matches an image that is based on SUSE.
func (cd *cachedData) isSUSE(id string) bool {
if cd.Valid {
if exists, suse := cd.idExists(id); exists {
return suse
}
}
suse := checkCommandInImage(id, "zypper")
if cd.Valid {
if suse {
cd.Suse = append(cd.Suse, id)
} else {
cd.Other = append(cd.Other, id)
}
}
return suse
}
// Writes all the cached data back to the cache file. This is needed because
// functions like `inSUSE` only write to memory. Therefore, once you're done
// with this instance, you should call this function to keep everything synced.
func (cd *cachedData) flush() {
if !cd.Valid {
// Silently fail, the user has probably already been notified about it.
return
}
file, err := os.OpenFile(cd.Path, os.O_RDWR|os.O_TRUNC, 0666)
if err != nil {
log.Printf("Cannot write to the cache file: %v", err)
return
}
enc := json.NewEncoder(file)
_ = enc.Encode(cd)
_ = file.Close()
}
// Empty the contents of the cache file.
func (cd *cachedData) reset() {
cd.Suse, cd.Other = []string{}, []string{}
cd.flush()
}
// Add the ID of the image identified by the provided name to the list
// of the outdated images.
func (cd *cachedData) addImageToListOfOutdatedOnes(name string) error {
imageId, err := getImageId(name)
if err != nil {
return err
}
if !arrayIncludeString(cd.Outdated, imageId) {
cd.Outdated = append(cd.Outdated, imageId)
cd.flush()
}
return nil
}
// Retrieves the path for the cache file. It checks the following directories
// in this specific order:
// 1. $HOME/.cache
// 2. /tmp
// It will try to open (or create if it doesn't exist) the cache file in each
// directory until it finds a directory that is accessible.
func cachePath() *os.File {
candidates := []string{filepath.Join(os.Getenv("HOME"), ".cache"), "/tmp"}
for _, dir := range candidates {
dirs := strings.Split(dir, ":")
for _, d := range dirs {
name := filepath.Join(d, cacheName)
file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0666)
if err == nil {
return file
}
}
}
return nil
}
// Create a cache file or get the current one if it already exists. If that is
// not possible, then the returned struct will be marked as invalid (meaning
// that `isSUSE` will work without caching).
func getCacheFile() *cachedData {
file := cachePath()
if file == nil {
log.Println("Could not find path for the cache!")
return &cachedData{Valid: false}
}
cd := &cachedData{Valid: true, Path: file.Name()}
dec := json.NewDecoder(file)
err := dec.Decode(&cd)
_ = file.Close()
if err != nil {
log.Println("Cache file has a bad format!")
return &cachedData{Valid: true, Path: file.Name()}
}
return cd
}