Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions coconut/cmd/configuration_history.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* === This file is part of ALICE O² ===
*
* Copyright 2019 CERN and copyright holders of ALICE O².
* Author: George Raduta <george.raduta@cern.ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In applying this license CERN does not waive the privileges and
* immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/

package cmd

import (
"github.com/AliceO2Group/Control/coconut/configuration"
"github.com/spf13/cobra"
)

var configurationHistoryCmd = &cobra.Command{
Use: "history <query>",
Aliases: []string{"h"},
Example: `coconut conf history <component>
coconut conf history <component> <entry>
coconut conf history <component>/<entry>`,
Short: "List all existing entries with timestamps of a specified component in Consul",
Long: `The configuration history command returns all entries with
all of their associated timestamps or returns all timestamps for a specified component and entry`,
Run: configuration.WrapCall(configuration.History),
Args: cobra.RangeArgs(0, 3),
}

func init() {
configurationCmd.AddCommand(configurationHistoryCmd)
configurationHistoryCmd.Flags().StringP("output", "o", "yaml", "output format for the returned entries (yaml/json)")
}
2 changes: 1 addition & 1 deletion coconut/cmd/configuration_list.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* === This file is part of ALICE O² ===
*
* Copyright 2018 CERN and copyright holders of ALICE O².
* Copyright 2019 CERN and copyright holders of ALICE O².
* Author: George Raduta <george.raduta@cern.ch>
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion coconut/cmd/configuration_show.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* === This file is part of ALICE O² ===
*
* Copyright 2018 CERN and copyright holders of ALICE O².
* Copyright 2019 CERN and copyright holders of ALICE O².
* Author: George Raduta <george.raduta@cern.ch>
*
* This program is free software: you can redistribute it and/or modify
Expand Down
120 changes: 119 additions & 1 deletion coconut/configuration/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
package configuration

import (
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/briandowns/spinner"
Expand All @@ -35,6 +37,7 @@ import (
"io"
"github.com/sirupsen/logrus"
"os"
"sort"
"github.com/AliceO2Group/Control/common/logger"
"fmt"
"strings"
Expand Down Expand Up @@ -64,6 +67,11 @@ const (
logicError = iota // Logic/Output error
)

var(
blue = color.New(color.FgHiBlue).SprintFunc()
red = color.New(color.FgHiRed).SprintFunc()
)

func WrapCall(call ConfigurationCall) RunFunc {
return func(cmd *cobra.Command, args []string) {
endpoint := viper.GetString("config_endpoint")
Expand Down Expand Up @@ -262,6 +270,68 @@ func Show(cfg *configuration.ConsulSource, cmd *cobra.Command, args []string, o
return nil, nonZero
}

func History(cfg *configuration.ConsulSource, cmd *cobra.Command, args []string, o io.Writer)(err error, code int) {
var key, component, entry string

if len(args) < 1 || len(args) > 2 {
err = errors.New(fmt.Sprintf("Accepts between 0 and 3 arg(s), but received %d", len(args)))
return err, invalidArgs
}
switch len(args) {
case 1:
if IsInputSingleValidWord(args[0]) {
component = args[0]
entry = ""
} else if IsInputNameValid(args[0]) && !strings.Contains(args[0], "@"){
splitCom := strings.Split(args[0], "/")
component = splitCom[0]
entry = splitCom[1]
} else {
return errors.New(fmt.Sprintf("Component and Entry name cannot contain `/ or `@`")), invalidArgs
}
case 2:
if IsInputSingleValidWord(args[0]) && IsInputSingleValidWord(args[1]) {
component = args[0]
entry = args[1]
} else {
return errors.New(fmt.Sprintf("Component and Entry name cannot contain `/ or `@`")), invalidArgs
}
}

key = componentsPath + component + "/" + entry
var keys sort.StringSlice
keys , err = cfg.GetKeysByPrefix(key, "")

if len(keys) == 0 {
return errors.New(fmt.Sprintf("No data was found")), emptyData
} else {
if entry != "" {
sort.Sort(sort.Reverse(keys))
drawTableHistoryConfigs([]string{}, keys, 0, o)
} else {
maxLen := GetMaxLenOfKey(keys)
var currentKeys sort.StringSlice
_, entry, _ := GetComponentEntryTimestamp(keys[0])

for _, value := range keys {
_, currentEntry, _ := GetComponentEntryTimestamp(value)
if currentEntry == entry {
currentKeys = append(currentKeys, value)
} else {
fmt.Fprintln(o, "- " + entry)
sort.Sort(sort.Reverse(currentKeys)) //sort in reverse of timestamps
drawTableHistoryConfigs([]string{}, currentKeys,maxLen, o)
currentKeys = []string{value}
entry = currentEntry
}
}
fmt.Fprintln(o, "- " + entry)
drawTableHistoryConfigs([]string{}, currentKeys,maxLen, o)
}
}
return nil, 0
}

func formatListOutput( cmd *cobra.Command, output []string)(parsedOutput []byte, err error) {
format, err := cmd.Flags().GetString("output")
if err != nil {
Expand Down Expand Up @@ -289,6 +359,16 @@ func IsInputSingleValidWord(input string) bool {
return !strings.Contains(input, "/") && !strings.Contains(input, "@")
}

// Method to parse a timestamp in the specified format
func GetTimestampInFormat(timestamp string, timeFormat string)(string, error){
timeStampAsInt, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return "", errors.New(fmt.Sprintf("Unable to identify timestamp"))
}
tm := time.Unix(timeStampAsInt, 0)
return tm.Format(timeFormat), nil
}

// Method to return the latest timestamp for a specified component & entry
// If no keys were passed an error and code exit 3 will be returned
func GetLatestTimestamp(keys []string, component string, entry string)(timestamp string, err error, code int) {
Expand Down Expand Up @@ -343,4 +423,42 @@ func GetListOfComponentsAndOrWithTimestamps(keys []string, keyPrefix string, use
}
}
return components, nil, nonZero
}
}

func drawTableHistoryConfigs(headers []string, history []string, max int, o io.Writer) {
table := tablewriter.NewWriter(o)
if len(headers) > 0 {
table.SetHeader(headers)
}
table.SetBorder(false)
table.SetColMinWidth(0, max)

for _, value := range history {
component, entry, timestamp := GetComponentEntryTimestamp(value)
prettyTimestamp, err := GetTimestampInFormat(timestamp, time.RFC822)
if err != nil {
prettyTimestamp = timestamp
}
configName := red(component) + "/" + blue(entry) + "@" + timestamp
table.Append([]string{configName, prettyTimestamp})
}
table.Render()
}

func GetComponentEntryTimestamp(key string)(string, string, string) {
key = strings.TrimPrefix(key, componentsPath)
key = strings.TrimPrefix(key, "/'")
key = strings.TrimSuffix(key, "/")
elements := strings.Split(key, "/")
return elements[0], elements[1], elements[2]
}

func GetMaxLenOfKey(keys []string) (maxLen int){
Comment thread
teo marked this conversation as resolved.
maxLen = 0
for _, value := range keys {
if len(value) - len(componentsPath) >= maxLen {
maxLen = len(value) - len(componentsPath)
}
}
return
}
Loading