blob: 15fc390ed1562f9c86f10448c8aaf0a516e0c2b5 [file] [log] [blame]
David K. Bainbridgedf9df632016-07-07 18:47:46 -07001// Copyright 2016 Open Networking Laboratory
2//
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//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
David K. Bainbridgef0da8732016-06-01 16:15:37 -070014package main
15
David K. Bainbridge546cdc32016-06-29 15:30:22 -070016import (
17 "fmt"
18 "net/url"
19 "strings"
20)
21
David K. Bainbridgef0da8732016-06-01 16:15:37 -070022type Storage interface {
23 Put(id string, update StatusMsg) error
24 Get(id string) (*StatusMsg, error)
David K. Bainbridge068e87d2016-06-30 13:53:19 -070025 Delete(id string) error
David K. Bainbridgef0da8732016-06-01 16:15:37 -070026 List() ([]StatusMsg, error)
27}
28
David K. Bainbridge546cdc32016-06-29 15:30:22 -070029func NewStorage(spec string) (Storage, error) {
30 conn, err := url.Parse(spec)
31 if err != nil {
32 return nil, err
33 }
34
35 switch strings.ToUpper(conn.Scheme) {
36 case "MEMORY":
37 return NewMemoryStorage(), nil
38 case "CONSUL":
39 return NewConsulStorage(spec)
40 default:
41 return nil, fmt.Errorf("Unknown storage scheme specified, '%s'", conn.Scheme)
42 }
43}
44
David K. Bainbridgef0da8732016-06-01 16:15:37 -070045type MemoryStorage struct {
46 Data map[string]StatusMsg
47}
48
49func NewMemoryStorage() *MemoryStorage {
50 return &MemoryStorage{
51 Data: make(map[string]StatusMsg),
52 }
53}
54
55func (s *MemoryStorage) Put(id string, update StatusMsg) error {
56 s.Data[id] = update
David K. Bainbridgef0da8732016-06-01 16:15:37 -070057 return nil
58}
59
60func (s *MemoryStorage) Get(id string) (*StatusMsg, error) {
61 m, ok := s.Data[id]
62 if !ok {
63 return nil, nil
64 }
65 return &m, nil
66}
67
David K. Bainbridge068e87d2016-06-30 13:53:19 -070068func (s *MemoryStorage) Delete(id string) error {
69 delete(s.Data, id)
70 return nil
71}
72
David K. Bainbridgef0da8732016-06-01 16:15:37 -070073func (s *MemoryStorage) List() ([]StatusMsg, error) {
74 r := make([]StatusMsg, len(s.Data))
75 i := 0
76 for _, v := range s.Data {
77 r[i] = v
David K. Bainbridge97ee8052016-06-14 00:52:07 -070078 i += 1
David K. Bainbridgef0da8732016-06-01 16:15:37 -070079 }
80 return r, nil
81}