locks: Use new json format for list/clear results (#1975)

Also minio-admin package has been updated
This commit is contained in:
Anis Elleuch
2017-01-19 12:07:45 -08:00
committed by Harshavardhana
parent 085a1e512f
commit 6b2e63e66c
9 changed files with 283 additions and 101 deletions
+9 -9
View File
@@ -68,19 +68,19 @@ EXAMPLES:
// lockClearMessage container to hold locks information.
type lockClearMessage struct {
Status string `json:"status"`
LockInfo madmin.VolumeLockInfo `json:"volumeLockInfo"`
Status string `json:"status"`
madmin.VolumeLockInfo
}
// String colorized service status message.
func (u lockClearMessage) String() string {
msg := fmt.Sprintf("%s/%s (LocksOnObject: %d, locksAcquiredOnObject: %d, totalBlockLocks:%d): ",
u.LockInfo.Bucket,
u.LockInfo.Object,
u.LockInfo.LocksOnObject,
u.LockInfo.LocksAcquiredOnObject,
u.LockInfo.TotalBlockedLocks)
for _, detail := range u.LockInfo.LockDetailsOnObject {
u.Bucket,
u.Object,
u.LocksOnObject,
u.LocksAcquiredOnObject,
u.TotalBlockedLocks)
for _, detail := range u.LockDetailsOnObject {
msg += fmt.Sprintf(" %+v", detail)
}
msg += "\n"
@@ -128,7 +128,7 @@ func mainAdminLockClear(ctx *cli.Context) error {
fatalIf(probe.NewError(e), "Cannot clear the specified locks.")
for _, l := range locksInfo {
printMsg(lockClearMessage{LockInfo: l})
printMsg(lockClearMessage{VolumeLockInfo: l})
}
return nil
+9 -9
View File
@@ -68,19 +68,19 @@ EXAMPLES:
// lockListMessage container to hold locks information.
type lockListMessage struct {
Status string `json:"status"`
LockInfo madmin.VolumeLockInfo `json:"volumeLockInfo"`
Status string `json:"status"`
madmin.VolumeLockInfo
}
// String colorized service status message.
func (u lockListMessage) String() string {
msg := fmt.Sprintf("%s/%s (LocksOnObject: %d, locksAcquiredOnObject: %d, totalBlockLocks:%d): ",
u.LockInfo.Bucket,
u.LockInfo.Object,
u.LockInfo.LocksOnObject,
u.LockInfo.LocksAcquiredOnObject,
u.LockInfo.TotalBlockedLocks)
for _, detail := range u.LockInfo.LockDetailsOnObject {
u.Bucket,
u.Object,
u.LocksOnObject,
u.LocksAcquiredOnObject,
u.TotalBlockedLocks)
for _, detail := range u.LockDetailsOnObject {
msg += fmt.Sprintf(" %+v", detail)
}
msg += "\n"
@@ -128,7 +128,7 @@ func mainAdminLockList(ctx *cli.Context) error {
fatalIf(probe.NewError(e), "Cannot get lock status.")
for _, l := range locksInfo {
printMsg(lockListMessage{LockInfo: l})
printMsg(lockListMessage{VolumeLockInfo: l})
}
return nil
+153 -42
View File
@@ -1,4 +1,4 @@
# Golang Admin Client API Reference [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# Golang Admin Client API Reference [![Slack](https://slack.minio.io/slack?type=svg)](https://slack.minio.io)
## Initialize Minio Admin Client object.
@@ -9,29 +9,29 @@
package main
import (
"fmt"
"fmt"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/minio/pkg/madmin"
)
func main() {
// Use a secure connection.
ssl := true
// Use a secure connection.
ssl := true
// Initialize minio client object.
mdmClnt, err := madmin.New("your-minio.example.com:9000", "YOUR-ACCESSKEYID", "YOUR-SECRETKEY", ssl)
if err != nil {
fmt.Println(err)
return
}
// Initialize minio client object.
mdmClnt, err := madmin.New("your-minio.example.com:9000", "YOUR-ACCESSKEYID", "YOUR-SECRETKEY", ssl)
if err != nil {
fmt.Println(err)
return
}
// Fetch service status.
st, err := mdmClnt.ServiceStatus()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%#v\n", st)
// Fetch service status.
st, err := mdmClnt.ServiceStatus()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%#v\n", st)
}
```
@@ -39,7 +39,6 @@ func main() {
| Service operations|LockInfo operations|Healing operations|
|:---|:---|:---|
|[`ServiceStatus`](#ServiceStatus)| | |
|[`ServiceStop`](#ServiceStop)| | |
|[`ServiceRestart`](#ServiceRestart)| | |
## 1. Constructor
@@ -63,16 +62,16 @@ __Parameters__
<a name="ServiceStatus"></a>
### ServiceStatus() (ServiceStatusMetadata, error)
Fetch service status, replies disk space used, backend type and total disks offline/online (XL).
Fetch service status, replies disk space used, backend type and total disks offline/online (applicable in distributed mode).
| Param | Type | Description |
|---|---|---|
|`serviceStatus` | _ServiceStatusMetadata_ | Represents current server status info in following format: |
|`serviceStatus` | _ServiceStatusMetadata_ | Represents current server status info in following format: |
| Param | Type | Description |
|---|---|---|
|`st.Total` | _int64_ | Total disk space. |
|`st.Total` | _int64_ | Total disk space. |
|`st.Free` | _int64_ | Free disk space. |
|`st.Backend`| _struct{}_ | Represents backend type embedded structure. |
@@ -87,7 +86,7 @@ Fetch service status, replies disk space used, backend type and total disks offl
__Example__
```go
st, err := madmClnt.ServiceStatus()
@@ -98,30 +97,13 @@ Fetch service status, replies disk space used, backend type and total disks offl
```
<a name="ServiceStop"></a>
### ServiceStop() (error)
If successful shuts down the running minio service, for distributed setup stops all remote minio servers.
__Example__
```go
st, err := madmClnt.ServiceStop()
if err != nil {
log.Fatalln(err)
}
log.Printf("Succes")
```
<a name="ServiceRestart"></a>
### ServiceRestart() (error)
If successful restarts the running minio service, for distributed setup restarts all remote minio servers.
__Example__
```go
@@ -129,7 +111,136 @@ If successful restarts the running minio service, for distributed setup restarts
if err != nil {
log.Fatalln(err)
}
log.Printf("Succes")
log.Printf("Success")
```
<a name="ListLocks"></a>
### ListLocks(bucket, prefix string, olderThan time.Duration) ([]VolumeLockInfo, error)
If successful returns information on the list of locks held on ``bucket`` matching ``prefix`` older than ``olderThan`` seconds.
__Example__
``` go
volLocks, err := madmClnt.ListLocks("mybucket", "myprefix", 30 * time.Second)
if err != nil {
log.Fatalln(err)
}
log.Println("List of locks: ", volLocks)
```
<a name="ClearLocks"></a>
### ClearLocks(bucket, prefix string, olderThan time.Duration) ([]VolumeLockInfo, error)
If successful returns information on the list of locks cleared on ``bucket`` matching ``prefix`` older than ``olderThan`` seconds.
__Example__
``` go
volLocks, err := madmClnt.ClearLocks("mybucket", "myprefix", 30 * time.Second)
if err != nil {
log.Fatalln(err)
}
log.Println("List of locks cleared: ", volLocks)
```
<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``.
__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="ListBucketsList"></a>
### ListBucketsList() 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)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed mybucket")
```
<a name="HealObject"></a>
### HealObject(bucket, object string, isDryRun bool) 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.
__Example__
``` go
isDryRun := false
err := madmClnt.HealObject("mybucket", "myobject", isDryRun)
if err != nil {
log.Fatalln(err)
}
log.Println("successfully healed mybucket/myobject")
```
+3 -3
View File
@@ -1,4 +1,4 @@
# Minio Admin Library. [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# Minio Admin Library. [![Slack](https://slack.minio.io/slack?type=svg)](https://slack.minio.io)
The Minio Admin Golang Client SDK provides APIs to manage Minio services.
This quickstart guide will show you how to install the Minio Admin client SDK, connect to Minio admin service, and provide a walkthrough of a simple file uploader.
@@ -105,16 +105,16 @@ go run service-status.go
### API Reference : Service Operations
* [`ServiceStatus`](./API.md#ServiceStatus)
* [`ServiceStop`](./API.md#ServiceStop)
* [`ServiceRestart`](./API.md#ServiceRestart)
* [`ServiceSetCredentials`](./API.md#ServiceSetCredentials)
## Full Examples
#### Full Examples : Service Operations
* [service-status.go](https://github.com/minio/minio/blob/master/pkg/madmin/examples/service-status.go)
* [service-stop.go](https://github.com/minio/minio/blob/master/pkg/madmin/examples/service-stop.go)
* [service-restart.go](https://github.com/minio/minio/blob/master/pkg/madmin/examples/service-restart.go)
* [service-set-credentials.go](https://github.com/minio/minio/blob/master/pkg/madmin/examples/service-set-credentials.go)
## Contribute
+27 -1
View File
@@ -16,7 +16,10 @@
package madmin
import "encoding/xml"
import (
"encoding/xml"
"net/http"
)
/* **** SAMPLE ERROR RESPONSE ****
<?xml version="1.0" encoding="UTF-8"?>
@@ -50,6 +53,29 @@ func (e ErrorResponse) Error() string {
return e.Message
}
const (
reportIssue = "Please report this issue at https://github.com/minio/minio-go/issues."
)
// httpRespToErrorResponse returns a new encoded ErrorResponse
// structure as error.
func httpRespToErrorResponse(resp *http.Response) error {
if resp == nil {
msg := "Response is empty. " + reportIssue
return ErrInvalidArgument(msg)
}
var errResp ErrorResponse
// Decode the xml error
err := xmlDecoder(resp.Body, &errResp)
if err != nil {
return ErrorResponse{
Code: resp.Status,
Message: "Failed to parse server response.",
}
}
return errResp
}
// ErrInvalidArgument - Invalid argument response.
func ErrInvalidArgument(message string) error {
return ErrorResponse{
+16 -10
View File
@@ -43,12 +43,12 @@ const (
// OpsLockState - represents lock specific details.
type OpsLockState struct {
OperationID string `json:"opsID"` // String containing operation ID.
LockSource string `json:"lockSource"` // Operation type (GetObject, PutObject...)
LockType lockType `json:"lockType"` // Lock type (RLock, WLock)
Status statusType `json:"status"` // Status can be Running/Ready/Blocked.
Since time.Time `json:"statusSince"` // Time when the lock was initially held.
Duration time.Duration `json:"statusDuration"` // Duration since the lock was held.
OperationID string `json:"id"` // String containing operation ID.
LockSource string `json:"source"` // Operation type (GetObject, PutObject...)
LockType lockType `json:"type"` // Lock type (RLock, WLock)
Status statusType `json:"status"` // Status can be Running/Ready/Blocked.
Since time.Time `json:"since"` // Time when the lock was initially held.
Duration time.Duration `json:"duration"` // Duration since the lock was held.
}
// VolumeLockInfo - represents summary and individual lock details of all
@@ -56,17 +56,23 @@ type OpsLockState struct {
type VolumeLockInfo struct {
Bucket string `json:"bucket"`
Object string `json:"object"`
// All locks blocked + running for given <volume,path> pair.
LocksOnObject int64 `json:"locksOnObject"`
LocksOnObject int64 `json:"-"`
// Count of operations which has successfully acquired the lock
// but hasn't unlocked yet( operation in progress).
LocksAcquiredOnObject int64 `json:"locksAcquiredOnObject"`
LocksAcquiredOnObject int64 `json:"-"`
// Count of operations which are blocked waiting for the lock
// to be released.
TotalBlockedLocks int64 `json:"locksBlockedOnObject"`
TotalBlockedLocks int64 `json:"-"`
// Count of all read locks
TotalReadLocks int64 `json:"readLocks"`
// Count of all write locks
TotalWriteLocks int64 `json:"writeLocks"`
// State information containing state of the locks for all operations
// on given <volume,path> pair.
LockDetailsOnObject []OpsLockState `json:"lockDetailsOnObject"`
LockDetailsOnObject []OpsLockState `json:"lockOwners"`
}
// getLockInfos - unmarshal []VolumeLockInfo from a reader.
+48 -24
View File
@@ -18,7 +18,9 @@
package madmin
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"io/ioutil"
"net/http"
@@ -95,30 +97,6 @@ func (adm *AdminClient) ServiceStatus() (ServiceStatusMetadata, error) {
return storageInfo, nil
}
// ServiceStop - Call Service Stop Management API to stop a specified Minio server
func (adm *AdminClient) ServiceStop() error {
//
reqData := requestData{}
reqData.queryValues = make(url.Values)
reqData.queryValues.Set("service", "")
reqData.customHeaders = make(http.Header)
reqData.customHeaders.Set(minioAdminOpHeader, "stop")
// Execute GET on bucket to list objects.
resp, err := adm.executeMethod("POST", reqData)
defer closeResponse(resp)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.New("Got HTTP Status: " + resp.Status)
}
return nil
}
// ServiceRestart - Call Service Restart API to restart a specified Minio server
func (adm *AdminClient) ServiceRestart() error {
//
@@ -141,3 +119,49 @@ func (adm *AdminClient) ServiceRestart() error {
}
return nil
}
// setCredsReq - xml to send to the server to set new credentials
type setCredsReq struct {
Username string `xml:"username"`
Password string `xml:"password"`
}
// ServiceSetCredentials - Call Service Set Credentials API to set new access and secret keys in the specified Minio server
func (adm *AdminClient) ServiceSetCredentials(access, secret string) error {
// Disallow sending with the server if the connection is not secure
if !adm.secure {
return errors.New("setting new credentials requires HTTPS connection to the server")
}
// 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})
if err != nil {
return err
}
reqData.contentBody = bytes.NewReader(body)
reqData.contentLength = int64(len(body))
reqData.contentMD5Bytes = sumMD5(body)
reqData.contentSHA256Bytes = sum256(body)
// Execute GET on bucket to list objects.
resp, err := adm.executeMethod("POST", reqData)
defer closeResponse(resp)
if err != nil {
return err
}
// Return error to the caller if http response code is different from 200
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp)
}
return nil
}
+15
View File
@@ -17,7 +17,9 @@
package madmin
import (
"crypto/md5"
"crypto/sha256"
"encoding/xml"
"io"
"io/ioutil"
"net"
@@ -35,6 +37,19 @@ func sum256(data []byte) []byte {
return hash.Sum(nil)
}
// sumMD5 calculate sumMD5 sum for an input byte array.
func sumMD5(data []byte) []byte {
hash := md5.New()
hash.Write(data)
return hash.Sum(nil)
}
// xmlDecoder provide decoded value in xml.
func xmlDecoder(body io.Reader, v interface{}) error {
d := xml.NewDecoder(body)
return d.Decode(v)
}
// getEndpointURL - construct a new endpoint.
func getEndpointURL(endpoint string, secure bool) (*url.URL, error) {
if strings.Contains(endpoint, ":") {
+3 -3
View File
@@ -80,10 +80,10 @@
"revisionTime": "2016-08-18T00:31:20Z"
},
{
"checksumSHA1": "5+Z11r2dweplJF0rTgmn1gtCsjw=",
"checksumSHA1": "gsJXCQU0qB6V7hdxCpJ64duQwn0=",
"path": "github.com/minio/minio/pkg/madmin",
"revision": "c8f57133a4384ea98206560b691f50e7520007b9",
"revisionTime": "2017-01-04T07:39:22Z"
"revision": "a17f1e875ce5944b2cdbb2c685f1ab32ed8adff5",
"revisionTime": "2017-01-19T19:19:57Z"
},
{
"path": "github.com/minio/minio/pkg/probe",