forked from dnaeon/gru
/
file.go
491 lines (400 loc) · 10.3 KB
/
file.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package resource
import (
"crypto/md5"
"errors"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"github.com/dnaeon/gru/utils"
)
// BaseFile type is the base type which is embedded by
// File, Directory and Link resources.
type BaseFile struct {
Base
// Path to the file. Defaults to the resource name.
Path string `luar:"-"`
// Permission bits to set on the file.
// For regular files defaults to 0644.
// For directories defaults to 0755.
Mode os.FileMode `luar:"mode"`
// Owner of the file. Defaults to the currently running user.
Owner string `luar:"owner"`
// Group of the file.
// Defaults to the group of the currently running user.
Group string `luar:"group"`
}
// isModeSynced returns a boolean indicating whether the
// permissions of the file managed by the resource are in sync.
func (bf *BaseFile) isModeSynced() (bool, error) {
dst := utils.NewFileUtil(bf.Path)
if !dst.Exists() {
return false, ErrResourceAbsent
}
mode, err := dst.Mode()
if err != nil {
return false, err
}
return mode.Perm() == bf.Mode, nil
}
// setMode sets the permissions on the file managed by the resource.
func (bf *BaseFile) setMode() error {
Logf("%s setting permissions to %#o\n", bf.ID(), bf.Mode)
dst := utils.NewFileUtil(bf.Path)
return dst.Chmod(bf.Mode)
}
// isOwnerSynced checks whether the file ownership is correct.
func (bf *BaseFile) isOwnerSynced() (bool, error) {
dst := utils.NewFileUtil(bf.Path)
if !dst.Exists() {
return false, ErrResourceAbsent
}
owner, err := dst.Owner()
if err != nil {
return false, err
}
return owner.User.Username == bf.Owner && owner.Group.Name == bf.Group, nil
}
// setOwner sets the ownership of the file.
func (bf *BaseFile) setOwner() error {
Logf("%s setting ownership to %s:%s\n", bf.ID(), bf.Owner, bf.Group)
dst := utils.NewFileUtil(bf.Path)
return dst.SetOwner(bf.Owner, bf.Group)
}
// File resource manages files.
//
// Example:
// foo = resource.file.new("/tmp/foo")
// foo.state = "present"
// foo.mode = tonumber("0600", 8)
// foo.owner = "root"
// foo.group = "wheel"
// foo.content = "content of file foo"
type File struct {
BaseFile
// Content of file to set.
Content []byte `luar:"content"`
// Source file to use for the file content.
Source string `luar:"source"`
}
// isContentSynced checks if the file content is in sync with the
// given content.
func (f *File) isContentSynced() (bool, error) {
// We don't have a content, assume content is correct
if f.Content == nil {
return true, nil
}
dst := utils.NewFileUtil(f.Path)
if !dst.Exists() {
return false, ErrResourceAbsent
}
dstMd5, err := dst.Md5()
if err != nil {
return false, err
}
srcMd5 := fmt.Sprintf("%x", md5.Sum(f.Content))
return srcMd5 == dstMd5, nil
}
// setContent sets the content of the file.
func (f *File) setContent() error {
dst := utils.NewFileUtil(f.Path)
dstMd5, err := dst.Md5()
if err != nil {
return err
}
Logf("%s setting content to md5:%s\n", f.ID(), dstMd5)
return ioutil.WriteFile(f.Path, f.Content, f.Mode)
}
// NewFile creates a resource for managing regular files.
func NewFile(name string) (Resource, error) {
// Defaults for owner and group
currentUser, err := user.Current()
if err != nil {
return nil, err
}
currentGroup, err := user.LookupGroupId(currentUser.Gid)
if err != nil {
return nil, err
}
// Resource defaults
f := &File{
BaseFile: BaseFile{
Base: Base{
Name: name,
Type: "file",
State: "present",
Require: make([]string, 0),
PresentStatesList: []string{"present"},
AbsentStatesList: []string{"absent"},
Concurrent: true,
Subscribe: make(TriggerMap),
},
Path: name,
Mode: 0644,
Owner: currentUser.Username,
Group: currentGroup.Name,
},
Content: nil,
Source: "",
}
// Set resource properties
f.PropertyList = []Property{
&ResourceProperty{
PropertyName: "mode",
PropertySetFunc: f.setMode,
PropertyIsSyncedFunc: f.isModeSynced,
},
&ResourceProperty{
PropertyName: "ownership",
PropertySetFunc: f.setOwner,
PropertyIsSyncedFunc: f.isOwnerSynced,
},
&ResourceProperty{
PropertyName: "content",
PropertySetFunc: f.setContent,
PropertyIsSyncedFunc: f.isContentSynced,
},
}
return f, nil
}
// Validate validates the file resource.
func (f *File) Validate() error {
if err := f.Base.Validate(); err != nil {
return err
}
if f.Source != "" && f.Content != nil {
return errors.New("cannot use both 'source' and 'content'")
}
return nil
}
// Initialize initializes the file resource.
func (f *File) Initialize() error {
// Set file content from the given source file if any.
// TODO: Currenly this works only for files in the site repo.
// TODO: Implement a generic file content fetcher.
if f.Source != "" {
src := filepath.Join(DefaultConfig.SiteRepo, f.Source)
content, err := ioutil.ReadFile(src)
if err != nil {
return err
}
f.Content = content
}
return nil
}
// Evaluate evaluates the state of the file resource.
func (f *File) Evaluate() (State, error) {
state := State{
Current: "unknown",
Want: f.State,
}
fi, err := os.Stat(f.Path)
if os.IsNotExist(err) {
state.Current = "absent"
return state, nil
}
state.Current = "present"
if !fi.Mode().IsRegular() {
return state, errors.New("path exists, but is not a regular file")
}
return state, nil
}
// Create creates the file managed by the resource.
func (f *File) Create() error {
Logf("%s creating file\n", f.ID())
return ioutil.WriteFile(f.Path, f.Content, f.Mode)
}
// Delete deletes the file managed by the resource.
func (f *File) Delete() error {
Logf("%s removing file\n", f.ID())
return os.Remove(f.Path)
}
// Directory resource manages directories.
//
// Example:
// bar = resource.directory.new("/tmp/bar")
// bar.state = "present"
// bar.mode = tonumber("0700", 8)
// bar.owner = "root"
// bar.group = "wheel"
type Directory struct {
BaseFile
// Parents flag specifies whether or not to create/delete
// parent directories. Defaults to false.
Parents bool `luar:"parents"`
}
// NewDirectory creates a resource for managing directories.
func NewDirectory(name string) (Resource, error) {
// Defaults for owner and group
currentUser, err := user.Current()
if err != nil {
return nil, err
}
currentGroup, err := user.LookupGroupId(currentUser.Gid)
if err != nil {
return nil, err
}
// Resource defaults
d := &Directory{
BaseFile: BaseFile{
Base: Base{
Name: name,
Type: "directory",
State: "present",
Require: make([]string, 0),
PresentStatesList: []string{"present"},
AbsentStatesList: []string{"absent"},
Concurrent: true,
Subscribe: make(TriggerMap),
},
Path: name,
Mode: 0755,
Owner: currentUser.Username,
Group: currentGroup.Name,
},
Parents: false,
}
// Set resource properties
d.PropertyList = []Property{
&ResourceProperty{
PropertyName: "mode",
PropertySetFunc: d.setMode,
PropertyIsSyncedFunc: d.isModeSynced,
},
&ResourceProperty{
PropertyName: "ownership",
PropertySetFunc: d.setOwner,
PropertyIsSyncedFunc: d.isOwnerSynced,
},
}
return d, nil
}
// Evaluate evaluates the state of the directory.
func (d *Directory) Evaluate() (State, error) {
state := State{
Current: "unknown",
Want: d.State,
}
fi, err := os.Stat(d.Path)
if os.IsNotExist(err) {
state.Current = "absent"
return state, nil
}
state.Current = "present"
if !fi.Mode().IsDir() {
return state, errors.New("path exists, but is not a directory")
}
return state, nil
}
// Create creates the directory.
func (d *Directory) Create() error {
Logf("%s creating directory\n", d.ID())
if d.Parents {
return os.MkdirAll(d.Path, d.Mode)
}
return os.Mkdir(d.Path, d.Mode)
}
// Delete removes the directory.
func (d *Directory) Delete() error {
Logf("%s removing directory\n")
if d.Parents {
return os.RemoveAll(d.Path)
}
return os.Remove(d.Path)
}
// Link resource manages links between files.
//
// Example:
// baz = resource.link.new("/tmp/baz")
// baz.state = "present"
// baz.source = "/tmp/qux"
type Link struct {
BaseFile
// Source file points to the file the link will be set to.
Source string `luar:"source"`
// Hard flag specifies whether or not to create a hard link to the file.
// Defaults to false.
Hard bool `luar:"hard"`
}
// NewLink creates a new resource for managing links between files.
func NewLink(name string) (Resource, error) {
l := &Link{
BaseFile: BaseFile{
Base: Base{
Name: name,
Type: "link",
State: "present",
Require: make([]string, 0),
PresentStatesList: []string{"present"},
AbsentStatesList: []string{"absent"},
Concurrent: true,
Subscribe: make(TriggerMap),
},
Path: name,
},
Source: "",
Hard: false,
}
return l, nil
}
// Validate validates the link resource.
func (l *Link) Validate() error {
if l.Source == "" {
return errors.New("must provide source file")
}
src := utils.NewFileUtil(l.Source)
if !src.Exists() {
return fmt.Errorf("source file %s does not exist", l.Source)
}
return nil
}
// Evaluate evaluates the state of the link.
func (l *Link) Evaluate() (State, error) {
state := State{
Current: "unknown",
Want: l.State,
}
_, err := os.Stat(l.Path)
if os.IsNotExist(err) {
state.Current = "absent"
return state, nil
}
state.Current = "present"
_, err = os.Readlink(l.Path)
if err != nil {
return state, fmt.Errorf("path exists, but is not a link: %s\n", err)
}
return state, nil
}
// Create creates the link.
func (l *Link) Create() error {
Logf("%s creating link\n", l.ID())
if l.Hard {
return os.Link(l.Source, l.Path)
}
return os.Symlink(l.Source, l.Path)
}
// Delete removes the link.
func (l *Link) Delete() error {
Logf("%s removing link\n", l.ID())
return os.Remove(l.Path)
}
func init() {
file := ProviderItem{
Type: "file",
Provider: NewFile,
Namespace: DefaultResourceNamespace,
}
dir := ProviderItem{
Type: "directory",
Provider: NewDirectory,
Namespace: DefaultResourceNamespace,
}
link := ProviderItem{
Type: "link",
Provider: NewLink,
Namespace: DefaultResourceNamespace,
}
RegisterProvider(file, dir, link)
}