This file is indexed.

/usr/share/gocode/src/github.com/ctdk/goiardi/datastore/datastore.go is in golang-github-ctdk-goiardi-dev 0.11.7-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/*
 * Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
 *
 * 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 datastore provides data store functionality. The data store is kept in
memory, but optionally the data store may be saved to a file to provide a
perisistent data store. This uses go-cache (https://github.com/pmylund/go-cache)
for storing the data.

The methods that set, get, and delete key/value pairs also take a `keyType`
argument that specifies what kind of object it is.
*/
package datastore

import (
	"bytes"
	"compress/zlib"
	"encoding/gob"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"reflect"
	"sort"
	"strings"
	"sync"

	"github.com/ctdk/goiardi/config"
	"github.com/pmylund/go-cache"
	"github.com/tideland/golib/logger"
)

// ErrorNodeStatus is for errors specific to the absence of node statuses in the
// system
type ErrorNodeStatus error

// Errors that may come up with the node statuses.
var (
	// ErrNoStatuses is returned where there are no node statuses in the
	// datastore at all.
	ErrNoStatuses ErrorNodeStatus = errors.New("No statuses in the datastore")

	// ErrNoStatusList is returned when there are statuses in the datastore,
	// but somehow the map of int slices associating a status with a node is
	// missing.
	ErrNoStatusList ErrorNodeStatus = errors.New("No status lists in the datastore")
)

// DataStore is the main data store struct, holding the key/value store and list
// of objects.
type DataStore struct {
	dsc     *cache.Cache
	objList map[string]map[string]bool
	m       sync.RWMutex
	updated bool
}

type dsFileStore struct {
	Cache   []byte
	ObjList []byte
}

type dsItem struct {
	Item interface{}
}

var dataStoreCache = initDataStore()

func initDataStore() *DataStore {
	ds := new(DataStore)
	ds.dsc = cache.New(0, 0)
	ds.objList = make(map[string]map[string]bool)
	return ds
}

// New creates a new data store instance, or returns an already created one.
func New() *DataStore {
	return dataStoreCache
}

func (ds *DataStore) makeKey(keyType string, key string) string {
	var newKey []string
	newKey = append(newKey, keyType)
	newKey = append(newKey, key)
	return strings.Join(newKey, ":")
}

// Set a value of the given type with the provided key.
func (ds *DataStore) Set(keyType string, key string, val interface{}) {
	dsKey := ds.makeKey(keyType, key)
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	if config.Config.UseUnsafeMemStore {
		ds.dsc.Set(dsKey, val, -1)
	} else {
		valBytes, err := encodeSafeVal(val)
		if err != nil {
			log.Fatalln(err)
		}
		ds.dsc.Set(dsKey, valBytes, -1)
	}
	ds.addToList(keyType, key)
}

// Get a value of the given type associated with the given key, if it exists.
func (ds *DataStore) Get(keyType string, key string) (interface{}, bool) {
	var val interface{}
	var found bool

	dsKey := ds.makeKey(keyType, key)
	ds.m.RLock()
	defer ds.m.RUnlock()

	if config.Config.UseUnsafeMemStore {
		val, found = ds.dsc.Get(dsKey)
	} else {
		valEnc, f := ds.dsc.Get(dsKey)
		found = f

		if valEnc != nil {
			var err error
			val, err = decodeSafeVal(valEnc)
			if err != nil {
				log.Fatalln(err)
			}
		}
	}
	if val != nil {
		ChkNilArray(val)
	}
	return val, found
}

func encodeSafeVal(val interface{}) ([]byte, error) {
	valBuf := new(bytes.Buffer)
	valItem := &dsItem{Item: val}
	enc := gob.NewEncoder(valBuf)
	err := enc.Encode(valItem)

	if err != nil {
		return nil, err
	}
	return valBuf.Bytes(), nil
}

func decodeSafeVal(valEnc interface{}) (interface{}, error) {
	valBuf := bytes.NewBuffer(valEnc.([]byte))
	valItem := new(dsItem)
	dec := gob.NewDecoder(valBuf)
	err := dec.Decode(&valItem)
	if err != nil {
		return nil, err
	}
	return valItem.Item, nil
}

// Delete a value from the data store.
func (ds *DataStore) Delete(keyType string, key string) {
	dsKey := ds.makeKey(keyType, key)
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	ds.dsc.Delete(dsKey)
	ds.removeFromList(keyType, key)
}

/* For the in-memory data store stuff, we need a convenient list of objects,
 * since it's not a database and we can't just pull that up. This won't be
 * useful normally. */

func (ds *DataStore) addToList(keyType string, key string) {
	if ds.objList[keyType] == nil {
		ds.objList[keyType] = make(map[string]bool)
	}
	ds.objList[keyType][key] = true
}

func (ds *DataStore) removeFromList(keyType string, key string) {
	if ds.objList[keyType] != nil {
		/* If it's nil, we don't have to worry about deleting the key */
		delete(ds.objList[keyType], key)
	}
}

// GetList returns a list of all objects of the given type.
func (ds *DataStore) GetList(keyType string) []string {
	j := make([]string, len(ds.objList[keyType]))
	i := 0
	ds.m.RLock()
	defer ds.m.RUnlock()
	for k := range ds.objList[keyType] {
		j[i] = k
		i++
	}
	sort.Strings(j)
	return j
}

// SetNodeStatus updates a node's status using the in-memory data store.
func (ds *DataStore) SetNodeStatus(nodeName string, obj interface{}, nsID ...int) error {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	nsKey := ds.makeKey("nodestatus", "nodestatuses")
	nsListKey := ds.makeKey("nodestatuslist", "nodestatuslists")
	a, _ := ds.dsc.Get(nsKey)
	if a == nil {
		a = make(map[int]interface{})
	}
	ns := a.(map[int]interface{})
	a, _ = ds.dsc.Get(nsListKey)
	if a == nil {
		a = make(map[string][]int)
	}
	nslist := a.(map[string][]int)
	var nextID int
	if nsID != nil {
		nextID = nsID[0]
	} else {
		nextID = getNextID(ns)
	}
	if config.Config.UseUnsafeMemStore {
		ns[nextID] = obj
	} else {
		n, err := encodeSafeVal(obj)
		if err != nil {
			return err
		}
		ns[nextID] = n
	}
	nslist[nodeName] = append(nslist[nodeName], nextID)

	ds.dsc.Set(nsKey, ns, -1)
	ds.dsc.Set(nsListKey, nslist, -1)
	return nil
}

// ReplaceNodeStatuses replaces the node statuses being stored in the data store
// with the provided statuses that have been ordered by age already. This is
// most useful when purging old statuses.
func (ds *DataStore) ReplaceNodeStatuses(nodeName string, objs []interface{}) error {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true

	// Delete the old statuses
	err := ds.deleteStatuses(nodeName)
	if err != nil {
		return err
	}

	// and put the ones we want to keep, if any, back in.
	if len(objs) == 0 {
		return nil
	}
	nsKey := ds.makeKey("nodestatus", "nodestatuses")
	nsListKey := ds.makeKey("nodestatuslist", "nodestatuslists")
	a, _ := ds.dsc.Get(nsKey)
	if a == nil {
		a = make(map[int]interface{})
	}
	ns := a.(map[int]interface{})
	a, _ = ds.dsc.Get(nsListKey)
	if a == nil {
		a = make(map[string][]int)
	}
	nslist := a.(map[string][]int)

	for _, o := range objs {
		nextID := getNextID(ns)
		if config.Config.UseUnsafeMemStore {
			ns[nextID] = o
		} else {
			n, err := encodeSafeVal(o)
			if err != nil {
				return err
			}
			ns[nextID] = n
		}
		nslist[nodeName] = append(nslist[nodeName], nextID)
	}
	ds.dsc.Set(nsKey, ns, -1)
	ds.dsc.Set(nsListKey, nslist, -1)
	return nil
}

// AllNodeStatuses returns a list of all statuses known for the given node from
// the in-memory data store.
func (ds *DataStore) AllNodeStatuses(nodeName string) ([]interface{}, error) {
	ds.m.RLock()
	defer ds.m.RUnlock()
	nsKey := ds.makeKey("nodestatus", "nodestatuses")
	nsListKey := ds.makeKey("nodestatuslist", "nodestatuslists")
	a, _ := ds.dsc.Get(nsKey)
	if a == nil {
		return nil, ErrNoStatuses
	}
	ns := a.(map[int]interface{})
	a, _ = ds.dsc.Get(nsListKey)
	if a == nil {
		return nil, ErrNoStatusList
	}
	nslist := a.(map[string][]int)
	arr := make([]interface{}, len(nslist[nodeName]))
	for i, v := range nslist[nodeName] {
		if config.Config.UseUnsafeMemStore {
			arr[i] = ns[v]
		} else {
			n, err := decodeSafeVal(ns[v])
			if err != nil {
				return nil, err
			}
			arr[i] = n
		}
	}
	return arr, nil
}

// LatestNodeStatus returns the latest status for a node from the in-memory
// data store.
func (ds *DataStore) LatestNodeStatus(nodeName string) (interface{}, error) {
	ds.m.RLock()
	defer ds.m.RUnlock()
	nsKey := ds.makeKey("nodestatus", "nodestatuses")
	nsListKey := ds.makeKey("nodestatuslist", "nodestatuslists")
	a, _ := ds.dsc.Get(nsKey)
	if a == nil {
		return nil, ErrNoStatuses
	}
	ns := a.(map[int]interface{})
	a, _ = ds.dsc.Get(nsListKey)
	if a == nil {
		return nil, ErrNoStatusList
	}
	nslist := a.(map[string][]int)
	nsarr := nslist[nodeName]
	if nsarr == nil {
		err := fmt.Errorf("no statuses found for node %s", nodeName)
		return nil, ErrorNodeStatus(err)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(nsarr)))
	var n interface{}
	var err error

	if config.Config.UseUnsafeMemStore {
		n = ns[nsarr[0]]
	} else {
		n, err = decodeSafeVal(ns[nsarr[0]])
		if err != nil {
			return nil, err
		}
	}

	return n, nil
}

// DeleteNodeStatus deletes all status reports for a node from the in-memory
// data store.
func (ds *DataStore) DeleteNodeStatus(nodeName string) error {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	return ds.deleteStatuses(nodeName)
}

func (ds *DataStore) deleteStatuses(nodeName string) error {
	nsKey := ds.makeKey("nodestatus", "nodestatuses")
	nsListKey := ds.makeKey("nodestatuslist", "nodestatuslists")
	a, _ := ds.dsc.Get(nsKey)
	if a == nil {
		return ErrNoStatuses
	}
	ns := a.(map[int]interface{})
	a, _ = ds.dsc.Get(nsListKey)
	if a == nil {
		return ErrNoStatusList
	}
	nslist := a.(map[string][]int)
	for _, v := range nslist[nodeName] {
		delete(ns, v)
	}
	delete(nslist, nodeName)
	ds.dsc.Set(nsKey, ns, -1)
	ds.dsc.Set(nsListKey, nslist, -1)
	return nil
}

func (ds *DataStore) getLogInfoMap() map[int]interface{} {
	dsKey := ds.makeKey("loginfo", "loginfos")
	var a interface{}
	if config.Config.UseUnsafeMemStore {
		a, _ = ds.dsc.Get(dsKey)
	} else {
		aEnc, _ := ds.dsc.Get(dsKey)
		if aEnc != nil {
			var err error
			a, err = decodeSafeVal(aEnc)
			if err != nil {
				log.Fatalln(err)
			}
		}
	}
	if a == nil {
		a = make(map[int]interface{})
	}
	arr := a.(map[int]interface{})
	return arr
}

func (ds *DataStore) setLogInfoMap(liMap map[int]interface{}) {
	dsKey := ds.makeKey("loginfo", "loginfos")
	if config.Config.UseUnsafeMemStore {
		ds.dsc.Set(dsKey, liMap, -1)
	} else {
		valBytes, err := encodeSafeVal(liMap)
		if err != nil {
			log.Fatalln(err)
		}
		ds.dsc.Set(dsKey, valBytes, -1)
	}
}

// SetLogInfo sets a loginfo in the data store. Unlike most of these objects,
// log infos are stored and retrieved by id, since they have no useful names.
func (ds *DataStore) SetLogInfo(obj interface{}, logID ...int) error {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	arr := ds.getLogInfoMap()
	var nextID int
	if logID != nil {
		nextID = logID[0]
	} else {
		nextID = getNextID(arr)
	}
	arr[nextID] = obj
	ds.setLogInfoMap(arr)
	return nil
}

// DeleteLogInfo deletes a logged event from the data store.
func (ds *DataStore) DeleteLogInfo(id int) error {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	arr := ds.getLogInfoMap()
	delete(arr, id)
	ds.setLogInfoMap(arr)
	return nil
}

// PurgeLogInfoBefore purges all the logged events with an id less than the one
// given from the data store.
func (ds *DataStore) PurgeLogInfoBefore(id int) (int64, error) {
	ds.m.Lock()
	defer ds.m.Unlock()
	ds.updated = true
	arr := ds.getLogInfoMap()
	newLogs := make(map[int]interface{})
	var purged int64
	for k, v := range arr {
		if k > id {
			newLogs[k] = v
		} else {
			purged++
		}
	}
	ds.setLogInfoMap(newLogs)
	return purged, nil
}

func getNextID(lis map[int]interface{}) int {
	if len(lis) == 0 {
		return 1
	}
	var keys []int
	for k := range lis {
		keys = append(keys, k)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))
	return keys[0] + 1
}

// GetLogInfo gets a loginfo by id.
func (ds *DataStore) GetLogInfo(id int) (interface{}, error) {
	ds.m.RLock()
	defer ds.m.RUnlock()
	arr := ds.getLogInfoMap()
	item := arr[id]
	if item == nil {
		err := fmt.Errorf("Log info with id %d not found", id)
		return nil, err
	}
	return item, nil
}

// GetLogInfoList gets all the log infos currently stored.
func (ds *DataStore) GetLogInfoList() map[int]interface{} {
	ds.m.RLock()
	defer ds.m.RUnlock()
	arr := ds.getLogInfoMap()
	return arr
}

// Save freezes and saves the data store to disk.
func (ds *DataStore) Save(dsFile string) error {
	if !ds.updated {
		return nil
	}
	logger.Debugf("Data has changed, saving data store to disk")
	if dsFile == "" {
		err := fmt.Errorf("Yikes! Cannot save data store to disk because no file was specified.")
		return err
	}
	fp, err := ioutil.TempFile(path.Dir(dsFile), "ds-store")
	if err != nil {
		return err
	}
	zfp := zlib.NewWriter(fp)

	fstore := new(dsFileStore)
	dscache := new(bytes.Buffer)
	objList := new(bytes.Buffer)
	ds.m.RLock()
	defer ds.m.RUnlock()
	ds.updated = false

	err = ds.dsc.Save(dscache)
	if err != nil {
		fp.Close()
		return err
	}
	enc := gob.NewEncoder(objList)
	defer func() {
		if x := recover(); x != nil {
			err = fmt.Errorf("Something went wrong encoding the data store with Gob")
		}
	}()
	err = enc.Encode(ds.objList)
	if err != nil {
		fp.Close()
		return err
	}
	fstore.Cache = dscache.Bytes()
	fstore.ObjList = objList.Bytes()
	enc = gob.NewEncoder(zfp)
	err = enc.Encode(fstore)
	zfp.Close()
	if err != nil {
		fp.Close()
		return err
	}
	err = fp.Close()
	if err != nil {
		return err
	}
	return os.Rename(fp.Name(), dsFile)
}

// Load the frozen data store from disk.
func (ds *DataStore) Load(dsFile string) error {
	if dsFile == "" {
		err := fmt.Errorf("Yikes! Cannot load data store from disk because no file was specified.")
		return err
	}

	fp, err := os.Open(dsFile)
	if err != nil {
		// It's fine for the file not to exist on startup
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	zfp, zerr := zlib.NewReader(fp)
	if zerr != nil {
		fp.Close()
		return zerr
	}
	dec := gob.NewDecoder(zfp)
	ds.m.Lock()
	defer ds.m.Unlock()
	fstore := new(dsFileStore)
	err = dec.Decode(&fstore)
	zfp.Close()
	if err != nil {
		fp.Close()
		log.Printf("error at fstore")
		return err
	}

	dscache := bytes.NewBuffer(fstore.Cache)
	objList := bytes.NewBuffer(fstore.ObjList)

	err = ds.dsc.Load(dscache)
	if err != nil {
		log.Println("error at dscache")
		fp.Close()
		return err
	}
	dec = gob.NewDecoder(objList)
	err = dec.Decode(&ds.objList)
	if err != nil {
		log.Println("error at objList")
		fp.Close()
		return err
	}
	return fp.Close()
}

// ChkNilArray examines an object, searching for empty slices.
// When restoring an object from either the in-memory data store after it has
// been saved to disk, or loading an object from the database with gob encoded
// data structures, empty slices are encoded as "null" when they're sent out as
// JSON to the client. This makes the client very unhappy, so those empty slices
// need to be recreated again. Annoying, but it's how it goes.
func ChkNilArray(obj interface{}) {
	s := reflect.ValueOf(obj).Elem()
	for i := 0; i < s.NumField(); i++ {
		v := s.Field(i)
		switch v.Kind() {
		case reflect.Slice:
			if v.IsNil() {
				o := reflect.MakeSlice(v.Type(), 0, 0)
				v.Set(o)
			}
		case reflect.Map:
			m := v.Interface()
			m = WalkMapForNil(m)
			g := reflect.ValueOf(m)
			v.Set(g)
		}
	}
}

// WalkMapForNil walks through the given map, searching for nil slices to create.
// This does not handle all possible cases, but it *does* handle the cases found
// with the chef objects in goiardi.
func WalkMapForNil(r interface{}) interface{} {
	switch m := r.(type) {
	case map[string]interface{}:
		for k, v := range m {
			m[k] = WalkMapForNil(v)
		}
		r = m
		return r
	case []string:
		if m == nil {
			m = make([]string, 0)
		}
		r = m
		return r
	case []interface{}:
		if m == nil {
			m = make([]interface{}, 0)
		}
		r = m
		return r
	default:
		return r
	}
}