New Admin API client-side implementation (#2350)

This commit is contained in:
Aditya Manthramurthy
2018-01-23 12:32:58 -08:00
committed by Harshavardhana
parent 83bb797389
commit 793cda2ca0
33 changed files with 2427 additions and 944 deletions
+1 -1
View File
@@ -122,7 +122,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
// Call get config API
c, e := client.SetConfig(os.Stdin)
fatalIf(probe.NewError(e), "Cannot get server configuration file.")
fatalIf(probe.NewError(e), "Cannot set server configuration file.")
// Print set config result
printMsg(configSetMessage{
+117
View File
@@ -0,0 +1,117 @@
/*
* Minio Client (C) 2018 Minio, Inc.
*
* 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 cmd
import (
"fmt"
"github.com/minio/minio/pkg/madmin"
)
type hri struct {
*madmin.HealResultItem
}
func newHRI(i *madmin.HealResultItem) *hri {
return &hri{i}
}
// getObjectHCCChange - returns before and after color change for
// objects
func (h hri) getObjectHCCChange() (b, a hCol, err error) {
parityShards := h.ParityBlocks
dataShards := h.DataBlocks
onlineBefore, onlineAfter := h.GetOnlineCounts()
surplusShardsBeforeHeal := onlineBefore - dataShards
surplusShardsAfterHeal := onlineAfter - dataShards
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
return
}
// getReplicatedFileHCCChange - fetches health color code for metadata
// files that are replicated.
func (h hri) getReplicatedFileHCCChange() (b, a hCol, err error) {
getColCode := func(numAvail int) (c hCol, err error) {
// calculate color code for replicated object similar
// to erasure coded objects
quorum := h.DiskCount/2 + 1
surplus := numAvail - quorum
parity := h.DiskCount - quorum
c, err = getHColCode(surplus, parity)
return
}
onlineBefore, onlineAfter := h.GetOnlineCounts()
b, err = getColCode(onlineBefore)
if err != nil {
return
}
a, err = getColCode(onlineAfter)
return
}
func (h hri) makeHealEntityString() string {
switch h.Type {
case madmin.HealItemObject:
return h.Bucket + "/" + h.Object
case madmin.HealItemBucket:
return h.Bucket
case madmin.HealItemMetadata:
return "[disk-format]"
case madmin.HealItemBucketMetadata:
return fmt.Sprintf("[bucket-metadata]%s/%s", h.Bucket, h.Object)
}
return "** unexpected **"
}
func (h hri) getHRTypeAndName() (typ, name string) {
name = fmt.Sprintf("%s/%s", h.Bucket, h.Object)
switch h.Type {
case madmin.HealItemMetadata:
typ = "system"
name = h.Detail
case madmin.HealItemBucketMetadata:
typ = "system"
name = "bucket-metadata:" + name
case madmin.HealItemBucket:
typ = "bucket"
case madmin.HealItemObject:
typ = "object"
default:
typ = fmt.Sprintf("!! Unknown heal result record %#v !!", h)
name = typ
}
return
}
func (h hri) getHealResultStr() string {
typ, name := h.getHRTypeAndName()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
return typ + ":" + name
default:
return name
}
}
+447
View File
@@ -0,0 +1,447 @@
/*
* Minio Client (C) 2018 Minio, Inc.
*
* 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 cmd
import (
"encoding/json"
"fmt"
"math"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
const (
lineWidth = 80
)
// An alias of string to represent the health color code of an object
type hCol string
const (
hColGrey hCol = "Grey"
hColRed = "Red"
hColYellow = "Yellow"
hColGreen = "Green"
)
// getHPrintCol - map color code to color for printing
func getHPrintCol(c hCol) *color.Color {
switch c {
case hColGrey:
return color.New(color.FgWhite, color.Bold)
case hColRed:
return color.New(color.FgRed, color.Bold)
case hColYellow:
return color.New(color.FgYellow, color.Bold)
case hColGreen:
return color.New(color.FgGreen, color.Bold)
}
return nil
}
var (
hColOrder = []hCol{hColRed, hColYellow, hColGreen}
hColTable = map[int][]int{
1: {0, -1, 1},
2: {0, 1, 2},
3: {1, 2, 3},
4: {1, 2, 4},
5: {1, 3, 5},
6: {2, 4, 6},
7: {2, 4, 7},
8: {2, 5, 8},
}
)
func getHColCode(surplusShards, parityShards int) (c hCol, err error) {
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
}
if surplusShards < 0 {
return hColGrey, err
}
colRow := hColTable[parityShards]
for index, val := range colRow {
if val != -1 && surplusShards <= val {
return hColOrder[index], err
}
}
return c, fmt.Errorf("cannot get a heal color code")
}
type uiData struct {
Bucket, Prefix string
Client *madmin.AdminClient
ClientToken string
ForceStart bool
HealOpts *madmin.HealOpts
LastItem *hri
Quiet bool
JSON bool
// Total time since heal start
HealDuration time.Duration
// Accumulated statistics of heal result records
BytesScanned int64
// Counter for objects, and another counter for all kinds of
// items
ObjectsScanned, ItemsScanned int64
// Counters for healed objects and all kinds of healed items
ObjectsHealed, ItemsHealed int64
// Map from online drives to number of objects with that many
// online drives.
ObjectsByOnlineDrives map[int]int64
// Map of health color code to number of objects with that
// health color code.
HealthCols map[hCol]int64
// channel to receive a prompt string to indicate activity on
// the terminal
CurChan (<-chan string)
}
func (ui *uiData) updateStats(i madmin.HealResultItem) error {
if i.Type == madmin.HealItemObject {
// Objects whose size could not be found have -1 size
// returned.
if i.ObjectSize >= 0 {
ui.BytesScanned += i.ObjectSize
}
ui.ObjectsScanned++
}
ui.ItemsScanned++
beforeUp, afterUp := i.GetOnlineCounts()
if afterUp > beforeUp {
if i.Type == madmin.HealItemObject {
ui.ObjectsHealed++
}
ui.ItemsHealed++
}
ui.ObjectsByOnlineDrives[afterUp]++
// Update health color stats:
// Fetch health color after heal:
var err error
var afterCol hCol
h := newHRI(&i)
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
_, afterCol, err = h.getReplicatedFileHCCChange()
default:
_, afterCol, err = h.getObjectHCCChange()
}
if err != nil {
return err
}
ui.HealthCols[afterCol]++
return nil
}
func (ui *uiData) updateDuration(s *madmin.HealTaskStatus) {
ui.HealDuration = UTCNow().Sub(s.StartTime)
}
func (ui *uiData) getProgress() (oCount, objSize, duration string) {
oCount = humanize.Comma(ui.ObjectsScanned)
duration = ui.HealDuration.Round(time.Second).String()
bytesScanned := float64(ui.BytesScanned)
// Compute unit for object size
magnitudes := []float64{1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50, 1 << 60}
units := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
var i int
for i = 0; i < len(magnitudes); i++ {
if bytesScanned <= magnitudes[i] {
break
}
}
numUnits := int(bytesScanned * (1 << 10) / magnitudes[i])
objSize = fmt.Sprintf("%d %s", numUnits, units[i])
return
}
func (ui *uiData) getPercentsNBars() (p map[hCol]float64, b map[hCol]string) {
// barChar, emptyBarChar := "█", "░"
barChar, emptyBarChar := "█", " "
barLen := 12
sum := float64(ui.ItemsScanned)
cols := []hCol{hColGrey, hColRed, hColYellow, hColGreen}
p = make(map[hCol]float64, len(cols))
b = make(map[hCol]string, len(cols))
var filledLen int
for _, col := range cols {
v := float64(ui.HealthCols[col])
if sum == 0 {
p[col] = 0
filledLen = 0
} else {
p[col] = v * 100 / sum
// round up the filled part
filledLen = int(math.Ceil(float64(barLen) * v / sum))
}
b[col] = strings.Repeat(barChar, filledLen) +
strings.Repeat(emptyBarChar, barLen-filledLen)
}
return
}
func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
lpad := func(s hCol) string {
return fmt.Sprintf("%-6s", string(s))
}
rpad := func(s hCol) string {
return fmt.Sprintf("%6s", string(s))
}
printColStr := func(before, after hCol) {
console.PrintC("[" + lpad(before) + " -> " + rpad(after) + "] ")
}
var b, a hCol
for _, item := range s.Items {
h := newHRI(&item)
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
default:
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return err
}
printColStr(b, a)
hrStr := h.getHealResultStr()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
default:
console.PrintC(hrStr, "\n")
}
}
return nil
}
func (ui *uiData) printStatsQuietly(s *madmin.HealTaskStatus) {
totalObjects, totalSize, totalTime := ui.getProgress()
healedStr := fmt.Sprintf("Healed:\t%s/%s objects; %s in %s\n",
humanize.Comma(ui.ObjectsHealed), totalObjects,
totalSize, totalTime)
console.PrintC(healedStr)
}
func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
type change struct {
Before string `json:"before"`
After string `json:"after"`
}
type healRec struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Type string `json:"type"`
Name string `json:"name"`
Health change `json:"health"`
Drives map[string]change `json:"drives"`
Size int64 `json:"size"`
}
makeHR := func(h *hri) (r healRec, err error) {
r.Status = "success"
r.Type, r.Name = h.getHRTypeAndName()
r.Drives = make(map[string]change)
var b, a hCol
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
default:
if h.Type == madmin.HealItemObject {
r.Size = h.ObjectSize
}
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return r, err
}
r.Health.Before = strings.ToLower(string(b))
r.Health.After = strings.ToLower(string(a))
for k := range h.DriveInfo.Before {
r.Drives[k] = change{h.DriveInfo.Before[k], h.DriveInfo.After[k]}
}
return r, nil
}
for _, item := range s.Items {
h := newHRI(&item)
r, err := makeHR(h)
if err != nil {
return err
}
jsonBytes, err := json.Marshal(r)
fatalIf(probe.NewError(err), "Unable to marshal to JSON")
console.Println(string(jsonBytes))
}
return nil
}
func (ui *uiData) printStatsJSON(s *madmin.HealTaskStatus) {
var summary struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Type string `json:"type"`
ObjectsScanned int64 `json:"objects_scanned"`
ObjectsHealed int64 `json:"objects_healed"`
ItemsScanned int64 `json:"items_scanned"`
ItemsHealed int64 `json:"items_healed"`
Size int64 `json:"size"`
ElapsedTime int64 `json:"duration"`
}
summary.Status = "success"
summary.Type = "summary"
summary.ObjectsScanned = ui.ObjectsScanned
summary.ObjectsHealed = ui.ObjectsHealed
summary.ItemsScanned = ui.ItemsScanned
summary.ItemsHealed = ui.ItemsHealed
summary.Size = ui.BytesScanned
summary.ElapsedTime = int64(ui.HealDuration.Round(time.Second).Seconds())
jBytes, err := json.Marshal(summary)
fatalIf(probe.NewError(err), "Unable to marshal to JSON")
console.Println(string(jBytes))
}
func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
itemCount := len(s.Items)
h := ui.LastItem
if itemCount > 0 {
item := s.Items[itemCount-1]
h = newHRI(&item)
ui.LastItem = h
}
scannedStr := "** waiting for status from server **"
if h != nil {
scannedStr = lineTrunc(h.makeHealEntityString(), lineWidth-len("Scanned: "))
}
totalObjects, totalSize, totalTime := ui.getProgress()
healedStr := fmt.Sprintf("%s/%s objects; %s in %s",
humanize.Comma(ui.ObjectsHealed), totalObjects,
totalSize, totalTime)
yellow := color.New(color.FgYellow, color.Bold)
console.PrintfCustomColor(yellow, " %s", <-ui.CurChan)
console.PrintC(fmt.Sprintf(" %s\n", scannedStr))
console.PrintC(fmt.Sprintf(" %s\n", healedStr))
dspOrder := []hCol{hColGreen, hColYellow, hColRed, hColGrey}
printColors := []*color.Color{}
for _, c := range dspOrder {
printColors = append(printColors, getHPrintCol(c))
}
t := console.NewTable(printColors, []bool{false, true, true}, 4)
percentMap, barMap := ui.getPercentsNBars()
cellText := make([][]string, len(dspOrder))
for i := range cellText {
cellText[i] = []string{
string(dspOrder[i]),
fmt.Sprintf(humanize.Comma(ui.HealthCols[dspOrder[i]])),
fmt.Sprintf("%5.1f%% %s", percentMap[dspOrder[i]], barMap[dspOrder[i]]),
}
}
t.DisplayTable(cellText)
return nil
}
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
// Update state
ui.updateDuration(s)
for _, i := range s.Items {
ui.updateStats(i)
}
// Update display
switch {
case ui.JSON:
err = ui.printItemsJSON(s)
case ui.Quiet:
err = ui.printItemsQuietly(s)
default:
err = ui.updateUI(s)
}
return
}
func (ui *uiData) DisplayAndFollowHealStatus() (err error) {
var res madmin.HealTaskStatus
for {
_, res, err = ui.Client.Heal(ui.Bucket, ui.Prefix, *ui.HealOpts,
ui.ClientToken, ui.ForceStart)
if err != nil {
return err
}
err = ui.UpdateDisplay(&res)
if err != nil {
return err
}
if res.Summary == "finished" {
break
}
if res.Summary == "stopped" {
fmt.Println("Heal had an error - ", res.FailureDetail)
break
}
time.Sleep(time.Second)
if !ui.JSON && !ui.Quiet {
console.RewindLines(8)
}
}
if ui.JSON {
ui.printStatsJSON(&res)
return nil
}
if ui.Quiet {
ui.printStatsQuietly(&res)
}
return nil
}
+44 -247
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2017 Minio, Inc.
* Minio Client (C) 2017-2018 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,7 @@
package cmd
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -29,23 +26,24 @@ import (
"github.com/minio/minio/pkg/madmin"
)
var (
adminHealFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "Heal recursively",
},
cli.BoolFlag{
Name: "fake, k",
Usage: "Issue a fake heal operation",
},
}
)
var adminHealFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "Heal recursively",
},
cli.BoolFlag{
Name: "dry-run, n",
Usage: "Only inspect data, but do not mutate",
},
cli.BoolFlag{
Name: "force-start, f",
Usage: "Force start a new heal sequence",
},
}
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "Manage heal tasks",
Before: adminHealBefore,
Usage: "Start an object heal operation",
Action: mainAdminHeal,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
@@ -68,223 +66,21 @@ EXAMPLES:
3. Heal all objects under 'dir' prefix
$ {{.HelpName}} --recursive play/testbucket/dir/
4. Issue a fake heal operation to list all objects to be healed
$ {{.HelpName}} --fake play
4. Issue a dry-run heal operation to inspect objects health but not heal them
$ {{.HelpName}} --dry-run play
5. Issue a fake heal operation to list all objects to be healed under 'dir' prefix
$ {{.HelpName}} --recursive --fake play/testbucket/dir/
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
$ {{.HelpName}} --recursive --dry-run play/testbucket/dir/
`,
}
// healMessage container to hold repair information.
type healMessage struct {
Status string `json:"status"`
Result madmin.HealResult `json:"result"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
}
// adminHealBefore used to provide users with temporary warning message
func adminHealBefore(ctx *cli.Context) error {
color.Yellow("\t *** mc admin heal is EXPERIMENTAL ***")
return setGlobalsFromContext(ctx)
}
// String colorized service status message.
func (u healMessage) String() string {
allOfflineTmpl := "is not healed since many disks were offline"
allHealedTmpl := "is healed on all disks"
someHealedTmpl := "is healed on some disks while other disks were offline"
msg := fmt.Sprintf("Object %s/%s ", u.Bucket, u.Object.Key)
switch u.Result.State {
case madmin.HealNone:
msg += allOfflineTmpl
case madmin.HealPartial:
msg += someHealedTmpl
case madmin.HealOK:
msg += allHealedTmpl
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healListMessage container to hold heal information.
type healListMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
}
// String colorized service status message.
func (u healListMessage) String() string {
msg := ""
var healStatus madmin.HealStatus
msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key)
healStatus = u.Object.HealObjectInfo.Status
// Print heal status
switch healStatus {
case madmin.CanHeal:
msg += "can be healed."
case madmin.CanPartiallyHeal:
msg += "can be partially healed."
case madmin.Corrupted:
msg += "cannot be healed."
case madmin.QuorumUnavailable:
msg += "quorum not available for healing."
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healBucketListMessage container to hold heal information.
type healBucketListMessage struct {
Status string `json:"status"`
Bucket madmin.BucketInfo `json:"bucket"`
}
// String colorized service status message.
func (u healBucketListMessage) String() string {
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
switch u.Bucket.HealBucketInfo.Status {
case madmin.CanHeal:
msg += "can be healed"
case madmin.Corrupted:
msg += "cannot be healed"
case madmin.QuorumUnavailable:
msg += "quorum not available for healing"
}
msg += ".\n"
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healBucketListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) {
// Search for objects that need healing
doneCh := make(chan struct{})
healObjectsCh, e := client.ListObjectsHeal(bucket, object, isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list objects to be healed.")
// Iterate over objects that need healing
for obj := range healObjectsCh {
// Continue to next object upon any error.
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot list objects to be healed.")
continue
}
// Heal object info is nil skip it, must be a directory.
if obj.HealObjectInfo == nil {
continue
}
// Check the heal status, and call heal object API only when an object can be healed
switch healInfo := *obj.HealObjectInfo; healInfo.Status {
case madmin.CanHeal, madmin.CanPartiallyHeal:
// Heal Object
var healResult madmin.HealResult
if healResult, e = client.HealObject(bucket, obj.Key, isFake); e != nil {
errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`")
continue
}
// Print successful message
if isFake {
printMsg(healListMessage{Bucket: bucket, Object: &obj})
} else {
printMsg(healMessage{Bucket: bucket, Object: &obj, Result: healResult})
}
case madmin.QuorumUnavailable:
errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.")
case madmin.Corrupted:
errorIf(errDummy().Trace(), obj.Key+" cannot be healed, not enough information.")
}
}
}
// checkAdminHealSyntax - validate all the passed arguments
func checkAdminHealSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
}
}
// listAllToBeHealed - list objects/uploads to be healed in the object
// store with alias `aliasedURL`
// - isIncomplete - if true we list uploads to be healed otherwise
// list objects to be healed
func listAllToBeHealed(client *madmin.AdminClient, aliasedURL string) *probe.Error {
s3Client, err := newClient(aliasedURL)
if err != nil {
return err
}
recursive := false
incomplete := false
listCh := s3Client.List(recursive, incomplete, DirFirst)
var buckets []string
for content := range listCh {
// Trim the leading slash and add to the list of buckets
buckets = append(buckets,
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
}
// isRecursive is always true since we have empty object names
// when `mc admin heal --fake [-r] s1/` is invoked.
isRecursive := true
// Iterate over all computed buckets
for _, currBucket := range buckets {
// Search for objects that need to be healed in the current bucket
doneCh := make(chan struct{})
listCh, e := client.ListObjectsHeal(currBucket, "", isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal objects.")
// Iterate over objects and print them when not errors
for obj := range listCh {
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.")
continue
}
// Skip for non-recursive use case.
if obj.HealObjectInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Object: &obj})
}
}
return nil
}
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
@@ -295,9 +91,6 @@ func mainAdminHeal(ctx *cli.Context) error {
args := ctx.Args()
aliasedURL := args.Get(0)
isRecursive := ctx.Bool("recursive")
isFake := ctx.Bool("fake")
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
// Create a new Minio Admin Client
@@ -310,29 +103,33 @@ func mainAdminHeal(ctx *cli.Context) error {
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
splits := splitStr(aliasedURL, "/", 3)
bucket, object := splits[1], splits[2]
bucket, prefix := splits[1], splits[2]
var e error
// Heal format if bucket is not specified and quit immediately
if bucket == "" {
// If --fake was given, print all objects that need to
// be healed.
if isFake {
lErr := listAllToBeHealed(client, aliasedURL)
fatalIf(lErr, "Unable to list all objects to be healed")
return nil
}
e = client.HealFormat(isFake)
fatalIf(probe.NewError(e), "Cannot heal the disks.")
return nil
opts := madmin.HealOpts{
Recursive: ctx.Bool("recursive"),
DryRun: ctx.Bool("dry-run"),
}
forceStart := ctx.Bool("force-start")
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart)
errorIf(probe.NewError(herr), "Failed to start heal sequence.")
// Heal the specified bucket
e = client.HealBucket(bucket, isFake)
fatalIf(probe.NewError(e), "Cannot heal bucket.")
healObjects(client, bucket, object, isRecursive, isFake)
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: client,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
Quiet: ctx.Bool("quiet"),
JSON: ctx.Bool("json"),
ObjectsByOnlineDrives: make(map[int]int64),
HealthCols: make(map[hCol]int64),
CurChan: cursorAnimate(),
}
errorIf(
probe.NewError(ui.DisplayAndFollowHealStatus()),
"Unable to display follow heal status.",
)
return nil
}
+3 -1
View File
@@ -23,6 +23,7 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminServiceRestartCmd = cli.Command{
@@ -89,7 +90,8 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
fatalIf(err, "Cannot get a configured admin connection.")
// Restart the specified Minio server
fatalIf(probe.NewError(client.ServiceRestart()), "Cannot restart server.")
fatalIf(probe.NewError(client.ServiceSendAction(
madmin.ServiceActionValueRestart)), "Cannot restart server.")
// Success..
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
+99
View File
@@ -0,0 +1,99 @@
/*
* Minio Client (C) 2018 Minio, Inc.
*
* 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 cmd
import (
"encoding/json"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "Stop a minio server",
Action: mainAdminServiceStop,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Stop a Minio server represented by its alias 'play'.
$ {{.HelpName}} play/
`,
}
// serviceStopMessage is container for make bucket success and failure messages.
type serviceStopMessage struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
}
// String colorized make bucket message.
func (s serviceStopMessage) String() string {
return console.Colorize("ServiceStop", "Stopped `"+s.ServerURL+"` successfully.")
}
// JSON jsonified make bucket message.
func (s serviceStopMessage) JSON() string {
serviceStopJSONBytes, e := json.Marshal(s)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceStopJSONBytes)
}
// checkAdminServiceStopSyntax - validate all the passed arguments
func checkAdminServiceStopSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
}
}
func mainAdminServiceStop(ctx *cli.Context) error {
// Validate serivce stop syntax.
checkAdminServiceStopSyntax(ctx)
// Set color.
console.SetColor("ServiceStop", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Stop the specified Minio server
pErr := client.ServiceSendAction(madmin.ServiceActionValueStop)
fatalIf(probe.NewError(pErr), "Cannot stop server.")
// Success..
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
return nil
}
+2 -1
View File
@@ -26,8 +26,9 @@ var adminServiceCmd = cli.Command{
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminServiceRestartCmd,
adminServiceStatusCmd,
adminServiceRestartCmd,
adminServiceStopCmd,
},
}
+3 -3
View File
@@ -107,8 +107,8 @@ func (p *progressBar) SetTotal(total int64) *progressBar {
}
// cursorAnimate - returns a animated rune through read channel for every read.
func cursorAnimate() <-chan rune {
cursorCh := make(chan rune)
func cursorAnimate() <-chan string {
cursorCh := make(chan string)
var cursors string
switch runtime.GOOS {
@@ -128,7 +128,7 @@ func cursorAnimate() <-chan rune {
go func() {
for {
for _, cursor := range cursors {
cursorCh <- cursor
cursorCh <- string(cursor)
}
}
}()
+1 -1
View File
@@ -48,7 +48,7 @@ func scanBarFactory() scanBarFunc {
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), <-cursorCh)
source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix)))
barText := scanPrefix + source
console.PrintC("\r" + barText + "\r")
+14
View File
@@ -118,3 +118,17 @@ func buildS3Config(alias, urlStr string, hostCfg *hostConfigV8) (*Config, *probe
return s3Config, nil
}
// lineTrunc - truncates a string to the given maximum length by
// adding ellipsis in the middle
func lineTrunc(content string, maxLen int) string {
runes := []rune(content)
rlen := len(runes)
if rlen <= maxLen {
return content
}
halfLen := maxLen / 2
fstPart := string(runes[0:halfLen])
sndPart := string(runes[rlen-halfLen:])
return fstPart + "…" + sndPart
}
+99
View File
@@ -19,6 +19,7 @@ package console
import (
"fmt"
"os"
"strings"
"sync"
"path/filepath"
@@ -63,6 +64,12 @@ var (
return
}
// PrintfCustomColor - prints a formatted string in a custom color.
PrintfCustomColor = func(c *color.Color, format string, data ...interface{}) {
consolePrintf("Print", c, format, data...)
return
}
// Fatal print a error message and exit.
Fatal = func(data ...interface{}) {
consolePrint("Fatal", Theme["Fatal"], data...)
@@ -353,3 +360,95 @@ func ProgramName() string {
_, progName := filepath.Split(os.Args[0])
return progName
}
// Table - data to print in table format with fixed row widths.
type Table struct {
// per-row colors
RowColors []*color.Color
// per-column align-right flag (aligns left by default)
AlignRight []bool
// Left margin width for table
TableIndentWidth int
}
// NewTable - create a new Table instance. Takes per-row colors and
// per-column right-align flags and table indentation width (i.e. left
// margin width)
func NewTable(rowColors []*color.Color, alignRight []bool, indentWidth int) *Table {
return &Table{rowColors, alignRight, indentWidth}
}
// DisplayTable - prints the table
func (t *Table) DisplayTable(rows [][]string) error {
numRows := len(rows)
numCols := len(rows[0])
if numRows != len(t.RowColors) {
return fmt.Errorf("row count and row-colors mismatch")
}
// Compute max. column widths
maxColWidths := make([]int, numCols)
for _, row := range rows {
if len(row) != len(t.AlignRight) {
return fmt.Errorf("col count and align-right mismatch")
}
for i, v := range row {
if len([]rune(v)) > maxColWidths[i] {
maxColWidths[i] = len([]rune(v))
}
}
}
// Compute per-cell text with padding and alignment applied.
paddedText := make([][]string, numRows)
for r, row := range rows {
paddedText[r] = make([]string, numCols)
for c, cell := range row {
if t.AlignRight[c] {
fmtStr := fmt.Sprintf("%%%ds", maxColWidths[c])
paddedText[r][c] = fmt.Sprintf(fmtStr, cell)
} else {
extraWidth := maxColWidths[c] - len([]rune(cell))
fmtStr := fmt.Sprintf("%%s%%%ds", extraWidth)
paddedText[r][c] = fmt.Sprintf(fmtStr, cell, "")
}
}
}
// Draw table top border
segments := make([]string, numCols)
for i, c := range maxColWidths {
segments[i] = strings.Repeat("─", c+2)
}
indentText := strings.Repeat(" ", t.TableIndentWidth)
border := fmt.Sprintf("%s┌%s┐", indentText, strings.Join(segments, "┬"))
fmt.Println(border)
// Print the table with colors
for r, row := range paddedText {
fmt.Print(indentText + "│ ")
for c, text := range row {
t.RowColors[r].Print(text)
if c != numCols-1 {
fmt.Print(" │ ")
}
}
fmt.Println(" │")
}
// Draw table bottom border
border = fmt.Sprintf("%s└%s┘", indentText, strings.Join(segments, "┴"))
fmt.Println(border)
return nil
}
// RewindLines - uses terminal escape symbols to clear and rewind
// upwards on the console for `n` lines.
func RewindLines(n int) {
for i := 0; i < n; i++ {
fmt.Printf("\033[1A\033[K")
}
}
+96 -130
View File
@@ -36,13 +36,11 @@ func main() {
```
| Service operations|LockInfo operations|Healing operations|Config operations| Misc |
|:---|:---|:---|:---|:---|
|[`ServiceStatus`](#ServiceStatus)| [`ListLocks`](#ListLocks)| [`ListObjectsHeal`](#ListObjectsHeal)|[`GetConfig`](#GetConfig)| [`SetCredentials`](#SetCredentials)|
|[`ServiceRestart`](#ServiceRestart)| [`ClearLocks`](#ClearLocks)| [`ListBucketsHeal`](#ListBucketsHeal)|[`SetConfig`](#SetConfig)||
| | |[`HealBucket`](#HealBucket) |||
| | |[`HealObject`](#HealObject)|||
| | |[`HealFormat`](#HealFormat)|||
| Service operations | LockInfo operations | Healing operations | Config operations | Misc |
|:------------------------------------|:----------------------------|:--------------------------------------|:--------------------------|:------------------------------------|
| [`ServiceStatus`](#ServiceStatus) | [`ListLocks`](#ListLocks) | [`Heal`](#Heal) | [`GetConfig`](#GetConfig) | [`SetCredentials`](#SetCredentials) |
| [`ServiceSendAction`](#ServiceSendAction) | [`ClearLocks`](#ClearLocks) | | [`SetConfig`](#SetConfig) | |
## 1. Constructor
<a name="Minio"></a>
@@ -60,8 +58,25 @@ __Parameters__
|`secretAccessKey` | _string_ |Secret key for the object storage endpoint. |
|`ssl` | _bool_ | Set this value to 'true' to enable secure (HTTPS) access. |
## 2. Admin API Version
## 2. Service operations
<a name="VersionInfo"></a>
### VersionInfo() (AdminAPIVersionInfo, error)
Fetch server's supported Administrative API version.
__Example__
``` go
info, err := madmClnt.VersionInfo()
if err != nil {
log.Fatalln(err)
}
log.Printf("%s\n", info.Version)
```
## 3. Service operations
<a name="ServiceStatus"></a>
### ServiceStatus() (ServiceStatusMetadata, error)
@@ -102,17 +117,19 @@ Fetch service status, replies disk space used, backend type and total disks offl
```
<a name="ServiceRestart"></a>
### ServiceRestart() (error)
If successful restarts the running minio service, for distributed setup restarts all remote minio servers.
<a name="ServiceSendAction"></a>
### ServiceSendAction(act ServiceActionValue) (error)
Sends a service action command to service - possible actions are restarting and stopping the server.
__Example__
```go
st, err := madmClnt.ServiceRestart()
// to restart
st, err := madmClnt.ServiceSendAction(ServiceActionValueRestart)
// or to stop
// st, err := madmClnt.ServiceSendAction(ServiceActionValueStop)
if err != nil {
log.Fatalln(err)
}
@@ -120,7 +137,7 @@ If successful restarts the running minio service, for distributed setup restarts
```
## 3. Info operations
## 4. Info operations
<a name="ServerInfo"></a>
### ServerInfo() ([]ServerInfo, error)
@@ -143,7 +160,7 @@ Fetch all information for all cluster nodes, such as uptime, region, network sta
```
## 4. Lock operations
## 5. Lock operations
<a name="ListLocks"></a>
### ListLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error)
@@ -175,146 +192,95 @@ __Example__
```
## 5. Heal operations
## 6. Heal operations
<a name="ListObjectsHeal"></a>
### ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error)
If successful returns information on the list of objects that need healing in ``bucket`` matching ``prefix``.
<a name="Heal"></a>
### Heal(bucket, prefix string, healOpts HealOpts, clientToken string, forceStart bool) (start HealStartSuccess, status HealTaskStatus, err error)
Start a heal sequence that scans data under given (possible empty)
`bucket` and `prefix`. The `recursive` bool turns on recursive
traversal under the given path. `dryRun` does not mutate on-disk data,
but performs data validation. `incomplete` enables healing of
multipart uploads that are in progress. `removeBadFiles` removes
unrecoverable files. `statisticsOnly` turns off detailed
heal-operations reporting in the status call.
Two heal sequences on overlapping paths may not be initiated.
The progress of a heal should be followed using the `HealStatus`
API. The server accumulates results of the heal traversal and waits
for the client to receive and acknowledge them using the status
API. When the statistics-only option is set, the server only maintains
aggregates statistics - in this case, no acknowledgement of results is
required.
__Example__
``` go
// Create a done channel to control 'ListObjectsHeal' go routine.
doneCh := make(chan struct{})
// Indicate to our routine to exit cleanly upon return.
defer close(doneCh)
// Set true if recursive listing is needed.
isRecursive := true
// List objects that need healing for a given bucket and
// prefix.
healObjectCh, err := madmClnt.ListObjectsHeal("mybucket", "myprefix", isRecursive, doneCh)
if err != nil {
fmt.Println(err)
return
}
for object := range healObjectsCh {
if object.Err != nil {
log.Fatalln(err)
return
}
if object.HealObjectInfo != nil {
switch healInfo := *object.HealObjectInfo; healInfo.Status {
case madmin.CanHeal:
fmt.Println(object.Key, " can be healed.")
case madmin.QuorumUnavailable:
fmt.Println(object.Key, " can't be healed until quorum is available.")
case madmin.Corrupted:
fmt.Println(object.Key, " can't be healed, not enough information.")
}
}
fmt.Println("object: ", object)
}
```
<a name="ListBucketsHeal"></a>
### ListBucketsHeal() error
If successful returns information on the list of buckets that need healing.
__Example__
``` go
// List buckets that need healing
healBucketsList, err := madmClnt.ListBucketsHeal()
if err != nil {
fmt.Println(err)
return
}
for bucket := range healBucketsList {
if bucket.HealBucketInfo != nil {
switch healInfo := *object.HealBucketInfo; healInfo.Status {
case madmin.CanHeal:
fmt.Println(bucket.Key, " can be healed.")
case madmin.QuorumUnavailable:
fmt.Println(bucket.Key, " can't be healed until quorum is available.")
case madmin.Corrupted:
fmt.Println(bucket.Key, " can't be healed, not enough information.")
}
}
fmt.Println("bucket: ", bucket)
}
```
<a name="HealBucket"></a>
### HealBucket(bucket string, isDryRun bool) error
If bucket is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the bucket is not healed, but heal bucket request is validated by the server. e.g, if the bucket exists, if bucket name is valid etc.
__Example__
``` go
isDryRun := false
err := madmClnt.HealBucket("mybucket", isDryRun)
healPath, err := madmClnt.HealStart("", "", true, false, true, false, false)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed mybucket")
log.Printf("Heal sequence started at %s", healPath)
```
<a name="HealObject"></a>
### HealObject(bucket, object string, isDryRun bool) (HealResult, error)
If object is successfully healed returns nil, otherwise returns error indicating the reason for failure. If isDryRun is true, then the object is not healed, but heal object request is validated by the server. e.g, if the object exists, if object name is valid etc.
#### HealTaskStatus structure
| Param | Type | Description |
|---|---|---|
|`h.State` | _HealState_ | Represents the result of heal operation. It could be one of `HealNone`, `HealPartial` or `HealOK`. |
| Param | Type | Description |
|----|--------|--------|
| s.Summary | _string_ | Short status of heal sequence |
| s.FailureDetail | _string_ | Error message in case of heal sequence failure |
| s.HealSettings | _HealOpts_ | Contains the booleans set in the `HealStart` call |
| s.Items | _[]HealResultItem_ | Heal records for actions performed by server |
| s.Statistics | _HealStatistics_ | Aggregate of heal records from beginning |
#### HealResultItem structure
| Value | Description |
|---|---|
|`HealNone` | Object wasn't healed on any of the disks |
|`HealPartial` | Object was healed on some of the disks needing heal |
| `HealOK` | Object was healed on all the disks needing heal |
| Param | Type | Description |
|------|-------|---------|
| ResultIndex | _int64_ | Index of the heal-result record |
| Type | _HealItemType_ | Represents kind of heal operation in the heal record |
| Bucket | _string_ | Bucket name |
| Object | _string_ | Object name |
| Detail | _string_ | Details about heal operation |
| DiskInfo.AvailableOn | _[]int_ | List of disks on which the healed entity is present and healthy |
| DiskInfo.HealedOn | _[]int_ | List of disks on which the healed entity was restored |
#### HealStatistics structure
Most parameters represent the aggregation of heal operations since the
start of the heal sequence.
| Param | Type | Description |
|-------|-----|----------|
| NumDisks | _int_ | Number of disks configured in the backend |
| NumBucketsScanned | _int64_ | Number of buckets scanned |
| BucketsMissingByDisk | _map[int]int64_ | Map of disk to number of buckets missing |
| BucketsAvailableByDisk | _map[int]int64_ | Map of disk to number of buckets available |
| BucketsHealedByDisk | _map[int]int64_ | Map of disk to number of buckets healed on |
| NumObjectsScanned | _int64_ | Number of objects scanned |
| NumUploadsScanned | _int64_ | Number of uploads scanned |
| ObjectsByAvailablePC | _map[int64]_ | Map of available part counts (after heal) to number of objects |
| ObjectsByHealedPC | _map[int64]_ | Map of healed part counts to number of objects |
| ObjectsMissingByDisk | _map[int64]_ | Map of disk number to number of objects with parts missing on that disk |
| ObjectsAvailableByDisk | _map[int64]_ | Map of disk number to number of objects available on that disk |
| ObjectsHealedByDisk | _map[int64]_ | Map of disk number to number of objects healed on that disk |
__Example__
``` go
isDryRun = false
healResult, err := madmClnt.HealObject("mybucket", "myobject", isDryRun)
res, err := madmClnt.HealStatus("", "")
if err != nil {
log.Fatalln(err)
}
log.Println("Heal-object result: ", healResult)
log.Printf("Heal sequence status data %#v", res)
```
<a name="HealFormat"></a>
### HealFormat(isDryRun bool) error
Heal storage format on available disks. This is used when disks were replaced or were found with missing format. This is supported only for erasure-coded backend.
__Example__
``` go
isDryRun := true
err := madmClnt.HealFormat(isDryRun)
if err != nil {
log.Fatalln(err)
}
isDryRun = false
err = madmClnt.HealFormat(isDryRun)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed storage format on available disks.")
```
## 6. Config operations
## 7. Config operations
<a name="GetConfig"></a>
### GetConfig() ([]byte, error)
@@ -373,7 +339,7 @@ __Example__
log.Println("SetConfig: ", string(buf.Bytes()))
```
## 7. Misc operations
## 8. Misc operations
<a name="SetCredentials"></a>
+3 -3
View File
@@ -54,7 +54,7 @@ func (e ErrorResponse) Error() string {
}
const (
reportIssue = "Please report this issue at https://github.com/minio/minio-go/issues."
reportIssue = "Please report this issue at https://github.com/minio/minio/issues."
)
// httpRespToErrorResponse returns a new encoded ErrorResponse
@@ -65,8 +65,8 @@ func httpRespToErrorResponse(resp *http.Response) error {
return ErrInvalidArgument(msg)
}
var errResp ErrorResponse
// Decode the xml error
err := xmlDecoder(resp.Body, &errResp)
// Decode the json error
err := jsonDecoder(resp.Body, &errResp)
if err != nil {
return ErrorResponse{
Code: resp.Status,
+10 -5
View File
@@ -71,6 +71,8 @@ type AdminClient struct {
const (
libraryName = "madmin-go"
libraryVersion = "0.0.1"
libraryAdminURLPrefix = "/minio/admin"
)
// User Agent should always following the below style.
@@ -176,6 +178,9 @@ type requestData struct {
customHeaders http.Header
queryValues url.Values
// Url path relative to admin API base endpoint
relPath string
contentBody io.Reader
contentLength int64
contentSHA256Bytes []byte
@@ -388,7 +393,7 @@ func (c AdminClient) newRequest(method string, reqData requestData) (req *http.R
location := "us-east-1"
// Construct a new target URL.
targetURL, err := c.makeTargetURL(reqData.queryValues)
targetURL, err := c.makeTargetURL(reqData)
if err != nil {
return nil, err
}
@@ -440,16 +445,16 @@ func (c AdminClient) newRequest(method string, reqData requestData) (req *http.R
}
// makeTargetURL make a new target url.
func (c AdminClient) makeTargetURL(queryValues url.Values) (*url.URL, error) {
func (c AdminClient) makeTargetURL(r requestData) (*url.URL, error) {
host := c.endpointURL.Host
scheme := c.endpointURL.Scheme
urlStr := scheme + "://" + host + "/"
urlStr := scheme + "://" + host + libraryAdminURLPrefix + r.relPath
// If there are any query values, add them to the end.
if len(queryValues) > 0 {
urlStr = urlStr + "?" + s3utils.QueryEncode(queryValues)
if len(r.queryValues) > 0 {
urlStr = urlStr + "?" + s3utils.QueryEncode(r.queryValues)
}
u, err := url.Parse(urlStr)
if err != nil {
+20 -38
View File
@@ -20,14 +20,10 @@ package madmin
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
const (
configQueryParam = "config"
)
// NodeSummary - represents the result of an operation part of
@@ -47,20 +43,14 @@ type SetConfigResult struct {
// GetConfig - returns the config.json of a minio setup.
func (adm *AdminClient) GetConfig() ([]byte, error) {
queryVal := make(url.Values)
queryVal.Set(configQueryParam, "")
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "get")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
// No TLS?
if !adm.secure {
return nil, fmt.Errorf("credentials/configuration cannot be retrieved over an insecure connection")
}
// Execute GET on /?config to get config of a setup.
resp, err := adm.executeMethod("GET", reqData)
// Execute GET on /minio/admin/v1/config to get config of a setup.
resp, err := adm.executeMethod("GET",
requestData{relPath: "/v1/config"})
defer closeResponse(resp)
if err != nil {
return nil, err
@@ -75,50 +65,42 @@ func (adm *AdminClient) GetConfig() ([]byte, error) {
}
// SetConfig - set config supplied as config.json for the setup.
func (adm *AdminClient) SetConfig(config io.Reader) (SetConfigResult, error) {
queryVal := url.Values{}
queryVal.Set(configQueryParam, "")
// Set x-minio-operation to set.
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "set")
func (adm *AdminClient) SetConfig(config io.Reader) (r SetConfigResult, err error) {
// No TLS?
if !adm.secure {
return r, fmt.Errorf("credentials/configuration cannot be updated over an insecure connection")
}
// Read config bytes to calculate MD5, SHA256 and content length.
configBytes, err := ioutil.ReadAll(config)
if err != nil {
return SetConfigResult{}, err
return r, err
}
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
relPath: "/v1/config",
contentBody: bytes.NewReader(configBytes),
contentMD5Bytes: sumMD5(configBytes),
contentSHA256Bytes: sum256(configBytes),
}
// Execute PUT on /?config to set config.
// Execute PUT on /minio/admin/v1/config to set config.
resp, err := adm.executeMethod("PUT", reqData)
defer closeResponse(resp)
if err != nil {
return SetConfigResult{}, err
return r, err
}
if resp.StatusCode != http.StatusOK {
return SetConfigResult{}, httpRespToErrorResponse(resp)
return r, httpRespToErrorResponse(resp)
}
var result SetConfigResult
jsonBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return SetConfigResult{}, err
return r, err
}
err = json.Unmarshal(jsonBytes, &result)
if err != nil {
return SetConfigResult{}, err
}
return result, nil
err = json.Unmarshal(jsonBytes, &r)
return r, err
}
-3
View File
@@ -19,7 +19,4 @@ package madmin
const (
// Unsigned payload.
unsignedPayload = "UNSIGNED-PAYLOAD"
// Admin operation header.
minioAdminOpHeader = "X-Minio-Operation"
)
+26 -22
View File
@@ -19,46 +19,50 @@ package madmin
import (
"bytes"
"encoding/xml"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// setCredsReq - xml to send to the server to set new credentials
type setCredsReq struct {
Username string `xml:"username"`
Password string `xml:"password"`
// SetCredsReq - xml to send to the server to set new credentials
type SetCredsReq struct {
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
}
// SetCredentials - Call Set Credentials API to set new access and secret keys in the specified Minio server
// SetCredentials - Call Set Credentials API to set new access and
// secret keys in the specified Minio server
func (adm *AdminClient) SetCredentials(access, secret string) error {
// Setup new request
reqData := requestData{}
reqData.queryValues = make(url.Values)
reqData.queryValues.Set("service", "")
reqData.customHeaders = make(http.Header)
reqData.customHeaders.Set(minioAdminOpHeader, "set-credentials")
// Setup request's body
body, err := xml.Marshal(setCredsReq{Username: access, Password: secret})
body, err := json.Marshal(SetCredsReq{access, secret})
if err != nil {
return err
}
reqData.contentBody = bytes.NewReader(body)
reqData.contentLength = int64(len(body))
reqData.contentMD5Bytes = sumMD5(body)
reqData.contentSHA256Bytes = sum256(body)
// No TLS?
if !adm.secure {
return fmt.Errorf("credentials cannot be updated over an insecure connection")
}
// Setup new request
reqData := requestData{
relPath: "/v1/config/credential",
contentBody: bytes.NewReader(body),
contentLength: int64(len(body)),
contentMD5Bytes: sumMD5(body),
contentSHA256Bytes: sum256(body),
}
// Execute GET on bucket to list objects.
resp, err := adm.executeMethod("POST", reqData)
resp, err := adm.executeMethod("PUT", reqData)
defer closeResponse(resp)
if err != nil {
return err
}
// Return error to the caller if http response code is different from 200
// Return error to the caller if http response code is
// different from 200
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
}
+105 -404
View File
@@ -20,456 +20,157 @@
package madmin
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// listBucketHealResult container for listObjects response.
type listBucketHealResult struct {
// A response can contain CommonPrefixes only if you have
// specified a delimiter.
CommonPrefixes []commonPrefix
// Metadata about each object returned.
Contents []ObjectInfo
Delimiter string
// Encoding type used to encode object keys in the response.
EncodingType string
// A flag that indicates whether or not ListObjects returned all of the results
// that satisfied the search criteria.
IsTruncated bool
Marker string
MaxKeys int64
Name string
// When response is truncated (the IsTruncated element value in
// the response is true), you can use the key name in this field
// as marker in the subsequent request to get next set of objects.
// Object storage lists objects in alphabetical order Note: This
// element is returned only if you have delimiter request
// parameter specified. If response does not include the NextMaker
// and it is truncated, you can use the value of the last Key in
// the response as the marker in the subsequent request to get the
// next set of object keys.
NextMarker string
Prefix string
// HealOpts - collection of options for a heal sequence
type HealOpts struct {
Recursive bool `json:"recursive"`
DryRun bool `json:"dryRun"`
}
// commonPrefix container for prefix response.
type commonPrefix struct {
Prefix string
// HealStartSuccess - holds information about a successfully started
// heal operation
type HealStartSuccess struct {
ClientToken string `json:"clientToken"`
ClientAddress string `json:"clientAddress"`
StartTime time.Time `json:"startTime"`
}
// Owner - bucket owner/principal
type Owner struct {
ID string
DisplayName string
// HealTaskStatus - status struct for a heal task
type HealTaskStatus struct {
Summary string `json:"summary"`
FailureDetail string `json:"detail"`
StartTime time.Time `json:"startTime"`
HealSettings HealOpts `json:"settings"`
NumDisks int `json:"numDisks"`
Items []HealResultItem `json:"items,omitempty"`
}
// Bucket container for bucket metadata
type Bucket struct {
Name string
CreationDate string // time string of format "2006-01-02T15:04:05.000Z"
HealBucketInfo *HealBucketInfo `xml:"HealBucketInfo,omitempty"`
}
// ListBucketsHealResponse - format for list buckets response
type ListBucketsHealResponse struct {
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListAllMyBucketsResult" json:"-"`
Owner Owner
// Container for one or more buckets.
Buckets struct {
Buckets []Bucket `xml:"Bucket"`
} // Buckets are nested
}
// HealStatus - represents different states of healing an object could be in.
type HealStatus int
// HealItemType - specify the type of heal operation in a healing
// result
type HealItemType string
// HealItemType constants
const (
// Healthy - Object that is already healthy
Healthy HealStatus = iota
// CanHeal - Object can be healed
CanHeal
// Corrupted - Object can't be healed
Corrupted
// QuorumUnavailable - Object can't be healed until read
// quorum is available
QuorumUnavailable
// CanPartiallyHeal - Object can't be healed completely until
// disks with missing parts come online
CanPartiallyHeal
HealItemMetadata HealItemType = "metadata"
HealItemBucket = "bucket"
HealItemBucketMetadata = "bucket-metadata"
HealItemObject = "object"
)
// HealBucketInfo - represents healing related information of a bucket.
type HealBucketInfo struct {
Status HealStatus
}
// BucketInfo - represents bucket metadata.
type BucketInfo struct {
// Name of the bucket.
Name string
// Date and time when the bucket was created.
Created time.Time
// Healing information
HealBucketInfo *HealBucketInfo `xml:"HealBucketInfo,omitempty"`
}
// HealObjectInfo - represents healing related information of an object.
type HealObjectInfo struct {
Status HealStatus
MissingDataCount int
MissingParityCount int
}
// ObjectInfo container for object metadata.
type ObjectInfo struct {
// An ETag is optionally set to md5sum of an object. In case of multipart objects,
// ETag is of the form MD5SUM-N where MD5SUM is md5sum of all individual md5sums of
// each parts concatenated into one string.
ETag string `json:"etag"`
Key string `json:"name"` // Name of the object
LastModified time.Time `json:"lastModified"` // Date and time the object was last modified.
Size int64 `json:"size"` // Size in bytes of the object.
ContentType string `json:"contentType"` // A standard MIME type describing the format of the object data.
// Collection of additional metadata on the object.
// eg: x-amz-meta-*, content-encoding etc.
Metadata http.Header `json:"metadata"`
// Owner name.
Owner struct {
DisplayName string `json:"name"`
ID string `json:"id"`
} `json:"owner"`
// The class of storage used to store the object.
StorageClass string `json:"storageClass"`
// Error
Err error `json:"-"`
HealObjectInfo *HealObjectInfo `json:"healObjectInfo,omitempty"`
}
type healQueryKey string
// Drive state constants
const (
healBucket healQueryKey = "bucket"
healObject healQueryKey = "object"
healPrefix healQueryKey = "prefix"
healMarker healQueryKey = "marker"
healDelimiter healQueryKey = "delimiter"
healMaxKey healQueryKey = "max-key"
healDryRun healQueryKey = "dry-run"
DriveStateOk string = "ok"
DriveStateOffline = "offline"
DriveStateCorrupt = "corrupt"
DriveStateMissing = "missing"
)
// mkHealQueryVal - helper function to construct heal REST API query params.
func mkHealQueryVal(bucket, prefix, marker, delimiter, maxKeyStr string) url.Values {
queryVal := make(url.Values)
queryVal.Set("heal", "")
queryVal.Set(string(healBucket), bucket)
queryVal.Set(string(healPrefix), prefix)
queryVal.Set(string(healMarker), marker)
queryVal.Set(string(healDelimiter), delimiter)
queryVal.Set(string(healMaxKey), maxKeyStr)
return queryVal
// HealResultItem - struct for an individual heal result item
type HealResultItem struct {
ResultIndex int64 `json:"resultId"`
Type HealItemType `json:"type"`
Bucket string `json:"bucket"`
Object string `json:"object"`
Detail string `json:"detail"`
ParityBlocks int `json:"parityBlocks,omitempty"`
DataBlocks int `json:"dataBlocks,omitempty"`
DiskCount int `json:"diskCount"`
DriveInfo struct {
// below maps are from drive endpoint to drive state
Before map[string]string `json:"before"`
After map[string]string `json:"after"`
} `json:"drives"`
ObjectSize int64 `json:"objectSize"`
}
// listObjectsHeal - issues heal list API request for a batch of maxKeys objects to be healed.
func (adm *AdminClient) listObjectsHeal(bucket, prefix, marker, delimiter string, maxKeys int) (listBucketHealResult, error) {
// Construct query params.
maxKeyStr := fmt.Sprintf("%d", maxKeys)
queryVal := mkHealQueryVal(bucket, prefix, marker, delimiter, maxKeyStr)
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "list-objects")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Empty 'list' of objects to be healed.
toBeHealedObjects := listBucketHealResult{}
// Execute GET on /?heal to list objects needing heal.
resp, err := adm.executeMethod("GET", reqData)
defer closeResponse(resp)
if err != nil {
return listBucketHealResult{}, err
}
if resp.StatusCode != http.StatusOK {
return toBeHealedObjects, httpRespToErrorResponse(resp)
}
err = xml.NewDecoder(resp.Body).Decode(&toBeHealedObjects)
return toBeHealedObjects, err
// InitDrives - initialize maps used to represent drive info
func (hri *HealResultItem) InitDrives() {
hri.DriveInfo.Before = make(map[string]string)
hri.DriveInfo.After = make(map[string]string)
}
// ListObjectsHeal - Lists upto maxKeys objects that needing heal matching bucket, prefix, marker, delimiter.
func (adm *AdminClient) ListObjectsHeal(bucket, prefix string, recursive bool, doneCh <-chan struct{}) (<-chan ObjectInfo, error) {
// Allocate new list objects channel.
objectStatCh := make(chan ObjectInfo, 1)
// Default listing is delimited at "/"
delimiter := "/"
if recursive {
// If recursive we do not delimit.
delimiter = ""
// GetOnlineCounts - returns the number of online disks before and
// after heal
func (hri *HealResultItem) GetOnlineCounts() (b, a int) {
if hri == nil {
return
}
// Initiate list objects goroutine here.
go func(objectStatCh chan<- ObjectInfo) {
defer close(objectStatCh)
// Save marker for next request.
var marker string
for {
// Get list of objects a maximum of 1000 per request.
result, err := adm.listObjectsHeal(bucket, prefix, marker, delimiter, 1000)
if err != nil {
objectStatCh <- ObjectInfo{
Err: err,
}
return
}
// If contents are available loop through and send over channel.
for _, object := range result.Contents {
// Save the marker.
marker = object.Key
select {
// Send object content.
case objectStatCh <- object:
// If receives done from the caller, return here.
case <-doneCh:
return
}
}
// Send all common prefixes if any.
// NOTE: prefixes are only present if the request is delimited.
for _, obj := range result.CommonPrefixes {
object := ObjectInfo{}
object.Key = obj.Prefix
object.Size = 0
select {
// Send object prefixes.
case objectStatCh <- object:
// If receives done from the caller, return here.
case <-doneCh:
return
}
}
// If next marker present, save it for next request.
if result.NextMarker != "" {
marker = result.NextMarker
}
// Listing ends result is not truncated, return right here.
if !result.IsTruncated {
return
}
for _, v := range hri.DriveInfo.Before {
if v == DriveStateOk {
b++
}
}(objectStatCh)
return objectStatCh, nil
}
const timeFormatAMZLong = "2006-01-02T15:04:05.000Z" // Reply date format with nanosecond precision.
// ListBucketsHeal - issues heal bucket list API request
func (adm *AdminClient) ListBucketsHeal() ([]BucketInfo, error) {
queryVal := url.Values{}
queryVal.Set("heal", "")
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "list-buckets")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Execute GET on /?heal to list objects needing heal.
resp, err := adm.executeMethod("GET", reqData)
defer closeResponse(resp)
if err != nil {
return []BucketInfo{}, err
}
if resp.StatusCode != http.StatusOK {
return []BucketInfo{}, httpRespToErrorResponse(resp)
}
var listBucketsHealResult ListBucketsHealResponse
err = xml.NewDecoder(resp.Body).Decode(&listBucketsHealResult)
if err != nil {
return []BucketInfo{}, err
}
var bucketsToBeHealed []BucketInfo
for _, bucket := range listBucketsHealResult.Buckets.Buckets {
creationDate, err := time.Parse(timeFormatAMZLong, bucket.CreationDate)
if err != nil {
return []BucketInfo{}, err
for _, v := range hri.DriveInfo.After {
if v == DriveStateOk {
a++
}
bucketsToBeHealed = append(bucketsToBeHealed,
BucketInfo{
Name: bucket.Name,
Created: creationDate,
HealBucketInfo: bucket.HealBucketInfo,
})
}
return bucketsToBeHealed, nil
return
}
// HealBucket - Heal the given bucket
func (adm *AdminClient) HealBucket(bucket string, dryrun bool) error {
// Construct query params.
queryVal := url.Values{}
queryVal.Set("heal", "")
queryVal.Set(string(healBucket), bucket)
if dryrun {
queryVal.Set(string(healDryRun), "")
// Heal - API endpoint to start heal and to fetch status
func (adm *AdminClient) Heal(bucket, prefix string, healOpts HealOpts,
clientToken string, forceStart bool) (
healStart HealStartSuccess, healTaskStatus HealTaskStatus, err error) {
body, err := json.Marshal(healOpts)
if err != nil {
return healStart, healTaskStatus, err
}
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "bucket")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
path := fmt.Sprintf("/v1/heal/%s", bucket)
if bucket != "" && prefix != "" {
path += "/" + prefix
}
// Execute POST on /?heal&bucket=mybucket to heal a bucket.
resp, err := adm.executeMethod("POST", reqData)
// execute POST request to heal api
queryVals := make(url.Values)
var contentBody io.Reader
if clientToken != "" {
queryVals.Set("clientToken", clientToken)
} else {
// Set a body only if clientToken is not given
contentBody = bytes.NewReader(body)
}
if forceStart {
queryVals.Set("forceStart", "true")
}
resp, err := adm.executeMethod("POST", requestData{
relPath: path,
contentBody: contentBody,
contentSHA256Bytes: sum256(body),
queryValues: queryVals,
})
defer closeResponse(resp)
if err != nil {
return err
return healStart, healTaskStatus, err
}
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
return healStart, healTaskStatus, httpRespToErrorResponse(resp)
}
return nil
}
// HealResult - represents result of heal-object admin API.
type HealResult struct {
State HealState `json:"state"`
}
// HealState - different states of heal operation
type HealState int
const (
// HealNone - none of the disks healed
HealNone HealState = iota
// HealPartial - some disks were healed, others were offline
HealPartial
// HealOK - all disks were healed
HealOK
)
// HealObject - Heal the given object.
func (adm *AdminClient) HealObject(bucket, object string, dryrun bool) (HealResult, error) {
// Construct query params.
queryVal := url.Values{}
queryVal.Set("heal", "")
queryVal.Set(string(healBucket), bucket)
queryVal.Set(string(healObject), object)
if dryrun {
queryVal.Set(string(healDryRun), "")
}
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "object")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Execute POST on /?heal&bucket=mybucket&object=myobject to heal an object.
resp, err := adm.executeMethod("POST", reqData)
defer closeResponse(resp)
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return HealResult{}, err
return healStart, healTaskStatus, err
}
if resp.StatusCode != http.StatusOK {
return HealResult{}, httpRespToErrorResponse(resp)
// Was it a status request?
if clientToken == "" {
err = json.Unmarshal(respBytes, &healStart)
} else {
err = json.Unmarshal(respBytes, &healTaskStatus)
}
// Healing is not performed so heal object result is empty.
if dryrun {
return HealResult{}, nil
}
jsonBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return HealResult{}, err
}
healResult := HealResult{}
err = json.Unmarshal(jsonBytes, &healResult)
if err != nil {
return HealResult{}, err
}
return healResult, nil
}
// HealFormat - heal storage format on available disks.
func (adm *AdminClient) HealFormat(dryrun bool) error {
queryVal := url.Values{}
queryVal.Set("heal", "")
if dryrun {
queryVal.Set(string(healDryRun), "")
}
// Set x-minio-operation to format.
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "format")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Execute POST on /?heal to heal storage format.
resp, err := adm.executeMethod("POST", reqData)
defer closeResponse(resp)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
}
return nil
return healStart, healTaskStatus, err
}
+1 -8
View File
@@ -21,7 +21,6 @@ import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
)
@@ -115,13 +114,7 @@ type ServerInfo struct {
// ServerInfo - Connect to a minio server and call Server Info Management API
// to fetch server's information represented by ServerInfo structure
func (adm *AdminClient) ServerInfo() ([]ServerInfo, error) {
// Prepare web service request
reqData := requestData{}
reqData.queryValues = make(url.Values)
reqData.queryValues.Set("info", "")
reqData.customHeaders = make(http.Header)
resp, err := adm.executeMethod("GET", reqData)
resp, err := adm.executeMethod("GET", requestData{relPath: "/v1/info"})
defer closeResponse(resp)
if err != nil {
return nil, err
+16 -26
View File
@@ -82,24 +82,19 @@ func getLockInfos(body io.Reader) ([]VolumeLockInfo, error) {
// ListLocks - Calls List Locks Management API to fetch locks matching
// bucket, prefix and held before the duration supplied.
func (adm *AdminClient) ListLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error) {
func (adm *AdminClient) ListLocks(bucket, prefix string,
duration time.Duration) ([]VolumeLockInfo, error) {
queryVal := make(url.Values)
queryVal.Set("lock", "")
queryVal.Set("bucket", bucket)
queryVal.Set("prefix", prefix)
queryVal.Set("duration", duration.String())
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "list")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Execute GET on /?lock to list locks.
resp, err := adm.executeMethod("GET", reqData)
queryVal.Set("older-than", duration.String())
// Execute GET on /minio/admin/v1/locks to list locks.
resp, err := adm.executeMethod("GET", requestData{
queryValues: queryVal,
relPath: "/v1/locks",
})
defer closeResponse(resp)
if err != nil {
return nil, err
@@ -114,24 +109,19 @@ func (adm *AdminClient) ListLocks(bucket, prefix string, duration time.Duration)
// ClearLocks - Calls Clear Locks Management API to clear locks held
// on bucket, matching prefix older than duration supplied.
func (adm *AdminClient) ClearLocks(bucket, prefix string, duration time.Duration) ([]VolumeLockInfo, error) {
func (adm *AdminClient) ClearLocks(bucket, prefix string,
duration time.Duration) ([]VolumeLockInfo, error) {
queryVal := make(url.Values)
queryVal.Set("lock", "")
queryVal.Set("bucket", bucket)
queryVal.Set("prefix", prefix)
queryVal.Set("duration", duration.String())
hdrs := make(http.Header)
hdrs.Set(minioAdminOpHeader, "clear")
reqData := requestData{
queryValues: queryVal,
customHeaders: hdrs,
}
// Execute POST on /?lock to clear locks.
resp, err := adm.executeMethod("POST", reqData)
resp, err := adm.executeMethod("DELETE", requestData{
queryValues: queryVal,
relPath: "/v1/locks",
})
defer closeResponse(resp)
if err != nil {
return nil, err
+48 -38
View File
@@ -18,69 +18,79 @@
package madmin
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// ServiceStatusMetadata - contains the response of service status API
type ServiceStatusMetadata struct {
Uptime time.Duration `json:"uptime"`
// ServerVersion - server version
type ServerVersion struct {
Version string `json:"version"`
CommitID string `json:"commitID"`
}
// ServiceStatus - Connect to a minio server and call Service Status Management API
// to fetch server's storage information represented by ServiceStatusMetadata structure
func (adm *AdminClient) ServiceStatus() (ServiceStatusMetadata, error) {
// ServiceStatus - contains the response of service status API
type ServiceStatus struct {
ServerVersion ServerVersion `json:"serverVersion"`
Uptime time.Duration `json:"uptime"`
}
// Prepare web service request
reqData := requestData{}
reqData.queryValues = make(url.Values)
reqData.queryValues.Set("service", "")
reqData.customHeaders = make(http.Header)
reqData.customHeaders.Set(minioAdminOpHeader, "status")
// Execute GET on bucket to list objects.
resp, err := adm.executeMethod("GET", reqData)
// ServiceStatus - Connect to a minio server and call Service Status
// Management API to fetch server's storage information represented by
// ServiceStatusMetadata structure
func (adm *AdminClient) ServiceStatus() (ss ServiceStatus, err error) {
// Request API to GET service status
resp, err := adm.executeMethod("GET", requestData{relPath: "/v1/service"})
defer closeResponse(resp)
if err != nil {
return ServiceStatusMetadata{}, err
return ss, err
}
// Check response http status code
if resp.StatusCode != http.StatusOK {
return ServiceStatusMetadata{}, httpRespToErrorResponse(resp)
return ss, httpRespToErrorResponse(resp)
}
// Unmarshal the server's json response
var serviceStatus ServiceStatusMetadata
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ServiceStatusMetadata{}, err
return ss, err
}
err = json.Unmarshal(respBytes, &serviceStatus)
if err != nil {
return ServiceStatusMetadata{}, err
}
return serviceStatus, nil
err = json.Unmarshal(respBytes, &ss)
return ss, err
}
// ServiceRestart - Call Service Restart API to restart a specified Minio server
func (adm *AdminClient) ServiceRestart() error {
//
reqData := requestData{}
reqData.queryValues = make(url.Values)
reqData.queryValues.Set("service", "")
reqData.customHeaders = make(http.Header)
reqData.customHeaders.Set(minioAdminOpHeader, "restart")
// ServiceActionValue - type to restrict service-action values
type ServiceActionValue string
// Execute GET on bucket to list objects.
resp, err := adm.executeMethod("POST", reqData)
const (
// ServiceActionValueRestart represents restart action
ServiceActionValueRestart ServiceActionValue = "restart"
// ServiceActionValueStop represents stop action
ServiceActionValueStop = "stop"
)
// ServiceAction - represents POST body for service action APIs
type ServiceAction struct {
Action ServiceActionValue `json:"action"`
}
// ServiceSendAction - Call Service Restart/Stop API to restart/stop a
// Minio server
func (adm *AdminClient) ServiceSendAction(action ServiceActionValue) error {
body, err := json.Marshal(ServiceAction{action})
if err != nil {
return err
}
// Request API to Restart server
resp, err := adm.executeMethod("POST", requestData{
relPath: "/v1/service",
contentBody: bytes.NewReader(body),
contentSHA256Bytes: sum256(body),
})
defer closeResponse(resp)
if err != nil {
return err
+4 -4
View File
@@ -18,7 +18,7 @@ package madmin
import (
"crypto/md5"
"encoding/xml"
"encoding/json"
"io"
"io/ioutil"
"net"
@@ -45,9 +45,9 @@ func sumMD5(data []byte) []byte {
return hash.Sum(nil)
}
// xmlDecoder provide decoded value in xml.
func xmlDecoder(body io.Reader, v interface{}) error {
d := xml.NewDecoder(body)
// jsonDecoder decode json to go type.
func jsonDecoder(body io.Reader, v interface{}) error {
d := json.NewDecoder(body)
return d.Decode(v)
}
+54
View File
@@ -0,0 +1,54 @@
/*
* Minio Cloud Storage, (C) 2017 Minio, Inc.
*
* 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 madmin
import (
"encoding/json"
"io/ioutil"
"net/http"
)
// AdminAPIVersionInfo - contains admin API version information
type AdminAPIVersionInfo struct {
Version string `json:"version"`
}
// VersionInfo - Connect to minio server and call the version API to
// retrieve the server API version
func (adm *AdminClient) VersionInfo() (verInfo AdminAPIVersionInfo, err error) {
var resp *http.Response
resp, err = adm.executeMethod("GET", requestData{relPath: "/version"})
defer closeResponse(resp)
if err != nil {
return verInfo, err
}
// Check response http status code
if resp.StatusCode != http.StatusOK {
return verInfo, httpRespToErrorResponse(resp)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return verInfo, err
}
// Unmarshal the server's json response
err = json.Unmarshal(respBytes, &verInfo)
return verInfo, err
}
+27
View File
@@ -0,0 +1,27 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+22
View File
@@ -0,0 +1,22 @@
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,!appengine,!gccgo
package intsets
func popcnt(x word) int
func havePOPCNT() bool
var hasPOPCNT = havePOPCNT()
// popcount returns the population count (number of set bits) of x.
func popcount(x word) int {
if hasPOPCNT {
return popcnt(x)
}
return popcountTable(x) // faster than Hacker's Delight
}
+30
View File
@@ -0,0 +1,30 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,!appengine,!gccgo
#include "textflag.h"
// func havePOPCNT() bool
TEXT ·havePOPCNT(SB),4,$0
MOVQ $1, AX
CPUID
SHRQ $23, CX
ANDQ $1, CX
MOVB CX, ret+0(FP)
RET
// func popcnt(word) int
TEXT ·popcnt(SB),NOSPLIT,$0-8
XORQ AX, AX
MOVQ x+0(FP), SI
// POPCNT (SI), AX is not recognized by Go assembler,
// so we assemble it ourselves.
BYTE $0xf3
BYTE $0x48
BYTE $0x0f
BYTE $0xb8
BYTE $0xc6
MOVQ AX, ret+8(FP)
RET
+9
View File
@@ -0,0 +1,9 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build gccgo
package intsets
func popcount(x word) int
+19
View File
@@ -0,0 +1,19 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build gccgo
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#define _STRINGIFY2_(x) #x
#define _STRINGIFY_(x) _STRINGIFY2_(x)
#define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__)
extern intptr_t popcount(uintptr_t x) __asm__(GOSYM_PREFIX GOPKGPATH ".popcount");
intptr_t popcount(uintptr_t x) {
return __builtin_popcountl((unsigned long)(x));
}
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !amd64 appengine
// +build !gccgo
package intsets
import "runtime"
// We compared three algorithms---Hacker's Delight, table lookup,
// and AMD64's SSE4.1 hardware POPCNT---on a 2.67GHz Xeon X5550.
//
// % GOARCH=amd64 go test -run=NONE -bench=Popcount
// POPCNT 5.12 ns/op
// Table 8.53 ns/op
// HackersDelight 9.96 ns/op
//
// % GOARCH=386 go test -run=NONE -bench=Popcount
// Table 10.4 ns/op
// HackersDelight 5.23 ns/op
//
// (AMD64's ABM1 hardware supports ntz and nlz too,
// but they aren't critical.)
// popcount returns the population count (number of set bits) of x.
func popcount(x word) int {
if runtime.GOARCH == "386" {
return popcountHD(uint32(x))
}
return popcountTable(x)
}
+967
View File
@@ -0,0 +1,967 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package intsets provides Sparse, a compact and fast representation
// for sparse sets of int values.
//
// The time complexity of the operations Len, Insert, Remove and Has
// is in O(n) but in practice those methods are faster and more
// space-efficient than equivalent operations on sets based on the Go
// map type. The IsEmpty, Min, Max, Clear and TakeMin operations
// require constant time.
//
package intsets // import "golang.org/x/tools/container/intsets"
// TODO(adonovan):
// - Add InsertAll(...int), RemoveAll(...int)
// - Add 'bool changed' results for {Intersection,Difference}With too.
//
// TODO(adonovan): implement Dense, a dense bit vector with a similar API.
// The space usage would be proportional to Max(), not Len(), and the
// implementation would be based upon big.Int.
//
// TODO(adonovan): experiment with making the root block indirect (nil
// iff IsEmpty). This would reduce the memory usage when empty and
// might simplify the aliasing invariants.
//
// TODO(adonovan): opt: make UnionWith and Difference faster.
// These are the hot-spots for go/pointer.
import (
"bytes"
"fmt"
)
// A Sparse is a set of int values.
// Sparse operations (even queries) are not concurrency-safe.
//
// The zero value for Sparse is a valid empty set.
//
// Sparse sets must be copied using the Copy method, not by assigning
// a Sparse value.
//
type Sparse struct {
// An uninitialized Sparse represents an empty set.
// An empty set may also be represented by
// root.next == root.prev == &root.
// In a non-empty set, root.next points to the first block and
// root.prev to the last.
// root.offset and root.bits are unused.
root block
}
type word uintptr
const (
_m = ^word(0)
bitsPerWord = 8 << (_m>>8&1 + _m>>16&1 + _m>>32&1)
bitsPerBlock = 256 // optimal value for go/pointer solver performance
wordsPerBlock = bitsPerBlock / bitsPerWord
)
// Limit values of implementation-specific int type.
const (
MaxInt = int(^uint(0) >> 1)
MinInt = -MaxInt - 1
)
// -- block ------------------------------------------------------------
// A set is represented as a circular doubly-linked list of blocks,
// each containing an offset and a bit array of fixed size
// bitsPerBlock; the blocks are ordered by increasing offset.
//
// The set contains an element x iff the block whose offset is x - (x
// mod bitsPerBlock) has the bit (x mod bitsPerBlock) set, where mod
// is the Euclidean remainder.
//
// A block may only be empty transiently.
//
type block struct {
offset int // offset mod bitsPerBlock == 0
bits [wordsPerBlock]word // contains at least one set bit
next, prev *block // doubly-linked list of blocks
}
// wordMask returns the word index (in block.bits)
// and single-bit mask for the block's ith bit.
func wordMask(i uint) (w uint, mask word) {
w = i / bitsPerWord
mask = 1 << (i % bitsPerWord)
return
}
// insert sets the block b's ith bit and
// returns true if it was not already set.
//
func (b *block) insert(i uint) bool {
w, mask := wordMask(i)
if b.bits[w]&mask == 0 {
b.bits[w] |= mask
return true
}
return false
}
// remove clears the block's ith bit and
// returns true if the bit was previously set.
// NB: may leave the block empty.
//
func (b *block) remove(i uint) bool {
w, mask := wordMask(i)
if b.bits[w]&mask != 0 {
b.bits[w] &^= mask
return true
}
return false
}
// has reports whether the block's ith bit is set.
func (b *block) has(i uint) bool {
w, mask := wordMask(i)
return b.bits[w]&mask != 0
}
// empty reports whether b.len()==0, but more efficiently.
func (b *block) empty() bool {
for _, w := range b.bits {
if w != 0 {
return false
}
}
return true
}
// len returns the number of set bits in block b.
func (b *block) len() int {
var l int
for _, w := range b.bits {
l += popcount(w)
}
return l
}
// max returns the maximum element of the block.
// The block must not be empty.
//
func (b *block) max() int {
bi := b.offset + bitsPerBlock
// Decrement bi by number of high zeros in last.bits.
for i := len(b.bits) - 1; i >= 0; i-- {
if w := b.bits[i]; w != 0 {
return bi - nlz(w) - 1
}
bi -= bitsPerWord
}
panic("BUG: empty block")
}
// min returns the minimum element of the block,
// and also removes it if take is set.
// The block must not be initially empty.
// NB: may leave the block empty.
//
func (b *block) min(take bool) int {
for i, w := range b.bits {
if w != 0 {
tz := ntz(w)
if take {
b.bits[i] = w &^ (1 << uint(tz))
}
return b.offset + int(i*bitsPerWord) + tz
}
}
panic("BUG: empty block")
}
// forEach calls f for each element of block b.
// f must not mutate b's enclosing Sparse.
func (b *block) forEach(f func(int)) {
for i, w := range b.bits {
offset := b.offset + i*bitsPerWord
for bi := 0; w != 0 && bi < bitsPerWord; bi++ {
if w&1 != 0 {
f(offset)
}
offset++
w >>= 1
}
}
}
// offsetAndBitIndex returns the offset of the block that would
// contain x and the bit index of x within that block.
//
func offsetAndBitIndex(x int) (int, uint) {
mod := x % bitsPerBlock
if mod < 0 {
// Euclidean (non-negative) remainder
mod += bitsPerBlock
}
return x - mod, uint(mod)
}
// -- Sparse --------------------------------------------------------------
// start returns the root's next block, which is the root block
// (if s.IsEmpty()) or the first true block otherwise.
// start has the side effect of ensuring that s is properly
// initialized.
//
func (s *Sparse) start() *block {
root := &s.root
if root.next == nil {
root.next = root
root.prev = root
} else if root.next.prev != root {
// Copying a Sparse x leads to pernicious corruption: the
// new Sparse y shares the old linked list, but iteration
// on y will never encounter &y.root so it goes into a
// loop. Fail fast before this occurs.
panic("A Sparse has been copied without (*Sparse).Copy()")
}
return root.next
}
// IsEmpty reports whether the set s is empty.
func (s *Sparse) IsEmpty() bool {
return s.start() == &s.root
}
// Len returns the number of elements in the set s.
func (s *Sparse) Len() int {
var l int
for b := s.start(); b != &s.root; b = b.next {
l += b.len()
}
return l
}
// Max returns the maximum element of the set s, or MinInt if s is empty.
func (s *Sparse) Max() int {
if s.IsEmpty() {
return MinInt
}
return s.root.prev.max()
}
// Min returns the minimum element of the set s, or MaxInt if s is empty.
func (s *Sparse) Min() int {
if s.IsEmpty() {
return MaxInt
}
return s.root.next.min(false)
}
// block returns the block that would contain offset,
// or nil if s contains no such block.
//
func (s *Sparse) block(offset int) *block {
b := s.start()
for b != &s.root && b.offset <= offset {
if b.offset == offset {
return b
}
b = b.next
}
return nil
}
// Insert adds x to the set s, and reports whether the set grew.
func (s *Sparse) Insert(x int) bool {
offset, i := offsetAndBitIndex(x)
b := s.start()
for b != &s.root && b.offset <= offset {
if b.offset == offset {
return b.insert(i)
}
b = b.next
}
// Insert new block before b.
new := &block{offset: offset}
new.next = b
new.prev = b.prev
new.prev.next = new
new.next.prev = new
return new.insert(i)
}
func (s *Sparse) removeBlock(b *block) {
b.prev.next = b.next
b.next.prev = b.prev
}
// Remove removes x from the set s, and reports whether the set shrank.
func (s *Sparse) Remove(x int) bool {
offset, i := offsetAndBitIndex(x)
if b := s.block(offset); b != nil {
if !b.remove(i) {
return false
}
if b.empty() {
s.removeBlock(b)
}
return true
}
return false
}
// Clear removes all elements from the set s.
func (s *Sparse) Clear() {
s.root.next = &s.root
s.root.prev = &s.root
}
// If set s is non-empty, TakeMin sets *p to the minimum element of
// the set s, removes that element from the set and returns true.
// Otherwise, it returns false and *p is undefined.
//
// This method may be used for iteration over a worklist like so:
//
// var x int
// for worklist.TakeMin(&x) { use(x) }
//
func (s *Sparse) TakeMin(p *int) bool {
head := s.start()
if head == &s.root {
return false
}
*p = head.min(true)
if head.empty() {
s.removeBlock(head)
}
return true
}
// Has reports whether x is an element of the set s.
func (s *Sparse) Has(x int) bool {
offset, i := offsetAndBitIndex(x)
if b := s.block(offset); b != nil {
return b.has(i)
}
return false
}
// forEach applies function f to each element of the set s in order.
//
// f must not mutate s. Consequently, forEach is not safe to expose
// to clients. In any case, using "range s.AppendTo()" allows more
// natural control flow with continue/break/return.
//
func (s *Sparse) forEach(f func(int)) {
for b := s.start(); b != &s.root; b = b.next {
b.forEach(f)
}
}
// Copy sets s to the value of x.
func (s *Sparse) Copy(x *Sparse) {
if s == x {
return
}
xb := x.start()
sb := s.start()
for xb != &x.root {
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = xb.offset
sb.bits = xb.bits
xb = xb.next
sb = sb.next
}
s.discardTail(sb)
}
// insertBlockBefore returns a new block, inserting it before next.
func (s *Sparse) insertBlockBefore(next *block) *block {
b := new(block)
b.next = next
b.prev = next.prev
b.prev.next = b
next.prev = b
return b
}
// discardTail removes block b and all its successors from s.
func (s *Sparse) discardTail(b *block) {
if b != &s.root {
b.prev.next = &s.root
s.root.prev = b.prev
}
}
// IntersectionWith sets s to the intersection s ∩ x.
func (s *Sparse) IntersectionWith(x *Sparse) {
if s == x {
return
}
xb := x.start()
sb := s.start()
for xb != &x.root && sb != &s.root {
switch {
case xb.offset < sb.offset:
xb = xb.next
case xb.offset > sb.offset:
sb = sb.next
s.removeBlock(sb.prev)
default:
var sum word
for i := range sb.bits {
r := xb.bits[i] & sb.bits[i]
sb.bits[i] = r
sum |= r
}
if sum != 0 {
sb = sb.next
} else {
// sb will be overwritten or removed
}
xb = xb.next
}
}
s.discardTail(sb)
}
// Intersection sets s to the intersection x ∩ y.
func (s *Sparse) Intersection(x, y *Sparse) {
switch {
case s == x:
s.IntersectionWith(y)
return
case s == y:
s.IntersectionWith(x)
return
case x == y:
s.Copy(x)
return
}
xb := x.start()
yb := y.start()
sb := s.start()
for xb != &x.root && yb != &y.root {
switch {
case xb.offset < yb.offset:
xb = xb.next
continue
case xb.offset > yb.offset:
yb = yb.next
continue
}
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = xb.offset
var sum word
for i := range sb.bits {
r := xb.bits[i] & yb.bits[i]
sb.bits[i] = r
sum |= r
}
if sum != 0 {
sb = sb.next
} else {
// sb will be overwritten or removed
}
xb = xb.next
yb = yb.next
}
s.discardTail(sb)
}
// Intersects reports whether s ∩ x ≠ ∅.
func (s *Sparse) Intersects(x *Sparse) bool {
sb := s.start()
xb := x.start()
for sb != &s.root && xb != &x.root {
switch {
case xb.offset < sb.offset:
xb = xb.next
case xb.offset > sb.offset:
sb = sb.next
default:
for i := range sb.bits {
if sb.bits[i]&xb.bits[i] != 0 {
return true
}
}
sb = sb.next
xb = xb.next
}
}
return false
}
// UnionWith sets s to the union s ∪ x, and reports whether s grew.
func (s *Sparse) UnionWith(x *Sparse) bool {
if s == x {
return false
}
var changed bool
xb := x.start()
sb := s.start()
for xb != &x.root {
if sb != &s.root && sb.offset == xb.offset {
for i := range xb.bits {
if sb.bits[i] != xb.bits[i] {
sb.bits[i] |= xb.bits[i]
changed = true
}
}
xb = xb.next
} else if sb == &s.root || sb.offset > xb.offset {
sb = s.insertBlockBefore(sb)
sb.offset = xb.offset
sb.bits = xb.bits
changed = true
xb = xb.next
}
sb = sb.next
}
return changed
}
// Union sets s to the union x ∪ y.
func (s *Sparse) Union(x, y *Sparse) {
switch {
case x == y:
s.Copy(x)
return
case s == x:
s.UnionWith(y)
return
case s == y:
s.UnionWith(x)
return
}
xb := x.start()
yb := y.start()
sb := s.start()
for xb != &x.root || yb != &y.root {
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
switch {
case yb == &y.root || (xb != &x.root && xb.offset < yb.offset):
sb.offset = xb.offset
sb.bits = xb.bits
xb = xb.next
case xb == &x.root || (yb != &y.root && yb.offset < xb.offset):
sb.offset = yb.offset
sb.bits = yb.bits
yb = yb.next
default:
sb.offset = xb.offset
for i := range xb.bits {
sb.bits[i] = xb.bits[i] | yb.bits[i]
}
xb = xb.next
yb = yb.next
}
sb = sb.next
}
s.discardTail(sb)
}
// DifferenceWith sets s to the difference s ∖ x.
func (s *Sparse) DifferenceWith(x *Sparse) {
if s == x {
s.Clear()
return
}
xb := x.start()
sb := s.start()
for xb != &x.root && sb != &s.root {
switch {
case xb.offset > sb.offset:
sb = sb.next
case xb.offset < sb.offset:
xb = xb.next
default:
var sum word
for i := range sb.bits {
r := sb.bits[i] & ^xb.bits[i]
sb.bits[i] = r
sum |= r
}
sb = sb.next
xb = xb.next
if sum == 0 {
s.removeBlock(sb.prev)
}
}
}
}
// Difference sets s to the difference x ∖ y.
func (s *Sparse) Difference(x, y *Sparse) {
switch {
case x == y:
s.Clear()
return
case s == x:
s.DifferenceWith(y)
return
case s == y:
var y2 Sparse
y2.Copy(y)
s.Difference(x, &y2)
return
}
xb := x.start()
yb := y.start()
sb := s.start()
for xb != &x.root && yb != &y.root {
if xb.offset > yb.offset {
// y has block, x has none
yb = yb.next
continue
}
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = xb.offset
switch {
case xb.offset < yb.offset:
// x has block, y has none
sb.bits = xb.bits
sb = sb.next
default:
// x and y have corresponding blocks
var sum word
for i := range sb.bits {
r := xb.bits[i] & ^yb.bits[i]
sb.bits[i] = r
sum |= r
}
if sum != 0 {
sb = sb.next
} else {
// sb will be overwritten or removed
}
yb = yb.next
}
xb = xb.next
}
for xb != &x.root {
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = xb.offset
sb.bits = xb.bits
sb = sb.next
xb = xb.next
}
s.discardTail(sb)
}
// SymmetricDifferenceWith sets s to the symmetric difference s ∆ x.
func (s *Sparse) SymmetricDifferenceWith(x *Sparse) {
if s == x {
s.Clear()
return
}
sb := s.start()
xb := x.start()
for xb != &x.root && sb != &s.root {
switch {
case sb.offset < xb.offset:
sb = sb.next
case xb.offset < sb.offset:
nb := s.insertBlockBefore(sb)
nb.offset = xb.offset
nb.bits = xb.bits
xb = xb.next
default:
var sum word
for i := range sb.bits {
r := sb.bits[i] ^ xb.bits[i]
sb.bits[i] = r
sum |= r
}
sb = sb.next
xb = xb.next
if sum == 0 {
s.removeBlock(sb.prev)
}
}
}
for xb != &x.root { // append the tail of x to s
sb = s.insertBlockBefore(sb)
sb.offset = xb.offset
sb.bits = xb.bits
sb = sb.next
xb = xb.next
}
}
// SymmetricDifference sets s to the symmetric difference x ∆ y.
func (s *Sparse) SymmetricDifference(x, y *Sparse) {
switch {
case x == y:
s.Clear()
return
case s == x:
s.SymmetricDifferenceWith(y)
return
case s == y:
s.SymmetricDifferenceWith(x)
return
}
sb := s.start()
xb := x.start()
yb := y.start()
for xb != &x.root && yb != &y.root {
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
switch {
case yb.offset < xb.offset:
sb.offset = yb.offset
sb.bits = yb.bits
sb = sb.next
yb = yb.next
case xb.offset < yb.offset:
sb.offset = xb.offset
sb.bits = xb.bits
sb = sb.next
xb = xb.next
default:
var sum word
for i := range sb.bits {
r := xb.bits[i] ^ yb.bits[i]
sb.bits[i] = r
sum |= r
}
if sum != 0 {
sb.offset = xb.offset
sb = sb.next
}
xb = xb.next
yb = yb.next
}
}
for xb != &x.root { // append the tail of x to s
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = xb.offset
sb.bits = xb.bits
sb = sb.next
xb = xb.next
}
for yb != &y.root { // append the tail of y to s
if sb == &s.root {
sb = s.insertBlockBefore(sb)
}
sb.offset = yb.offset
sb.bits = yb.bits
sb = sb.next
yb = yb.next
}
s.discardTail(sb)
}
// SubsetOf reports whether s ∖ x = ∅.
func (s *Sparse) SubsetOf(x *Sparse) bool {
if s == x {
return true
}
sb := s.start()
xb := x.start()
for sb != &s.root {
switch {
case xb == &x.root || xb.offset > sb.offset:
return false
case xb.offset < sb.offset:
xb = xb.next
default:
for i := range sb.bits {
if sb.bits[i]&^xb.bits[i] != 0 {
return false
}
}
sb = sb.next
xb = xb.next
}
}
return true
}
// Equals reports whether the sets s and t have the same elements.
func (s *Sparse) Equals(t *Sparse) bool {
if s == t {
return true
}
sb := s.start()
tb := t.start()
for {
switch {
case sb == &s.root && tb == &t.root:
return true
case sb == &s.root || tb == &t.root:
return false
case sb.offset != tb.offset:
return false
case sb.bits != tb.bits:
return false
}
sb = sb.next
tb = tb.next
}
}
// String returns a human-readable description of the set s.
func (s *Sparse) String() string {
var buf bytes.Buffer
buf.WriteByte('{')
s.forEach(func(x int) {
if buf.Len() > 1 {
buf.WriteByte(' ')
}
fmt.Fprintf(&buf, "%d", x)
})
buf.WriteByte('}')
return buf.String()
}
// BitString returns the set as a string of 1s and 0s denoting the sum
// of the i'th powers of 2, for each i in s. A radix point, always
// preceded by a digit, appears if the sum is non-integral.
//
// Examples:
// {}.BitString() = "0"
// {4,5}.BitString() = "110000"
// {-3}.BitString() = "0.001"
// {-3,0,4,5}.BitString() = "110001.001"
//
func (s *Sparse) BitString() string {
if s.IsEmpty() {
return "0"
}
min, max := s.Min(), s.Max()
var nbytes int
if max > 0 {
nbytes = max
}
nbytes++ // zero bit
radix := nbytes
if min < 0 {
nbytes += len(".") - min
}
b := make([]byte, nbytes)
for i := range b {
b[i] = '0'
}
if radix < nbytes {
b[radix] = '.'
}
s.forEach(func(x int) {
if x >= 0 {
x += len(".")
}
b[radix-x] = '1'
})
return string(b)
}
// GoString returns a string showing the internal representation of
// the set s.
//
func (s *Sparse) GoString() string {
var buf bytes.Buffer
for b := s.start(); b != &s.root; b = b.next {
fmt.Fprintf(&buf, "block %p {offset=%d next=%p prev=%p",
b, b.offset, b.next, b.prev)
for _, w := range b.bits {
fmt.Fprintf(&buf, " 0%016x", w)
}
fmt.Fprintf(&buf, "}\n")
}
return buf.String()
}
// AppendTo returns the result of appending the elements of s to slice
// in order.
func (s *Sparse) AppendTo(slice []int) []int {
s.forEach(func(x int) {
slice = append(slice, x)
})
return slice
}
// -- Testing/debugging ------------------------------------------------
// check returns an error if the representation invariants of s are violated.
func (s *Sparse) check() error {
if !s.root.empty() {
return fmt.Errorf("non-empty root block")
}
if s.root.offset != 0 {
return fmt.Errorf("root block has non-zero offset %d", s.root.offset)
}
for b := s.start(); b != &s.root; b = b.next {
if b.offset%bitsPerBlock != 0 {
return fmt.Errorf("bad offset modulo: %d", b.offset)
}
if b.empty() {
return fmt.Errorf("empty block")
}
if b.prev.next != b {
return fmt.Errorf("bad prev.next link")
}
if b.next.prev != b {
return fmt.Errorf("bad next.prev link")
}
if b.prev != &s.root {
if b.offset <= b.prev.offset {
return fmt.Errorf("bad offset order: b.offset=%d, prev.offset=%d",
b.offset, b.prev.offset)
}
}
}
return nil
}
+84
View File
@@ -0,0 +1,84 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package intsets
// From Hacker's Delight, fig 5.2.
func popcountHD(x uint32) int {
x -= (x >> 1) & 0x55555555
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return int(x & 0x0000003f)
}
var a [1 << 8]byte
func init() {
for i := range a {
var n byte
for x := i; x != 0; x >>= 1 {
if x&1 != 0 {
n++
}
}
a[i] = n
}
}
func popcountTable(x word) int {
return int(a[byte(x>>(0*8))] +
a[byte(x>>(1*8))] +
a[byte(x>>(2*8))] +
a[byte(x>>(3*8))] +
a[byte(x>>(4*8))] +
a[byte(x>>(5*8))] +
a[byte(x>>(6*8))] +
a[byte(x>>(7*8))])
}
// nlz returns the number of leading zeros of x.
// From Hacker's Delight, fig 5.11.
func nlz(x word) int {
x |= (x >> 1)
x |= (x >> 2)
x |= (x >> 4)
x |= (x >> 8)
x |= (x >> 16)
x |= (x >> 32)
return popcount(^x)
}
// ntz returns the number of trailing zeros of x.
// From Hacker's Delight, fig 5.13.
func ntz(x word) int {
if x == 0 {
return bitsPerWord
}
n := 1
if bitsPerWord == 64 {
if (x & 0xffffffff) == 0 {
n = n + 32
x = x >> 32
}
}
if (x & 0x0000ffff) == 0 {
n = n + 16
x = x >> 16
}
if (x & 0x000000ff) == 0 {
n = n + 8
x = x >> 8
}
if (x & 0x0000000f) == 0 {
n = n + 4
x = x >> 4
}
if (x & 0x00000003) == 0 {
n = n + 2
x = x >> 2
}
return n - int(x&1)
}
+3 -9
View File
@@ -98,10 +98,10 @@
"revisionTime": "2017-10-28T03:50:25Z"
},
{
"checksumSHA1": "ndi8tLipWnO8YiBUB0l4e/PhVHI=",
"checksumSHA1": "gWUkcm51sWJmmk64Fai+q7pKDEg=",
"path": "github.com/minio/minio/pkg/madmin",
"revision": "dd5a3289dd66d9734a584d08835fd600f97963bd",
"revisionTime": "2018-01-18T22:39:39Z"
"revision": "a337ea4d11eb2ae87144a76cdefd6f77ae7303a4",
"revisionTime": "2018-01-22T22:54:55Z"
},
{
"checksumSHA1": "5r3V/rzpVqjJvzE/K5sR2LHEteM=",
@@ -133,12 +133,6 @@
"revision": "7ebf11b20233d0eba0f1a28dbd124e7fdd44aee2",
"revisionTime": "2017-03-19T21:23:05Z"
},
{
"checksumSHA1": "vCbb0vMh0GcGoYk33LRxReyLZlM=",
"path": "github.com/minio/sha256-simd",
"revision": "ad98a36ba0da87206e3378c556abbfeaeaa98668",
"revisionTime": "2017-12-13T22:06:25Z"
},
{
"path": "github.com/pkg/profile",
"revision": "19396ecfda37c1c9ddaa52019adca59d582e4832",