CombinedText
stringlengths
4
3.42M
package models type CreateRequest struct { SenderPubKey []byte SenderOutput string } type CreateResponse struct { ID string Timeout int64 Fee int64 ReceiverPubKey []byte ReceiverOutput string FundingAddress string } type OpenRequest struct { ID string TxID string Vout uint32 SenderSig []byte } type OpenResponse struct { } type SendRequest struct { ID string Amount int64 SenderSig []byte Target string } type SendResponse struct { } type CloseRequest struct { ID string } type CloseResponse struct { CloseTx []byte } add better json tags package models type CreateRequest struct { SenderPubKey []byte `json:"senderPubKey"` SenderOutput string `json:"senderOutput"` } type CreateResponse struct { ID string `json:"id"` Timeout int64 `json:"timeout"` Fee int64 `json:"fee"` ReceiverPubKey []byte `json:"receiverPubKey"` ReceiverOutput string `json:"receiverOutput"` FundingAddress string `json:"fundingAddress"` } type OpenRequest struct { ID string `json:"id"` TxID string `json:"txid"` Vout uint32 `json:"vout"` SenderSig []byte `json:"senderSig"` } type OpenResponse struct { } type SendRequest struct { ID string `json:"id"` Amount int64 `json:"amount"` SenderSig []byte `json:"senderSig"` Target string `json:"target"` } type SendResponse struct { } type CloseRequest struct { ID string `json:"id"` } type CloseResponse struct { CloseTx []byte `json:"closeTx"` }
// Copyright 2016, Google Inc. // 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. package gax import ( "context" "time" ) // APICall is a user defined call stub. type APICall func(context.Context, CallSettings) error // Invoke calls the given APICall, // performing retries as specified by opts, if any. func Invoke(ctx context.Context, call APICall, opts ...CallOption) error { var settings CallSettings for _, opt := range opts { opt.Resolve(&settings) } return invoke(ctx, call, settings, Sleep) } // Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing. // If interrupted, Sleep returns ctx.Err(). func Sleep(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) select { case <-ctx.Done(): t.Stop() return ctx.Err() case <-t.C: return nil } } type sleeper func(ctx context.Context, d time.Duration) error // invoke implements Invoke, taking an additional sleeper argument for testing. func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { var retryer Retryer for { err := call(ctx, settings) if err == nil { return nil } if settings.Retry == nil { return err } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r } else { return err } } if d, ok := retryer.Retry(err); !ok { return err } else if err = sp(ctx, d); err != nil { return err } } } never retry permanent connection errors (#73) Now that https://github.com/grpc/grpc-go/pull/2508 is in, gRPC plumbs the last connection error when we attempt to make an RPC on a clientconn that has not been successfully conencted. So, in this CL, we check errors for a permanent connection problem. Specifically if certificates are misconfigured, or ca-certificates are missing, we expect not to be able to establish a connection in a reasonable amount of time and instead bail out and return the error to the user to fix. Fixes https://github.com/googleapis/google-cloud-go/issues/1234 // Copyright 2016, Google Inc. // 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. package gax import ( "context" "strings" "time" ) // APICall is a user defined call stub. type APICall func(context.Context, CallSettings) error // Invoke calls the given APICall, // performing retries as specified by opts, if any. func Invoke(ctx context.Context, call APICall, opts ...CallOption) error { var settings CallSettings for _, opt := range opts { opt.Resolve(&settings) } return invoke(ctx, call, settings, Sleep) } // Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing. // If interrupted, Sleep returns ctx.Err(). func Sleep(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) select { case <-ctx.Done(): t.Stop() return ctx.Err() case <-t.C: return nil } } type sleeper func(ctx context.Context, d time.Duration) error // invoke implements Invoke, taking an additional sleeper argument for testing. func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { var retryer Retryer for { err := call(ctx, settings) if err == nil { return nil } if settings.Retry == nil { return err } // Never retry permanent certificate errors. (e.x. if ca-certificates // are not installed). We should only make very few, targeted // exceptions: many (other) status=Unavailable should be retried, such // as if there's a network hiccup, or the internet goes out for a // minute. This is also why here we are doing string parsing instead of // simply making Unavailable a non-retried code elsewhere. if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { return err } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r } else { return err } } if d, ok := retryer.Retry(err); !ok { return err } else if err = sp(ctx, d); err != nil { return err } } }
package orchestrators import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "math/rand" "net" "net/http" "net/url" "regexp" "sort" "strings" "time" "unicode/utf8" "github.com/camptocamp/bivac/pkg/volume" //"github.com/rancher/go-rancher-metadata/metadata" "github.com/rancher/go-rancher/v2" "golang.org/x/net/websocket" ) // CattleConfig stores Cattle configuration type CattleConfig struct { URL string AccessKey string SecretKey string } // CattleOrchestrator implements a container orchestrator for Cattle type CattleOrchestrator struct { config *CattleConfig client *client.RancherClient } // NewCattleOrchestrator creates a Cattle client func NewCattleOrchestrator(config *CattleConfig) (o *CattleOrchestrator, err error) { o = &CattleOrchestrator{ config: config, } o.client, err = client.NewRancherClient(&client.ClientOpts{ Url: config.URL, AccessKey: config.AccessKey, SecretKey: config.SecretKey, Timeout: 30 * time.Second, }) if err != nil { err = fmt.Errorf("failed to create new Rancher client: %s", err) } return } // GetName returns the orchestrator name func (*CattleOrchestrator) GetName() string { return "cattle" } // GetPath returns the backup path func (*CattleOrchestrator) GetPath(v *volume.Volume) string { return v.Hostname } // GetVolumes returns the Cattle volumes, inspected and filtered func (o *CattleOrchestrator) GetVolumes(volumeFilters volume.Filters) (volumes []*volume.Volume, err error) { vs, err := o.client.Volume.List(&client.ListOpts{ Filters: map[string]interface{}{ "limit": -2, "all": true, }, }) if err != nil { err = fmt.Errorf("failed to list volumes: %s", err) return } var mountpoint string var h *client.Host for _, v := range vs.Data { if len(v.Mounts) < 1 { mountpoint = "/data" } else { mountpoint = v.Mounts[0].Path } var hostID, hostname string var spc *client.StoragePoolCollection err = o.rawAPICall("GET", v.Links["storagePools"], "", &spc) if err != nil { continue } if len(spc.Data) == 0 { continue } if len(spc.Data[0].HostIds) == 0 { continue } hostID = spc.Data[0].HostIds[0] h, err = o.client.Host.ById(hostID) if err != nil { hostname = hostID } else { hostname = h.Hostname } v := &volume.Volume{ ID: v.Id, Name: v.Name, Mountpoint: mountpoint, HostBind: hostID, Hostname: hostname, } if b, _, _ := o.blacklistedVolume(v, volumeFilters); b { continue } volumes = append(volumes, v) } return } func createAgentName() string { var letter = []rune("abcdefghijklmnopqrstuvwxyz0123456789") b := make([]rune, 10) for i := range b { b[i] = letter[rand.Intn(len(letter))] } return "bivac-agent-" + string(b) } // DeployAgent creates a `bivac agent` container func (o *CattleOrchestrator) DeployAgent(image string, cmd []string, envs []string, v *volume.Volume) (success bool, output string, err error) { success = false environment := make(map[string]interface{}) for _, env := range envs { splitted := strings.Split(env, "=") environment[splitted[0]] = splitted[1] } container, err := o.client.Container.Create(&client.Container{ Name: createAgentName(), RequestedHostId: v.HostBind, ImageUuid: "docker:" + image, Command: cmd, Environment: environment, RestartPolicy: &client.RestartPolicy{ MaximumRetryCount: 1, Name: "on-failure", }, Labels: map[string]interface{}{ "io.rancher.container.pull_image": "always", }, DataVolumes: []string{ v.Name + ":" + v.Mountpoint, }, }) if err != nil { err = fmt.Errorf("failed to create an agent container: %s", err) return } defer o.RemoveContainer(container) stopped := false terminated := false timeoutCount := 0 for !terminated && timeoutCount <= 30 { container, err := o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect agent: %s", err) return false, "", err } // This workaround is awful but it's the only way to know if the container failed. if container.State == "stopped" { if container.StartCount == 1 { if stopped == false { stopped = true time.Sleep(5 * time.Second) } else { terminated = true success = true } } else { success = false terminated = true } } else if container.State == "starting" { timeoutCount++ } time.Sleep(1 * time.Second) } if timeoutCount == 30 { success = false err = fmt.Errorf("failed to start container: timeout") return } container, err = o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect the agent before retrieving the logs: %s", err) return false, "", err } var hostAccess *client.HostAccess logsParams := `{"follow":false,"lines":9999,"since":"","timestamps":true}` err = o.rawAPICall("POST", container.Links["self"]+"/?action=logs", logsParams, &hostAccess) if err != nil { err = fmt.Errorf("failed to read response from rancher: %s", err) return } origin := o.config.URL u, err := url.Parse(hostAccess.Url) if err != nil { err = fmt.Errorf("failed to parse rancher server url: %s", err) return } q := u.Query() q.Set("token", hostAccess.Token) u.RawQuery = q.Encode() ws, err := websocket.Dial(u.String(), "", origin) if err != nil { err = fmt.Errorf("failed to open websocket with rancher server: %s", err) return } defer ws.Close() var data bytes.Buffer io.Copy(&data, ws) re := regexp.MustCompile(`(?m)[0-9]{2,} [ZT\-\:\.0-9]+ (.*)`) for _, line := range re.FindAllStringSubmatch(data.String(), -1) { output = strings.Join([]string{output, line[1]}, "\n") } return } // RemoveContainer remove container based on its ID func (o *CattleOrchestrator) RemoveContainer(container *client.Container) { err := o.client.Container.Delete(container) if err != nil { err = fmt.Errorf("failed to remove container: %s", err) return } removed := false for !removed { container, err := o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect container: %s", err) return } if container.Removed != "" { removed = true } } return } // GetContainersMountingVolume returns containers mounting a volume func (o *CattleOrchestrator) GetContainersMountingVolume(v *volume.Volume) (mountedVolumes []*volume.MountedVolume, err error) { vol, err := o.client.Volume.ById(v.ID) if err != nil { err = fmt.Errorf("failed to get volume: %s", err) return } for _, mount := range vol.Mounts { instance, err := o.client.Container.ById(mount.InstanceId) if err != nil { continue } if instance.State != "running" { continue } mv := &volume.MountedVolume{ ContainerID: mount.InstanceId, Volume: v, Path: mount.Path, } mountedVolumes = append(mountedVolumes, mv) } return } // ContainerExec executes a command in a container func (o *CattleOrchestrator) ContainerExec(mountedVolumes *volume.MountedVolume, command []string) (stdout string, err error) { container, err := o.client.Container.ById(mountedVolumes.ContainerID) if err != nil { err = fmt.Errorf("failed to retrieve container: %s", err) return } hostAccess, err := o.client.Container.ActionExecute(container, &client.ContainerExec{ AttachStdin: false, AttachStdout: true, Command: command, Tty: false, }) if err != nil { err = fmt.Errorf("failed to prepare command execution in containers: %s", err) return } origin := o.config.URL u, err := url.Parse(hostAccess.Url) if err != nil { err = fmt.Errorf("failed to parse rancher server url: %s", err) return } q := u.Query() q.Set("token", hostAccess.Token) u.RawQuery = q.Encode() ws, err := websocket.Dial(u.String(), "", origin) if err != nil { err = fmt.Errorf("failed to open websocket with rancher server: %s", err) return } var data bytes.Buffer io.Copy(&data, ws) rawStdout, _ := base64.StdEncoding.DecodeString(data.String()) stdout = string(rawStdout) return } func (o *CattleOrchestrator) blacklistedVolume(vol *volume.Volume, volumeFilters volume.Filters) (bool, string, string) { if utf8.RuneCountInString(vol.Name) == 64 || utf8.RuneCountInString(vol.Name) == 0 { return true, "unnamed", "" } if strings.Contains(vol.Name, "/") { return true, "unnamed", "path" } // Use whitelist if defined if l := volumeFilters.Whitelist; len(l) > 0 && l[0] != "" { sort.Strings(l) i := sort.SearchStrings(l, vol.Name) if i < len(l) && l[i] == vol.Name { return false, "", "" } return true, "blacklisted", "whitelist config" } i := sort.SearchStrings(volumeFilters.Blacklist, vol.Name) if i < len(volumeFilters.Blacklist) && volumeFilters.Blacklist[i] == vol.Name { return true, "blacklisted", "blacklist config" } return false, "", "" } func (o *CattleOrchestrator) rawAPICall(method, endpoint string, data string, object interface{}) (err error) { // TODO: Use go-rancher. // It was impossible to use it, maybe a problem in go-rancher or a lack of documentation. clientHTTP := &http.Client{} //v := url.Values{} req, err := http.NewRequest(method, endpoint, strings.NewReader(data)) req.SetBasicAuth(o.config.AccessKey, o.config.SecretKey) resp, err := clientHTTP.Do(req) defer resp.Body.Close() if err != nil { err = fmt.Errorf("failed to execute POST request: %s", err) return } body, err := ioutil.ReadAll(resp.Body) if err != nil { err = fmt.Errorf("failed to read response from rancher: %s", err) return } err = json.Unmarshal(body, object) if err != nil { err = fmt.Errorf("failed to unmarshal: %s", err) return } return } func DetectCattle() bool { _, err := net.LookupHost("rancher-metadata") if err != nil { return false } return true } improve timeout deploy agent cattle package orchestrators import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "math/rand" "net" "net/http" "net/url" "regexp" "sort" "strings" "time" "unicode/utf8" "github.com/camptocamp/bivac/pkg/volume" //"github.com/rancher/go-rancher-metadata/metadata" "github.com/rancher/go-rancher/v2" "golang.org/x/net/websocket" ) // CattleConfig stores Cattle configuration type CattleConfig struct { URL string AccessKey string SecretKey string } // CattleOrchestrator implements a container orchestrator for Cattle type CattleOrchestrator struct { config *CattleConfig client *client.RancherClient } // NewCattleOrchestrator creates a Cattle client func NewCattleOrchestrator(config *CattleConfig) (o *CattleOrchestrator, err error) { o = &CattleOrchestrator{ config: config, } o.client, err = client.NewRancherClient(&client.ClientOpts{ Url: config.URL, AccessKey: config.AccessKey, SecretKey: config.SecretKey, Timeout: 30 * time.Second, }) if err != nil { err = fmt.Errorf("failed to create new Rancher client: %s", err) } return } // GetName returns the orchestrator name func (*CattleOrchestrator) GetName() string { return "cattle" } // GetPath returns the backup path func (*CattleOrchestrator) GetPath(v *volume.Volume) string { return v.Hostname } // GetVolumes returns the Cattle volumes, inspected and filtered func (o *CattleOrchestrator) GetVolumes(volumeFilters volume.Filters) (volumes []*volume.Volume, err error) { vs, err := o.client.Volume.List(&client.ListOpts{ Filters: map[string]interface{}{ "limit": -2, "all": true, }, }) if err != nil { err = fmt.Errorf("failed to list volumes: %s", err) return } var mountpoint string var h *client.Host for _, v := range vs.Data { if len(v.Mounts) < 1 { mountpoint = "/data" } else { mountpoint = v.Mounts[0].Path } var hostID, hostname string var spc *client.StoragePoolCollection err = o.rawAPICall("GET", v.Links["storagePools"], "", &spc) if err != nil { continue } if len(spc.Data) == 0 { continue } if len(spc.Data[0].HostIds) == 0 { continue } hostID = spc.Data[0].HostIds[0] h, err = o.client.Host.ById(hostID) if err != nil { hostname = hostID } else { hostname = h.Hostname } v := &volume.Volume{ ID: v.Id, Name: v.Name, Mountpoint: mountpoint, HostBind: hostID, Hostname: hostname, } if b, _, _ := o.blacklistedVolume(v, volumeFilters); b { continue } volumes = append(volumes, v) } return } func createAgentName() string { var letter = []rune("abcdefghijklmnopqrstuvwxyz0123456789") b := make([]rune, 10) for i := range b { b[i] = letter[rand.Intn(len(letter))] } return "bivac-agent-" + string(b) } // DeployAgent creates a `bivac agent` container func (o *CattleOrchestrator) DeployAgent(image string, cmd []string, envs []string, v *volume.Volume) (success bool, output string, err error) { success = false environment := make(map[string]interface{}) for _, env := range envs { splitted := strings.Split(env, "=") environment[splitted[0]] = splitted[1] } container, err := o.client.Container.Create(&client.Container{ Name: createAgentName(), RequestedHostId: v.HostBind, ImageUuid: "docker:" + image, Command: cmd, Environment: environment, RestartPolicy: &client.RestartPolicy{ MaximumRetryCount: 1, Name: "on-failure", }, Labels: map[string]interface{}{ "io.rancher.container.pull_image": "always", }, DataVolumes: []string{ v.Name + ":" + v.Mountpoint, }, }) if err != nil { err = fmt.Errorf("failed to create an agent container: %s", err) return } defer o.RemoveContainer(container) stopped := false terminated := false timeout := time.After(60 * time.Second) for !terminated { container, err := o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect agent: %s", err) return false, "", err } // This workaround is awful but it's the only way to know if the container failed. if container.State == "stopped" { if container.StartCount == 1 { if stopped == false { stopped = true time.Sleep(5 * time.Second) } else { terminated = true success = true } } else { success = false terminated = true } } else if container.State == "starting" { select { case <-timeout: err = fmt.Errorf("failed to start agent: timeout") return false, "", err default: continue } } time.Sleep(1 * time.Second) } container, err = o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect the agent before retrieving the logs: %s", err) return false, "", err } var hostAccess *client.HostAccess logsParams := `{"follow":false,"lines":9999,"since":"","timestamps":true}` err = o.rawAPICall("POST", container.Links["self"]+"/?action=logs", logsParams, &hostAccess) if err != nil { err = fmt.Errorf("failed to read response from rancher: %s", err) return } origin := o.config.URL u, err := url.Parse(hostAccess.Url) if err != nil { err = fmt.Errorf("failed to parse rancher server url: %s", err) return } q := u.Query() q.Set("token", hostAccess.Token) u.RawQuery = q.Encode() ws, err := websocket.Dial(u.String(), "", origin) if err != nil { err = fmt.Errorf("failed to open websocket with rancher server: %s", err) return } defer ws.Close() var data bytes.Buffer io.Copy(&data, ws) re := regexp.MustCompile(`(?m)[0-9]{2,} [ZT\-\:\.0-9]+ (.*)`) for _, line := range re.FindAllStringSubmatch(data.String(), -1) { output = strings.Join([]string{output, line[1]}, "\n") } return } // RemoveContainer remove container based on its ID func (o *CattleOrchestrator) RemoveContainer(container *client.Container) { err := o.client.Container.Delete(container) if err != nil { err = fmt.Errorf("failed to remove container: %s", err) return } removed := false for !removed { container, err := o.client.Container.ById(container.Id) if err != nil { err = fmt.Errorf("failed to inspect container: %s", err) return } if container.Removed != "" { removed = true } } return } // GetContainersMountingVolume returns containers mounting a volume func (o *CattleOrchestrator) GetContainersMountingVolume(v *volume.Volume) (mountedVolumes []*volume.MountedVolume, err error) { vol, err := o.client.Volume.ById(v.ID) if err != nil { err = fmt.Errorf("failed to get volume: %s", err) return } for _, mount := range vol.Mounts { instance, err := o.client.Container.ById(mount.InstanceId) if err != nil { continue } if instance.State != "running" { continue } mv := &volume.MountedVolume{ ContainerID: mount.InstanceId, Volume: v, Path: mount.Path, } mountedVolumes = append(mountedVolumes, mv) } return } // ContainerExec executes a command in a container func (o *CattleOrchestrator) ContainerExec(mountedVolumes *volume.MountedVolume, command []string) (stdout string, err error) { container, err := o.client.Container.ById(mountedVolumes.ContainerID) if err != nil { err = fmt.Errorf("failed to retrieve container: %s", err) return } hostAccess, err := o.client.Container.ActionExecute(container, &client.ContainerExec{ AttachStdin: false, AttachStdout: true, Command: command, Tty: false, }) if err != nil { err = fmt.Errorf("failed to prepare command execution in containers: %s", err) return } origin := o.config.URL u, err := url.Parse(hostAccess.Url) if err != nil { err = fmt.Errorf("failed to parse rancher server url: %s", err) return } q := u.Query() q.Set("token", hostAccess.Token) u.RawQuery = q.Encode() ws, err := websocket.Dial(u.String(), "", origin) if err != nil { err = fmt.Errorf("failed to open websocket with rancher server: %s", err) return } var data bytes.Buffer io.Copy(&data, ws) rawStdout, _ := base64.StdEncoding.DecodeString(data.String()) stdout = string(rawStdout) return } func (o *CattleOrchestrator) blacklistedVolume(vol *volume.Volume, volumeFilters volume.Filters) (bool, string, string) { if utf8.RuneCountInString(vol.Name) == 64 || utf8.RuneCountInString(vol.Name) == 0 { return true, "unnamed", "" } if strings.Contains(vol.Name, "/") { return true, "unnamed", "path" } // Use whitelist if defined if l := volumeFilters.Whitelist; len(l) > 0 && l[0] != "" { sort.Strings(l) i := sort.SearchStrings(l, vol.Name) if i < len(l) && l[i] == vol.Name { return false, "", "" } return true, "blacklisted", "whitelist config" } i := sort.SearchStrings(volumeFilters.Blacklist, vol.Name) if i < len(volumeFilters.Blacklist) && volumeFilters.Blacklist[i] == vol.Name { return true, "blacklisted", "blacklist config" } return false, "", "" } func (o *CattleOrchestrator) rawAPICall(method, endpoint string, data string, object interface{}) (err error) { // TODO: Use go-rancher. // It was impossible to use it, maybe a problem in go-rancher or a lack of documentation. clientHTTP := &http.Client{} //v := url.Values{} req, err := http.NewRequest(method, endpoint, strings.NewReader(data)) req.SetBasicAuth(o.config.AccessKey, o.config.SecretKey) resp, err := clientHTTP.Do(req) defer resp.Body.Close() if err != nil { err = fmt.Errorf("failed to execute POST request: %s", err) return } body, err := ioutil.ReadAll(resp.Body) if err != nil { err = fmt.Errorf("failed to read response from rancher: %s", err) return } err = json.Unmarshal(body, object) if err != nil { err = fmt.Errorf("failed to unmarshal: %s", err) return } return } func DetectCattle() bool { _, err := net.LookupHost("rancher-metadata") if err != nil { return false } return true }
package trafcacc import ( "encoding/binary" "errors" "sync" "sync/atomic" "time" "github.com/Sirupsen/logrus" ) type cmd uint8 const ( data cmd = iota close closed connect connected ping pong rqu ack ) type packet struct { Senderid uint32 Connid uint32 Seqid uint32 Buf []byte Cmd cmd udp bool } func (p *packet) copy() *packet { var buf []byte if len(p.Buf) > 0 { buf = make([]byte, len(p.Buf)) copy(buf, p.Buf) } return &packet{ Senderid: p.Senderid, Connid: p.Connid, Seqid: p.Seqid, Cmd: p.Cmd, Buf: buf, udp: p.udp, } } func (p *packet) encode(b []byte) (n int) { defer func() { if r := recover(); r != nil { n = -1 } }() n = binary.PutUvarint(b, uint64(p.Senderid)) n += binary.PutUvarint(b[n:], uint64(p.Connid)) n += binary.PutUvarint(b[n:], uint64(p.Seqid)) n += binary.PutUvarint(b[n:], uint64(p.Cmd)) n += binary.PutUvarint(b[n:], uint64(len(p.Buf))) if len(p.Buf) > 0 { n += copy(b[n:], p.Buf) //b = append(b[:n], p.Buf...) } return n } func decodePacket(b []byte, p *packet) (err error) { defer func() { if r := recover(); r != nil { err = errors.New("packet decode panic") } }() err = errors.New("packet decode err") i, n := binary.Uvarint(b) if n <= 0 { return } p.Senderid = uint32(i) i, m := binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Connid = uint32(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Seqid = uint32(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Cmd = cmd(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } if i > 0 { n += m p.Buf = b[n : n+int(i)] } return nil } type queue struct { *sync.Cond queue map[uint32]*packet nxrqutime map[uint32]time.Time waitingSeqid uint32 closed int64 } func newQueue() *queue { return &queue{ Cond: sync.NewCond(&sync.Mutex{}), queue: make(map[uint32]*packet), nxrqutime: make(map[uint32]time.Time), waitingSeqid: 1, } } func (q *queue) len() int { return len(q.queue) } func (q *queue) isClosed() bool { return atomic.LoadInt64(&q.closed) != 0 } func (q *queue) arrived() bool { if q.isClosed() { return true } if _, exist := q.queue[q.waitingSeqid]; exist { return true } return false } type packetQueue struct { queues map[uint64]*queue mux sync.RWMutex popudp uint64 poptcp uint64 } func newPacketQueue() *packetQueue { return &packetQueue{ queues: make(map[uint64]*queue), } } func (pq *packetQueue) create(senderid, connid uint32) (isnew bool) { key := packetKey(senderid, connid) pq.mux.Lock() defer pq.mux.Unlock() if _, exist := pq.queues[key]; !exist { pq.queues[key] = newQueue() return true } return false } func (pq *packetQueue) close(senderid, connid uint32) { key := packetKey(senderid, connid) // TODO: wait queue drained cleanedup? pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { // set q.queue = nil ? atomic.StoreInt64(&q.closed, 1) q.Broadcast() go func() { // expired after 30 minutes <-time.After(30 * time.Minute) pq.mux.Lock() delete(pq.queues, key) pq.mux.Unlock() }() } } func (pq *packetQueue) len() (n int) { pq.mux.RLock() defer pq.mux.RUnlock() for _, v := range pq.queues { v.L.Lock() n += len(v.queue) v.L.Unlock() } return } func (pq *packetQueue) add(p *packet) (waitingSeqid uint32) { key := packetKey(p.Senderid, p.Connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() _, ok := q.queue[p.Seqid] if p.Seqid >= q.waitingSeqid && !ok { q.queue[p.Seqid] = p defer q.Broadcast() if p.Seqid >= q.waitingSeqid { if t, ok := q.nxrqutime[q.waitingSeqid]; !ok || time.Now().After(t) { waitingSeqid = q.waitingSeqid q.nxrqutime[q.waitingSeqid] = time.Now().Add(time.Second / 4) } } } q.L.Unlock() } else { logrus.WithFields(logrus.Fields{ "packet": p, "exist": exist, "q": q, "key": key, "pq": pq, }).Warnln("packetQueue havn't been created, dropping") } return } func (pq *packetQueue) waiting(senderid, connid uint32) (waitingSeqid uint32) { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() waitingSeqid = q.waitingSeqid q.L.Unlock() return } return 0 } func (pq *packetQueue) waitforArrived(senderid, connid uint32) { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() for !q.arrived() { q.Wait() } q.L.Unlock() } else { logrus.Warnln("waitforArrived() wait on deteled/closed queue") } } func (pq *packetQueue) isClosed(senderid, connid uint32) bool { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { return q.isClosed() } return true } func (pq *packetQueue) pop(senderid, connid uint32) *packet { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { // TODO: closed? // if q.isClosed() { // return nil // } q.L.Lock() p, exist := q.queue[q.waitingSeqid] if exist { delete(q.queue, q.waitingSeqid) if _, ok := q.queue[q.waitingSeqid]; ok { delete(q.queue, q.waitingSeqid) } q.waitingSeqid++ q.L.Unlock() defer q.Broadcast() if p.Cmd == close || p.Cmd == closed { pq.close(senderid, connid) return nil } if p.udp { atomic.AddUint64(&pq.popudp, uint64(len(p.Buf))) } else { atomic.AddUint64(&pq.poptcp, uint64(len(p.Buf))) } return p } q.L.Unlock() } return nil } request resend packet if sequence out of order (improve) package trafcacc import ( "encoding/binary" "errors" "sync" "sync/atomic" "time" "github.com/Sirupsen/logrus" ) type cmd uint8 const ( data cmd = iota close closed connect connected ping pong rqu ack ) type packet struct { Senderid uint32 Connid uint32 Seqid uint32 Buf []byte Cmd cmd udp bool } func (p *packet) copy() *packet { var buf []byte if len(p.Buf) > 0 { buf = make([]byte, len(p.Buf)) copy(buf, p.Buf) } return &packet{ Senderid: p.Senderid, Connid: p.Connid, Seqid: p.Seqid, Cmd: p.Cmd, Buf: buf, udp: p.udp, } } func (p *packet) encode(b []byte) (n int) { defer func() { if r := recover(); r != nil { n = -1 } }() n = binary.PutUvarint(b, uint64(p.Senderid)) n += binary.PutUvarint(b[n:], uint64(p.Connid)) n += binary.PutUvarint(b[n:], uint64(p.Seqid)) n += binary.PutUvarint(b[n:], uint64(p.Cmd)) n += binary.PutUvarint(b[n:], uint64(len(p.Buf))) if len(p.Buf) > 0 { n += copy(b[n:], p.Buf) //b = append(b[:n], p.Buf...) } return n } func decodePacket(b []byte, p *packet) (err error) { defer func() { if r := recover(); r != nil { err = errors.New("packet decode panic") } }() err = errors.New("packet decode err") i, n := binary.Uvarint(b) if n <= 0 { return } p.Senderid = uint32(i) i, m := binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Connid = uint32(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Seqid = uint32(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } n += m p.Cmd = cmd(i) i, m = binary.Uvarint(b[n:]) if m <= 0 { return } if i > 0 { n += m p.Buf = b[n : n+int(i)] } return nil } type queue struct { *sync.Cond queue map[uint32]*packet nxrqutime map[uint32]time.Time waitingSeqid uint32 closed int64 } func newQueue() *queue { return &queue{ Cond: sync.NewCond(&sync.Mutex{}), queue: make(map[uint32]*packet), nxrqutime: make(map[uint32]time.Time), waitingSeqid: 1, } } func (q *queue) len() int { return len(q.queue) } func (q *queue) isClosed() bool { return atomic.LoadInt64(&q.closed) != 0 } func (q *queue) arrived() bool { if q.isClosed() { return true } if _, exist := q.queue[q.waitingSeqid]; exist { return true } return false } type packetQueue struct { queues map[uint64]*queue mux sync.RWMutex popudp uint64 poptcp uint64 } func newPacketQueue() *packetQueue { return &packetQueue{ queues: make(map[uint64]*queue), } } func (pq *packetQueue) create(senderid, connid uint32) (isnew bool) { key := packetKey(senderid, connid) pq.mux.Lock() defer pq.mux.Unlock() if _, exist := pq.queues[key]; !exist { pq.queues[key] = newQueue() return true } return false } func (pq *packetQueue) close(senderid, connid uint32) { key := packetKey(senderid, connid) // TODO: wait queue drained cleanedup? pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { // set q.queue = nil ? atomic.StoreInt64(&q.closed, 1) q.Broadcast() go func() { // expired after 30 minutes <-time.After(30 * time.Minute) pq.mux.Lock() delete(pq.queues, key) pq.mux.Unlock() }() } } func (pq *packetQueue) len() (n int) { pq.mux.RLock() defer pq.mux.RUnlock() for _, v := range pq.queues { v.L.Lock() n += len(v.queue) v.L.Unlock() } return } func (pq *packetQueue) add(p *packet) (waitingSeqid uint32) { key := packetKey(p.Senderid, p.Connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() _, ok := q.queue[p.Seqid] if p.Seqid >= q.waitingSeqid && !ok { q.queue[p.Seqid] = p defer q.Broadcast() if p.Seqid >= q.waitingSeqid { if t, ok := q.nxrqutime[q.waitingSeqid]; !ok || time.Now().After(t) { waitingSeqid = q.waitingSeqid } } } q.L.Unlock() } else { logrus.WithFields(logrus.Fields{ "packet": p, "exist": exist, "q": q, "key": key, "pq": pq, }).Warnln("packetQueue havn't been created, dropping") } return } func (pq *packetQueue) waiting(senderid, connid uint32) (waitingSeqid uint32) { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() if t, ok := q.nxrqutime[q.waitingSeqid]; !ok || time.Now().After(t) { waitingSeqid = q.waitingSeqid q.nxrqutime[q.waitingSeqid] = time.Now().Add(time.Second / 4) } q.L.Unlock() return } return 0 } func (pq *packetQueue) waitforArrived(senderid, connid uint32) { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { q.L.Lock() for !q.arrived() { q.Wait() } q.L.Unlock() } else { logrus.Warnln("waitforArrived() wait on deteled/closed queue") } } func (pq *packetQueue) isClosed(senderid, connid uint32) bool { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { return q.isClosed() } return true } func (pq *packetQueue) pop(senderid, connid uint32) *packet { key := packetKey(senderid, connid) pq.mux.Lock() q, exist := pq.queues[key] pq.mux.Unlock() if exist && q != nil { // TODO: closed? // if q.isClosed() { // return nil // } q.L.Lock() p, exist := q.queue[q.waitingSeqid] if exist { delete(q.queue, q.waitingSeqid) if _, ok := q.queue[q.waitingSeqid]; ok { delete(q.queue, q.waitingSeqid) } q.waitingSeqid++ q.L.Unlock() defer q.Broadcast() if p.Cmd == close || p.Cmd == closed { pq.close(senderid, connid) return nil } if p.udp { atomic.AddUint64(&pq.popudp, uint64(len(p.Buf))) } else { atomic.AddUint64(&pq.poptcp, uint64(len(p.Buf))) } return p } q.L.Unlock() } return nil }
package v8 /* #include "v8_wrap.h" */ import "C" import "unsafe" type embedable struct { data interface{} } func (this embedable) GetPrivateData() interface{} { return this.data } func (this *embedable) SetPrivateData(data interface{}) { this.data = data } func GetVersion() string { return C.GoString(C.V8_GetVersion()) } //number of isolate data slots func GetIsolateNumberOfDataSlots() uint{ return uint(C.V8_Isolate_GetNumberOfDataSlots()) } func SetFlagsFromString(cmd string) { cs := C.CString(cmd) defer C.free(unsafe.Pointer(cs)) C.V8_SetFlagsFromString(cs, C.int(len(cmd))) } // Set default array buffer allocator to V8 for // ArrayBuffer, ArrayBufferView, Int8Array... // If you want to use your own allocator. You can implement it in C++ // and invoke v8::SetArrayBufferAllocator by your self func UseDefaultArrayBufferAllocator() { C.V8_UseDefaultArrayBufferAllocator() } add typescript compile script test package v8 /* #include "v8_wrap.h" */ import "C" import "unsafe" type embedable struct { data interface{} } //GetPrivateData get private data func (e embedable) GetPrivateData() interface{} { return e.data } //SetPrivateData set private data func (e *embedable) SetPrivateData(data interface{}) { e.data = data } //GetVersion get v8 version func GetVersion() string { return C.GoString(C.V8_GetVersion()) } //GetIsolateNumberOfDataSlots get number of isolate data slots func GetIsolateNumberOfDataSlots() uint { return uint(C.V8_Isolate_GetNumberOfDataSlots()) } //SetFlagsFromString set flags from string. func SetFlagsFromString(cmd string) { cs := C.CString(cmd) defer C.free(unsafe.Pointer(cs)) C.V8_SetFlagsFromString(cs, C.int(len(cmd))) } //UseDefaultArrayBufferAllocator Set default array buffer allocator to V8 for // ArrayBuffer, ArrayBufferView, Int8Array... // If you want to use your own allocator. You can implement it in C++ // and invoke v8::SetArrayBufferAllocator by your self func UseDefaultArrayBufferAllocator() { C.V8_UseDefaultArrayBufferAllocator() }
package repo import ( "bufio" "context" "fmt" "regexp" "strings" "time" "unicode" "github.com/blevesearch/segment" "github.com/google/go-github/v33/github" "github.com/google/pullsheet/pkg/ghcache" "github.com/peterbourgon/diskv" "k8s.io/klog/v2" ) var notSegmentRe = regexp.MustCompile(`[/-_]+`) // ReviewSummary a summary of a users reviews on a PR type ReviewSummary struct { URL string Date string Project string Reviewer string PRAuthor string PRComments int ReviewComments int Words int Title string } type comment struct { Author string Body string Review bool CreatedAt time.Time } // MergedReviews returns a list of pull requests in a project (merged only) func MergedReviews(ctx context.Context, dv *diskv.Diskv, c *github.Client, org string, project string, since time.Time, until time.Time, users []string) ([]*ReviewSummary, error) { prs, err := MergedPulls(ctx, dv, c, org, project, since, until, nil) if err != nil { return nil, fmt.Errorf("pulls: %v", err) } klog.Infof("found %d PR's to check reviews for", len(prs)) reviews := []*ReviewSummary{} matchUser := map[string]bool{} for _, u := range users { matchUser[strings.ToLower(u)] = true } for _, pr := range prs { // username -> summary prMap := map[string]*ReviewSummary{} comments := []comment{} // There is wickedness in the GitHub API: PR comments are available via the Issues API, and PR *review* comments are available via the PullRequests API cs, err := ghcache.PullRequestsListComments(ctx, dv, c, pr.GetMergedAt(), org, project, pr.GetNumber()) if err != nil { return nil, err } for _, c := range cs { if isBot(c.GetUser()) { continue } body := strings.TrimSpace(c.GetBody()) comments = append(comments, comment{Author: c.GetUser().GetLogin(), Body: body, CreatedAt: c.GetCreatedAt(), Review: true}) } is, err := ghcache.IssuesListComments(ctx, dv, c, pr.GetMergedAt(), org, project, pr.GetNumber()) if err != nil { return nil, err } for _, i := range is { if isBot(i.GetUser()) { continue } body := strings.TrimSpace(i.GetBody()) if (strings.HasPrefix(body, "/") || strings.HasPrefix(body, "cc")) && len(body) < 64 { klog.Infof("ignoring tag comment: %q", body) continue } comments = append(comments, comment{Author: i.GetUser().GetLogin(), Body: body, CreatedAt: i.GetCreatedAt(), Review: false}) } for _, c := range comments { if c.CreatedAt.After(until) { continue } if c.CreatedAt.Before(since) { continue } if len(matchUser) > 0 && !matchUser[strings.ToLower(c.Author)] { continue } if c.Author == pr.GetUser().GetLogin() { continue } wordCount := wordCount(c.Body) if prMap[c.Author] == nil { prMap[c.Author] = &ReviewSummary{ URL: pr.GetHTMLURL(), PRAuthor: pr.GetUser().GetLogin(), Reviewer: c.Author, Project: project, Title: strings.TrimSpace(pr.GetTitle()), } } if c.Review { prMap[c.Author].ReviewComments++ } else { prMap[c.Author].PRComments++ } prMap[c.Author].Date = c.CreatedAt.Format(dateForm) prMap[c.Author].Words += wordCount klog.Infof("%d word comment by %s: %q for %s/%s #%d", wordCount, c.Author, strings.TrimSpace(c.Body), org, project, pr.GetNumber()) } for _, rs := range prMap { reviews = append(reviews, rs) } } return reviews, err } // wordCount counts words in a string, irrespective of language func wordCount(s string) int { // Don't count certain items, like / or - as word segments s = notSegmentRe.ReplaceAllString(s, "") words := 0 scanner := bufio.NewScanner(strings.NewReader(s)) scanner.Split(segment.SplitWords) for scanner.Scan() { if !unicode.IsLetter(rune(scanner.Bytes()[0])) { continue } words++ } return words } func isBot(u *github.User) bool { if u.GetType() == "bot" { return true } if strings.Contains(u.GetBio(), "stale issues") { return true } if strings.HasSuffix(u.GetLogin(), "-bot") || strings.HasSuffix(u.GetLogin(), "-robot") || strings.HasSuffix(u.GetLogin(), "_bot") || strings.HasSuffix(u.GetLogin(), "_robot") { return true } if strings.HasPrefix(u.GetLogin(), "codecov") || strings.HasPrefix(u.GetLogin(), "Travis") { return true } return false } Improve debug messages package repo import ( "bufio" "context" "fmt" "regexp" "strings" "time" "unicode" "github.com/blevesearch/segment" "github.com/google/go-github/v33/github" "github.com/google/pullsheet/pkg/ghcache" "github.com/peterbourgon/diskv" "k8s.io/klog/v2" ) var notSegmentRe = regexp.MustCompile(`[/-_]+`) // ReviewSummary a summary of a users reviews on a PR type ReviewSummary struct { URL string Date string Project string Reviewer string PRAuthor string PRComments int ReviewComments int Words int Title string } type comment struct { Author string Body string Review bool CreatedAt time.Time } // MergedReviews returns a list of pull requests in a project (merged only) func MergedReviews(ctx context.Context, dv *diskv.Diskv, c *github.Client, org string, project string, since time.Time, until time.Time, users []string) ([]*ReviewSummary, error) { prs, err := MergedPulls(ctx, dv, c, org, project, since, until, nil) if err != nil { return nil, fmt.Errorf("pulls: %v", err) } klog.Infof("found %d PR's in %s/%s to find reviews for", len(prs), org, project) reviews := []*ReviewSummary{} matchUser := map[string]bool{} for _, u := range users { matchUser[strings.ToLower(u)] = true } for _, pr := range prs { // username -> summary prMap := map[string]*ReviewSummary{} comments := []comment{} // There is wickedness in the GitHub API: PR comments are available via the Issues API, and PR *review* comments are available via the PullRequests API cs, err := ghcache.PullRequestsListComments(ctx, dv, c, pr.GetMergedAt(), org, project, pr.GetNumber()) if err != nil { return nil, err } for _, c := range cs { if isBot(c.GetUser()) { continue } body := strings.TrimSpace(c.GetBody()) comments = append(comments, comment{Author: c.GetUser().GetLogin(), Body: body, CreatedAt: c.GetCreatedAt(), Review: true}) } is, err := ghcache.IssuesListComments(ctx, dv, c, pr.GetMergedAt(), org, project, pr.GetNumber()) if err != nil { return nil, err } for _, i := range is { if isBot(i.GetUser()) { continue } body := strings.TrimSpace(i.GetBody()) if (strings.HasPrefix(body, "/") || strings.HasPrefix(body, "cc")) && len(body) < 64 { klog.Infof("ignoring tag comment in %s: %q", i.GetHTMLURL(), body) continue } comments = append(comments, comment{Author: i.GetUser().GetLogin(), Body: body, CreatedAt: i.GetCreatedAt(), Review: false}) } for _, c := range comments { if c.CreatedAt.After(until) { continue } if c.CreatedAt.Before(since) { continue } if len(matchUser) > 0 && !matchUser[strings.ToLower(c.Author)] { continue } if c.Author == pr.GetUser().GetLogin() { continue } wordCount := wordCount(c.Body) if prMap[c.Author] == nil { prMap[c.Author] = &ReviewSummary{ URL: pr.GetHTMLURL(), PRAuthor: pr.GetUser().GetLogin(), Reviewer: c.Author, Project: project, Title: strings.TrimSpace(pr.GetTitle()), } } if c.Review { prMap[c.Author].ReviewComments++ } else { prMap[c.Author].PRComments++ } prMap[c.Author].Date = c.CreatedAt.Format(dateForm) prMap[c.Author].Words += wordCount klog.Infof("%d word comment by %s: %q for %s/%s #%d", wordCount, c.Author, strings.TrimSpace(c.Body), org, project, pr.GetNumber()) } for _, rs := range prMap { reviews = append(reviews, rs) } } return reviews, err } // wordCount counts words in a string, irrespective of language func wordCount(s string) int { // Don't count certain items, like / or - as word segments s = notSegmentRe.ReplaceAllString(s, "") words := 0 scanner := bufio.NewScanner(strings.NewReader(s)) scanner.Split(segment.SplitWords) for scanner.Scan() { if !unicode.IsLetter(rune(scanner.Bytes()[0])) { continue } words++ } return words } func isBot(u *github.User) bool { if u.GetType() == "bot" { return true } if strings.Contains(u.GetBio(), "stale issues") { return true } if strings.HasSuffix(u.GetLogin(), "-bot") || strings.HasSuffix(u.GetLogin(), "-robot") || strings.HasSuffix(u.GetLogin(), "_bot") || strings.HasSuffix(u.GetLogin(), "_robot") { return true } if strings.HasPrefix(u.GetLogin(), "codecov") || strings.HasPrefix(u.GetLogin(), "Travis") { return true } return false }
// Copyright 2016 The kube-etcd-controller Authors // // 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 k8sutil import ( "encoding/json" "fmt" "net/http" "net/url" "strings" "time" "github.com/coreos/kube-etcd-controller/pkg/spec" "github.com/coreos/kube-etcd-controller/pkg/util/etcdutil" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" unversionedAPI "k8s.io/kubernetes/pkg/api/unversioned" k8sv1api "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" ) const ( // TODO: This is constant for current purpose. We might make it configurable later. etcdDir = "/var/etcd" dataDir = etcdDir + "/data" backupFile = "/var/etcd/latest.backup" etcdVersionAnnotationKey = "etcd.version" annotationPrometheusScrape = "prometheus.io/scrape" annotationPrometheusPort = "prometheus.io/port" ) func GetEtcdVersion(pod *api.Pod) string { return pod.Annotations[etcdVersionAnnotationKey] } func SetEtcdVersion(pod *api.Pod, version string) { pod.Annotations[etcdVersionAnnotationKey] = version } func GetPodNames(pods []*api.Pod) []string { res := []string{} for _, p := range pods { res = append(res, p.Name) } return res } func makeRestoreInitContainerSpec(backupAddr, name, token, version string) string { spec := []api.Container{ { Name: "fetch-backup", Image: "tutum/curl", Command: []string{ "/bin/sh", "-c", fmt.Sprintf("curl -o %s http://%s/backup", backupFile, backupAddr), }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, { Name: "restore-datadir", Image: MakeEtcdImage(version), Command: []string{ "/bin/sh", "-c", fmt.Sprintf("ETCDCTL_API=3 etcdctl snapshot restore %[1]s"+ " --name %[2]s"+ " --initial-cluster %[2]s=http://%[2]s:2380"+ " --initial-cluster-token %[3]s"+ " --initial-advertise-peer-urls http://%[2]s:2380"+ " --data-dir %[4]s", backupFile, name, token, dataDir), }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, } b, err := json.Marshal(spec) if err != nil { panic(err) } return string(b) } func MakeEtcdImage(version string) string { return fmt.Sprintf("quay.io/coreos/etcd:%v", version) } func GetNodePortString(srv *api.Service) string { return fmt.Sprint(srv.Spec.Ports[0].NodePort) } func MakeBackupHostPort(clusterName string) string { return fmt.Sprintf("%s:19999", makeBackupName(clusterName)) } func PodWithAddMemberInitContainer(p *api.Pod, name string, peerURLs []string, cs *spec.ClusterSpec) *api.Pod { endpoints := cs.Seed.MemberClientEndpoints containerSpec := []api.Container{ { Name: "add-member", Image: MakeEtcdImage(cs.Version), Command: []string{ "/bin/sh", "-c", fmt.Sprintf("ETCDCTL_API=3 etcdctl --endpoints=%s member add %s --peer-urls=%s", strings.Join(endpoints, ","), name, strings.Join(peerURLs, ",")), }, }, } b, err := json.Marshal(containerSpec) if err != nil { panic(err) } p.Annotations[k8sv1api.PodInitContainersAnnotationKey] = string(b) return p } func PodWithNodeSelector(p *api.Pod, ns map[string]string) *api.Pod { p.Spec.NodeSelector = ns return p } func makeBackupName(clusterName string) string { return fmt.Sprintf("%s-backup-tool", clusterName) } func CreateEtcdService(kclient *unversioned.Client, etcdName, clusterName, ns string) error { svc := makeEtcdService(etcdName, clusterName) if _, err := kclient.Services(ns).Create(svc); err != nil { return err } return nil } func CreateEtcdNodePortService(kclient *unversioned.Client, etcdName, clusterName, ns string) (*api.Service, error) { svc := makeEtcdNodePortService(etcdName, clusterName) return kclient.Services(ns).Create(svc) } func CreateAndWaitPod(kclient *unversioned.Client, ns string, pod *api.Pod, timeout time.Duration) error { if _, err := kclient.Pods(ns).Create(pod); err != nil { return err } w, err := kclient.Pods(ns).Watch(api.SingleObject(api.ObjectMeta{Name: pod.Name})) if err != nil { return err } _, err = watch.Until(timeout, w, unversioned.PodRunning) // TODO: cleanup pod on failure return err } // TODO: converge the port logic with member ClientAddr() and PeerAddr() func makeEtcdService(etcdName, clusterName string) *api.Service { labels := map[string]string{ "app": "etcd", "etcd_node": etcdName, "etcd_cluster": clusterName, } svc := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: etcdName, Labels: labels, Annotations: map[string]string{ annotationPrometheusScrape: "true", annotationPrometheusPort: "2379", }, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Name: "server", Port: 2380, TargetPort: intstr.FromInt(2380), Protocol: api.ProtocolTCP, }, { Name: "client", Port: 2379, TargetPort: intstr.FromInt(2379), Protocol: api.ProtocolTCP, }, }, Selector: labels, }, } return svc } func makeEtcdNodePortService(etcdName, clusterName string) *api.Service { labels := map[string]string{ "etcd_node": etcdName, "etcd_cluster": clusterName, } svc := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: etcdName + "-nodeport", Labels: labels, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Name: "server", Port: 2380, TargetPort: intstr.FromInt(2380), Protocol: api.ProtocolTCP, }, }, Type: api.ServiceTypeNodePort, Selector: labels, }, } return svc } func AddRecoveryToPod(pod *api.Pod, clusterName, name, token string, cs *spec.ClusterSpec) { pod.Annotations[k8sv1api.PodInitContainersAnnotationKey] = makeRestoreInitContainerSpec(MakeBackupHostPort(clusterName), name, token, cs.Version) } func MakeEtcdPod(m *etcdutil.Member, initialCluster []string, clusterName, state, token string, cs *spec.ClusterSpec) *api.Pod { commands := []string{ "/usr/local/bin/etcd", "--data-dir", dataDir, "--name", m.Name, "--initial-advertise-peer-urls", m.PeerAddr(), "--listen-peer-urls", "http://0.0.0.0:2380", "--listen-client-urls", "http://0.0.0.0:2379", "--advertise-client-urls", m.ClientAddr(), "--initial-cluster", strings.Join(initialCluster, ","), "--initial-cluster-state", state, } if state == "new" { commands = append(commands, "--initial-cluster-token", token) } pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: m.Name, Labels: map[string]string{ "app": "etcd", "etcd_node": m.Name, "etcd_cluster": clusterName, }, Annotations: map[string]string{}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Command: commands, Name: m.Name, Image: MakeEtcdImage(cs.Version), Ports: []api.ContainerPort{ { Name: "server", ContainerPort: int32(2380), Protocol: api.ProtocolTCP, }, }, // For readiness probe, we only requires the etcd server to respond, not // quorumly accessible. Because reconcile relies on readiness, and // reconcile could handle disaster recovery. ReadinessProbe: &api.Probe{ Handler: api.Handler{ Exec: &api.ExecAction{ Command: []string{"/bin/sh", "-c", "ETCDCTL_API=3 etcdctl get --consistency=s foo"}, }, }, // If an etcd member tries to join quorum, it has 5s strict check // It can still serve client request. InitialDelaySeconds: 5, TimeoutSeconds: 10, PeriodSeconds: 10, FailureThreshold: 3, }, // a pod is alive only if a get succeeds // the etcd pod should die if liveness probing fails. LivenessProbe: &api.Probe{ Handler: api.Handler{ Exec: &api.ExecAction{ Command: []string{"/bin/sh", "-c", "ETCDCTL_API=3 etcdctl get foo"}, }, }, InitialDelaySeconds: 10, TimeoutSeconds: 10, // probe every 60 seconds PeriodSeconds: 60, // failed for 3 minutes FailureThreshold: 3, }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, }, RestartPolicy: api.RestartPolicyNever, SecurityContext: &api.PodSecurityContext{ HostNetwork: cs.HostNetwork, }, Volumes: []api.Volume{ {Name: "etcd-data", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, }, }, } SetEtcdVersion(pod, cs.Version) if !cs.AntiAffinity { return pod } // set pod anti-affinity with the pods that belongs to the same etcd cluster affinity := api.Affinity{ PodAntiAffinity: &api.PodAntiAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: []api.PodAffinityTerm{ { LabelSelector: &unversionedAPI.LabelSelector{ MatchLabels: map[string]string{ "etcd_cluster": clusterName, }, }, }, }, }, } affinityb, err := json.Marshal(affinity) if err != nil { panic("failed to marshal affinty struct") } pod.Annotations[api.AffinityAnnotationKey] = string(affinityb) if len(cs.NodeSelector) != 0 { pod = PodWithNodeSelector(pod, cs.NodeSelector) } return pod } func MustGetInClusterMasterHost() string { cfg, err := restclient.InClusterConfig() if err != nil { panic(err) } return cfg.Host } // tlsConfig isn't modified inside this function. // The reason it's a pointer is that it's not necessary to have tlsconfig to create a client. func MustCreateClient(host string, tlsInsecure bool, tlsConfig *restclient.TLSClientConfig) *unversioned.Client { if len(host) == 0 { c, err := unversioned.NewInCluster() if err != nil { panic(err) } return c } cfg := &restclient.Config{ Host: host, QPS: 100, Burst: 100, } hostUrl, err := url.Parse(host) if err != nil { panic(fmt.Sprintf("error parsing host url %s : %v", host, err)) } if hostUrl.Scheme == "https" { cfg.TLSClientConfig = *tlsConfig cfg.Insecure = tlsInsecure } c, err := unversioned.New(cfg) if err != nil { panic(err) } return c } func IsKubernetesResourceAlreadyExistError(err error) bool { se, ok := err.(*apierrors.StatusError) if !ok { return false } if se.Status().Code == http.StatusConflict && se.Status().Reason == unversionedAPI.StatusReasonAlreadyExists { return true } return false } func IsKubernetesResourceNotFoundError(err error) bool { se, ok := err.(*apierrors.StatusError) if !ok { return false } if se.Status().Code == http.StatusNotFound && se.Status().Reason == unversionedAPI.StatusReasonNotFound { return true } return false } func ListETCDCluster(host, ns string, httpClient *http.Client) (*http.Response, error) { return httpClient.Get(fmt.Sprintf("%s/apis/coreos.com/v1/namespaces/%s/etcdclusters", host, ns)) } func WatchETCDCluster(host, ns string, httpClient *http.Client, resourceVersion string) (*http.Response, error) { return httpClient.Get(fmt.Sprintf("%s/apis/coreos.com/v1/namespaces/%s/etcdclusters?watch=true&resourceVersion=%s", host, ns, resourceVersion)) } func WaitEtcdTPRReady(httpClient *http.Client, interval, timeout time.Duration, host, ns string) error { return wait.Poll(interval, timeout, func() (bool, error) { resp, err := ListETCDCluster(host, ns, httpClient) if err != nil { return false, err } defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: return true, nil case http.StatusNotFound: // not set up yet. wait. return false, nil default: return false, fmt.Errorf("invalid status code: %v", resp.Status) } }) } func SliceReadyAndUnreadyPods(podList *api.PodList) (ready, unready []*api.Pod) { for i := range podList.Items { pod := &podList.Items[i] if pod.Status.Phase == api.PodRunning && api.IsPodReady(pod) { ready = append(ready, pod) continue } unready = append(unready, pod) } return } func EtcdPodListOpt(clusterName string) api.ListOptions { return api.ListOptions{ LabelSelector: labels.SelectorFromSet(map[string]string{ "etcd_cluster": clusterName, "app": "etcd", }), } } k8sutil: change etcd container name to 'etcd' // Copyright 2016 The kube-etcd-controller Authors // // 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 k8sutil import ( "encoding/json" "fmt" "net/http" "net/url" "strings" "time" "github.com/coreos/kube-etcd-controller/pkg/spec" "github.com/coreos/kube-etcd-controller/pkg/util/etcdutil" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" unversionedAPI "k8s.io/kubernetes/pkg/api/unversioned" k8sv1api "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" ) const ( // TODO: This is constant for current purpose. We might make it configurable later. etcdDir = "/var/etcd" dataDir = etcdDir + "/data" backupFile = "/var/etcd/latest.backup" etcdVersionAnnotationKey = "etcd.version" annotationPrometheusScrape = "prometheus.io/scrape" annotationPrometheusPort = "prometheus.io/port" ) func GetEtcdVersion(pod *api.Pod) string { return pod.Annotations[etcdVersionAnnotationKey] } func SetEtcdVersion(pod *api.Pod, version string) { pod.Annotations[etcdVersionAnnotationKey] = version } func GetPodNames(pods []*api.Pod) []string { res := []string{} for _, p := range pods { res = append(res, p.Name) } return res } func makeRestoreInitContainerSpec(backupAddr, name, token, version string) string { spec := []api.Container{ { Name: "fetch-backup", Image: "tutum/curl", Command: []string{ "/bin/sh", "-c", fmt.Sprintf("curl -o %s http://%s/backup", backupFile, backupAddr), }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, { Name: "restore-datadir", Image: MakeEtcdImage(version), Command: []string{ "/bin/sh", "-c", fmt.Sprintf("ETCDCTL_API=3 etcdctl snapshot restore %[1]s"+ " --name %[2]s"+ " --initial-cluster %[2]s=http://%[2]s:2380"+ " --initial-cluster-token %[3]s"+ " --initial-advertise-peer-urls http://%[2]s:2380"+ " --data-dir %[4]s", backupFile, name, token, dataDir), }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, } b, err := json.Marshal(spec) if err != nil { panic(err) } return string(b) } func MakeEtcdImage(version string) string { return fmt.Sprintf("quay.io/coreos/etcd:%v", version) } func GetNodePortString(srv *api.Service) string { return fmt.Sprint(srv.Spec.Ports[0].NodePort) } func MakeBackupHostPort(clusterName string) string { return fmt.Sprintf("%s:19999", makeBackupName(clusterName)) } func PodWithAddMemberInitContainer(p *api.Pod, name string, peerURLs []string, cs *spec.ClusterSpec) *api.Pod { endpoints := cs.Seed.MemberClientEndpoints containerSpec := []api.Container{ { Name: "add-member", Image: MakeEtcdImage(cs.Version), Command: []string{ "/bin/sh", "-c", fmt.Sprintf("ETCDCTL_API=3 etcdctl --endpoints=%s member add %s --peer-urls=%s", strings.Join(endpoints, ","), name, strings.Join(peerURLs, ",")), }, }, } b, err := json.Marshal(containerSpec) if err != nil { panic(err) } p.Annotations[k8sv1api.PodInitContainersAnnotationKey] = string(b) return p } func PodWithNodeSelector(p *api.Pod, ns map[string]string) *api.Pod { p.Spec.NodeSelector = ns return p } func makeBackupName(clusterName string) string { return fmt.Sprintf("%s-backup-tool", clusterName) } func CreateEtcdService(kclient *unversioned.Client, etcdName, clusterName, ns string) error { svc := makeEtcdService(etcdName, clusterName) if _, err := kclient.Services(ns).Create(svc); err != nil { return err } return nil } func CreateEtcdNodePortService(kclient *unversioned.Client, etcdName, clusterName, ns string) (*api.Service, error) { svc := makeEtcdNodePortService(etcdName, clusterName) return kclient.Services(ns).Create(svc) } func CreateAndWaitPod(kclient *unversioned.Client, ns string, pod *api.Pod, timeout time.Duration) error { if _, err := kclient.Pods(ns).Create(pod); err != nil { return err } w, err := kclient.Pods(ns).Watch(api.SingleObject(api.ObjectMeta{Name: pod.Name})) if err != nil { return err } _, err = watch.Until(timeout, w, unversioned.PodRunning) // TODO: cleanup pod on failure return err } // TODO: converge the port logic with member ClientAddr() and PeerAddr() func makeEtcdService(etcdName, clusterName string) *api.Service { labels := map[string]string{ "app": "etcd", "etcd_node": etcdName, "etcd_cluster": clusterName, } svc := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: etcdName, Labels: labels, Annotations: map[string]string{ annotationPrometheusScrape: "true", annotationPrometheusPort: "2379", }, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Name: "server", Port: 2380, TargetPort: intstr.FromInt(2380), Protocol: api.ProtocolTCP, }, { Name: "client", Port: 2379, TargetPort: intstr.FromInt(2379), Protocol: api.ProtocolTCP, }, }, Selector: labels, }, } return svc } func makeEtcdNodePortService(etcdName, clusterName string) *api.Service { labels := map[string]string{ "etcd_node": etcdName, "etcd_cluster": clusterName, } svc := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: etcdName + "-nodeport", Labels: labels, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Name: "server", Port: 2380, TargetPort: intstr.FromInt(2380), Protocol: api.ProtocolTCP, }, }, Type: api.ServiceTypeNodePort, Selector: labels, }, } return svc } func AddRecoveryToPod(pod *api.Pod, clusterName, name, token string, cs *spec.ClusterSpec) { pod.Annotations[k8sv1api.PodInitContainersAnnotationKey] = makeRestoreInitContainerSpec(MakeBackupHostPort(clusterName), name, token, cs.Version) } func MakeEtcdPod(m *etcdutil.Member, initialCluster []string, clusterName, state, token string, cs *spec.ClusterSpec) *api.Pod { commands := []string{ "/usr/local/bin/etcd", "--data-dir", dataDir, "--name", m.Name, "--initial-advertise-peer-urls", m.PeerAddr(), "--listen-peer-urls", "http://0.0.0.0:2380", "--listen-client-urls", "http://0.0.0.0:2379", "--advertise-client-urls", m.ClientAddr(), "--initial-cluster", strings.Join(initialCluster, ","), "--initial-cluster-state", state, } if state == "new" { commands = append(commands, "--initial-cluster-token", token) } pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: m.Name, Labels: map[string]string{ "app": "etcd", "etcd_node": m.Name, "etcd_cluster": clusterName, }, Annotations: map[string]string{}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Command: commands, Name: "etcd", Image: MakeEtcdImage(cs.Version), Ports: []api.ContainerPort{ { Name: "server", ContainerPort: int32(2380), Protocol: api.ProtocolTCP, }, }, // For readiness probe, we only requires the etcd server to respond, not // quorumly accessible. Because reconcile relies on readiness, and // reconcile could handle disaster recovery. ReadinessProbe: &api.Probe{ Handler: api.Handler{ Exec: &api.ExecAction{ Command: []string{"/bin/sh", "-c", "ETCDCTL_API=3 etcdctl get --consistency=s foo"}, }, }, // If an etcd member tries to join quorum, it has 5s strict check // It can still serve client request. InitialDelaySeconds: 5, TimeoutSeconds: 10, PeriodSeconds: 10, FailureThreshold: 3, }, // a pod is alive only if a get succeeds // the etcd pod should die if liveness probing fails. LivenessProbe: &api.Probe{ Handler: api.Handler{ Exec: &api.ExecAction{ Command: []string{"/bin/sh", "-c", "ETCDCTL_API=3 etcdctl get foo"}, }, }, InitialDelaySeconds: 10, TimeoutSeconds: 10, // probe every 60 seconds PeriodSeconds: 60, // failed for 3 minutes FailureThreshold: 3, }, VolumeMounts: []api.VolumeMount{ {Name: "etcd-data", MountPath: etcdDir}, }, }, }, RestartPolicy: api.RestartPolicyNever, SecurityContext: &api.PodSecurityContext{ HostNetwork: cs.HostNetwork, }, Volumes: []api.Volume{ {Name: "etcd-data", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, }, }, } SetEtcdVersion(pod, cs.Version) if !cs.AntiAffinity { return pod } // set pod anti-affinity with the pods that belongs to the same etcd cluster affinity := api.Affinity{ PodAntiAffinity: &api.PodAntiAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: []api.PodAffinityTerm{ { LabelSelector: &unversionedAPI.LabelSelector{ MatchLabels: map[string]string{ "etcd_cluster": clusterName, }, }, }, }, }, } affinityb, err := json.Marshal(affinity) if err != nil { panic("failed to marshal affinty struct") } pod.Annotations[api.AffinityAnnotationKey] = string(affinityb) if len(cs.NodeSelector) != 0 { pod = PodWithNodeSelector(pod, cs.NodeSelector) } return pod } func MustGetInClusterMasterHost() string { cfg, err := restclient.InClusterConfig() if err != nil { panic(err) } return cfg.Host } // tlsConfig isn't modified inside this function. // The reason it's a pointer is that it's not necessary to have tlsconfig to create a client. func MustCreateClient(host string, tlsInsecure bool, tlsConfig *restclient.TLSClientConfig) *unversioned.Client { if len(host) == 0 { c, err := unversioned.NewInCluster() if err != nil { panic(err) } return c } cfg := &restclient.Config{ Host: host, QPS: 100, Burst: 100, } hostUrl, err := url.Parse(host) if err != nil { panic(fmt.Sprintf("error parsing host url %s : %v", host, err)) } if hostUrl.Scheme == "https" { cfg.TLSClientConfig = *tlsConfig cfg.Insecure = tlsInsecure } c, err := unversioned.New(cfg) if err != nil { panic(err) } return c } func IsKubernetesResourceAlreadyExistError(err error) bool { se, ok := err.(*apierrors.StatusError) if !ok { return false } if se.Status().Code == http.StatusConflict && se.Status().Reason == unversionedAPI.StatusReasonAlreadyExists { return true } return false } func IsKubernetesResourceNotFoundError(err error) bool { se, ok := err.(*apierrors.StatusError) if !ok { return false } if se.Status().Code == http.StatusNotFound && se.Status().Reason == unversionedAPI.StatusReasonNotFound { return true } return false } func ListETCDCluster(host, ns string, httpClient *http.Client) (*http.Response, error) { return httpClient.Get(fmt.Sprintf("%s/apis/coreos.com/v1/namespaces/%s/etcdclusters", host, ns)) } func WatchETCDCluster(host, ns string, httpClient *http.Client, resourceVersion string) (*http.Response, error) { return httpClient.Get(fmt.Sprintf("%s/apis/coreos.com/v1/namespaces/%s/etcdclusters?watch=true&resourceVersion=%s", host, ns, resourceVersion)) } func WaitEtcdTPRReady(httpClient *http.Client, interval, timeout time.Duration, host, ns string) error { return wait.Poll(interval, timeout, func() (bool, error) { resp, err := ListETCDCluster(host, ns, httpClient) if err != nil { return false, err } defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: return true, nil case http.StatusNotFound: // not set up yet. wait. return false, nil default: return false, fmt.Errorf("invalid status code: %v", resp.Status) } }) } func SliceReadyAndUnreadyPods(podList *api.PodList) (ready, unready []*api.Pod) { for i := range podList.Items { pod := &podList.Items[i] if pod.Status.Phase == api.PodRunning && api.IsPodReady(pod) { ready = append(ready, pod) continue } unready = append(unready, pod) } return } func EtcdPodListOpt(clusterName string) api.ListOptions { return api.ListOptions{ LabelSelector: labels.SelectorFromSet(map[string]string{ "etcd_cluster": clusterName, "app": "etcd", }), } }
package collector import ( "database/sql" _ "github.com/mattn/go-sqlite3" "io/ioutil" . "launchpad.net/gocheck" "os" "path/filepath" "testing" ) func Test(t *testing.T) { TestingT(t) } type S struct{ db *sql.DB } var _ = Suite(&S{}) func (s *S) SetUpSuite(c *C) { s.db, _ = sql.Open("sqlite3", "./tsuru.db") _, err := s.db.Exec("CREATE TABLE apps (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name varchar(255), framework varchar(255), state varchar(255), ip varchar(100))") c.Check(err, IsNil) } func (s *S) TearDownSuite(c *C) { s.db.Close() os.Remove("./tsuru.db") } func (s *S) TestCollectorUpdate(c *C) { insertApp, _ := s.db.Prepare("INSERT INTO apps (id, name, state) VALUES (?, ?, ?)") tx, _ := s.db.Begin() stmt := tx.Stmt(insertApp) defer stmt.Close() stmt.Exec(1, "umaappqq", "STOPPED") tx.Commit() var collector Collector out := &output{ Services: map[string]Service{ "umaappqq": Service{ Units: map[string]Unit{ "umaappqq/0": Unit{ State: "started", Machine: 1, }, }, }, }, Machines: map[int]interface{}{ 0: map[interface{}]interface{}{ "dns-name": "192.168.0.10", "instance-id": "i-00000zz6", "instance-state": "running", "state": "running", }, 1: map[interface{}]interface{}{ "dns-name": "192.168.0.11", "instance-id": "i-00000zz7", "instance-state": "running", "state": "running", }, }, } collector.Update(s.db, out) rows, _ := s.db.Query("SELECT state, ip FROM apps WHERE id = 1") var state, ip string for rows.Next() { rows.Scan(&state, &ip) } c.Assert(state, DeepEquals, "STARTED") c.Assert(ip, DeepEquals, "192.168.0.11") } func (s *S) TestCollectorParser(c *C) { var collector Collector file, _ := os.Open(filepath.Join("testdata", "output.yaml")) jujuOutput, _ := ioutil.ReadAll(file) file.Close() expected := &output{ Services: map[string]Service{ "umaappqq": Service{ Units: map[string]Unit{ "umaappqq/0": Unit{ State: "started", Machine: 1, }, }, }, }, Machines: map[int]interface{}{ 0: map[interface{}]interface{}{ "dns-name": "192.168.0.10", "instance-id": "i-00000zz6", "instance-state": "running", "state": "running", }, 1: map[interface{}]interface{}{ "dns-name": "192.168.0.11", "instance-id": "i-00000zz7", "instance-state": "running", "state": "running", }, }, } c.Assert(collector.Parse(jujuOutput), DeepEquals, expected) } collect: gofmt -w . package collector import ( "database/sql" _ "github.com/mattn/go-sqlite3" "io/ioutil" . "launchpad.net/gocheck" "os" "path/filepath" "testing" ) func Test(t *testing.T) { TestingT(t) } type S struct { db *sql.DB } var _ = Suite(&S{}) func (s *S) SetUpSuite(c *C) { s.db, _ = sql.Open("sqlite3", "./tsuru.db") _, err := s.db.Exec("CREATE TABLE apps (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name varchar(255), framework varchar(255), state varchar(255), ip varchar(100))") c.Check(err, IsNil) } func (s *S) TearDownSuite(c *C) { s.db.Close() os.Remove("./tsuru.db") } func (s *S) TestCollectorUpdate(c *C) { insertApp, _ := s.db.Prepare("INSERT INTO apps (id, name, state) VALUES (?, ?, ?)") tx, _ := s.db.Begin() stmt := tx.Stmt(insertApp) defer stmt.Close() stmt.Exec(1, "umaappqq", "STOPPED") tx.Commit() var collector Collector out := &output{ Services: map[string]Service{ "umaappqq": Service{ Units: map[string]Unit{ "umaappqq/0": Unit{ State: "started", Machine: 1, }, }, }, }, Machines: map[int]interface{}{ 0: map[interface{}]interface{}{ "dns-name": "192.168.0.10", "instance-id": "i-00000zz6", "instance-state": "running", "state": "running", }, 1: map[interface{}]interface{}{ "dns-name": "192.168.0.11", "instance-id": "i-00000zz7", "instance-state": "running", "state": "running", }, }, } collector.Update(s.db, out) rows, _ := s.db.Query("SELECT state, ip FROM apps WHERE id = 1") var state, ip string for rows.Next() { rows.Scan(&state, &ip) } c.Assert(state, DeepEquals, "STARTED") c.Assert(ip, DeepEquals, "192.168.0.11") } func (s *S) TestCollectorParser(c *C) { var collector Collector file, _ := os.Open(filepath.Join("testdata", "output.yaml")) jujuOutput, _ := ioutil.ReadAll(file) file.Close() expected := &output{ Services: map[string]Service{ "umaappqq": Service{ Units: map[string]Unit{ "umaappqq/0": Unit{ State: "started", Machine: 1, }, }, }, }, Machines: map[int]interface{}{ 0: map[interface{}]interface{}{ "dns-name": "192.168.0.10", "instance-id": "i-00000zz6", "instance-state": "running", "state": "running", }, 1: map[interface{}]interface{}{ "dns-name": "192.168.0.11", "instance-id": "i-00000zz7", "instance-state": "running", "state": "running", }, }, } c.Assert(collector.Parse(jujuOutput), DeepEquals, expected) }
// Copyright 2015 Google Inc. All Rights Reserved. // // 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 gcsproxy_test import ( "errors" "fmt" "io" "io/ioutil" "strings" "testing" "github.com/jacobsa/gcloud/gcs" "github.com/jacobsa/gcloud/gcs/mock_gcs" "github.com/jacobsa/gcsfuse/gcsproxy" . "github.com/jacobsa/oglematchers" "github.com/jacobsa/oglemock" . "github.com/jacobsa/ogletest" "golang.org/x/net/context" "google.golang.org/cloud/storage" ) func TestOgletest(t *testing.T) { RunTests(t) } //////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////// // An oglemock.Matcher that accepts a predicate function and a description, // making it easy to make anonymous matcher types. type predicateMatcher struct { Desc string Predicate func(interface{}) error } var _ Matcher = &predicateMatcher{} func (m *predicateMatcher) Matches(candidate interface{}) error { return m.Predicate(candidate) } func (m *predicateMatcher) Description() string { return m.Desc } func nameIs(name string) Matcher { return &predicateMatcher{ Desc: fmt.Sprintf("Name is: %s", name), Predicate: func(candidate interface{}) error { req := candidate.(*gcs.CreateObjectRequest) if req.Attrs.Name != name { return errors.New("") } return nil }, } } func contentsAre(s string) Matcher { return &predicateMatcher{ Desc: fmt.Sprintf("Object contents are: %s", s), Predicate: func(candidate interface{}) error { // Snarf the contents. req := candidate.(*gcs.CreateObjectRequest) contents, err := ioutil.ReadAll(req.Contents) if err != nil { panic(err) } // Compare if string(contents) != s { return errors.New("") } return nil }, } } //////////////////////////////////////////////////////////////////////// // Invariant-checking object proxy //////////////////////////////////////////////////////////////////////// // A wrapper around ObjectProxy that calls CheckInvariants whenever invariants // should hold. For catching logic errors early in the test. type checkingObjectProxy struct { wrapped *gcsproxy.ObjectProxy } func (op *checkingObjectProxy) Name() string { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Name() } func (op *checkingObjectProxy) Stat(ctx context.Context) (uint64, bool, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Stat(ctx) } func (op *checkingObjectProxy) ReadAt(b []byte, o int64) (int, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.ReadAt(context.Background(), b, o) } func (op *checkingObjectProxy) WriteAt(b []byte, o int64) (int, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.WriteAt(context.Background(), b, o) } func (op *checkingObjectProxy) Truncate(n uint64) error { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Truncate(context.Background(), n) } func (op *checkingObjectProxy) Sync() (uint64, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Sync(context.Background()) } //////////////////////////////////////////////////////////////////////// // Boilerplate //////////////////////////////////////////////////////////////////////// type ObjectProxyTest struct { objectName string bucket mock_gcs.MockBucket op checkingObjectProxy } func (t *ObjectProxyTest) setUp(ti *TestInfo, srcGeneration uint64) { t.objectName = "some/object" t.bucket = mock_gcs.NewMockBucket(ti.MockController, "bucket") var err error t.op.wrapped, err = gcsproxy.NewObjectProxy( t.bucket, t.objectName, srcGeneration) if err != nil { panic(err) } } //////////////////////////////////////////////////////////////////////// // No source object //////////////////////////////////////////////////////////////////////// // A test whose initial conditions are a fresh object proxy without a source // object set. type NoSourceObjectTest struct { ObjectProxyTest } var _ SetUpInterface = &NoSourceObjectTest{} func init() { RegisterTestSuite(&NoSourceObjectTest{}) } func (t *NoSourceObjectTest) SetUp(ti *TestInfo) { t.ObjectProxyTest.setUp(ti, 0) } func (t *NoSourceObjectTest) Name() { ExpectEq(t.objectName, t.op.Name()) } func (t *NoSourceObjectTest) NoteLatest_NegativeSize() { o := &storage.Object{ Name: t.objectName, Generation: 1234, Size: -1, } err := t.op.NoteLatest(o) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("size"))) ExpectThat(err, Error(HasSubstr("-1"))) } func (t *NoSourceObjectTest) NoteLatest_WrongName() { o := &storage.Object{ Name: t.objectName + "foo", Generation: 1234, Size: 0, } err := t.op.NoteLatest(o) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("name"))) ExpectThat(err, Error(HasSubstr("foo"))) } func (t *NoSourceObjectTest) Size_InitialState() { size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) } func (t *NoSourceObjectTest) Size_AfterTruncatingToZero() { var err error // Truncate err = t.op.Truncate(0) AssertEq(nil, err) // Size size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) } func (t *NoSourceObjectTest) Size_AfterTruncatingToNonZero() { var err error // Truncate err = t.op.Truncate(123) AssertEq(nil, err) // Size size, err := t.op.Size() AssertEq(nil, err) ExpectEq(123, size) } func (t *NoSourceObjectTest) Size_AfterReading() { var err error // Read buf := make([]byte, 0) n, err := t.op.ReadAt(buf, 0) AssertEq(nil, err) AssertEq(0, n) // Size size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) } func (t *NoSourceObjectTest) Read_InitialState() { type testCase struct { offset int64 size int expectedErr error expectedN int } testCases := []testCase{ // Empty ranges testCase{0, 0, nil, 0}, testCase{17, 0, nil, 0}, // Non-empty ranges testCase{0, 10, io.EOF, 0}, testCase{17, 10, io.EOF, 0}, } for _, tc := range testCases { buf := make([]byte, tc.size) n, err := t.op.ReadAt(buf, tc.offset) AssertEq(tc.expectedErr, err, "Test case: %v", tc) AssertEq(tc.expectedN, n, "Test case: %v", tc) } } func (t *NoSourceObjectTest) WriteToEndOfObjectThenRead() { var buf []byte var n int var err error // Extend the object by writing twice. n, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) AssertEq(len("taco"), n) n, err = t.op.WriteAt([]byte("burrito"), int64(len("taco"))) AssertEq(nil, err) AssertEq(len("burrito"), n) // Read the whole thing. buf = make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(len("tacoburrito"), n) ExpectEq("tacoburrito", string(buf[:n])) // Read a range in the middle. buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 3) AssertEq(nil, err) ExpectEq(4, n) ExpectEq("obur", string(buf[:n])) } func (t *NoSourceObjectTest) WritePastEndOfObjectThenRead() { var n int var err error var buf []byte // Extend the object by writing past its end. n, err = t.op.WriteAt([]byte("taco"), 2) AssertEq(nil, err) AssertEq(len("taco"), n) // Check its size. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(2+len("taco"), size) // Read the whole thing. buf = make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(2+len("taco"), n) ExpectEq("\x00\x00taco", string(buf[:n])) // Read a range in the middle. buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 1) AssertEq(nil, err) ExpectEq(4, n) ExpectEq("\x00tac", string(buf[:n])) } func (t *NoSourceObjectTest) WriteWithinObjectThenRead() { var n int var err error var buf []byte // Write several bytes to extend the object. n, err = t.op.WriteAt([]byte("00000"), 0) AssertEq(nil, err) AssertEq(len("00000"), n) // Overwrite some in the middle. n, err = t.op.WriteAt([]byte("11"), 1) AssertEq(nil, err) AssertEq(len("11"), n) // Read the whole thing. buf = make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(len("01100"), n) ExpectEq("01100", string(buf[:n])) } func (t *NoSourceObjectTest) GrowByTruncating() { var n int var err error var buf []byte // Truncate err = t.op.Truncate(4) AssertEq(nil, err) // Size size, err := t.op.Size() AssertEq(nil, err) ExpectEq(4, size) // Read the whole thing. buf = make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(4, n) ExpectEq("\x00\x00\x00\x00", string(buf[:n])) } func (t *NoSourceObjectTest) Sync_NoInteractions() { // CreateObject -- should receive an empty string. ExpectCall(t.bucket, "CreateObject")( Any(), AllOf(nameIs(t.objectName), contentsAre(""))). WillOnce(oglemock.Return(nil, errors.New(""))) // Sync t.op.Sync() } func (t *NoSourceObjectTest) Sync_ReadCallsOnly() { // Make a Read call buf := make([]byte, 0) n, err := t.op.ReadAt(buf, 0) AssertEq(nil, err) AssertEq(0, n) // CreateObject -- should receive an empty string. ExpectCall(t.bucket, "CreateObject")( Any(), AllOf(nameIs(t.objectName), contentsAre(""))). WillOnce(oglemock.Return(nil, errors.New(""))) // Sync t.op.Sync() } func (t *NoSourceObjectTest) Sync_AfterWriting() { var n int var err error // Write some data. n, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) AssertEq(len("taco"), n) n, err = t.op.WriteAt([]byte("burrito"), int64(len("taco"))) AssertEq(nil, err) AssertEq(len("burrito"), n) // CreateObject -- should receive the contents we wrote above. ExpectCall(t.bucket, "CreateObject")( Any(), AllOf(nameIs(t.objectName), contentsAre("tacoburrito"))). WillOnce(oglemock.Return(nil, errors.New(""))) // Sync t.op.Sync() } func (t *NoSourceObjectTest) Sync_AfterTruncating() { // Truncate outwards. err := t.op.Truncate(2) AssertEq(nil, err) // CreateObject -- should receive null bytes. ExpectCall(t.bucket, "CreateObject")( Any(), AllOf(nameIs(t.objectName), contentsAre("\x00\x00"))). WillOnce(oglemock.Return(nil, errors.New(""))) // Sync t.op.Sync() } func (t *NoSourceObjectTest) Sync_CreateObjectFails() { var n int var err error // Write some data. n, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) AssertEq(len("taco"), n) // First call to create object: fail. ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // Sync -- should fail. _, err = t.op.Sync() AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("CreateObject"))) ExpectThat(err, Error(HasSubstr("taco"))) // The data we wrote before should still be present. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(len("taco"), size) buf := make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("taco", string(buf[:n])) // The file should still be regarded as dirty -- a further call to Sync // should call CreateObject again. ExpectCall(t.bucket, "CreateObject")( Any(), AllOf(nameIs(t.objectName), contentsAre("taco"))). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Sync() } func (t *NoSourceObjectTest) Sync_Successful() { var n int var err error // Dirty the proxy. n, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) AssertEq(len("taco"), n) // Have the call to CreateObject succeed. expected := &storage.Object{ Name: t.objectName, } ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(expected, nil)) // Sync -- should succeed o, err := t.op.Sync() AssertEq(nil, err) ExpectEq(expected, o) // Further calls to Sync should do nothing. o2, err := t.op.Sync() AssertEq(nil, err) ExpectEq(o, o2) // The data we wrote before should still be present. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(len("taco"), size) buf := make([]byte, 1024) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("taco", string(buf[:n])) } func (t *NoSourceObjectTest) NoteLatest_NoInteractions() { // NoteLatest newObj := &storage.Object{ Name: t.objectName, Generation: 17, Size: 19, } err := t.op.NoteLatest(newObj) AssertEq(nil, err) // The size should be reflected. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(19, size) // Sync should return the new object without doing anything interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(newObj, syncResult) // A read should cause the object to be faulted in. ExpectCall(t.bucket, "NewReader")(Any(), t.objectName). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(make([]byte, 1), 0) } func (t *NoSourceObjectTest) NoteLatest_AfterWriting() { var err error // Write _, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) // NoteLatest newObj := &storage.Object{ Name: t.objectName, Generation: 17, Size: 19, } err = t.op.NoteLatest(newObj) AssertEq(nil, err) // The new size should be reflected. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(19, size) // Sync should return the new object without doing anything interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(newObj, syncResult) // A read should cause the object to be faulted in. ExpectCall(t.bucket, "NewReader")(Any(), t.objectName). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(make([]byte, 1), 0) } func (t *NoSourceObjectTest) Clean_NoInteractions() { var buf []byte var n int var err error // Clean err = t.op.Clean() AssertEq(nil, err) // Sizing and reading should still work. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(0, n) } func (t *NoSourceObjectTest) Clean_AfterReading() { var buf []byte var n int var err error // Read buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(0, n) // Clean err = t.op.Clean() AssertEq(nil, err) // Sizing and reading should still work. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(0, n) } func (t *NoSourceObjectTest) Clean_AfterWriting() { var buf []byte var n int var err error // Write _, err = t.op.WriteAt([]byte("taco"), 0) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Should be back to empty. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(0, n) } func (t *NoSourceObjectTest) Clean_AfterTruncating() { var buf []byte var n int var err error // Truncate err = t.op.Truncate(1) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Should be back to empty. size, err := t.op.Size() AssertEq(nil, err) ExpectEq(0, size) buf = make([]byte, 4) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq(0, n) } //////////////////////////////////////////////////////////////////////// // Source object present //////////////////////////////////////////////////////////////////////// // A test whose initial conditions are an object proxy branching from a source // object in the bucket. type SourceObjectPresentTest struct { ObjectProxyTest sourceObject *storage.Object } var _ SetUpInterface = &SourceObjectPresentTest{} func init() { RegisterTestSuite(&SourceObjectPresentTest{}) } func (t *SourceObjectPresentTest) SetUp(ti *TestInfo) { t.ObjectProxyTest.setUp(ti, 123) } func (t *SourceObjectPresentTest) Size_InitialState() { size, err := t.op.Size() AssertEq(nil, err) ExpectEq(t.sourceObject.Size, size) } func (t *SourceObjectPresentTest) Read_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // ReadAt t.op.ReadAt(make([]byte, 1), 0) } func (t *SourceObjectPresentTest) Read_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt _, err := t.op.ReadAt(make([]byte, 1), 0) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(make([]byte, 1), 0) } func (t *SourceObjectPresentTest) Read_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Reads n, err = t.op.ReadAt(buf[:1], 2) AssertEq(nil, err) ExpectEq("c", string(buf[:n])) n, err = t.op.ReadAt(buf[:10], 0) AssertEq(io.EOF, err) ExpectEq("taco", string(buf[:n])) // Sync should do nothing interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) Write_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // WriteAt t.op.WriteAt([]byte(""), 0) } func (t *SourceObjectPresentTest) Write_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt _, err := t.op.WriteAt([]byte(""), 0) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.WriteAt([]byte(""), 0) } func (t *SourceObjectPresentTest) Write_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Write _, err = t.op.WriteAt([]byte("burrito"), 3) AssertEq(nil, err) // Read n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("tacburrito", string(buf[:n])) // The object should be regarded as dirty by Sync. ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Sync() } func (t *SourceObjectPresentTest) Truncate_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // WriteAt t.op.Truncate(1) } func (t *SourceObjectPresentTest) Truncate_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt err := t.op.Truncate(1) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Truncate(1) } func (t *SourceObjectPresentTest) Truncate_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Truncate err = t.op.Truncate(1) AssertEq(nil, err) // Read n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("t", string(buf[:n])) // The object should be regarded as dirty by Sync. ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Sync() } func (t *SourceObjectPresentTest) Sync_NoInteractions() { // Sync should do nothing interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_EarlierThanPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject o.Generation-- err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been ignored. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_SameAsPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been ignored. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_NewerThanPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject o.Generation++ err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been adopted. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(o, syncResult) } func (t *SourceObjectPresentTest) Clean_NoInteractions() { var err error // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should still have to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) Clean_AfterReading() { buf := make([]byte, 1024) var n int var err error // Read, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) AssertEq("taco", string(buf[:n])) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next read should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(buf, 0) } func (t *SourceObjectPresentTest) Clean_AfterWriting() { var err error // Write, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("")), nil)) _, err = t.op.WriteAt([]byte("a"), 0) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next write should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.WriteAt([]byte("a"), 0) } func (t *SourceObjectPresentTest) Clean_AfterTruncating() { var err error // Truncate, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("")), nil)) err = t.op.Truncate(1) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next truncation should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Truncate(1) } Fixed NoSourceObjectTest test names. // Copyright 2015 Google Inc. All Rights Reserved. // // 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 gcsproxy_test import ( "errors" "fmt" "io" "io/ioutil" "strings" "testing" "github.com/jacobsa/gcloud/gcs" "github.com/jacobsa/gcloud/gcs/mock_gcs" "github.com/jacobsa/gcsfuse/gcsproxy" . "github.com/jacobsa/oglematchers" "github.com/jacobsa/oglemock" . "github.com/jacobsa/ogletest" "golang.org/x/net/context" "google.golang.org/cloud/storage" ) func TestOgletest(t *testing.T) { RunTests(t) } //////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////// // An oglemock.Matcher that accepts a predicate function and a description, // making it easy to make anonymous matcher types. type predicateMatcher struct { Desc string Predicate func(interface{}) error } var _ Matcher = &predicateMatcher{} func (m *predicateMatcher) Matches(candidate interface{}) error { return m.Predicate(candidate) } func (m *predicateMatcher) Description() string { return m.Desc } func nameIs(name string) Matcher { return &predicateMatcher{ Desc: fmt.Sprintf("Name is: %s", name), Predicate: func(candidate interface{}) error { req := candidate.(*gcs.CreateObjectRequest) if req.Attrs.Name != name { return errors.New("") } return nil }, } } func contentsAre(s string) Matcher { return &predicateMatcher{ Desc: fmt.Sprintf("Object contents are: %s", s), Predicate: func(candidate interface{}) error { // Snarf the contents. req := candidate.(*gcs.CreateObjectRequest) contents, err := ioutil.ReadAll(req.Contents) if err != nil { panic(err) } // Compare if string(contents) != s { return errors.New("") } return nil }, } } //////////////////////////////////////////////////////////////////////// // Invariant-checking object proxy //////////////////////////////////////////////////////////////////////// // A wrapper around ObjectProxy that calls CheckInvariants whenever invariants // should hold. For catching logic errors early in the test. type checkingObjectProxy struct { wrapped *gcsproxy.ObjectProxy } func (op *checkingObjectProxy) Name() string { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Name() } func (op *checkingObjectProxy) Stat() (uint64, bool, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Stat(context.Background()) } func (op *checkingObjectProxy) ReadAt(b []byte, o int64) (int, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.ReadAt(context.Background(), b, o) } func (op *checkingObjectProxy) WriteAt(b []byte, o int64) (int, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.WriteAt(context.Background(), b, o) } func (op *checkingObjectProxy) Truncate(n uint64) error { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Truncate(context.Background(), n) } func (op *checkingObjectProxy) Sync() (uint64, error) { op.wrapped.CheckInvariants() defer op.wrapped.CheckInvariants() return op.wrapped.Sync(context.Background()) } //////////////////////////////////////////////////////////////////////// // Boilerplate //////////////////////////////////////////////////////////////////////// type ObjectProxyTest struct { objectName string bucket mock_gcs.MockBucket op checkingObjectProxy } func (t *ObjectProxyTest) setUp(ti *TestInfo, srcGeneration uint64) { t.objectName = "some/object" t.bucket = mock_gcs.NewMockBucket(ti.MockController, "bucket") var err error t.op.wrapped, err = gcsproxy.NewObjectProxy( t.bucket, t.objectName, srcGeneration) if err != nil { panic(err) } } //////////////////////////////////////////////////////////////////////// // No source object //////////////////////////////////////////////////////////////////////// // A test whose initial conditions are a fresh object proxy without a source // object set. type NoSourceObjectTest struct { ObjectProxyTest } var _ SetUpInterface = &NoSourceObjectTest{} func init() { RegisterTestSuite(&NoSourceObjectTest{}) } func (t *NoSourceObjectTest) SetUp(ti *TestInfo) { t.ObjectProxyTest.setUp(ti, 0) } func (t *NoSourceObjectTest) Name() { ExpectEq(t.objectName, t.op.Name()) } func (t *NoSourceObjectTest) Stat_CallsBucket() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_BucketFails() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_BucketSaysFound() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_InitialState() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_AfterShortening() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_AfterGrowing() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_AfterReading() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Stat_AfterWriting() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Read_InitialState() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) WriteToEndOfObjectThenRead() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) WritePastEndOfObjectThenRead() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) WriteWithinObjectThenRead() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) GrowByTruncating() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_NoInteractions() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_ReadCallsOnly() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_AfterWriting() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_AfterTruncating() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_CreateObjectFails() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_CreateObjectSaysPreconditionFailed() { AssertTrue(false, "TODO") } func (t *NoSourceObjectTest) Sync_Successful() { AssertTrue(false, "TODO") } //////////////////////////////////////////////////////////////////////// // Source object present //////////////////////////////////////////////////////////////////////// // A test whose initial conditions are an object proxy branching from a source // object in the bucket. type SourceObjectPresentTest struct { ObjectProxyTest sourceObject *storage.Object } var _ SetUpInterface = &SourceObjectPresentTest{} func init() { RegisterTestSuite(&SourceObjectPresentTest{}) } func (t *SourceObjectPresentTest) SetUp(ti *TestInfo) { t.ObjectProxyTest.setUp(ti, 123) } func (t *SourceObjectPresentTest) Size_InitialState() { size, err := t.op.Size() AssertEq(nil, err) ExpectEq(t.sourceObject.Size, size) } func (t *SourceObjectPresentTest) Read_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // ReadAt t.op.ReadAt(make([]byte, 1), 0) } func (t *SourceObjectPresentTest) Read_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt _, err := t.op.ReadAt(make([]byte, 1), 0) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(make([]byte, 1), 0) } func (t *SourceObjectPresentTest) Read_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Reads n, err = t.op.ReadAt(buf[:1], 2) AssertEq(nil, err) ExpectEq("c", string(buf[:n])) n, err = t.op.ReadAt(buf[:10], 0) AssertEq(io.EOF, err) ExpectEq("taco", string(buf[:n])) // Sync should do nothing interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) Write_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // WriteAt t.op.WriteAt([]byte(""), 0) } func (t *SourceObjectPresentTest) Write_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt _, err := t.op.WriteAt([]byte(""), 0) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.WriteAt([]byte(""), 0) } func (t *SourceObjectPresentTest) Write_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Write _, err = t.op.WriteAt([]byte("burrito"), 3) AssertEq(nil, err) // Read n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("tacburrito", string(buf[:n])) // The object should be regarded as dirty by Sync. ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Sync() } func (t *SourceObjectPresentTest) Truncate_CallsNewReader() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), t.sourceObject.Name). WillOnce(oglemock.Return(nil, errors.New(""))) // WriteAt t.op.Truncate(1) } func (t *SourceObjectPresentTest) Truncate_NewReaderFails() { // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New("taco"))) // ReadAt err := t.op.Truncate(1) AssertNe(nil, err) ExpectThat(err, Error(HasSubstr("NewReader"))) ExpectThat(err, Error(HasSubstr("taco"))) // A subsequent call should cause it to happen all over again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Truncate(1) } func (t *SourceObjectPresentTest) Truncate_NewReaderSucceeds() { buf := make([]byte, 1024) var n int var err error // Bucket.NewReader ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) // Truncate err = t.op.Truncate(1) AssertEq(nil, err) // Read n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) ExpectEq("t", string(buf[:n])) // The object should be regarded as dirty by Sync. ExpectCall(t.bucket, "CreateObject")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Sync() } func (t *SourceObjectPresentTest) Sync_NoInteractions() { // Sync should do nothing interesting. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_EarlierThanPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject o.Generation-- err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been ignored. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_SameAsPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been ignored. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) NoteLatest_NewerThanPrev() { var err error // NoteLatest o := &storage.Object{} *o = *t.sourceObject o.Generation++ err = t.op.NoteLatest(o) AssertEq(nil, err) // The input should have been adopted. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(o, syncResult) } func (t *SourceObjectPresentTest) Clean_NoInteractions() { var err error // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should still have to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) } func (t *SourceObjectPresentTest) Clean_AfterReading() { buf := make([]byte, 1024) var n int var err error // Read, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("taco")), nil)) n, err = t.op.ReadAt(buf, 0) AssertEq(io.EOF, err) AssertEq("taco", string(buf[:n])) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next read should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.ReadAt(buf, 0) } func (t *SourceObjectPresentTest) Clean_AfterWriting() { var err error // Write, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("")), nil)) _, err = t.op.WriteAt([]byte("a"), 0) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next write should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.WriteAt([]byte("a"), 0) } func (t *SourceObjectPresentTest) Clean_AfterTruncating() { var err error // Truncate, successfully. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(ioutil.NopCloser(strings.NewReader("")), nil)) err = t.op.Truncate(1) AssertEq(nil, err) // Clean err = t.op.Clean() AssertEq(nil, err) // Sync should need to do nothing. syncResult, err := t.op.Sync() AssertEq(nil, err) ExpectEq(t.sourceObject, syncResult) // The next truncation should need to fetch the object again. ExpectCall(t.bucket, "NewReader")(Any(), Any()). WillOnce(oglemock.Return(nil, errors.New(""))) t.op.Truncate(1) }
// Package listing is a generate subcommand that scans // requested directory and generates a .go file with // a list of all found files. package listing import ( "os" "path/filepath" "github.com/anonx/sunplate/command" "github.com/anonx/sunplate/generation/output" "github.com/anonx/sunplate/log" p "github.com/anonx/sunplate/path" ) // Start is an entry point of listing subcommand. // It expects two parameters. // basePath is where to find files necessary for generation of listing. // params is a map with the following keys: // --path defines what directory to analyze ("./views" by-default). // --output is a path to directory where to create a new package ("./assets" by-default). // --package is what package should be created as a result ("views" by-default). func Start(params command.Data) { inputDir := params.Default("--input", "./views") outputDir := params.Default("--output", "./assets/views") outPkg := params.Default("--package", "views") // Start search of files. fs, fn := walkFunc(inputDir) filepath.Walk(inputDir, fn) // Generate and save a new package. t := output.NewType( outPkg, filepath.Join( p.SunplateDir("generation", "listing"), "./listing.go.template", ), ) t.CreateDir(outputDir) t.Extension = ".go" // Save generated file as a .go source. t.Context = map[string]interface{}{ "files": fs, "input": params.Default("--path", "./views"), } t.Generate() } // walkFunc returns a map of files and a function that may be used for validation // of found files. Successfully validated ones are stored to the files variable. func walkFunc(dir string) (map[string]string, func(string, os.FileInfo, error) error) { files := map[string]string{} return files, func(path string, info os.FileInfo, err error) error { // Make sure there are no any errors. if err != nil { log.Warn.Printf(`An error occured while creating a listing: "%s".`, err) return err } // Assure it is not a directory. if info.IsDir() { return nil } // Add files to the list. log.Trace.Printf(`Path "%s" discovered.`, path) files[p.Prefixless(path, dir)] = path return nil } } Use filenames rather than paths in generated listings // Package listing is a generate subcommand that scans // requested directory and generates a .go file with // a list of all found files. package listing import ( "os" "path/filepath" "github.com/anonx/sunplate/command" "github.com/anonx/sunplate/generation/output" "github.com/anonx/sunplate/log" p "github.com/anonx/sunplate/path" ) // Start is an entry point of listing subcommand. // It expects two parameters. // basePath is where to find files necessary for generation of listing. // params is a map with the following keys: // --path defines what directory to analyze ("./views" by-default). // --output is a path to directory where to create a new package ("./assets" by-default). // --package is what package should be created as a result ("views" by-default). func Start(params command.Data) { inputDir := params.Default("--input", "./views") outputDir := params.Default("--output", "./assets/views") outPkg := params.Default("--package", "views") // Start search of files. fs, fn := walkFunc(inputDir) filepath.Walk(inputDir, fn) // Generate and save a new package. t := output.NewType( outPkg, filepath.Join( p.SunplateDir("generation", "listing"), "./listing.go.template", ), ) t.CreateDir(outputDir) t.Extension = ".go" // Save generated file as a .go source. t.Context = map[string]interface{}{ "files": fs, "input": params.Default("--path", "./views"), } t.Generate() } // walkFunc returns a map of files and a function that may be used for validation // of found files. Successfully validated ones are stored to the files variable. func walkFunc(dir string) (map[string]string, func(string, os.FileInfo, error) error) { files := map[string]string{} dir = p.Prefixless(dir, "./") + "/" // This is required to get right file names. return files, func(path string, info os.FileInfo, err error) error { // Make sure there are no any errors. if err != nil { log.Warn.Printf(`An error occured while creating a listing: "%s".`, err) return err } // Assure it is not a directory. if info.IsDir() { return nil } // Add files to the list. log.Trace.Printf(`Path "%s" discovered.`, path) files[p.Prefixless(path, dir)] = path return nil } }
// Copyright 2017 The nvim-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 commands import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "nvim-go/config" "nvim-go/internal/cover" "nvim-go/nvimutil" "github.com/davecgh/go-spew/spew" "github.com/neovim/go-client/nvim" "github.com/pkg/errors" ) // cmdCoverEval struct type for Eval of GoBuild command. type cmdCoverEval struct { Cwd string `msgpack:",array"` File string `msgpack:",array"` } func (c *Commands) cmdCover(eval *cmdCoverEval) { go func() { err := c.cover(eval) switch e := err.(type) { case error: nvimutil.ErrorWrap(c.Nvim, e) case []*nvim.QuickfixError: c.ctx.Errlist["Cover"] = e nvimutil.ErrorList(c.Nvim, c.ctx.Errlist, true) } }() } // cover run the go tool cover command and highlight current buffer based cover // profile result. func (c *Commands) cover(eval *cmdCoverEval) interface{} { defer nvimutil.Profile(time.Now(), "GoCover") coverFile, err := ioutil.TempFile(os.TempDir(), "nvim-go-cover") if err != nil { return errors.WithStack(err) } defer os.Remove(coverFile.Name()) cmd := exec.Command("go", strings.Fields(fmt.Sprintf("test -cover -covermode=%s -coverprofile=%s .", config.CoverMode, coverFile.Name()))...) if len(config.CoverFlags) > 0 { cmd.Args = append(cmd.Args, config.CoverFlags...) } cmd.Dir = filepath.Dir(eval.File) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if coverErr := cmd.Run(); coverErr != nil && coverErr.(*exec.ExitError) != nil { errlist, err := nvimutil.ParseError(stderr.Bytes(), eval.Cwd, &c.ctx.Build) if err != nil { return errors.WithStack(err) } return errlist } delete(c.ctx.Errlist, "Cover") profile, err := cover.ParseProfiles(coverFile.Name()) if err != nil { return errors.WithStack(err) } b, err := c.Nvim.CurrentBuffer() if err != nil { return errors.WithStack(err) } buf, err := c.Nvim.BufferLines(b, 0, -1, true) if err != nil { return errors.WithStack(err) } highlighted := make(map[int]bool) var res int // for ignore the msgpack decode errror. not used for _, prof := range profile { if filepath.Base(prof.FileName) == filepath.Base(eval.File) { if config.DebugEnable { log.Printf("prof.Blocks:\n%+v\n", spew.Sdump(prof.Blocks)) log.Printf("prof.Boundaries():\n%+v\n", spew.Sdump(prof.Boundaries(nvimutil.ToByteSlice(buf)))) } for _, block := range prof.Blocks { for line := block.StartLine - 1; line <= block.EndLine-1; line++ { // nvim_buf_add_highlight line started by 0 // not highlighting the last RBRACE of the function if line == block.EndLine-1 && block.EndCol == 2 { break } var hl string switch { case block.Count == 0: hl = "GoCoverMiss" case block.Count-block.NumStmt == 0: hl = "GoCoverPartial" default: hl = "GoCoverHit" } if !highlighted[line] { c.Batch.AddBufferHighlight(b, 0, hl, line, 0, -1, &res) highlighted[line] = true } } } } } return errors.WithStack(c.Batch.Execute()) } commands/cover: change catch error stdio to stdout 'go test -cover ...' command will output the error to stdout Signed-off-by: Koichi Shiraishi <2e5bdfebde234ed3509bcfc18121c70b6631e207@gmail.com> // Copyright 2017 The nvim-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 commands import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "nvim-go/config" "nvim-go/internal/cover" "nvim-go/nvimutil" "github.com/davecgh/go-spew/spew" "github.com/neovim/go-client/nvim" "github.com/pkg/errors" ) // cmdCoverEval struct type for Eval of GoBuild command. type cmdCoverEval struct { Cwd string `msgpack:",array"` File string `msgpack:",array"` } func (c *Commands) cmdCover(eval *cmdCoverEval) { go func() { err := c.cover(eval) switch e := err.(type) { case error: nvimutil.ErrorWrap(c.Nvim, e) case []*nvim.QuickfixError: c.ctx.Errlist["Cover"] = e nvimutil.ErrorList(c.Nvim, c.ctx.Errlist, true) } }() } // cover run the go tool cover command and highlight current buffer based cover // profile result. func (c *Commands) cover(eval *cmdCoverEval) interface{} { defer nvimutil.Profile(time.Now(), "GoCover") coverFile, err := ioutil.TempFile(os.TempDir(), "nvim-go-cover") if err != nil { return errors.WithStack(err) } defer os.Remove(coverFile.Name()) cmd := exec.Command("go", strings.Fields(fmt.Sprintf("test -cover -covermode=%s -coverprofile=%s .", config.CoverMode, coverFile.Name()))...) if len(config.CoverFlags) > 0 { cmd.Args = append(cmd.Args, config.CoverFlags...) } cmd.Dir = filepath.Dir(eval.File) var stdout bytes.Buffer cmd.Stdout = &stdout if coverErr := cmd.Run(); coverErr != nil && coverErr.(*exec.ExitError) != nil { errlist, err := nvimutil.ParseError(stdout.Bytes(), filepath.Dir(eval.File), &c.ctx.Build) if err != nil { return errors.WithStack(err) } return errlist } delete(c.ctx.Errlist, "Cover") profile, err := cover.ParseProfiles(coverFile.Name()) if err != nil { return errors.WithStack(err) } b, err := c.Nvim.CurrentBuffer() if err != nil { return errors.WithStack(err) } buf, err := c.Nvim.BufferLines(b, 0, -1, true) if err != nil { return errors.WithStack(err) } highlighted := make(map[int]bool) var res int // for ignore the msgpack decode errror. not used for _, prof := range profile { if filepath.Base(prof.FileName) == filepath.Base(eval.File) { if config.DebugEnable { log.Printf("prof.Blocks:\n%+v\n", spew.Sdump(prof.Blocks)) log.Printf("prof.Boundaries():\n%+v\n", spew.Sdump(prof.Boundaries(nvimutil.ToByteSlice(buf)))) } for _, block := range prof.Blocks { for line := block.StartLine - 1; line <= block.EndLine-1; line++ { // nvim_buf_add_highlight line started by 0 // not highlighting the last RBRACE of the function if line == block.EndLine-1 && block.EndCol == 2 { break } var hl string switch { case block.Count == 0: hl = "GoCoverMiss" case block.Count-block.NumStmt == 0: hl = "GoCoverPartial" default: hl = "GoCoverHit" } if !highlighted[line] { c.Batch.AddBufferHighlight(b, 0, hl, line, 0, -1, &res) highlighted[line] = true } } } } } return errors.WithStack(c.Batch.Execute()) }
// Copied and modified from sigar_linux.go. package gosigar import ( "io/ioutil" "runtime" "strconv" "strings" "unsafe" ) /* #include <sys/param.h> #include <sys/mount.h> #include <sys/ucred.h> #include <sys/types.h> #include <sys/sysctl.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <time.h> */ import "C" func init() { system.ticks = uint64(C.sysconf(C._SC_CLK_TCK)) Procd = "/compat/linux/proc" getLinuxBootTime() } func getMountTableFileName() string { return Procd + "/mtab" } func (self *Uptime) Get() error { ts := C.struct_timespec{} if _, err := C.clock_gettime(C.CLOCK_UPTIME, &ts); err != nil { return err } self.Length = float64(ts.tv_sec) + 1e-9*float64(ts.tv_nsec) return nil } func (self *FDUsage) Get() error { val := C.uint32_t(0) sc := C.size_t(4) name := C.CString("kern.openfiles") _, err := C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0) C.free(unsafe.Pointer(name)) if err != nil { return err } self.Open = uint64(val) name = C.CString("kern.maxfiles") _, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0) C.free(unsafe.Pointer(name)) if err != nil { return err } self.Max = uint64(val) self.Unused = self.Max - self.Open return nil } func (self *ProcFDUsage) Get(pid int) error { err := readFile("/proc/"+strconv.Itoa(pid)+"/rlimit", func(line string) bool { if strings.HasPrefix(line, "nofile") { fields := strings.Fields(line) if len(fields) == 3 { self.SoftLimit, _ = strconv.ParseUint(fields[1], 10, 64) self.HardLimit, _ = strconv.ParseUint(fields[2], 10, 64) } return false } return true }) if err != nil { return err } // linprocfs only provides this information for this process (self). fds, err := ioutil.ReadDir(procFileName(pid, "fd")) if err != nil { return err } self.Open = uint64(len(fds)) return nil } func parseCpuStat(self *Cpu, line string) error { fields := strings.Fields(line) self.User, _ = strtoull(fields[1]) self.Nice, _ = strtoull(fields[2]) self.Sys, _ = strtoull(fields[3]) self.Idle, _ = strtoull(fields[4]) return nil } func (self *ProcTime) Get(pid int) error { return ErrNotImplemented{runtime.GOOS} } Use the common version of Get(pid) (#91) // Copied and modified from sigar_linux.go. package gosigar import ( "io/ioutil" "strconv" "strings" "unsafe" ) /* #include <sys/param.h> #include <sys/mount.h> #include <sys/ucred.h> #include <sys/types.h> #include <sys/sysctl.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <time.h> */ import "C" func init() { system.ticks = uint64(C.sysconf(C._SC_CLK_TCK)) Procd = "/compat/linux/proc" getLinuxBootTime() } func getMountTableFileName() string { return Procd + "/mtab" } func (self *Uptime) Get() error { ts := C.struct_timespec{} if _, err := C.clock_gettime(C.CLOCK_UPTIME, &ts); err != nil { return err } self.Length = float64(ts.tv_sec) + 1e-9*float64(ts.tv_nsec) return nil } func (self *FDUsage) Get() error { val := C.uint32_t(0) sc := C.size_t(4) name := C.CString("kern.openfiles") _, err := C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0) C.free(unsafe.Pointer(name)) if err != nil { return err } self.Open = uint64(val) name = C.CString("kern.maxfiles") _, err = C.sysctlbyname(name, unsafe.Pointer(&val), &sc, nil, 0) C.free(unsafe.Pointer(name)) if err != nil { return err } self.Max = uint64(val) self.Unused = self.Max - self.Open return nil } func (self *ProcFDUsage) Get(pid int) error { err := readFile("/proc/"+strconv.Itoa(pid)+"/rlimit", func(line string) bool { if strings.HasPrefix(line, "nofile") { fields := strings.Fields(line) if len(fields) == 3 { self.SoftLimit, _ = strconv.ParseUint(fields[1], 10, 64) self.HardLimit, _ = strconv.ParseUint(fields[2], 10, 64) } return false } return true }) if err != nil { return err } // linprocfs only provides this information for this process (self). fds, err := ioutil.ReadDir(procFileName(pid, "fd")) if err != nil { return err } self.Open = uint64(len(fds)) return nil } func parseCpuStat(self *Cpu, line string) error { fields := strings.Fields(line) self.User, _ = strtoull(fields[1]) self.Nice, _ = strtoull(fields[2]) self.Sys, _ = strtoull(fields[3]) self.Idle, _ = strtoull(fields[4]) return nil }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // Contributor: Julien Vehent jvehent@mozilla.com [:ulfr] package signer // import "go.mozilla.org/autograph/signer" import ( "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/base64" "encoding/pem" "fmt" "io" "math/big" "regexp" "strings" "time" "go.mozilla.org/autograph/database" "github.com/DataDog/datadog-go/statsd" "github.com/ThalesIgnite/crypto11" "github.com/miekg/pkcs11" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) // IDFormat is a regex for the format IDs must follow const IDFormat = `^[a-zA-Z0-9-_]{1,64}$` // RSACacheConfig is a config for the RSAKeyCache type RSACacheConfig struct { // NumKeys is the number of RSA keys matching the issuer size // to cache NumKeys uint64 // NumGenerators is the number of key generator workers to run // that populate the RSA key cache NumGenerators uint8 // GeneratorSleepDuration is how frequently each cache key // generator tries to add a key to the cache chan GeneratorSleepDuration time.Duration // FetchTimeout is how long a consumer waits for the cache // before generating its own key FetchTimeout time.Duration // StatsSampleRate is how frequently the monitor reports the // cache size and capacity StatsSampleRate time.Duration } // RecommendationConfig is a config for the XPI recommendation file type RecommendationConfig struct { // AllowedStates is a map of strings the signer is allowed to // set in the recommendations file to true indicating whether // they're allowed or not AllowedStates map[string]bool `yaml:"states,omitempty"` // FilePath is the path in the XPI to save the recommendations // file FilePath string `yaml:"path,omitempty"` // ValidityRelativeStart is when to set the recommendation // validity not_before relative to now ValidityRelativeStart time.Duration `yaml:"relative_start,omitempty"` // ValidityDuration is when to set the recommendation validity // not_after relative to now // // i.e. // ValidityRelativeStart ValidityDuration // <----------------------> <-------------------> // | | | // not_before now / signing TS not_after ValidityDuration time.Duration `yaml:"duration,omitempty"` } // Configuration defines the parameters of a signer type Configuration struct { ID string `json:"id"` Type string `json:"type"` Mode string `json:"mode"` PrivateKey string `json:"privatekey,omitempty"` PublicKey string `json:"publickey,omitempty"` IssuerPrivKey string `json:"issuerprivkey,omitempty"` IssuerCert string `json:"issuercert,omitempty"` Certificate string `json:"certificate,omitempty"` DB *database.Handler `json:"-"` // X5U (X.509 URL) is a URL that points to an X.509 public key // certificate chain to validate a content signature X5U string `json:"x5u,omitempty"` // RSACacheConfig for XPI signers this specifies config for an // RSA cache RSACacheConfig RSACacheConfig `json:"rsacacheconfig,omitempty"` // RecommendationConfig specifies config values for // recommendations files for XPI signers RecommendationConfig RecommendationConfig `yaml:"recommendation,omitempty"` // NoPKCS7SignedAttributes for signing legacy APKs don't sign // attributes and use a legacy PKCS7 digest NoPKCS7SignedAttributes bool `json:"nopkcs7signedattributes,omitempty"` // KeyID is the fingerprint of the gpg key or subkey to use // e.g. 0xA2B637F535A86009 for the gpg2 signer type KeyID string `json:"keyid,omitempty"` // Passphrase is the optional passphrase to use decrypt the // gpg secret key for the gpg2 signer type Passphrase string `json:"passphrase,omitempty"` // Validity is the lifetime of a end-entity certificate Validity time.Duration `json:"validity,omitempty"` // ClockSkewTolerance increase the lifetime of a certificate // to account for clients with skewed clocks by adding days // to the notbefore and notafter values. For example, a certificate // with a validity of 30d and a clock skew tolerance of 10 days will // have a total validity of 10+30+10=50 days. ClockSkewTolerance time.Duration `json:"clock_skew_tolerance,omitempty"` // ChainUploadLocation is the target a certificate chain should be // uploaded to in order for clients to find it at the x5u location. ChainUploadLocation string `json:"chain_upload_location,omitempty"` // CaCert is the certificate of the root of the pki, when used CaCert string `json:"cacert,omitempty"` // Hash is a hash algorithm like 'sha1' or 'sha256' Hash string `json:"hash,omitempty"` // SaltLength controls the length of the salt used in a RSA PSS // signature. It can either be a number of bytes, or one of the special // PSSSaltLength constants from the rsa package. SaltLength int `json:"saltlength,omitempty"` // SignerOpts contains options for signing with a Signer SignerOpts crypto.SignerOpts `json:"signer_opts,omitempty"` isHsmAvailable bool hsmCtx *pkcs11.Ctx } // InitHSM indicates that an HSM has been initialized func (cfg *Configuration) InitHSM(ctx *pkcs11.Ctx) { cfg.isHsmAvailable = true cfg.hsmCtx = ctx } // Signer is an interface to a configurable issuer of digital signatures type Signer interface { Config() Configuration } // StatefulSigner is an interface to an issuer of digital signatures // that stores out of memory state (files, HSM or DB connections, // etc.) to clean up at exit type StatefulSigner interface { AtExit() error } // HashSigner is an interface to a signer able to sign hashes type HashSigner interface { SignHash(data []byte, options interface{}) (Signature, error) GetDefaultOptions() interface{} } // DataSigner is an interface to a signer able to sign raw data type DataSigner interface { SignData(data []byte, options interface{}) (Signature, error) GetDefaultOptions() interface{} } // FileSigner is an interface to a signer able to sign files type FileSigner interface { SignFile(file []byte, options interface{}) (SignedFile, error) GetDefaultOptions() interface{} } // Signature is an interface to a digital signature type Signature interface { Marshal() (signature string, err error) } // SignedFile is an []bytes that contains file data type SignedFile []byte // GetKeysAndRand parses a configuration to retrieve the private and public key // of a signer, as well as a RNG and a marshalled public key. It knows to handle // HSMs as needed, and thus removes that complexity from individual signers. func (cfg *Configuration) GetKeysAndRand() (priv crypto.PrivateKey, pub crypto.PublicKey, rng io.Reader, publicKey string, err error) { priv, err = cfg.GetPrivateKey() if err != nil { return } var ( publicKeyBytes []byte unmarshaledPub crypto.PublicKey ) switch privateKey := priv.(type) { case *rsa.PrivateKey: pub = privateKey.Public() unmarshaledPub = &privateKey.PublicKey rng = rand.Reader case *ecdsa.PrivateKey: pub = privateKey.Public() unmarshaledPub = &privateKey.PublicKey rng = rand.Reader case *crypto11.PKCS11PrivateKeyECDSA: pub = privateKey.Public() unmarshaledPub = privateKey.PubKey.(*ecdsa.PublicKey) rng = new(crypto11.PKCS11RandReader) case *crypto11.PKCS11PrivateKeyRSA: pub = privateKey.Public() unmarshaledPub = privateKey.PubKey.(*rsa.PublicKey) rng = new(crypto11.PKCS11RandReader) default: err = errors.Errorf("unsupported private key type %T", priv) return } publicKeyBytes, err = x509.MarshalPKIXPublicKey(unmarshaledPub) if err != nil { err = errors.Wrap(err, "failed to asn1 marshal %T public key") return } publicKey = base64.StdEncoding.EncodeToString(publicKeyBytes) return } // GetPrivateKey uses a signer configuration to determine where a private // key should be accessed from. If it is in local configuration, it will // be parsed and loaded in the signer. If it is in an HSM, it will be // used via a PKCS11 interface. This is completely transparent to the // caller, who should simply assume that the privatekey implements a // crypto.Sign interface // // Note that we assume the PKCS11 library has been previously initialized func (cfg *Configuration) GetPrivateKey() (crypto.PrivateKey, error) { cfg.PrivateKey = removePrivateKeyNewlines(cfg.PrivateKey) if cfg.PrivateKeyHasPEMPrefix() { return ParsePrivateKey([]byte(cfg.PrivateKey)) } // otherwise, we assume the privatekey represents a label in the HSM if cfg.isHsmAvailable { key, err := crypto11.FindKeyPair(nil, []byte(cfg.PrivateKey)) if err != nil { return nil, err } return key, nil } return nil, fmt.Errorf("no suitable key found") } // ParsePrivateKey takes a PEM blocks are returns a crypto.PrivateKey // It tries to parse as many known key types as possible before failing and // returning all the errors it encountered. func ParsePrivateKey(keyPEMBlock []byte) (key crypto.PrivateKey, err error) { var ( keyDERBlock *pem.Block skippedBlockTypes []string ) for { keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) if keyDERBlock == nil { if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { return nil, errors.New("signer: found a certificate rather than a key in the PEM for the private key") } return nil, fmt.Errorf("signer: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes) } if strings.HasSuffix(keyDERBlock.Type, "PRIVATE KEY") { break } skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) } // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. // Code taken from the crypto/tls standard library. if key, err = x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } var savedErr []string savedErr = append(savedErr, "pkcs1: "+err.Error()) if key, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes); err == nil { switch key := key.(type) { case *rsa.PrivateKey, *ecdsa.PrivateKey: return key, nil } } savedErr = append(savedErr, "pkcs8: "+err.Error()) if key, err = x509.ParseECPrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } savedErr = append(savedErr, "ecdsa: "+err.Error()) if key, err = parseDSAPKCS8PrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } savedErr = append(savedErr, "dsa: "+err.Error()) return nil, errors.New("failed to parse private key, make sure to use PKCS1 for RSA and PKCS8 for (EC)DSA. errors: " + strings.Join(savedErr, ";;; ")) } // parseDSAPKCS8PrivateKey returns a DSA private key from its ASN.1 DER encoding func parseDSAPKCS8PrivateKey(der []byte) (*dsa.PrivateKey, error) { var k struct { Version int Algo pkix.AlgorithmIdentifier Priv []byte } rest, err := asn1.Unmarshal(der, &k) if err != nil { return nil, err } if len(rest) > 0 { return nil, errors.New("garbage after DSA key") } var params dsa.Parameters _, err = asn1.Unmarshal(k.Algo.Parameters.FullBytes, &params) if err != nil { return nil, err } // FIXME: couldn't get asn1.Unmarshal to properly parse the OCTET STRING // tag in front of the X value of the DSA key, but doing it manually by // stripping off the first two bytes and loading it as a bigint works if len(k.Priv) < 22 { return nil, errors.New("DSA key is too short") } x := new(big.Int).SetBytes(k.Priv[2:]) return &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: params.P, Q: params.Q, G: params.G, }, }, X: x, }, nil } func removePrivateKeyNewlines(confPrivateKey string) string { // make sure heading newlines are removed removeNewlines := regexp.MustCompile(`^(\r?\n)`) return removeNewlines.ReplaceAllString(confPrivateKey, "") } // PrivateKeyHasPEMPrefix returns whether the signer configuration // prefix begins with `-----BEGIN` (indicating a PEM block) after // stripping newlines func (cfg *Configuration) PrivateKeyHasPEMPrefix() bool { // if a private key in the config starts with a PEM header, it is // defined locally and is parsed and returned return strings.HasPrefix(removePrivateKeyNewlines(cfg.PrivateKey), "-----BEGIN") } // CheckHSMConnection is the default implementation of // CheckHSMConnection (exposed via the signer.Configuration // interface). It tried to fetch the signer private key and errors if // that fails or the private key is not an HSM key handle. func (cfg *Configuration) CheckHSMConnection() error { if cfg.PrivateKeyHasPEMPrefix() { return errors.Errorf("private key for signer %s has a PEM prefix and is not an HSM key label", cfg.ID) } if !cfg.isHsmAvailable { return errors.Errorf("HSM is not available for signer %s", cfg.ID) } privKey, err := cfg.GetPrivateKey() if err != nil { return errors.Wrapf(err, "error fetching private key for signer %s", cfg.ID) } // returns 0 if the key is not stored in the hsm if GetPrivKeyHandle(privKey) != 0 { return nil } return errors.Errorf("Unable to check HSM connection for signer %s private key is not stored in the HSM", cfg.ID) } // MakeKey generates a new key of type keyTpl and returns the priv and public interfaces. // If an HSM is available, it is used to generate and store the key, in which case 'priv' // just points to the HSM handler and must be used via the crypto.Signer interface. func (cfg *Configuration) MakeKey(keyTpl interface{}, keyName string) (priv crypto.PrivateKey, pub crypto.PublicKey, err error) { if cfg.isHsmAvailable { var slots []uint slots, err = cfg.hsmCtx.GetSlotList(true) if err != nil { return nil, nil, errors.Wrap(err, "failed to list PKCS#11 Slots") } if len(slots) < 1 { return nil, nil, errors.New("failed to find a usable slot in hsm context") } keyNameBytes := []byte(keyName) switch keyTplType := keyTpl.(type) { case *ecdsa.PublicKey: priv, err = crypto11.GenerateECDSAKeyPairOnSlot(slots[0], keyNameBytes, keyNameBytes, keyTplType) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate ecdsa key in hsm") } pub = priv.(*crypto11.PKCS11PrivateKeyECDSA).PubKey.(*ecdsa.PublicKey) return case *rsa.PublicKey: keySize := keyTplType.Size() priv, err = crypto11.GenerateRSAKeyPairOnSlot(slots[0], keyNameBytes, keyNameBytes, keySize) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate rsa key in hsm") } pub = priv.(*crypto11.PKCS11PrivateKeyRSA).PubKey.(*rsa.PublicKey) return default: return nil, nil, errors.Errorf("making key of type %T is not supported", keyTpl) } } // no hsm, make keys in memory switch keyTplType := keyTpl.(type) { case *ecdsa.PublicKey: switch keyTplType.Params().Name { case "P-256": priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case "P-384": priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) default: return nil, nil, fmt.Errorf("unsupported curve %q", keyTpl.(*ecdsa.PublicKey).Params().Name) } if err != nil { return nil, nil, errors.Wrap(err, "failed to generate ecdsa key in memory") } pub = priv.(*ecdsa.PrivateKey).Public() return case *rsa.PublicKey: keySize := keyTplType.Size() priv, err = rsa.GenerateKey(rand.Reader, keySize) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate rsa key in memory") } pub = priv.(*rsa.PrivateKey).Public() return default: return nil, nil, errors.Errorf("making key of type %T is not supported", keyTpl) } } // GetPrivKeyHandle returns the hsm handler object id of a key stored in the hsm, // or 0 if the key is not stored in the hsm func GetPrivKeyHandle(priv crypto.PrivateKey) uint { switch priv.(type) { case *crypto11.PKCS11PrivateKeyECDSA: return uint(priv.(*crypto11.PKCS11PrivateKeyECDSA).Handle) case *crypto11.PKCS11PrivateKeyRSA: return uint(priv.(*crypto11.PKCS11PrivateKeyRSA).Handle) } return 0 } // StatsClient is a helper for sending statsd stats with the relevant // tags for the signer and error handling type StatsClient struct { // signerTags is the signerTags []string // stats is the statsd client for reporting metrics stats *statsd.Client } // NewStatsClient makes a new stats client func NewStatsClient(signerConfig Configuration, stats *statsd.Client) (*StatsClient, error) { if stats == nil { return nil, errors.Errorf("xpi: statsd client is nil. Could not create StatsClient for signer %s", signerConfig.ID) } return &StatsClient{ stats: stats, signerTags: []string{ fmt.Sprintf("autograph-signer-id:%s", signerConfig.ID), fmt.Sprintf("autograph-signer-type:%s", signerConfig.Type), fmt.Sprintf("autograph-signer-mode:%s", signerConfig.Mode), }, }, nil } // SendGauge checks for a statsd client and when one is present sends // a statsd gauge with the given name, int value cast to float64, tags // for the signer, and sampling rate of 1 func (s *StatsClient) SendGauge(name string, value int) { if s.stats == nil { log.Warnf("xpi: statsd client is nil. Could not send gauge %s with value %v", name, value) return } err := s.stats.Gauge(name, float64(value), s.signerTags, 1) if err != nil { log.Warnf("Error sending gauge %s: %s", name, err) } } // SendHistogram checks for a statsd client and when one is present // sends a statsd histogram with the given name, time.Duration value // converted to ms, cast to float64, tags for the signer, and sampling // rate of 1 func (s *StatsClient) SendHistogram(name string, value time.Duration) { if s.stats == nil { log.Warnf("xpi: statsd client is nil. Could not send histogram %s with value %s", name, value) return } err := s.stats.Histogram(name, float64(value/time.Millisecond), s.signerTags, 1) if err != nil { log.Warnf("Error sending histogram %s: %s", name, err) } } signer: use HSM RNG when available i.e. not based on private key type // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // Contributor: Julien Vehent jvehent@mozilla.com [:ulfr] package signer // import "go.mozilla.org/autograph/signer" import ( "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/base64" "encoding/pem" "fmt" "io" "math/big" "regexp" "strings" "time" "go.mozilla.org/autograph/database" "github.com/DataDog/datadog-go/statsd" "github.com/ThalesIgnite/crypto11" "github.com/miekg/pkcs11" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) // IDFormat is a regex for the format IDs must follow const IDFormat = `^[a-zA-Z0-9-_]{1,64}$` // RSACacheConfig is a config for the RSAKeyCache type RSACacheConfig struct { // NumKeys is the number of RSA keys matching the issuer size // to cache NumKeys uint64 // NumGenerators is the number of key generator workers to run // that populate the RSA key cache NumGenerators uint8 // GeneratorSleepDuration is how frequently each cache key // generator tries to add a key to the cache chan GeneratorSleepDuration time.Duration // FetchTimeout is how long a consumer waits for the cache // before generating its own key FetchTimeout time.Duration // StatsSampleRate is how frequently the monitor reports the // cache size and capacity StatsSampleRate time.Duration } // RecommendationConfig is a config for the XPI recommendation file type RecommendationConfig struct { // AllowedStates is a map of strings the signer is allowed to // set in the recommendations file to true indicating whether // they're allowed or not AllowedStates map[string]bool `yaml:"states,omitempty"` // FilePath is the path in the XPI to save the recommendations // file FilePath string `yaml:"path,omitempty"` // ValidityRelativeStart is when to set the recommendation // validity not_before relative to now ValidityRelativeStart time.Duration `yaml:"relative_start,omitempty"` // ValidityDuration is when to set the recommendation validity // not_after relative to now // // i.e. // ValidityRelativeStart ValidityDuration // <----------------------> <-------------------> // | | | // not_before now / signing TS not_after ValidityDuration time.Duration `yaml:"duration,omitempty"` } // Configuration defines the parameters of a signer type Configuration struct { ID string `json:"id"` Type string `json:"type"` Mode string `json:"mode"` PrivateKey string `json:"privatekey,omitempty"` PublicKey string `json:"publickey,omitempty"` IssuerPrivKey string `json:"issuerprivkey,omitempty"` IssuerCert string `json:"issuercert,omitempty"` Certificate string `json:"certificate,omitempty"` DB *database.Handler `json:"-"` // X5U (X.509 URL) is a URL that points to an X.509 public key // certificate chain to validate a content signature X5U string `json:"x5u,omitempty"` // RSACacheConfig for XPI signers this specifies config for an // RSA cache RSACacheConfig RSACacheConfig `json:"rsacacheconfig,omitempty"` // RecommendationConfig specifies config values for // recommendations files for XPI signers RecommendationConfig RecommendationConfig `yaml:"recommendation,omitempty"` // NoPKCS7SignedAttributes for signing legacy APKs don't sign // attributes and use a legacy PKCS7 digest NoPKCS7SignedAttributes bool `json:"nopkcs7signedattributes,omitempty"` // KeyID is the fingerprint of the gpg key or subkey to use // e.g. 0xA2B637F535A86009 for the gpg2 signer type KeyID string `json:"keyid,omitempty"` // Passphrase is the optional passphrase to use decrypt the // gpg secret key for the gpg2 signer type Passphrase string `json:"passphrase,omitempty"` // Validity is the lifetime of a end-entity certificate Validity time.Duration `json:"validity,omitempty"` // ClockSkewTolerance increase the lifetime of a certificate // to account for clients with skewed clocks by adding days // to the notbefore and notafter values. For example, a certificate // with a validity of 30d and a clock skew tolerance of 10 days will // have a total validity of 10+30+10=50 days. ClockSkewTolerance time.Duration `json:"clock_skew_tolerance,omitempty"` // ChainUploadLocation is the target a certificate chain should be // uploaded to in order for clients to find it at the x5u location. ChainUploadLocation string `json:"chain_upload_location,omitempty"` // CaCert is the certificate of the root of the pki, when used CaCert string `json:"cacert,omitempty"` // Hash is a hash algorithm like 'sha1' or 'sha256' Hash string `json:"hash,omitempty"` // SaltLength controls the length of the salt used in a RSA PSS // signature. It can either be a number of bytes, or one of the special // PSSSaltLength constants from the rsa package. SaltLength int `json:"saltlength,omitempty"` // SignerOpts contains options for signing with a Signer SignerOpts crypto.SignerOpts `json:"signer_opts,omitempty"` isHsmAvailable bool hsmCtx *pkcs11.Ctx } // InitHSM indicates that an HSM has been initialized func (cfg *Configuration) InitHSM(ctx *pkcs11.Ctx) { cfg.isHsmAvailable = true cfg.hsmCtx = ctx } // Signer is an interface to a configurable issuer of digital signatures type Signer interface { Config() Configuration } // StatefulSigner is an interface to an issuer of digital signatures // that stores out of memory state (files, HSM or DB connections, // etc.) to clean up at exit type StatefulSigner interface { AtExit() error } // HashSigner is an interface to a signer able to sign hashes type HashSigner interface { SignHash(data []byte, options interface{}) (Signature, error) GetDefaultOptions() interface{} } // DataSigner is an interface to a signer able to sign raw data type DataSigner interface { SignData(data []byte, options interface{}) (Signature, error) GetDefaultOptions() interface{} } // FileSigner is an interface to a signer able to sign files type FileSigner interface { SignFile(file []byte, options interface{}) (SignedFile, error) GetDefaultOptions() interface{} } // Signature is an interface to a digital signature type Signature interface { Marshal() (signature string, err error) } // SignedFile is an []bytes that contains file data type SignedFile []byte // GetRand returns a cryptographically secure random number from the // HSM if available and otherwise rand.Reader func (cfg *Configuration) GetRand() io.Reader { if cfg.isHsmAvailable { return new(crypto11.PKCS11RandReader) } return rand.Reader } // GetKeysAndRand parses a configuration to retrieve the private and public key // of a signer, as well as a RNG and a marshalled public key. It knows to handle // HSMs as needed, and thus removes that complexity from individual signers. func (cfg *Configuration) GetKeysAndRand() (priv crypto.PrivateKey, pub crypto.PublicKey, rng io.Reader, publicKey string, err error) { priv, err = cfg.GetPrivateKey() if err != nil { return } var ( publicKeyBytes []byte unmarshaledPub crypto.PublicKey ) rng = cfg.GetRand() switch privateKey := priv.(type) { case *rsa.PrivateKey: pub = privateKey.Public() unmarshaledPub = &privateKey.PublicKey case *ecdsa.PrivateKey: pub = privateKey.Public() unmarshaledPub = &privateKey.PublicKey case *crypto11.PKCS11PrivateKeyECDSA: pub = privateKey.Public() unmarshaledPub = privateKey.PubKey.(*ecdsa.PublicKey) case *crypto11.PKCS11PrivateKeyRSA: pub = privateKey.Public() unmarshaledPub = privateKey.PubKey.(*rsa.PublicKey) default: err = errors.Errorf("unsupported private key type %T", priv) return } publicKeyBytes, err = x509.MarshalPKIXPublicKey(unmarshaledPub) if err != nil { err = errors.Wrap(err, "failed to asn1 marshal %T public key") return } publicKey = base64.StdEncoding.EncodeToString(publicKeyBytes) return } // GetPrivateKey uses a signer configuration to determine where a private // key should be accessed from. If it is in local configuration, it will // be parsed and loaded in the signer. If it is in an HSM, it will be // used via a PKCS11 interface. This is completely transparent to the // caller, who should simply assume that the privatekey implements a // crypto.Sign interface // // Note that we assume the PKCS11 library has been previously initialized func (cfg *Configuration) GetPrivateKey() (crypto.PrivateKey, error) { cfg.PrivateKey = removePrivateKeyNewlines(cfg.PrivateKey) if cfg.PrivateKeyHasPEMPrefix() { return ParsePrivateKey([]byte(cfg.PrivateKey)) } // otherwise, we assume the privatekey represents a label in the HSM if cfg.isHsmAvailable { key, err := crypto11.FindKeyPair(nil, []byte(cfg.PrivateKey)) if err != nil { return nil, err } return key, nil } return nil, fmt.Errorf("no suitable key found") } // ParsePrivateKey takes a PEM blocks are returns a crypto.PrivateKey // It tries to parse as many known key types as possible before failing and // returning all the errors it encountered. func ParsePrivateKey(keyPEMBlock []byte) (key crypto.PrivateKey, err error) { var ( keyDERBlock *pem.Block skippedBlockTypes []string ) for { keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) if keyDERBlock == nil { if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { return nil, errors.New("signer: found a certificate rather than a key in the PEM for the private key") } return nil, fmt.Errorf("signer: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes) } if strings.HasSuffix(keyDERBlock.Type, "PRIVATE KEY") { break } skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) } // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. // Code taken from the crypto/tls standard library. if key, err = x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } var savedErr []string savedErr = append(savedErr, "pkcs1: "+err.Error()) if key, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes); err == nil { switch key := key.(type) { case *rsa.PrivateKey, *ecdsa.PrivateKey: return key, nil } } savedErr = append(savedErr, "pkcs8: "+err.Error()) if key, err = x509.ParseECPrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } savedErr = append(savedErr, "ecdsa: "+err.Error()) if key, err = parseDSAPKCS8PrivateKey(keyDERBlock.Bytes); err == nil { return key, nil } savedErr = append(savedErr, "dsa: "+err.Error()) return nil, errors.New("failed to parse private key, make sure to use PKCS1 for RSA and PKCS8 for (EC)DSA. errors: " + strings.Join(savedErr, ";;; ")) } // parseDSAPKCS8PrivateKey returns a DSA private key from its ASN.1 DER encoding func parseDSAPKCS8PrivateKey(der []byte) (*dsa.PrivateKey, error) { var k struct { Version int Algo pkix.AlgorithmIdentifier Priv []byte } rest, err := asn1.Unmarshal(der, &k) if err != nil { return nil, err } if len(rest) > 0 { return nil, errors.New("garbage after DSA key") } var params dsa.Parameters _, err = asn1.Unmarshal(k.Algo.Parameters.FullBytes, &params) if err != nil { return nil, err } // FIXME: couldn't get asn1.Unmarshal to properly parse the OCTET STRING // tag in front of the X value of the DSA key, but doing it manually by // stripping off the first two bytes and loading it as a bigint works if len(k.Priv) < 22 { return nil, errors.New("DSA key is too short") } x := new(big.Int).SetBytes(k.Priv[2:]) return &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: params.P, Q: params.Q, G: params.G, }, }, X: x, }, nil } func removePrivateKeyNewlines(confPrivateKey string) string { // make sure heading newlines are removed removeNewlines := regexp.MustCompile(`^(\r?\n)`) return removeNewlines.ReplaceAllString(confPrivateKey, "") } // PrivateKeyHasPEMPrefix returns whether the signer configuration // prefix begins with `-----BEGIN` (indicating a PEM block) after // stripping newlines func (cfg *Configuration) PrivateKeyHasPEMPrefix() bool { // if a private key in the config starts with a PEM header, it is // defined locally and is parsed and returned return strings.HasPrefix(removePrivateKeyNewlines(cfg.PrivateKey), "-----BEGIN") } // CheckHSMConnection is the default implementation of // CheckHSMConnection (exposed via the signer.Configuration // interface). It tried to fetch the signer private key and errors if // that fails or the private key is not an HSM key handle. func (cfg *Configuration) CheckHSMConnection() error { if cfg.PrivateKeyHasPEMPrefix() { return errors.Errorf("private key for signer %s has a PEM prefix and is not an HSM key label", cfg.ID) } if !cfg.isHsmAvailable { return errors.Errorf("HSM is not available for signer %s", cfg.ID) } privKey, err := cfg.GetPrivateKey() if err != nil { return errors.Wrapf(err, "error fetching private key for signer %s", cfg.ID) } // returns 0 if the key is not stored in the hsm if GetPrivKeyHandle(privKey) != 0 { return nil } return errors.Errorf("Unable to check HSM connection for signer %s private key is not stored in the HSM", cfg.ID) } // MakeKey generates a new key of type keyTpl and returns the priv and public interfaces. // If an HSM is available, it is used to generate and store the key, in which case 'priv' // just points to the HSM handler and must be used via the crypto.Signer interface. func (cfg *Configuration) MakeKey(keyTpl interface{}, keyName string) (priv crypto.PrivateKey, pub crypto.PublicKey, err error) { if cfg.isHsmAvailable { var slots []uint slots, err = cfg.hsmCtx.GetSlotList(true) if err != nil { return nil, nil, errors.Wrap(err, "failed to list PKCS#11 Slots") } if len(slots) < 1 { return nil, nil, errors.New("failed to find a usable slot in hsm context") } keyNameBytes := []byte(keyName) switch keyTplType := keyTpl.(type) { case *ecdsa.PublicKey: priv, err = crypto11.GenerateECDSAKeyPairOnSlot(slots[0], keyNameBytes, keyNameBytes, keyTplType) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate ecdsa key in hsm") } pub = priv.(*crypto11.PKCS11PrivateKeyECDSA).PubKey.(*ecdsa.PublicKey) return case *rsa.PublicKey: keySize := keyTplType.Size() priv, err = crypto11.GenerateRSAKeyPairOnSlot(slots[0], keyNameBytes, keyNameBytes, keySize) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate rsa key in hsm") } pub = priv.(*crypto11.PKCS11PrivateKeyRSA).PubKey.(*rsa.PublicKey) return default: return nil, nil, errors.Errorf("making key of type %T is not supported", keyTpl) } } // no hsm, make keys in memory switch keyTplType := keyTpl.(type) { case *ecdsa.PublicKey: switch keyTplType.Params().Name { case "P-256": priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case "P-384": priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) default: return nil, nil, fmt.Errorf("unsupported curve %q", keyTpl.(*ecdsa.PublicKey).Params().Name) } if err != nil { return nil, nil, errors.Wrap(err, "failed to generate ecdsa key in memory") } pub = priv.(*ecdsa.PrivateKey).Public() return case *rsa.PublicKey: keySize := keyTplType.Size() priv, err = rsa.GenerateKey(rand.Reader, keySize) if err != nil { return nil, nil, errors.Wrap(err, "failed to generate rsa key in memory") } pub = priv.(*rsa.PrivateKey).Public() return default: return nil, nil, errors.Errorf("making key of type %T is not supported", keyTpl) } } // GetPrivKeyHandle returns the hsm handler object id of a key stored in the hsm, // or 0 if the key is not stored in the hsm func GetPrivKeyHandle(priv crypto.PrivateKey) uint { switch priv.(type) { case *crypto11.PKCS11PrivateKeyECDSA: return uint(priv.(*crypto11.PKCS11PrivateKeyECDSA).Handle) case *crypto11.PKCS11PrivateKeyRSA: return uint(priv.(*crypto11.PKCS11PrivateKeyRSA).Handle) } return 0 } // StatsClient is a helper for sending statsd stats with the relevant // tags for the signer and error handling type StatsClient struct { // signerTags is the signerTags []string // stats is the statsd client for reporting metrics stats *statsd.Client } // NewStatsClient makes a new stats client func NewStatsClient(signerConfig Configuration, stats *statsd.Client) (*StatsClient, error) { if stats == nil { return nil, errors.Errorf("xpi: statsd client is nil. Could not create StatsClient for signer %s", signerConfig.ID) } return &StatsClient{ stats: stats, signerTags: []string{ fmt.Sprintf("autograph-signer-id:%s", signerConfig.ID), fmt.Sprintf("autograph-signer-type:%s", signerConfig.Type), fmt.Sprintf("autograph-signer-mode:%s", signerConfig.Mode), }, }, nil } // SendGauge checks for a statsd client and when one is present sends // a statsd gauge with the given name, int value cast to float64, tags // for the signer, and sampling rate of 1 func (s *StatsClient) SendGauge(name string, value int) { if s.stats == nil { log.Warnf("xpi: statsd client is nil. Could not send gauge %s with value %v", name, value) return } err := s.stats.Gauge(name, float64(value), s.signerTags, 1) if err != nil { log.Warnf("Error sending gauge %s: %s", name, err) } } // SendHistogram checks for a statsd client and when one is present // sends a statsd histogram with the given name, time.Duration value // converted to ms, cast to float64, tags for the signer, and sampling // rate of 1 func (s *StatsClient) SendHistogram(name string, value time.Duration) { if s.stats == nil { log.Warnf("xpi: statsd client is nil. Could not send histogram %s with value %s", name, value) return } err := s.stats.Histogram(name, float64(value/time.Millisecond), s.signerTags, 1) if err != nil { log.Warnf("Error sending histogram %s: %s", name, err) } }
package genericoauth_test import ( "net/http" "code.cloudfoundry.org/lager/lagertest" "golang.org/x/oauth2" "github.com/concourse/atc/auth/genericoauth" "github.com/concourse/atc/auth/provider" "github.com/concourse/atc/db" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Generic OAuth Provider", func() { var ( dbGenericOAuth *db.GenericOAuth redirectURI string goaProvider provider.Provider state string ) JustBeforeEach(func() { goaProvider = genericoauth.NewProvider(dbGenericOAuth, redirectURI) }) BeforeEach(func() { dbGenericOAuth = &db.GenericOAuth{} redirectURI = "redirect-uri" state = "some-random-guid" }) It("constructs HTTP client with disable keep alive context", func() { httpClient := goaProvider.PreTokenClient() Expect(httpClient).NotTo(BeNil()) Expect(httpClient.Transport).NotTo(BeNil()) Expect(httpClient.Transport.(*http.Transport).DisableKeepAlives).To(BeTrue()) }) It("constructs the Auth URL with the redirect uri", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("redirect_uri=redirect-uri")) }) It("constructs the Auth URL with the state param", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("state=some-random-guid")) }) It("doesn't do any user authorization", func() { verifyResult, err := goaProvider.Verify(lagertest.NewTestLogger("test"), nil) Expect(err).ToNot(HaveOccurred()) Expect(verifyResult).To(Equal(true)) }) Context("DisplayName is configured", func() { BeforeEach(func() { dbGenericOAuth = &db.GenericOAuth{DisplayName: "Cyborgs"} }) It("uses the configured DisplayName instead of the provider name", func() { displayName := goaProvider.DisplayName() Expect(displayName).To(Equal("Cyborgs")) Expect(genericoauth.ProviderName).ToNot(Equal("Cyborgs")) }) }) Context("Auth URL params are configured", func() { BeforeEach(func() { redirectURI = "redirect-uri" dbGenericOAuth = &db.GenericOAuth{ AuthURLParams: map[string]string{"param1": "value1", "param2": "value2"}, } }) It("constructs the Auth URL with the configured Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("param1=value1")) Expect(authURI).To(ContainSubstring("param2=value2")) }) It("merges the passed in Auth URL params with the configured Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("param3", "value3")}...) Expect(authURI).To(ContainSubstring("param1=value1")) Expect(authURI).To(ContainSubstring("param2=value2")) Expect(authURI).To(ContainSubstring("param3=value3")) }) It("URL encodes the Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("question#1", "are your tests passing?")}...) Expect(authURI).To(ContainSubstring("question%231=are+your+tests+passing%3F")) }) }) }) Fixed generic oauth provider test and removed display name test The display name test is covered by the api get auth methods test package genericoauth_test import ( "net/http" "code.cloudfoundry.org/lager/lagertest" "golang.org/x/oauth2" "github.com/concourse/atc/auth/genericoauth" "github.com/concourse/atc/auth/provider" "github.com/concourse/atc/db" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Generic OAuth Provider", func() { var ( dbGenericOAuth *db.GenericOAuth redirectURI string goaProvider provider.Provider state string ) JustBeforeEach(func() { goaProvider = genericoauth.NewProvider(dbGenericOAuth, redirectURI) }) BeforeEach(func() { dbGenericOAuth = &db.GenericOAuth{} redirectURI = "redirect-uri" state = "some-random-guid" }) It("constructs HTTP client with disable keep alive context", func() { httpClient, err := goaProvider.PreTokenClient() Expect(httpClient).NotTo(BeNil()) Expect(httpClient.Transport).NotTo(BeNil()) Expect(httpClient.Transport.(*http.Transport).DisableKeepAlives).To(BeTrue()) Expect(err).NotTo(HaveOccurred()) }) It("constructs the Auth URL with the redirect uri", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("redirect_uri=redirect-uri")) }) It("constructs the Auth URL with the state param", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("state=some-random-guid")) }) It("doesn't do any user authorization", func() { verifyResult, err := goaProvider.Verify(lagertest.NewTestLogger("test"), nil) Expect(err).ToNot(HaveOccurred()) Expect(verifyResult).To(Equal(true)) }) Context("Auth URL params are configured", func() { BeforeEach(func() { redirectURI = "redirect-uri" dbGenericOAuth = &db.GenericOAuth{ AuthURLParams: map[string]string{"param1": "value1", "param2": "value2"}, } }) It("constructs the Auth URL with the configured Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{}...) Expect(authURI).To(ContainSubstring("param1=value1")) Expect(authURI).To(ContainSubstring("param2=value2")) }) It("merges the passed in Auth URL params with the configured Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("param3", "value3")}...) Expect(authURI).To(ContainSubstring("param1=value1")) Expect(authURI).To(ContainSubstring("param2=value2")) Expect(authURI).To(ContainSubstring("param3=value3")) }) It("URL encodes the Auth URL params", func() { authURI := goaProvider.AuthCodeURL(state, []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("question#1", "are your tests passing?")}...) Expect(authURI).To(ContainSubstring("question%231=are+your+tests+passing%3F")) }) }) })
/* dnsserver.go * * Copyright (C) 2016 Alexandre ACEBEDO * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package servers import ( "errors" "fmt" "github.com/aacebedo/dnsdock/src/utils" "github.com/miekg/dns" "net" "regexp" "strings" "sync" "time" ) // Service represents a container and an attached DNS record type Service struct { Name string Image string IPs []net.IP TTL int Aliases []string } // NewService creates a new service func NewService() (s *Service) { s = &Service{TTL: -1} return } func (s Service) String() string { return fmt.Sprintf(` Name: %s Aliases: %s IPs: %s TTL: %d `, s.Name, s.Aliases, s.IPs, s.TTL) } // ServiceListProvider represents the entrypoint to get containers type ServiceListProvider interface { AddService(string, Service) RemoveService(string) error GetService(string) (Service, error) GetAllServices() map[string]Service } // DNSServer represents a DNS server type DNSServer struct { config *utils.Config server *dns.Server mux *dns.ServeMux services map[string]*Service lock *sync.RWMutex } // NewDNSServer create a new DNSServer func NewDNSServer(c *utils.Config) *DNSServer { s := &DNSServer{ config: c, services: make(map[string]*Service), lock: &sync.RWMutex{}, } logger.Debugf("Handling DNS requests for '%s'.", c.Domain.String()) s.mux = dns.NewServeMux() s.mux.HandleFunc(c.Domain.String()+".", s.handleRequest) s.mux.HandleFunc("in-addr.arpa.", s.handleReverseRequest) s.mux.HandleFunc(".", s.handleForward) s.server = &dns.Server{Addr: c.DnsAddr, Net: "udp", Handler: s.mux} return s } // Start starts the DNSServer func (s *DNSServer) Start() error { return s.server.ListenAndServe() } // Stop stops the DNSServer func (s *DNSServer) Stop() { s.server.Shutdown() } // AddService adds a new container and thus new DNS records func (s *DNSServer) AddService(id string, service Service) { if len(service.IPs) > 0 { defer s.lock.Unlock() s.lock.Lock() id = s.getExpandedID(id) s.services[id] = &service logger.Debugf(`Added service: '%s' %s`, id, service) for _, alias := range service.Aliases { logger.Debugf("Handling DNS requests for '%s'.", alias) s.mux.HandleFunc(alias+".", s.handleRequest) } } else { logger.Warningf("Service '%s' ignored: No IP provided:", id, id) } } // RemoveService removes a new container and thus DNS records func (s *DNSServer) RemoveService(id string) error { defer s.lock.Unlock() s.lock.Lock() id = s.getExpandedID(id) if _, ok := s.services[id]; !ok { return errors.New("No such service: " + id) } for _, alias := range s.services[id].Aliases { s.mux.HandleRemove(alias + ".") } delete(s.services, id) logger.Debugf("Removed service '%s'", id) return nil } // GetService reads a service from the repository func (s *DNSServer) GetService(id string) (Service, error) { defer s.lock.RUnlock() s.lock.RLock() id = s.getExpandedID(id) if s, ok := s.services[id]; ok { return *s, nil } // Check for a pa return *new(Service), errors.New("No such service: " + id) } // GetAllServices reads all services from the repository func (s *DNSServer) GetAllServices() map[string]Service { defer s.lock.RUnlock() s.lock.RLock() list := make(map[string]Service, len(s.services)) for id, service := range s.services { list[id] = *service } return list } func (s *DNSServer) listDomains(service *Service) chan string { c := make(chan string) go func() { if service.Image == "" { c <- service.Name + "." + s.config.Domain.String() + "." } else { domain := service.Image + "." + s.config.Domain.String() + "." c <- service.Name + "." + domain c <- domain } for _, alias := range service.Aliases { c <- alias + "." } close(c) }() return c } func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { logger.Debugf("Using DNS forwarding for '%s'", r.Question[0].Name) logger.Debugf("Forwarding DNS nameservers: %s", s.config.Nameservers.String()) // Otherwise just forward the request to another server c := new(dns.Client) // look at each Nameserver, stop on success for i := range s.config.Nameservers { logger.Debugf("Using Nameserver %s", s.config.Nameservers[i]) in, _, err := c.Exchange(r, s.config.Nameservers[i]) if err == nil { if s.config.ForceTtl { logger.Debugf("Forcing Ttl value of the forwarded response") for _, rr := range in.Answer { rr.Header().Ttl = uint32(s.config.Ttl) } } w.WriteMsg(in) return } if i == (len(s.config.Nameservers) - 1) { logger.Fatalf("DNS fowarding for '%s' failed: no more nameservers to try", err.Error()) // Send failure reply m := new(dns.Msg) m.SetReply(r) m.Ns = s.createSOA() m.SetRcode(r, dns.RcodeRefused) // REFUSED w.WriteMsg(m) } else { logger.Errorf("DNS fowarding for '%s' failed: trying next Nameserver...", err.Error()) } } } func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { rr := new(dns.A) var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ Name: n, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: uint32(ttl), } if len(service.IPs) != 0 { if len(service.IPs) > 1 { logger.Warningf("Multiple IP address found for container '%s'. Only the first address will be used", service.Name) } rr.A = service.IPs[0] } else { logger.Errorf("No valid IP address found for container '%s' ", service.Name) } return rr } func (s *DNSServer) makeServiceMX(n string, service *Service) dns.RR { rr := new(dns.MX) var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ Name: n, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: uint32(ttl), } rr.Mx = n return rr } func (s *DNSServer) handleRequest(w dns.ResponseWriter, r *dns.Msg) { m := new(dns.Msg) m.SetReply(r) m.RecursionAvailable = true // Send empty response for empty requests if len(r.Question) == 0 { m.Ns = s.createSOA() w.WriteMsg(m) return } // respond to SOA requests if r.Question[0].Qtype == dns.TypeSOA { m.Answer = s.createSOA() w.WriteMsg(m) return } m.Answer = make([]dns.RR, 0, 2) query := r.Question[0].Name // trim off any trailing dot if query[len(query)-1] == '.' { query = query[:len(query)-1] } logger.Debugf("DNS request for query '%s' from remote '%s'", query, w.RemoteAddr()) for service := range s.queryServices(query) { var rr dns.RR switch r.Question[0].Qtype { case dns.TypeA: rr = s.makeServiceA(r.Question[0].Name, service) case dns.TypeMX: rr = s.makeServiceMX(r.Question[0].Name, service) default: // this query type isn't supported, but we do have // a record with this name. Per RFC 4074 sec. 3, we // immediately return an empty NOERROR reply. m.Ns = s.createSOA() m.MsgHdr.Authoritative = true w.WriteMsg(m) return } logger.Debugf("DNS record found for query '%s'", query) m.Answer = append(m.Answer, rr) } // We didn't find a record corresponding to the query if len(m.Answer) == 0 { m.Ns = s.createSOA() m.SetRcode(r, dns.RcodeNameError) // NXDOMAIN logger.Debugf("No DNS record found for query '%s'", query) } w.WriteMsg(m) } func (s *DNSServer) handleReverseRequest(w dns.ResponseWriter, r *dns.Msg) { m := new(dns.Msg) m.SetReply(r) m.RecursionAvailable = true // Send empty response for empty requests if len(r.Question) == 0 { m.Ns = s.createSOA() w.WriteMsg(m) return } m.Answer = make([]dns.RR, 0, 2) query := r.Question[0].Name // trim off any trailing dot if query[len(query)-1] == '.' { query = query[:len(query)-1] } for service := range s.queryIP(query) { if r.Question[0].Qtype != dns.TypePTR { m.Ns = s.createSOA() w.WriteMsg(m) return } var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } for domain := range s.listDomains(service) { rr := new(dns.PTR) rr.Hdr = dns.RR_Header{ Name: r.Question[0].Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: uint32(ttl), } rr.Ptr = domain m.Answer = append(m.Answer, rr) } } if len(m.Answer) != 0 { w.WriteMsg(m) } else { // We didn't find a record corresponding to the query, // try forwarding s.handleForward(w, r) } } func (s *DNSServer) queryIP(query string) chan *Service { c := make(chan *Service, 3) reversedIP := strings.TrimSuffix(query, ".in-addr.arpa") ip := strings.Join(reverse(strings.Split(reversedIP, ".")), ".") go func() { defer s.lock.RUnlock() s.lock.RLock() for _, service := range s.services { if service.IPs[0].String() == ip { c <- service } } close(c) }() return c } func (s *DNSServer) queryServices(query string) chan *Service { c := make(chan *Service, 3) go func() { query := strings.Split(strings.ToLower(query), ".") defer s.lock.RUnlock() s.lock.RLock() for _, service := range s.services { // create the name for this service, skip empty strings test := []string{} // todo: add some cache to avoid calculating this every time if len(service.Name) > 0 { test = append(test, strings.Split(strings.ToLower(service.Name), ".")...) } if len(service.Image) > 0 { test = append(test, strings.Split(service.Image, ".")...) } test = append(test, s.config.Domain...) if isPrefixQuery(query, test) { c <- service } // check aliases for _, alias := range service.Aliases { if isPrefixQuery(query, strings.Split(alias, ".")) { c <- service } } } close(c) }() return c } // Checks for a partial match for container SHA and outputs it if found. func (s *DNSServer) getExpandedID(in string) (out string) { out = in // Hard to make a judgement on small image names. if len(in) < 4 { return } if isHex, _ := regexp.MatchString("^[0-9a-f]+$", in); !isHex { return } for id := range s.services { if len(id) == 64 { if isHex, _ := regexp.MatchString("^[0-9a-f]+$", id); isHex { if strings.HasPrefix(id, in) { out = id return } } } } return } // TTL is used from config so that not-found result responses are not cached // for a long time. The other defaults left as is(skydns source) because they // do not have an use case in this situation. func (s *DNSServer) createSOA() []dns.RR { dom := dns.Fqdn(s.config.Domain.String() + ".") soa := &dns.SOA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: uint32(s.config.Ttl)}, Ns: "dnsdock." + dom, Mbox: "dnsdock.dnsdock." + dom, Serial: uint32(time.Now().Truncate(time.Hour).Unix()), Refresh: 28800, Retry: 7200, Expire: 604800, Minttl: uint32(s.config.Ttl), } return []dns.RR{soa} } // isPrefixQuery is used to determine whether "query" is a potential prefix // query for "name". It allows for wildcards (*) in the query. However is makes // one exception to accomodate the desired behavior we wish from dnsdock, // namely, the query may be longer than "name" and still be a valid prefix // query for "name". // Examples: // foo.bar.baz.qux is a valid query for bar.baz.qux (longer prefix is okay) // foo.*.baz.qux is a valid query for bar.baz.qux (wildcards okay) // *.baz.qux is a valid query for baz.baz.qux (wildcard prefix okay) func isPrefixQuery(query, name []string) bool { for i, j := len(query)-1, len(name)-1; i >= 0 && j >= 0; i, j = i-1, j-1 { if query[i] != name[j] && query[i] != "*" { return false } } return len(name) >= len(query) } func reverse(input []string) []string { if len(input) == 0 { return input } return append(reverse(input[1:]), input[0]) } Solved #90 /* dnsserver.go * * Copyright (C) 2016 Alexandre ACEBEDO * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package servers import ( "errors" "fmt" "github.com/aacebedo/dnsdock/src/utils" "github.com/miekg/dns" "net" "regexp" "strings" "sync" "time" ) // Service represents a container and an attached DNS record type Service struct { Name string Image string IPs []net.IP TTL int Aliases []string } // NewService creates a new service func NewService() (s *Service) { s = &Service{TTL: -1} return } func (s Service) String() string { return fmt.Sprintf(` Name: %s Aliases: %s IPs: %s TTL: %d `, s.Name, s.Aliases, s.IPs, s.TTL) } // ServiceListProvider represents the entrypoint to get containers type ServiceListProvider interface { AddService(string, Service) RemoveService(string) error GetService(string) (Service, error) GetAllServices() map[string]Service } // DNSServer represents a DNS server type DNSServer struct { config *utils.Config server *dns.Server mux *dns.ServeMux services map[string]*Service lock *sync.RWMutex } // NewDNSServer create a new DNSServer func NewDNSServer(c *utils.Config) *DNSServer { s := &DNSServer{ config: c, services: make(map[string]*Service), lock: &sync.RWMutex{}, } logger.Debugf("Handling DNS requests for '%s'.", c.Domain.String()) s.mux = dns.NewServeMux() s.mux.HandleFunc(c.Domain.String()+".", s.handleRequest) s.mux.HandleFunc("in-addr.arpa.", s.handleReverseRequest) s.mux.HandleFunc(".", s.handleForward) s.server = &dns.Server{Addr: c.DnsAddr, Net: "udp", Handler: s.mux} return s } // Start starts the DNSServer func (s *DNSServer) Start() error { return s.server.ListenAndServe() } // Stop stops the DNSServer func (s *DNSServer) Stop() { s.server.Shutdown() } // AddService adds a new container and thus new DNS records func (s *DNSServer) AddService(id string, service Service) { if len(service.IPs) > 0 { defer s.lock.Unlock() s.lock.Lock() id = s.getExpandedID(id) s.services[id] = &service logger.Debugf(`Added service: '%s' %s`, id, service) for _, alias := range service.Aliases { logger.Debugf("Handling DNS requests for '%s'.", alias) s.mux.HandleFunc(alias+".", s.handleRequest) } } else { logger.Warningf("Service '%s' ignored: No IP provided:", id, id) } } // RemoveService removes a new container and thus DNS records func (s *DNSServer) RemoveService(id string) error { defer s.lock.Unlock() s.lock.Lock() id = s.getExpandedID(id) if _, ok := s.services[id]; !ok { return errors.New("No such service: " + id) } for _, alias := range s.services[id].Aliases { s.mux.HandleRemove(alias + ".") } delete(s.services, id) logger.Debugf("Removed service '%s'", id) return nil } // GetService reads a service from the repository func (s *DNSServer) GetService(id string) (Service, error) { defer s.lock.RUnlock() s.lock.RLock() id = s.getExpandedID(id) if s, ok := s.services[id]; ok { return *s, nil } // Check for a pa return *new(Service), errors.New("No such service: " + id) } // GetAllServices reads all services from the repository func (s *DNSServer) GetAllServices() map[string]Service { defer s.lock.RUnlock() s.lock.RLock() list := make(map[string]Service, len(s.services)) for id, service := range s.services { list[id] = *service } return list } func (s *DNSServer) listDomains(service *Service) chan string { c := make(chan string) go func() { if service.Image == "" { c <- service.Name + "." + s.config.Domain.String() + "." } else { domain := service.Image + "." + s.config.Domain.String() + "." c <- service.Name + "." + domain c <- domain } for _, alias := range service.Aliases { c <- alias + "." } close(c) }() return c } func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { logger.Debugf("Using DNS forwarding for '%s'", r.Question[0].Name) logger.Debugf("Forwarding DNS nameservers: %s", s.config.Nameservers.String()) // Otherwise just forward the request to another server c := new(dns.Client) // look at each Nameserver, stop on success for i := range s.config.Nameservers { logger.Debugf("Using Nameserver %s", s.config.Nameservers[i]) in, _, err := c.Exchange(r, s.config.Nameservers[i]) if err == nil { if s.config.ForceTtl { logger.Debugf("Forcing Ttl value of the forwarded response") for _, rr := range in.Answer { rr.Header().Ttl = uint32(s.config.Ttl) } } w.WriteMsg(in) return } if i == (len(s.config.Nameservers) - 1) { logger.Warningf("DNS fowarding failed: no more nameservers to try") // Send failure reply m := new(dns.Msg) m.SetReply(r) m.Ns = s.createSOA() m.SetRcode(r, dns.RcodeRefused) // REFUSED w.WriteMsg(m) } else { logger.Debugf("DNS fowarding failed: trying next Nameserver...") } } } func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { rr := new(dns.A) var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ Name: n, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: uint32(ttl), } if len(service.IPs) != 0 { if len(service.IPs) > 1 { logger.Warningf("Multiple IP address found for container '%s'. Only the first address will be used", service.Name) } rr.A = service.IPs[0] } else { logger.Errorf("No valid IP address found for container '%s' ", service.Name) } return rr } func (s *DNSServer) makeServiceMX(n string, service *Service) dns.RR { rr := new(dns.MX) var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ Name: n, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: uint32(ttl), } rr.Mx = n return rr } func (s *DNSServer) handleRequest(w dns.ResponseWriter, r *dns.Msg) { m := new(dns.Msg) m.SetReply(r) m.RecursionAvailable = true // Send empty response for empty requests if len(r.Question) == 0 { m.Ns = s.createSOA() w.WriteMsg(m) return } // respond to SOA requests if r.Question[0].Qtype == dns.TypeSOA { m.Answer = s.createSOA() w.WriteMsg(m) return } m.Answer = make([]dns.RR, 0, 2) query := r.Question[0].Name // trim off any trailing dot if query[len(query)-1] == '.' { query = query[:len(query)-1] } logger.Debugf("DNS request for query '%s' from remote '%s'", query, w.RemoteAddr()) for service := range s.queryServices(query) { var rr dns.RR switch r.Question[0].Qtype { case dns.TypeA: rr = s.makeServiceA(r.Question[0].Name, service) case dns.TypeMX: rr = s.makeServiceMX(r.Question[0].Name, service) default: // this query type isn't supported, but we do have // a record with this name. Per RFC 4074 sec. 3, we // immediately return an empty NOERROR reply. m.Ns = s.createSOA() m.MsgHdr.Authoritative = true w.WriteMsg(m) return } logger.Debugf("DNS record found for query '%s'", query) m.Answer = append(m.Answer, rr) } // We didn't find a record corresponding to the query if len(m.Answer) == 0 { m.Ns = s.createSOA() m.SetRcode(r, dns.RcodeNameError) // NXDOMAIN logger.Debugf("No DNS record found for query '%s'", query) } w.WriteMsg(m) } func (s *DNSServer) handleReverseRequest(w dns.ResponseWriter, r *dns.Msg) { m := new(dns.Msg) m.SetReply(r) m.RecursionAvailable = true // Send empty response for empty requests if len(r.Question) == 0 { m.Ns = s.createSOA() w.WriteMsg(m) return } m.Answer = make([]dns.RR, 0, 2) query := r.Question[0].Name // trim off any trailing dot if query[len(query)-1] == '.' { query = query[:len(query)-1] } for service := range s.queryIP(query) { if r.Question[0].Qtype != dns.TypePTR { m.Ns = s.createSOA() w.WriteMsg(m) return } var ttl int if service.TTL != -1 { ttl = service.TTL } else { ttl = s.config.Ttl } for domain := range s.listDomains(service) { rr := new(dns.PTR) rr.Hdr = dns.RR_Header{ Name: r.Question[0].Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: uint32(ttl), } rr.Ptr = domain m.Answer = append(m.Answer, rr) } } if len(m.Answer) != 0 { w.WriteMsg(m) } else { // We didn't find a record corresponding to the query, // try forwarding s.handleForward(w, r) } } func (s *DNSServer) queryIP(query string) chan *Service { c := make(chan *Service, 3) reversedIP := strings.TrimSuffix(query, ".in-addr.arpa") ip := strings.Join(reverse(strings.Split(reversedIP, ".")), ".") go func() { defer s.lock.RUnlock() s.lock.RLock() for _, service := range s.services { if service.IPs[0].String() == ip { c <- service } } close(c) }() return c } func (s *DNSServer) queryServices(query string) chan *Service { c := make(chan *Service, 3) go func() { query := strings.Split(strings.ToLower(query), ".") defer s.lock.RUnlock() s.lock.RLock() for _, service := range s.services { // create the name for this service, skip empty strings test := []string{} // todo: add some cache to avoid calculating this every time if len(service.Name) > 0 { test = append(test, strings.Split(strings.ToLower(service.Name), ".")...) } if len(service.Image) > 0 { test = append(test, strings.Split(service.Image, ".")...) } test = append(test, s.config.Domain...) if isPrefixQuery(query, test) { c <- service } // check aliases for _, alias := range service.Aliases { if isPrefixQuery(query, strings.Split(alias, ".")) { c <- service } } } close(c) }() return c } // Checks for a partial match for container SHA and outputs it if found. func (s *DNSServer) getExpandedID(in string) (out string) { out = in // Hard to make a judgement on small image names. if len(in) < 4 { return } if isHex, _ := regexp.MatchString("^[0-9a-f]+$", in); !isHex { return } for id := range s.services { if len(id) == 64 { if isHex, _ := regexp.MatchString("^[0-9a-f]+$", id); isHex { if strings.HasPrefix(id, in) { out = id return } } } } return } // TTL is used from config so that not-found result responses are not cached // for a long time. The other defaults left as is(skydns source) because they // do not have an use case in this situation. func (s *DNSServer) createSOA() []dns.RR { dom := dns.Fqdn(s.config.Domain.String() + ".") soa := &dns.SOA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: uint32(s.config.Ttl)}, Ns: "dnsdock." + dom, Mbox: "dnsdock.dnsdock." + dom, Serial: uint32(time.Now().Truncate(time.Hour).Unix()), Refresh: 28800, Retry: 7200, Expire: 604800, Minttl: uint32(s.config.Ttl), } return []dns.RR{soa} } // isPrefixQuery is used to determine whether "query" is a potential prefix // query for "name". It allows for wildcards (*) in the query. However is makes // one exception to accomodate the desired behavior we wish from dnsdock, // namely, the query may be longer than "name" and still be a valid prefix // query for "name". // Examples: // foo.bar.baz.qux is a valid query for bar.baz.qux (longer prefix is okay) // foo.*.baz.qux is a valid query for bar.baz.qux (wildcards okay) // *.baz.qux is a valid query for baz.baz.qux (wildcard prefix okay) func isPrefixQuery(query, name []string) bool { for i, j := len(query)-1, len(name)-1; i >= 0 && j >= 0; i, j = i-1, j-1 { if query[i] != name[j] && query[i] != "*" { return false } } return len(name) >= len(query) } func reverse(input []string) []string { if len(input) == 0 { return input } return append(reverse(input[1:]), input[0]) }
package web import ( "encoding/json" "fmt" "net/http" "net/url" "sort" "strconv" "strings" "github.com/MiniProfiler/go/miniprofiler" "github.com/StackExchange/scollector/opentsdb" ) func Query(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) { ts := make(opentsdb.TagSet) tags := strings.Split(r.FormValue("tags"), ",") for i := 0; i < len(tags); i += 2 { if i+1 < len(tags) { ts[tags[i]] = tags[i+1] } } var oro opentsdb.RateOptions oro.Counter = r.FormValue("counter") == "true" if r.FormValue("cmax") != "" { cmax, err := strconv.Atoi(r.FormValue("cmax")) if err != nil { serveError(w, err) } oro.CounterMax = cmax } if r.FormValue("creset") != "" { creset, err := strconv.Atoi(r.FormValue("creset")) if err != nil { serveError(w, err) } oro.ResetValue = creset } oq := opentsdb.Query{ Aggregator: r.FormValue("aggregator"), Metric: r.FormValue("metric"), Tags: ts, Rate: r.FormValue("rate") == "true", Downsample: r.FormValue("downsample"), RateOptions: oro, } oreq := opentsdb.Request{ Start: r.FormValue("start"), End: r.FormValue("end"), Queries: []*opentsdb.Query{&oq}, } var err error var tr opentsdb.ResponseSet q, _ := url.QueryUnescape(oreq.String()) t.StepCustomTiming("tsdb", "query", q, func() { tr, err = tsdbHost.Query(oreq) }) if err != nil { serveError(w, err) return } qr, err := rickchart(tr) if err != nil { serveError(w, err) return } b, err := json.Marshal(qr) if err != nil { serveError(w, err) return } w.Write(b) } func rickchart(r opentsdb.ResponseSet) ([]*RickSeries, error) { //This currently does a mod operation to limit DPs returned to 3000, will want to refactor this //into something smarter max_dp := 3000 series := make([]*RickSeries, len(r)) for i, resp := range r { dps_mod := 1 if len(resp.DPS) > max_dp { dps_mod = (len(resp.DPS) + max_dp) / max_dp } dps := make([]RickDP, 0) j := 0 for k, v := range resp.DPS { if j%dps_mod == 0 { ki, err := strconv.ParseInt(k, 10, 64) if err != nil { return nil, err } dps = append(dps, RickDP{ X: ki, Y: v, }) } j += 1 } sort.Sort(ByX(dps)) var id []string for k, v := range resp.Tags { id = append(id, fmt.Sprintf("%v=%v", k, v)) } series[i] = &RickSeries{ Name: strings.Join(id, ","), Data: dps, } } return series, nil } type RickSeries struct { Name string `json:"name"` Data []RickDP `json:"data"` } type RickDP struct { X int64 `json:"x"` Y opentsdb.Point `json:"y"` } type ByX []RickDP func (a ByX) Len() int { return len(a) } func (a ByX) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByX) Less(i, j int) bool { return a[i].X < a[j].X } Richshaw needs series to have series data. So we don't add it unless there are datapoints. package web import ( "encoding/json" "fmt" "net/http" "net/url" "sort" "strconv" "strings" "github.com/MiniProfiler/go/miniprofiler" "github.com/StackExchange/scollector/opentsdb" ) func Query(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) { ts := make(opentsdb.TagSet) tags := strings.Split(r.FormValue("tags"), ",") for i := 0; i < len(tags); i += 2 { if i+1 < len(tags) { ts[tags[i]] = tags[i+1] } } var oro opentsdb.RateOptions oro.Counter = r.FormValue("counter") == "true" if r.FormValue("cmax") != "" { cmax, err := strconv.Atoi(r.FormValue("cmax")) if err != nil { serveError(w, err) } oro.CounterMax = cmax } if r.FormValue("creset") != "" { creset, err := strconv.Atoi(r.FormValue("creset")) if err != nil { serveError(w, err) } oro.ResetValue = creset } oq := opentsdb.Query{ Aggregator: r.FormValue("aggregator"), Metric: r.FormValue("metric"), Tags: ts, Rate: r.FormValue("rate") == "true", Downsample: r.FormValue("downsample"), RateOptions: oro, } oreq := opentsdb.Request{ Start: r.FormValue("start"), End: r.FormValue("end"), Queries: []*opentsdb.Query{&oq}, } var err error var tr opentsdb.ResponseSet q, _ := url.QueryUnescape(oreq.String()) t.StepCustomTiming("tsdb", "query", q, func() { tr, err = tsdbHost.Query(oreq) }) if err != nil { serveError(w, err) return } qr, err := rickchart(tr) if err != nil { serveError(w, err) return } b, err := json.Marshal(qr) if err != nil { serveError(w, err) return } w.Write(b) } func rickchart(r opentsdb.ResponseSet) ([]*RickSeries, error) { //This currently does a mod operation to limit DPs returned to 3000, will want to refactor this //into something smarter max_dp := 3000 var series []*RickSeries for _, resp := range r { dps_mod := 1 if len(resp.DPS) > max_dp { dps_mod = (len(resp.DPS) + max_dp) / max_dp } dps := make([]RickDP, 0) j := 0 for k, v := range resp.DPS { if j%dps_mod == 0 { ki, err := strconv.ParseInt(k, 10, 64) if err != nil { return nil, err } dps = append(dps, RickDP{ X: ki, Y: v, }) } j += 1 } sort.Sort(ByX(dps)) var id []string for k, v := range resp.Tags { id = append(id, fmt.Sprintf("%v=%v", k, v)) } if len(dps) > 0 { series = append(series, &RickSeries{ Name: strings.Join(id, ","), Data: dps, }) } } return series, nil } type RickSeries struct { Name string `json:"name"` Data []RickDP `json:"data"` } type RickDP struct { X int64 `json:"x"` Y opentsdb.Point `json:"y"` } type ByX []RickDP func (a ByX) Len() int { return len(a) } func (a ByX) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByX) Less(i, j int) bool { return a[i].X < a[j].X }
// The MIT License (MIT) // // Copyright (c) 2016 Alexey Derbyshev // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package ugo // ChainWrapper is the special struct, // containing resulting and middleware data type ChainWrapper struct { Mid Seq // Mid is for middleware calculations Res Object // Res if for resulting data } func (wrapper *ChainWrapper) Each(cb Action) *ChainWrapper { Each(wrapper.Mid, cb) return wrapper } func (wrapper *ChainWrapper) ForEach(cb Action) *ChainWrapper { return wrapper.Each(cb) } func (wrapper *ChainWrapper) Map(cb Callback) *ChainWrapper { wrapper.Mid = Map(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Collect(cb Callback) *ChainWrapper { return wrapper.Map(cb) } func (wrapper *ChainWrapper) Filter(cb Predicate) *ChainWrapper { wrapper.Mid = Filter(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Select(cb Predicate) *ChainWrapper { return wrapper.Filter(cb) } func (wrapper *ChainWrapper) Reject(cb Predicate) *ChainWrapper { wrapper.Mid = Reject(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Reduce(cb Collector, initial Object) *ChainWrapper { wrapper.Res = Reduce(wrapper.Mid, cb, initial) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Inject(cb Collector, initial Object) *ChainWrapper { return wrapper.Reduce(cb, initial) } func (wrapper *ChainWrapper) FoldL(cb Collector, initial Object) *ChainWrapper { return wrapper.Reduce(cb, initial) } func (wrapper *ChainWrapper) ReduceRight(cb Collector, initial Object) *ChainWrapper { wrapper.Res = ReduceRight(wrapper.Mid, cb, initial) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) FoldR(cb Collector, initial Object) *ChainWrapper { return wrapper.ReduceRight(cb, initial) } func (wrapper *ChainWrapper) Min(cb Comparator) *ChainWrapper { wrapper.Res = Min(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Max(cb Comparator) *ChainWrapper { wrapper.Res = Max(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Find(cb Predicate) *ChainWrapper { wrapper.Res = Find(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Detect(cb Predicate) *ChainWrapper { return wrapper.Find(cb) } func (wrapper *ChainWrapper) FindLast(cb Predicate) *ChainWrapper { wrapper.Res = FindLast(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) FindIndex(cb Predicate) *ChainWrapper { wrapper.Res = FindIndex(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) FindLastIndex(cb Predicate) *ChainWrapper { wrapper.Res = FindLastIndex(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Some(cb Predicate) *ChainWrapper { wrapper.Res = Some(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Any(cb Predicate) *ChainWrapper { return wrapper.Some(cb) } func (wrapper *ChainWrapper) IndexOf(target Object, isSorted bool, cb Comparator) *ChainWrapper { wrapper.Res = IndexOf(wrapper.Mid, target, isSorted, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) LastIndexOf(target Object, cb Comparator) *ChainWrapper { wrapper.Res = LastIndexOf(wrapper.Mid, target, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Contains(target Object, isSorted bool, cb Comparator) *ChainWrapper { wrapper.Res = Contains(wrapper.Mid, target, isSorted, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Includes(target Object, isSorted bool, cb Comparator) *ChainWrapper { return wrapper.Contains(target, isSorted, cb) } func (wrapper *ChainWrapper) Every(cb Predicate) *ChainWrapper { wrapper.Res = Every(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) All(cb Predicate) *ChainWrapper { return wrapper.Every(cb) } func (wrapper *ChainWrapper) Uniq(cb Comparator) *ChainWrapper { wrapper.Mid = Uniq(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Unique(cb Comparator) *ChainWrapper { return wrapper.Uniq(cb) } func (wrapper *ChainWrapper) Difference(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Difference(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Without(nonGrata Object, cb Comparator) *ChainWrapper { wrapper.Mid = Without(wrapper.Mid, nonGrata, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Intersection(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Intersection(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Union(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Union(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) SortBy(cb Comparator) *ChainWrapper { wrapper.Mid = SortBy(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) CountBy(cb Callback) *ChainWrapper { wrapper.Res = CountBy(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) GroupBy(cb Callback) *ChainWrapper { wrapper.Res = GroupBy(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Remove(pos int) *ChainWrapper { wrapper.Mid = Remove(wrapper.Mid, pos) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Insert(tg Object, pos int) *ChainWrapper { wrapper.Mid = Insert(wrapper.Mid, tg, pos) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Concat(next Seq) *ChainWrapper { wrapper.Mid = Concat(wrapper.Mid, next) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Shuffle() *ChainWrapper { wrapper.Mid = ShuffledCopy(wrapper.Mid) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) Reverse() *ChainWrapper { wrapper.Mid = ReversedCopy(wrapper.Mid) wrapper.Res = wrapper.Mid return wrapper } func (wrapper *ChainWrapper) EqualsStrict(other Seq, cb Comparator) *ChainWrapper { wrapper.Res = EqualsStrict(wrapper.Mid, other, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) EqualsNotStrict(other Seq, cb Comparator) *ChainWrapper { wrapper.Res = EqualsNotStrict(wrapper.Mid, other, cb) wrapper.Mid = nil return wrapper } func (wrapper *ChainWrapper) Value() Object { return wrapper.Res } Added comments for chaining wrapper methods // The MIT License (MIT) // // Copyright (c) 2016 Alexey Derbyshev // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package ugo // ChainWrapper is the special struct, // containing resulting and middleware data type ChainWrapper struct { Mid Seq // Mid is for middleware calculations Res Object // Res if for resulting data } // Each is a chaining wrapper for #Each func (wrapper *ChainWrapper) Each(cb Action) *ChainWrapper { Each(wrapper.Mid, cb) return wrapper } // ForEach is a chaining wrapper for #ForEach func (wrapper *ChainWrapper) ForEach(cb Action) *ChainWrapper { return wrapper.Each(cb) } // Map is a chaining wrapper for #Map func (wrapper *ChainWrapper) Map(cb Callback) *ChainWrapper { wrapper.Mid = Map(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } // Collect is a chaining wrapper for #Collect func (wrapper *ChainWrapper) Collect(cb Callback) *ChainWrapper { return wrapper.Map(cb) } // Filter is a chaining wrapper for #Filter func (wrapper *ChainWrapper) Filter(cb Predicate) *ChainWrapper { wrapper.Mid = Filter(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } // Select is a chaining wrapper for #Select func (wrapper *ChainWrapper) Select(cb Predicate) *ChainWrapper { return wrapper.Filter(cb) } // Reject is a chaining wrapper for #Reject func (wrapper *ChainWrapper) Reject(cb Predicate) *ChainWrapper { wrapper.Mid = Reject(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } // Reduce is a chaining wrapper for #Reduce func (wrapper *ChainWrapper) Reduce(cb Collector, initial Object) *ChainWrapper { wrapper.Res = Reduce(wrapper.Mid, cb, initial) wrapper.Mid = nil return wrapper } // Inject is a chaining wrapper for #Inject func (wrapper *ChainWrapper) Inject(cb Collector, initial Object) *ChainWrapper { return wrapper.Reduce(cb, initial) } // FoldL is a chaining wrapper for #FoldL func (wrapper *ChainWrapper) FoldL(cb Collector, initial Object) *ChainWrapper { return wrapper.Reduce(cb, initial) } // ReduceRight is a chaining wrapper for #ReduceRight func (wrapper *ChainWrapper) ReduceRight(cb Collector, initial Object) *ChainWrapper { wrapper.Res = ReduceRight(wrapper.Mid, cb, initial) wrapper.Mid = nil return wrapper } // FoldR is a chaining wrapper for #FoldR func (wrapper *ChainWrapper) FoldR(cb Collector, initial Object) *ChainWrapper { return wrapper.ReduceRight(cb, initial) } // Min is a chaining wrapper for #Min func (wrapper *ChainWrapper) Min(cb Comparator) *ChainWrapper { wrapper.Res = Min(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Max is a chaining wrapper for #Max func (wrapper *ChainWrapper) Max(cb Comparator) *ChainWrapper { wrapper.Res = Max(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Find is a chaining wrapper for #Find func (wrapper *ChainWrapper) Find(cb Predicate) *ChainWrapper { wrapper.Res = Find(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Detect is a chaining wrapper for #Detect func (wrapper *ChainWrapper) Detect(cb Predicate) *ChainWrapper { return wrapper.Find(cb) } // FindLast is a chaining wrapper for #FindLast func (wrapper *ChainWrapper) FindLast(cb Predicate) *ChainWrapper { wrapper.Res = FindLast(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // FindIndex is a chaining wrapper for #FindIndex func (wrapper *ChainWrapper) FindIndex(cb Predicate) *ChainWrapper { wrapper.Res = FindIndex(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // FindLastIndex is a chaining wrapper for #FindLastIndex func (wrapper *ChainWrapper) FindLastIndex(cb Predicate) *ChainWrapper { wrapper.Res = FindLastIndex(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Some is a chaining wrapper for #Some func (wrapper *ChainWrapper) Some(cb Predicate) *ChainWrapper { wrapper.Res = Some(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Any is a chaining wrapper for #Any func (wrapper *ChainWrapper) Any(cb Predicate) *ChainWrapper { return wrapper.Some(cb) } // IndexOf is a chaining wrapper for #IndexOf func (wrapper *ChainWrapper) IndexOf(target Object, isSorted bool, cb Comparator) *ChainWrapper { wrapper.Res = IndexOf(wrapper.Mid, target, isSorted, cb) wrapper.Mid = nil return wrapper } // LastIndexOf is a chaining wrapper for #LastIndexOf func (wrapper *ChainWrapper) LastIndexOf(target Object, cb Comparator) *ChainWrapper { wrapper.Res = LastIndexOf(wrapper.Mid, target, cb) wrapper.Mid = nil return wrapper } // Contains is a chaining wrapper for #Contains func (wrapper *ChainWrapper) Contains(target Object, isSorted bool, cb Comparator) *ChainWrapper { wrapper.Res = Contains(wrapper.Mid, target, isSorted, cb) wrapper.Mid = nil return wrapper } // Includes is a chaining wrapper for #Includes func (wrapper *ChainWrapper) Includes(target Object, isSorted bool, cb Comparator) *ChainWrapper { return wrapper.Contains(target, isSorted, cb) } // Every is a chaining wrapper for #Every func (wrapper *ChainWrapper) Every(cb Predicate) *ChainWrapper { wrapper.Res = Every(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // All is a chaining wrapper for #All func (wrapper *ChainWrapper) All(cb Predicate) *ChainWrapper { return wrapper.Every(cb) } // Uniq is a chaining wrapper for #Uniq func (wrapper *ChainWrapper) Uniq(cb Comparator) *ChainWrapper { wrapper.Mid = Uniq(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } // Unique is a chaining wrapper for #Unique func (wrapper *ChainWrapper) Unique(cb Comparator) *ChainWrapper { return wrapper.Uniq(cb) } // Differenc is a chaining wrapper for #Differenc func (wrapper *ChainWrapper) Difference(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Difference(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } // Without is a chaining wrapper for #Without func (wrapper *ChainWrapper) Without(nonGrata Object, cb Comparator) *ChainWrapper { wrapper.Mid = Without(wrapper.Mid, nonGrata, cb) wrapper.Res = wrapper.Mid return wrapper } // Intersection is a chaining wrapper for #Intersection func (wrapper *ChainWrapper) Intersection(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Intersection(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } // Union is a chaining wrapper for #Union func (wrapper *ChainWrapper) Union(other Seq, cb Comparator) *ChainWrapper { wrapper.Mid = Union(wrapper.Mid, other, cb) wrapper.Res = wrapper.Mid return wrapper } // SortBy is a chaining wrapper for #SortBy func (wrapper *ChainWrapper) SortBy(cb Comparator) *ChainWrapper { wrapper.Mid = SortBy(wrapper.Mid, cb) wrapper.Res = wrapper.Mid return wrapper } // CountBy is a chaining wrapper for #CountBy func (wrapper *ChainWrapper) CountBy(cb Callback) *ChainWrapper { wrapper.Res = CountBy(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // GroupBy is a chaining wrapper for #GroupBy func (wrapper *ChainWrapper) GroupBy(cb Callback) *ChainWrapper { wrapper.Res = GroupBy(wrapper.Mid, cb) wrapper.Mid = nil return wrapper } // Remove is a chaining wrapper for #Remove func (wrapper *ChainWrapper) Remove(pos int) *ChainWrapper { wrapper.Mid = Remove(wrapper.Mid, pos) wrapper.Res = wrapper.Mid return wrapper } // Insert is a chaining wrapper for #Insert func (wrapper *ChainWrapper) Insert(tg Object, pos int) *ChainWrapper { wrapper.Mid = Insert(wrapper.Mid, tg, pos) wrapper.Res = wrapper.Mid return wrapper } // Concat is a chaining wrapper for #Concat func (wrapper *ChainWrapper) Concat(next Seq) *ChainWrapper { wrapper.Mid = Concat(wrapper.Mid, next) wrapper.Res = wrapper.Mid return wrapper } // Shuffle is a chaining wrapper for #Shuffle func (wrapper *ChainWrapper) Shuffle() *ChainWrapper { wrapper.Mid = ShuffledCopy(wrapper.Mid) wrapper.Res = wrapper.Mid return wrapper } // Reverse is a chaining wrapper for #Reverse func (wrapper *ChainWrapper) Reverse() *ChainWrapper { wrapper.Mid = ReversedCopy(wrapper.Mid) wrapper.Res = wrapper.Mid return wrapper } // EqualsStrict is a chaining wrapper for #EqualsStrict func (wrapper *ChainWrapper) EqualsStrict(other Seq, cb Comparator) *ChainWrapper { wrapper.Res = EqualsStrict(wrapper.Mid, other, cb) wrapper.Mid = nil return wrapper } // EqualsNotStrict is a chaining wrapper for #EqualsNotStrict func (wrapper *ChainWrapper) EqualsNotStrict(other Seq, cb Comparator) *ChainWrapper { wrapper.Res = EqualsNotStrict(wrapper.Mid, other, cb) wrapper.Mid = nil return wrapper } // Value returns result of calculations, you've done through chaining calls func (wrapper *ChainWrapper) Value() Object { return wrapper.Res }
package main import ( "sync" ) type Backends struct { Length int current int Addresses []string sync.Mutex } func NewBackends() *Backends { addresses := []string{} current := 0 length := 0 return &Backends{ Length: length, current: current, Addresses: addresses, } } func (self *Backends) NextAddress() (addess string) { self.Lock() index := self.current self.current = self.current + 1 if self.current > self.Length -1 { self.current = 0 } self.Unlock() return self.Addresses[index] } func (self *Backends) Add(addresses ...string) { self.Lock() for _, item := range addresses { self.Addresses = append(self.Addresses, item) } self.Length = len(self.Addresses) self.Unlock() } ran goimports package main import ( "sync" ) type Backends struct { Length int current int Addresses []string sync.Mutex } func NewBackends() *Backends { addresses := []string{} current := 0 length := 0 return &Backends{ Length: length, current: current, Addresses: addresses, } } func (self *Backends) NextAddress() (addess string) { self.Lock() index := self.current self.current = self.current + 1 if self.current > self.Length-1 { self.current = 0 } self.Unlock() return self.Addresses[index] } func (self *Backends) Add(addresses ...string) { self.Lock() for _, item := range addresses { self.Addresses = append(self.Addresses, item) } self.Length = len(self.Addresses) self.Unlock() }
package gitstats import ( "fmt" "log" "time" "github.com/google/go-github/github" "github.com/intelsdi-x/snap/control/plugin" "github.com/intelsdi-x/snap/control/plugin/cpolicy" "github.com/intelsdi-x/snap/core" "github.com/intelsdi-x/snap/core/ctypes" "golang.org/x/oauth2" ) const ( // Name of plugin Name = "rt-gitstats" // Version of plugin Version = 1 // Type of plugin Type = plugin.CollectorPluginType ) // make sure that we actually satisify requierd interface var _ plugin.CollectorPlugin = (*Gitstats)(nil) var ( repoMetricNames = []string{ "forks", "issues", "network", "stars", "subscribers", "watches", "size", } userMetricNames = []string{ "public_repos", "public_gists", "followers", "following", "private_repos", "private_gists", "plan_private_repos", "plan_seats", "plan_filled_seats", } ) type Gitstats struct { } // CollectMetrics collects metrics for testing func (f *Gitstats) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) { var err error conf := mts[0].Config().Table() log.Printf("%v", conf) accessToken, ok := conf["access_token"] if !ok || accessToken.(ctypes.ConfigValueStr).Value == "" { return nil, fmt.Errorf("access token missing from config, %v", conf) } owner, ok := conf["owner"] if !ok || owner.(ctypes.ConfigValueStr).Value == "" { return nil, fmt.Errorf("owner missing from config") } repo, ok := conf["repo"] if !ok || repo.(ctypes.ConfigValueStr).Value == "" { return nil, fmt.Errorf("repo missing from config") } metrics, err := gitStats(accessToken.(ctypes.ConfigValueStr).Value, owner.(ctypes.ConfigValueStr).Value, repo.(ctypes.ConfigValueStr).Value, mts) if err != nil { return nil, err } log.Printf("fetched %d metrics for repo %s/%s", len(metrics), owner.(ctypes.ConfigValueStr).Value, repo.(ctypes.ConfigValueStr).Value) return metrics, nil } func gitStats(accessToken, owner, repo string, mts []plugin.MetricType) ([]plugin.MetricType, error) { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: accessToken}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) client := github.NewClient(tc) repoStats, err := getRepo(client, owner, repo) if err != nil { return nil, err } userStats, err := getUser(client, owner) if err != nil { return nil, err } metrics := make([]plugin.MetricType, 0) for _, m := range mts { stat := m.Namespace()[6].Value if value, ok := repoStats[stat]; ok { mt := plugin.MetricType{ Data_: value, Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", owner, repo, stat), Timestamp_: time.Now(), Version_: m.Version(), } metrics = append(metrics, mt) } if value, ok := userStats[stat]; ok { mt := plugin.MetricType{ Data_: value, Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "owner", owner, stat), Timestamp_: time.Now(), Version_: m.Version(), } metrics = append(metrics, mt) } } return metrics, nil } func getUser(client *github.Client, owner string) (map[string]int, error) { //get contributor stats, then traverse and count. https://api.github.com/repos/openstack/nova/stats/contributors user, _, err := client.Users.Get(owner) if err != nil { return nil, err } stats := make(map[string]int) if user.PublicRepos != nil { stats["public_repos"] = *user.PublicRepos } if user.PublicGists != nil { stats["public_gists"] = *user.PublicGists } if user.Followers != nil { stats["followers"] = *user.Followers } if user.Following != nil { stats["following"] = *user.Following } if *user.Type == "Organization" { org, _, err := client.Organizations.Get(owner) if err != nil { return nil, err } if org.PrivateGists != nil { stats["private_gists"] = *org.PrivateGists } if org.TotalPrivateRepos != nil { stats["private_repos"] = *org.TotalPrivateRepos } if org.DiskUsage != nil { stats["disk_usage"] = *org.DiskUsage } } return stats, nil } func getRepo(client *github.Client, owner, repo string) (map[string]int, error) { resp, _, err := client.Repositories.Get(owner, repo) if err != nil { return nil, err } stats := make(map[string]int) if resp.ForksCount != nil { stats["forks"] = *resp.ForksCount } if resp.OpenIssuesCount != nil { stats["issues"] = *resp.OpenIssuesCount } if resp.NetworkCount != nil { stats["network"] = *resp.NetworkCount } if resp.StargazersCount != nil { stats["stars"] = *resp.StargazersCount } if resp.SubscribersCount != nil { stats["subcribers"] = *resp.SubscribersCount } if resp.WatchersCount != nil { stats["watchers"] = *resp.WatchersCount } if resp.Size != nil { stats["size"] = *resp.Size } return stats, nil } //GetMetricTypes returns metric types for testing func (f *Gitstats) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) { mts := []plugin.MetricType{} for _, metricName := range repoMetricNames { mts = append(mts, plugin.MetricType{ Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", "*", "*", metricName), Config_: cfg.ConfigDataNode, }) } for _, metricName := range userMetricNames { mts = append(mts, plugin.MetricType{ Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", "*", "*", metricName), Config_: cfg.ConfigDataNode, }) } return mts, nil } //GetConfigPolicy returns a ConfigPolicyTree for testing func (f *Gitstats) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { c := cpolicy.New() rule, _ := cpolicy.NewStringRule("access_token", true) rule2, _ := cpolicy.NewStringRule("owner", true) rule3, _ := cpolicy.NewStringRule("repo", true) p := cpolicy.NewPolicyNode() p.Add(rule) p.Add(rule2) p.Add(rule3) c.Add([]string{"raintank", "apps", "gitstats"}, p) return c, nil } //Meta returns meta data for testing func Meta() *plugin.PluginMeta { return plugin.NewPluginMeta( Name, Version, Type, []string{plugin.SnapGOBContentType}, []string{plugin.SnapGOBContentType}, plugin.Unsecure(true), plugin.ConcurrencyCount(1000), ) } make repo name optional. package gitstats import ( "fmt" "log" "time" "github.com/google/go-github/github" "github.com/intelsdi-x/snap/control/plugin" "github.com/intelsdi-x/snap/control/plugin/cpolicy" "github.com/intelsdi-x/snap/core" "github.com/intelsdi-x/snap/core/ctypes" "golang.org/x/oauth2" ) const ( // Name of plugin Name = "rt-gitstats" // Version of plugin Version = 1 // Type of plugin Type = plugin.CollectorPluginType ) // make sure that we actually satisify requierd interface var _ plugin.CollectorPlugin = (*Gitstats)(nil) var ( repoMetricNames = []string{ "forks", "issues", "network", "stars", "subscribers", "watches", "size", } userMetricNames = []string{ "public_repos", "public_gists", "followers", "following", "private_repos", "private_gists", "plan_private_repos", "plan_seats", "plan_filled_seats", } ) type Gitstats struct { } // CollectMetrics collects metrics for testing func (f *Gitstats) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) { var err error conf := mts[0].Config().Table() log.Printf("%v", conf) accessToken, ok := conf["access_token"] if !ok || accessToken.(ctypes.ConfigValueStr).Value == "" { return nil, fmt.Errorf("access token missing from config, %v", conf) } owner, ok := conf["owner"] if !ok || owner.(ctypes.ConfigValueStr).Value == "" { return nil, fmt.Errorf("owner missing from config") } repo, ok := conf["repo"] if !ok || repo.(ctypes.ConfigValueStr).Value == "" { repo = "" } metrics, err := gitStats(accessToken.(ctypes.ConfigValueStr).Value, owner.(ctypes.ConfigValueStr).Value, repo.(ctypes.ConfigValueStr).Value, mts) if err != nil { return nil, err } log.Printf("fetched %d metrics for repo %s/%s", len(metrics), owner.(ctypes.ConfigValueStr).Value, repo.(ctypes.ConfigValueStr).Value) return metrics, nil } func gitStats(accessToken, owner, repo string, mts []plugin.MetricType) ([]plugin.MetricType, error) { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: accessToken}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) client := github.NewClient(tc) var repoStats map[string]int var err error if owner != "" { repoStats, err = getRepo(client, owner, repo) if err != nil { return nil, err } } userStats, err := getUser(client, owner) if err != nil { return nil, err } metrics := make([]plugin.MetricType, 0) for _, m := range mts { stat := m.Namespace()[6].Value if value, ok := repoStats[stat]; ok { mt := plugin.MetricType{ Data_: value, Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", owner, repo, stat), Timestamp_: time.Now(), Version_: m.Version(), } metrics = append(metrics, mt) } if value, ok := userStats[stat]; ok { mt := plugin.MetricType{ Data_: value, Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "owner", owner, stat), Timestamp_: time.Now(), Version_: m.Version(), } metrics = append(metrics, mt) } } return metrics, nil } func getUser(client *github.Client, owner string) (map[string]int, error) { //get contributor stats, then traverse and count. https://api.github.com/repos/openstack/nova/stats/contributors user, _, err := client.Users.Get(owner) if err != nil { return nil, err } stats := make(map[string]int) if user.PublicRepos != nil { stats["public_repos"] = *user.PublicRepos } if user.PublicGists != nil { stats["public_gists"] = *user.PublicGists } if user.Followers != nil { stats["followers"] = *user.Followers } if user.Following != nil { stats["following"] = *user.Following } if *user.Type == "Organization" { org, _, err := client.Organizations.Get(owner) if err != nil { return nil, err } if org.PrivateGists != nil { stats["private_gists"] = *org.PrivateGists } if org.TotalPrivateRepos != nil { stats["private_repos"] = *org.TotalPrivateRepos } if org.DiskUsage != nil { stats["disk_usage"] = *org.DiskUsage } } return stats, nil } func getRepo(client *github.Client, owner, repo string) (map[string]int, error) { resp, _, err := client.Repositories.Get(owner, repo) if err != nil { return nil, err } stats := make(map[string]int) if resp.ForksCount != nil { stats["forks"] = *resp.ForksCount } if resp.OpenIssuesCount != nil { stats["issues"] = *resp.OpenIssuesCount } if resp.NetworkCount != nil { stats["network"] = *resp.NetworkCount } if resp.StargazersCount != nil { stats["stars"] = *resp.StargazersCount } if resp.SubscribersCount != nil { stats["subcribers"] = *resp.SubscribersCount } if resp.WatchersCount != nil { stats["watchers"] = *resp.WatchersCount } if resp.Size != nil { stats["size"] = *resp.Size } return stats, nil } //GetMetricTypes returns metric types for testing func (f *Gitstats) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) { mts := []plugin.MetricType{} for _, metricName := range repoMetricNames { mts = append(mts, plugin.MetricType{ Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", "*", "*", metricName), Config_: cfg.ConfigDataNode, }) } for _, metricName := range userMetricNames { mts = append(mts, plugin.MetricType{ Namespace_: core.NewNamespace("raintank", "apps", "gitstats", "repo", "*", "*", metricName), Config_: cfg.ConfigDataNode, }) } return mts, nil } //GetConfigPolicy returns a ConfigPolicyTree for testing func (f *Gitstats) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { c := cpolicy.New() rule, _ := cpolicy.NewStringRule("access_token", true) rule2, _ := cpolicy.NewStringRule("owner", true) rule3, _ := cpolicy.NewStringRule("repo", false, "") p := cpolicy.NewPolicyNode() p.Add(rule) p.Add(rule2) p.Add(rule3) c.Add([]string{"raintank", "apps", "gitstats"}, p) return c, nil } //Meta returns meta data for testing func Meta() *plugin.PluginMeta { return plugin.NewPluginMeta( Name, Version, Type, []string{plugin.SnapGOBContentType}, []string{plugin.SnapGOBContentType}, plugin.Unsecure(true), plugin.ConcurrencyCount(1000), ) }
package engine import ( "encoding/base64" "errors" "net/url" "time" "github.com/keybase/client/go/kex2" "github.com/keybase/client/go/libkb" keybase1 "github.com/keybase/client/go/protocol" rpc "github.com/keybase/go-framed-msgpack-rpc" jsonw "github.com/keybase/go-jsonw" "golang.org/x/net/context" ) // Kex2Provisionee is an engine. type Kex2Provisionee struct { libkb.Contextified device *libkb.Device secret kex2.Secret secretCh chan kex2.Secret eddsa libkb.NaclKeyPair dh libkb.NaclKeyPair uid keybase1.UID username string sessionToken keybase1.SessionToken csrfToken keybase1.CsrfToken pps keybase1.PassphraseStream lks *libkb.LKSec ctx *Context } // Kex2Provisionee implements kex2.Provisionee, libkb.UserBasic, // and libkb.SessionReader interfaces. var _ kex2.Provisionee = (*Kex2Provisionee)(nil) var _ libkb.UserBasic = (*Kex2Provisionee)(nil) var _ libkb.SessionReader = (*Kex2Provisionee)(nil) // NewKex2Provisionee creates a Kex2Provisionee engine. func NewKex2Provisionee(g *libkb.GlobalContext, device *libkb.Device, secret kex2.Secret) *Kex2Provisionee { return &Kex2Provisionee{ Contextified: libkb.NewContextified(g), device: device, secret: secret, secretCh: make(chan kex2.Secret), } } // Name is the unique engine name. func (e *Kex2Provisionee) Name() string { return "Kex2Provisionee" } // GetPrereqs returns the engine prereqs. func (e *Kex2Provisionee) Prereqs() Prereqs { return Prereqs{} } // RequiredUIs returns the required UIs. func (e *Kex2Provisionee) RequiredUIs() []libkb.UIKind { return []libkb.UIKind{ libkb.ProvisionUIKind, } } // SubConsumers returns the other UI consumers for this engine. func (e *Kex2Provisionee) SubConsumers() []libkb.UIConsumer { return nil } // Run starts the engine. func (e *Kex2Provisionee) Run(ctx *Context) error { e.G().Log.Debug("+ Kex2Provisionee.Run()") // check device struct: if len(e.device.Type) == 0 { return errors.New("provisionee device requires Type to be set") } if e.device.ID.IsNil() { return errors.New("provisionee device requires ID to be set") } // ctx is needed in some of the kex2 functions: e.ctx = ctx karg := kex2.KexBaseArg{ Ctx: context.TODO(), Mr: libkb.NewKexRouter(e.G()), DeviceID: e.device.ID, Secret: e.secret, SecretChannel: e.secretCh, Timeout: 5 * time.Minute, } parg := kex2.ProvisioneeArg{ KexBaseArg: karg, Provisionee: e, } err := kex2.RunProvisionee(parg) e.G().Log.Debug("- Kex2Provisionee.Run() -> %s", libkb.ErrToOk(err)) return err } // AddSecret inserts a received secret into the provisionee's // secret channel. func (e *Kex2Provisionee) AddSecret(s kex2.Secret) { e.secretCh <- s } // GetLogFactory implements GetLogFactory in kex2.Provisionee. func (e *Kex2Provisionee) GetLogFactory() rpc.LogFactory { return rpc.NewSimpleLogFactory(e.G().Log, nil) } // HandleHello implements HandleHello in kex2.Provisionee. func (e *Kex2Provisionee) HandleHello(harg keybase1.HelloArg) (res keybase1.HelloRes, err error) { e.G().Log.Debug("+ HandleHello()") defer func() { e.G().Log.Debug("- HandleHello() -> %s", libkb.ErrToOk(err)) }() // save parts of the hello arg for later: e.uid = harg.Uid e.sessionToken = harg.Token e.csrfToken = harg.Csrf e.pps = harg.Pps jw, err := jsonw.Unmarshal([]byte(harg.SigBody)) if err != nil { return res, err } // need the username later: e.username, err = jw.AtPath("body.key.username").GetString() if err != nil { return res, err } e.eddsa, err = libkb.GenerateNaclSigningKeyPair() if err != nil { return res, err } if err = e.addDeviceSibkey(jw); err != nil { return res, err } if err = e.reverseSig(jw); err != nil { return res, err } out, err := jw.Marshal() if err != nil { return res, err } return keybase1.HelloRes(out), err } // HandleDidCounterSign implements HandleDidCounterSign in // kex2.Provisionee interface. func (e *Kex2Provisionee) HandleDidCounterSign(sig []byte) (err error) { e.G().Log.Debug("+ HandleDidCounterSign()") defer func() { e.G().Log.Debug("- HandleDidCounterSign() -> %s", libkb.ErrToOk(err)) }() e.G().Log.Debug("HandleDidCounterSign sig: %s", string(sig)) // load self user (to load merkle root) _, err = libkb.LoadUser(libkb.NewLoadUserByNameArg(e.G(), e.username)) if err != nil { return err } // decode sig decSig, err := e.decodeSig(sig) if err != nil { return err } e.dh, err = libkb.GenerateNaclDHKeyPair() if err != nil { return err } // make a keyproof for the dh key, signed w/ e.eddsa dhSig, dhSigID, err := e.dhKeyProof(e.dh, decSig.eldestKID, decSig.seqno, decSig.linkID) if err != nil { return err } // create the key args for eddsa, dh keys eddsaArgs, err := makeKeyArgs(decSig.sigID, sig, libkb.SibkeyType, e.eddsa, decSig.eldestKID, decSig.signingKID) if err != nil { return err } dhArgs, err := makeKeyArgs(dhSigID, []byte(dhSig), libkb.SubkeyType, e.dh, decSig.eldestKID, e.eddsa.GetKID()) if err != nil { return err } // logged in, so save the login state err = e.saveLoginState() if err != nil { return err } // push the LKS server half err = e.pushLKSServerHalf() if err != nil { return err } // save device and keys locally err = e.localSave() if err != nil { return err } // post the key sigs to the api server err = e.postSigs(eddsaArgs, dhArgs) if err != nil { return err } return err } type decodedSig struct { sigID keybase1.SigID linkID libkb.LinkID seqno int eldestKID keybase1.KID signingKID keybase1.KID } func (e *Kex2Provisionee) decodeSig(sig []byte) (*decodedSig, error) { body, err := base64.StdEncoding.DecodeString(string(sig)) if err != nil { return nil, err } packet, err := libkb.DecodePacket(body) if err != nil { return nil, err } naclSig, ok := packet.Body.(*libkb.NaclSigInfo) if !ok { return nil, libkb.UnmarshalError{T: "Nacl signature"} } jw, err := jsonw.Unmarshal(naclSig.Payload) if err != nil { return nil, err } res := decodedSig{ sigID: libkb.ComputeSigIDFromSigBody(body), linkID: libkb.ComputeLinkID(naclSig.Payload), } res.seqno, err = jw.AtKey("seqno").GetInt() if err != nil { return nil, err } seldestKID, err := jw.AtPath("body.key.eldest_kid").GetString() if err != nil { return nil, err } res.eldestKID = keybase1.KIDFromString(seldestKID) ssigningKID, err := jw.AtPath("body.key.kid").GetString() if err != nil { return nil, err } res.signingKID = keybase1.KIDFromString(ssigningKID) return &res, nil } // GetName implements libkb.UserBasic interface. func (e *Kex2Provisionee) GetName() string { return e.username } // GetUID implements libkb.UserBasic interface. func (e *Kex2Provisionee) GetUID() keybase1.UID { return e.uid } // APIArgs implements libkb.SessionReader interface. func (e *Kex2Provisionee) APIArgs() (token, csrf string) { return string(e.sessionToken), string(e.csrfToken) } func (e *Kex2Provisionee) addDeviceSibkey(jw *jsonw.Wrapper) error { if e.device.Description == nil { e.G().Log.Debug("prompting for device name") // TODO: get existing device names arg := keybase1.PromptNewDeviceNameArg{} name, err := e.ctx.ProvisionUI.PromptNewDeviceName(context.TODO(), arg) if err != nil { return err } e.device.Description = &name e.G().Log.Debug("got device name: %q", name) } s := libkb.DeviceStatusActive e.device.Status = &s e.device.Kid = e.eddsa.GetKID() dw, err := e.device.Export(libkb.SibkeyType) if err != nil { return err } jw.SetValueAtPath("body.device", dw) if err = jw.SetValueAtPath("body.sibkey.kid", jsonw.NewString(e.eddsa.GetKID().String())); err != nil { return err } return nil } func (e *Kex2Provisionee) reverseSig(jw *jsonw.Wrapper) error { // need to set reverse_sig to nil before making reverse sig: if err := jw.SetValueAtPath("body.sibkey.reverse_sig", jsonw.NewNil()); err != nil { return err } sig, _, _, err := libkb.SignJSON(jw, e.eddsa) if err != nil { return err } // put the signature in reverse_sig if err := jw.SetValueAtPath("body.sibkey.reverse_sig", jsonw.NewString(sig)); err != nil { return err } return nil } // postSigs takes the HTTP args for the signing key and encrypt // key and posts them to the api server. func (e *Kex2Provisionee) postSigs(signingArgs, encryptArgs *libkb.HTTPArgs) error { payload := make(libkb.JSONPayload) payload["sigs"] = []map[string]string{firstValues(signingArgs.ToValues()), firstValues(encryptArgs.ToValues())} arg := libkb.APIArg{ Endpoint: "key/multi", NeedSession: true, JSONPayload: payload, SessionR: e, Contextified: libkb.NewContextified(e.G()), } _, err := e.G().API.PostJSON(arg) return err } func makeKeyArgs(sigID keybase1.SigID, sig []byte, delType libkb.DelegationType, key libkb.GenericKey, eldestKID, signingKID keybase1.KID) (*libkb.HTTPArgs, error) { pub, err := key.Encode() if err != nil { return nil, err } args := libkb.HTTPArgs{ "sig_id_base": libkb.S{Val: sigID.ToString(false)}, "sig_id_short": libkb.S{Val: sigID.ToShortID()}, "sig": libkb.S{Val: string(sig)}, "type": libkb.S{Val: string(delType)}, "is_remote_proof": libkb.B{Val: false}, "public_key": libkb.S{Val: pub}, "eldest_kid": libkb.S{Val: eldestKID.String()}, "signing_kid": libkb.S{Val: signingKID.String()}, } return &args, nil } func (e *Kex2Provisionee) dhKeyProof(dh libkb.GenericKey, eldestKID keybase1.KID, seqno int, linkID libkb.LinkID) (sig string, sigID keybase1.SigID, err error) { delg := libkb.Delegator{ ExistingKey: e.eddsa, NewKey: dh, DelegationType: libkb.SubkeyType, Expire: libkb.NaclDHExpireIn, EldestKID: eldestKID, Device: e.device, LastSeqno: libkb.Seqno(seqno), PrevLinkID: linkID, SigningUser: e, Contextified: libkb.NewContextified(e.G()), } jw, err := libkb.KeyProof(delg) if err != nil { return "", "", err } e.G().Log.Debug("dh key proof: %s", jw.MarshalPretty()) dhSig, dhSigID, _, err := libkb.SignJSON(jw, e.eddsa) if err != nil { return "", "", err } return dhSig, dhSigID, nil } func (e *Kex2Provisionee) pushLKSServerHalf() error { // make new lks ppstream := libkb.NewPassphraseStream(e.pps.PassphraseStream) ppstream.SetGeneration(libkb.PassphraseGeneration(e.pps.Generation)) e.lks = libkb.NewLKSec(ppstream, e.uid, e.G()) e.lks.GenerateServerHalf() // make client half recovery chrKID := e.dh.GetKID() chrText, err := e.lks.EncryptClientHalfRecovery(e.dh) if err != nil { return err } err = libkb.PostDeviceLKS(e, e.device.ID, e.device.Type, e.lks.GetServerHalf(), e.lks.Generation(), chrText, chrKID) if err != nil { return err } // Sync the LKS stuff back from the server, so that subsequent // attempts to use public key login will work. /* err = e.G().LoginState().RunSecretSyncer(e.uid) if err != nil { return err } */ return nil } func (e *Kex2Provisionee) localSave() error { if err := e.saveConfig(); err != nil { return err } if err := e.saveKeys(); err != nil { return err } return nil } func (e *Kex2Provisionee) saveLoginState() error { var err error aerr := e.G().LoginState().Account(func(a *libkb.Account) { err = a.LoadLoginSession(e.username) if err != nil { return } err = a.SaveState(string(e.sessionToken), string(e.csrfToken), libkb.NewNormalizedUsername(e.username), e.uid) if err != nil { return } }, "Kex2Provisionee - saveLoginState()") if aerr != nil { return aerr } if err != nil { return err } return nil } func (e *Kex2Provisionee) saveConfig() error { wr := e.G().Env.GetConfigWriter() if wr == nil { return errors.New("couldn't get config writer") } if err := wr.SetDeviceID(e.device.ID); err != nil { return err } if err := wr.Write(); err != nil { return err } e.G().Log.Debug("Set Device ID to %s in config file", e.device.ID) return nil } func (e *Kex2Provisionee) saveKeys() error { _, err := libkb.WriteLksSKBToKeyring(e.eddsa, e.lks, nil) if err != nil { return err } _, err = libkb.WriteLksSKBToKeyring(e.dh, e.lks, nil) if err != nil { return err } return nil } func firstValues(vals url.Values) map[string]string { res := make(map[string]string) for k, v := range vals { res[k] = v[0] } return res } Include device names in prompt on kex2 provisionee package engine import ( "encoding/base64" "errors" "net/url" "time" "github.com/keybase/client/go/kex2" "github.com/keybase/client/go/libkb" keybase1 "github.com/keybase/client/go/protocol" rpc "github.com/keybase/go-framed-msgpack-rpc" jsonw "github.com/keybase/go-jsonw" "golang.org/x/net/context" ) // Kex2Provisionee is an engine. type Kex2Provisionee struct { libkb.Contextified device *libkb.Device secret kex2.Secret secretCh chan kex2.Secret eddsa libkb.NaclKeyPair dh libkb.NaclKeyPair uid keybase1.UID username string sessionToken keybase1.SessionToken csrfToken keybase1.CsrfToken pps keybase1.PassphraseStream lks *libkb.LKSec ctx *Context } // Kex2Provisionee implements kex2.Provisionee, libkb.UserBasic, // and libkb.SessionReader interfaces. var _ kex2.Provisionee = (*Kex2Provisionee)(nil) var _ libkb.UserBasic = (*Kex2Provisionee)(nil) var _ libkb.SessionReader = (*Kex2Provisionee)(nil) // NewKex2Provisionee creates a Kex2Provisionee engine. func NewKex2Provisionee(g *libkb.GlobalContext, device *libkb.Device, secret kex2.Secret) *Kex2Provisionee { return &Kex2Provisionee{ Contextified: libkb.NewContextified(g), device: device, secret: secret, secretCh: make(chan kex2.Secret), } } // Name is the unique engine name. func (e *Kex2Provisionee) Name() string { return "Kex2Provisionee" } // GetPrereqs returns the engine prereqs. func (e *Kex2Provisionee) Prereqs() Prereqs { return Prereqs{} } // RequiredUIs returns the required UIs. func (e *Kex2Provisionee) RequiredUIs() []libkb.UIKind { return []libkb.UIKind{ libkb.ProvisionUIKind, } } // SubConsumers returns the other UI consumers for this engine. func (e *Kex2Provisionee) SubConsumers() []libkb.UIConsumer { return nil } // Run starts the engine. func (e *Kex2Provisionee) Run(ctx *Context) error { e.G().Log.Debug("+ Kex2Provisionee.Run()") // check device struct: if len(e.device.Type) == 0 { return errors.New("provisionee device requires Type to be set") } if e.device.ID.IsNil() { return errors.New("provisionee device requires ID to be set") } // ctx is needed in some of the kex2 functions: e.ctx = ctx karg := kex2.KexBaseArg{ Ctx: context.TODO(), Mr: libkb.NewKexRouter(e.G()), DeviceID: e.device.ID, Secret: e.secret, SecretChannel: e.secretCh, Timeout: 5 * time.Minute, } parg := kex2.ProvisioneeArg{ KexBaseArg: karg, Provisionee: e, } err := kex2.RunProvisionee(parg) e.G().Log.Debug("- Kex2Provisionee.Run() -> %s", libkb.ErrToOk(err)) return err } // AddSecret inserts a received secret into the provisionee's // secret channel. func (e *Kex2Provisionee) AddSecret(s kex2.Secret) { e.secretCh <- s } // GetLogFactory implements GetLogFactory in kex2.Provisionee. func (e *Kex2Provisionee) GetLogFactory() rpc.LogFactory { return rpc.NewSimpleLogFactory(e.G().Log, nil) } // HandleHello implements HandleHello in kex2.Provisionee. func (e *Kex2Provisionee) HandleHello(harg keybase1.HelloArg) (res keybase1.HelloRes, err error) { e.G().Log.Debug("+ HandleHello()") defer func() { e.G().Log.Debug("- HandleHello() -> %s", libkb.ErrToOk(err)) }() // save parts of the hello arg for later: e.uid = harg.Uid e.sessionToken = harg.Token e.csrfToken = harg.Csrf e.pps = harg.Pps jw, err := jsonw.Unmarshal([]byte(harg.SigBody)) if err != nil { return res, err } // need the username later: e.username, err = jw.AtPath("body.key.username").GetString() if err != nil { return res, err } e.eddsa, err = libkb.GenerateNaclSigningKeyPair() if err != nil { return res, err } if err = e.addDeviceSibkey(jw); err != nil { return res, err } if err = e.reverseSig(jw); err != nil { return res, err } out, err := jw.Marshal() if err != nil { return res, err } return keybase1.HelloRes(out), err } // HandleDidCounterSign implements HandleDidCounterSign in // kex2.Provisionee interface. func (e *Kex2Provisionee) HandleDidCounterSign(sig []byte) (err error) { e.G().Log.Debug("+ HandleDidCounterSign()") defer func() { e.G().Log.Debug("- HandleDidCounterSign() -> %s", libkb.ErrToOk(err)) }() e.G().Log.Debug("HandleDidCounterSign sig: %s", string(sig)) // load self user (to load merkle root) _, err = libkb.LoadUser(libkb.NewLoadUserByNameArg(e.G(), e.username)) if err != nil { return err } // decode sig decSig, err := e.decodeSig(sig) if err != nil { return err } e.dh, err = libkb.GenerateNaclDHKeyPair() if err != nil { return err } // make a keyproof for the dh key, signed w/ e.eddsa dhSig, dhSigID, err := e.dhKeyProof(e.dh, decSig.eldestKID, decSig.seqno, decSig.linkID) if err != nil { return err } // create the key args for eddsa, dh keys eddsaArgs, err := makeKeyArgs(decSig.sigID, sig, libkb.SibkeyType, e.eddsa, decSig.eldestKID, decSig.signingKID) if err != nil { return err } dhArgs, err := makeKeyArgs(dhSigID, []byte(dhSig), libkb.SubkeyType, e.dh, decSig.eldestKID, e.eddsa.GetKID()) if err != nil { return err } // logged in, so save the login state err = e.saveLoginState() if err != nil { return err } // push the LKS server half err = e.pushLKSServerHalf() if err != nil { return err } // save device and keys locally err = e.localSave() if err != nil { return err } // post the key sigs to the api server err = e.postSigs(eddsaArgs, dhArgs) if err != nil { return err } return err } type decodedSig struct { sigID keybase1.SigID linkID libkb.LinkID seqno int eldestKID keybase1.KID signingKID keybase1.KID } func (e *Kex2Provisionee) decodeSig(sig []byte) (*decodedSig, error) { body, err := base64.StdEncoding.DecodeString(string(sig)) if err != nil { return nil, err } packet, err := libkb.DecodePacket(body) if err != nil { return nil, err } naclSig, ok := packet.Body.(*libkb.NaclSigInfo) if !ok { return nil, libkb.UnmarshalError{T: "Nacl signature"} } jw, err := jsonw.Unmarshal(naclSig.Payload) if err != nil { return nil, err } res := decodedSig{ sigID: libkb.ComputeSigIDFromSigBody(body), linkID: libkb.ComputeLinkID(naclSig.Payload), } res.seqno, err = jw.AtKey("seqno").GetInt() if err != nil { return nil, err } seldestKID, err := jw.AtPath("body.key.eldest_kid").GetString() if err != nil { return nil, err } res.eldestKID = keybase1.KIDFromString(seldestKID) ssigningKID, err := jw.AtPath("body.key.kid").GetString() if err != nil { return nil, err } res.signingKID = keybase1.KIDFromString(ssigningKID) return &res, nil } // GetName implements libkb.UserBasic interface. func (e *Kex2Provisionee) GetName() string { return e.username } // GetUID implements libkb.UserBasic interface. func (e *Kex2Provisionee) GetUID() keybase1.UID { return e.uid } // APIArgs implements libkb.SessionReader interface. func (e *Kex2Provisionee) APIArgs() (token, csrf string) { return string(e.sessionToken), string(e.csrfToken) } func (e *Kex2Provisionee) addDeviceSibkey(jw *jsonw.Wrapper) error { if e.device.Description == nil { // need user to get existing device names user, err := libkb.LoadUser(libkb.NewLoadUserByNameArg(e.G(), e.username)) if err != nil { return err } existingDevices, err := user.DeviceNames() if err != nil { e.G().Log.Debug("proceeding despite error getting existing device names: %s", err) } e.G().Log.Debug("prompting for device name") arg := keybase1.PromptNewDeviceNameArg{ ExistingDevices: existingDevices, } name, err := e.ctx.ProvisionUI.PromptNewDeviceName(context.TODO(), arg) if err != nil { return err } e.device.Description = &name e.G().Log.Debug("got device name: %q", name) } s := libkb.DeviceStatusActive e.device.Status = &s e.device.Kid = e.eddsa.GetKID() dw, err := e.device.Export(libkb.SibkeyType) if err != nil { return err } jw.SetValueAtPath("body.device", dw) if err = jw.SetValueAtPath("body.sibkey.kid", jsonw.NewString(e.eddsa.GetKID().String())); err != nil { return err } return nil } func (e *Kex2Provisionee) reverseSig(jw *jsonw.Wrapper) error { // need to set reverse_sig to nil before making reverse sig: if err := jw.SetValueAtPath("body.sibkey.reverse_sig", jsonw.NewNil()); err != nil { return err } sig, _, _, err := libkb.SignJSON(jw, e.eddsa) if err != nil { return err } // put the signature in reverse_sig if err := jw.SetValueAtPath("body.sibkey.reverse_sig", jsonw.NewString(sig)); err != nil { return err } return nil } // postSigs takes the HTTP args for the signing key and encrypt // key and posts them to the api server. func (e *Kex2Provisionee) postSigs(signingArgs, encryptArgs *libkb.HTTPArgs) error { payload := make(libkb.JSONPayload) payload["sigs"] = []map[string]string{firstValues(signingArgs.ToValues()), firstValues(encryptArgs.ToValues())} arg := libkb.APIArg{ Endpoint: "key/multi", NeedSession: true, JSONPayload: payload, SessionR: e, Contextified: libkb.NewContextified(e.G()), } _, err := e.G().API.PostJSON(arg) return err } func makeKeyArgs(sigID keybase1.SigID, sig []byte, delType libkb.DelegationType, key libkb.GenericKey, eldestKID, signingKID keybase1.KID) (*libkb.HTTPArgs, error) { pub, err := key.Encode() if err != nil { return nil, err } args := libkb.HTTPArgs{ "sig_id_base": libkb.S{Val: sigID.ToString(false)}, "sig_id_short": libkb.S{Val: sigID.ToShortID()}, "sig": libkb.S{Val: string(sig)}, "type": libkb.S{Val: string(delType)}, "is_remote_proof": libkb.B{Val: false}, "public_key": libkb.S{Val: pub}, "eldest_kid": libkb.S{Val: eldestKID.String()}, "signing_kid": libkb.S{Val: signingKID.String()}, } return &args, nil } func (e *Kex2Provisionee) dhKeyProof(dh libkb.GenericKey, eldestKID keybase1.KID, seqno int, linkID libkb.LinkID) (sig string, sigID keybase1.SigID, err error) { delg := libkb.Delegator{ ExistingKey: e.eddsa, NewKey: dh, DelegationType: libkb.SubkeyType, Expire: libkb.NaclDHExpireIn, EldestKID: eldestKID, Device: e.device, LastSeqno: libkb.Seqno(seqno), PrevLinkID: linkID, SigningUser: e, Contextified: libkb.NewContextified(e.G()), } jw, err := libkb.KeyProof(delg) if err != nil { return "", "", err } e.G().Log.Debug("dh key proof: %s", jw.MarshalPretty()) dhSig, dhSigID, _, err := libkb.SignJSON(jw, e.eddsa) if err != nil { return "", "", err } return dhSig, dhSigID, nil } func (e *Kex2Provisionee) pushLKSServerHalf() error { // make new lks ppstream := libkb.NewPassphraseStream(e.pps.PassphraseStream) ppstream.SetGeneration(libkb.PassphraseGeneration(e.pps.Generation)) e.lks = libkb.NewLKSec(ppstream, e.uid, e.G()) e.lks.GenerateServerHalf() // make client half recovery chrKID := e.dh.GetKID() chrText, err := e.lks.EncryptClientHalfRecovery(e.dh) if err != nil { return err } err = libkb.PostDeviceLKS(e, e.device.ID, e.device.Type, e.lks.GetServerHalf(), e.lks.Generation(), chrText, chrKID) if err != nil { return err } // Sync the LKS stuff back from the server, so that subsequent // attempts to use public key login will work. /* err = e.G().LoginState().RunSecretSyncer(e.uid) if err != nil { return err } */ return nil } func (e *Kex2Provisionee) localSave() error { if err := e.saveConfig(); err != nil { return err } if err := e.saveKeys(); err != nil { return err } return nil } func (e *Kex2Provisionee) saveLoginState() error { var err error aerr := e.G().LoginState().Account(func(a *libkb.Account) { err = a.LoadLoginSession(e.username) if err != nil { return } err = a.SaveState(string(e.sessionToken), string(e.csrfToken), libkb.NewNormalizedUsername(e.username), e.uid) if err != nil { return } }, "Kex2Provisionee - saveLoginState()") if aerr != nil { return aerr } if err != nil { return err } return nil } func (e *Kex2Provisionee) saveConfig() error { wr := e.G().Env.GetConfigWriter() if wr == nil { return errors.New("couldn't get config writer") } if err := wr.SetDeviceID(e.device.ID); err != nil { return err } if err := wr.Write(); err != nil { return err } e.G().Log.Debug("Set Device ID to %s in config file", e.device.ID) return nil } func (e *Kex2Provisionee) saveKeys() error { _, err := libkb.WriteLksSKBToKeyring(e.eddsa, e.lks, nil) if err != nil { return err } _, err = libkb.WriteLksSKBToKeyring(e.dh, e.lks, nil) if err != nil { return err } return nil } func firstValues(vals url.Values) map[string]string { res := make(map[string]string) for k, v := range vals { res[k] = v[0] } return res }
package entities import ( "crypto/sha1" "errors" "fmt" db "github.com/fclairamb/m2mp/go/m2mp-db" "github.com/gocql/gocql" "log" "time" ) const ( DEVICE_NODE_PATH = "/device/" DEVICE_BY_IDENT_NODE_PATH = DEVICE_NODE_PATH + "by-ident/" DEVICE_DEFAULT_NODE_PATH = "/device/default/" ) // Device type Device struct { // Device's node Node *db.RegistryNode // I removed all the caching code around settings, settingsToSend, commands, serverSettings, etc. because // we don't care about performance at this stage and it might lead to caching issues } func NewDeviceDefault() *Device { return &Device{Node: db.NewRegistryNode(DEVICE_DEFAULT_NODE_PATH)} } // Device by ID func NewDeviceById(devId gocql.UUID) *Device { return &Device{Node: db.NewRegistryNode(DEVICE_NODE_PATH + devId.String() + "/")} } // Device by ident func NewDeviceByIdent(ident string) (*Device, error) { node := db.NewRegistryNode(DEVICE_BY_IDENT_NODE_PATH + ident) if node.Exists() { sid := node.Values()["id"] id, err := gocql.ParseUUID(sid) if err != nil { return nil, err } return NewDeviceById(id), nil } return nil, errors.New("No device by that ident") } // Device by ident (created if it doesn't exist) func NewDeviceByIdentCreate(ident string) (*Device, error) { d, err := NewDeviceByIdent(ident) if d != nil { return d, nil } hasher := sha1.New() hasher.Write([]byte(ident)) sum := hasher.Sum(nil) id, err := gocql.UUIDFromBytes(sum[:16]) if err != nil { return nil, err } node := db.NewRegistryNode(DEVICE_BY_IDENT_NODE_PATH + ident + "/").Create() node.SetValue("id", id.String()) device := NewDeviceById(id) device.Node.Create() device.Node.SetValue("ident", ident) { // We put it in the default domain def, _ := NewDomainByNameCreate("default") device.SetDomain(def) } return device, nil } func (d *Device) Delete() error { if dom := d.Domain(); dom != nil { dom.Node.GetChild("devices").DelValue(d.Id()) } return d.Node.Delete(false) } func (d *Domain) Devices() []*Device { devices := []*Device{} for n, _ := range d.Node.GetChild("devices").Values() { devId, err := gocql.ParseUUID(n) if err == nil { devices = append(devices, NewDeviceById(devId)) } else { // This should never happen log.Print("Invalid device id:", err) } } return devices } func (d *Device) Id() string { return d.Node.Name() } func (d *Device) Name() string { return d.GetServerSettingsPublicNode().Value("name") } func (d *Device) Ident() string { return d.Node.Value("ident") } func (d *Device) SetName(name string) error { return d.GetServerSettingsPublicNode().SetValue("name", name) } func (d *Device) getCommandsNode() *db.RegistryNode { return d.Node.GetChild("commands").Check() } func (d *Device) getCommandsResponseNode() *db.RegistryNode { return d.Node.GetChild("commands-response").Check() } func (d *Device) getSettingsNode() *db.RegistryNode { return d.Node.GetChild("settings").Check() } func (d *Device) getSettingsToSendNode() *db.RegistryNode { return d.Node.GetChild("settings-to-send").Check() } func (d *Device) getSettingsAckTimeNode() *db.RegistryNode { return d.Node.GetChild("settings-ack-time").Check() } func (d *Device) getStatusNode() *db.RegistryNode { return d.Node.GetChild("status").Check() } func (d *Device) getServerSettingsNode() *db.RegistryNode { return d.Node.GetChild("server-settings").Check() } func (d *Device) GetServerSettingsPublicNode() *db.RegistryNode { return d.Node.GetChild("server-settings-public").Check() } // Add a command to send to the device func (d *Device) AddCommand(cmd string) (string, error) { cmdId, err := gocql.RandomUUID() if err != nil { return "", err } err = d.getCommandsNode().SetValue(cmdId.String(), cmd) if err != nil { return "", err } return cmdId.String(), nil } func (d *Device) Status(name string) string { return d.getStatusNode().Value(name) } func (d *Device) SetStatus(name, value string) error { return d.getStatusNode().SetValue(name, value) } func (d *Device) Setting(name string) string { return d.getSettingsNode().Value(name) } // Define a setting func (d *Device) SetSetting(name, value string) (err error) { err = d.getSettingsNode().SetValue(name, value) if err == nil { err = d.getSettingsToSendNode().SetValue(name, value) } if err == nil { err = d.getSettingsAckTimeNode().DelValue(name) } return } // Delete a setting func (d *Device) DelSetting(name string) (err error) { err = d.getSettingsNode().DelValue(name) if err == nil { err = d.getSettingsToSendNode().DelValue(name) } return err } func (d *Device) AckSetting(name, ackedValue string) (err error) { toSend := d.getSettingsToSendNode() defined := d.getSettingsNode() { // Delete the setting to send valueToSend := toSend.Value(name) if ackedValue == valueToSend { err = toSend.DelValue(name) if err == nil { d.getSettingsAckTimeNode().SetValue(name, fmt.Sprintf("%d", time.Now().UnixNano()%1e6/1e3)) } } } // Save the setting (whatever happens) if err == nil { err = defined.SetValue(name, ackedValue) } return } func (d *Device) Settings() map[string]string { return d.getSettingsNode().Values() } func (d *Device) SettingsToSend() map[string]string { return d.getSettingsToSendNode().Values() } func (d *Device) Commands() map[string]string { return d.getCommandsNode().Values() } // Acknowledge a command with its ID func (d *Device) AckCommand(cmdId string) error { return d.getCommandsNode().DelValue(cmdId) } func (d *Device) AckCommandWithResponse(cmdId, response string) error { d.AckCommand(cmdId) return d.getCommandsResponseNode().SetValue(cmdId, response) } func (dev *Device) SetDomain(d *Domain) error { { // We remove it from the previous domain previousDomain := dev.Domain() if previousDomain != nil { previousDomain.Node.GetChild("devices").Check().DelValue(dev.Id()) } } // We set the domain id dev.Node.SetValue("domain", d.Id()) // And add it to the references of the new domain d.Node.GetChild("devices").Check().SetValue(dev.Id(), "") return nil } func (dev *Device) Domain() *Domain { sDomainId := dev.Node.Values()["domain"] domainId, err := gocql.ParseUUID(sDomainId) if err != nil { return nil } return NewDomainById(domainId) } func (d *Device) TSID() string { return "dev-" + d.Id() } func (d *Device) SaveTSTime(dataType string, time time.Time, data string) error { return db.SaveTSTime(d.TSID(), dataType, time, data) } func (d *Device) SaveTSTimeObj(dataType string, time time.Time, obj interface{}) error { return db.SaveTSTimeObj(d.TSID(), dataType, time, obj) } go/db/entities: Added device's owner information. package entities import ( "crypto/sha1" "errors" "fmt" db "github.com/fclairamb/m2mp/go/m2mp-db" "github.com/gocql/gocql" "log" "time" ) const ( DEVICE_NODE_PATH = "/device/" DEVICE_BY_IDENT_NODE_PATH = DEVICE_NODE_PATH + "by-ident/" DEVICE_DEFAULT_NODE_PATH = "/device/default/" ) // Device type Device struct { // Device's node Node *db.RegistryNode // I removed all the caching code around settings, settingsToSend, commands, serverSettings, etc. because // we don't care about performance at this stage and it might lead to caching issues } func NewDeviceDefault() *Device { return &Device{Node: db.NewRegistryNode(DEVICE_DEFAULT_NODE_PATH)} } // Device by ID func NewDeviceById(devId gocql.UUID) *Device { return &Device{Node: db.NewRegistryNode(DEVICE_NODE_PATH + devId.String() + "/")} } // Device by ident func NewDeviceByIdent(ident string) (*Device, error) { node := db.NewRegistryNode(DEVICE_BY_IDENT_NODE_PATH + ident) if node.Exists() { sid := node.Values()["id"] id, err := gocql.ParseUUID(sid) if err != nil { return nil, err } return NewDeviceById(id), nil } return nil, errors.New("No device by that ident") } // Device by ident (created if it doesn't exist) func NewDeviceByIdentCreate(ident string) (*Device, error) { d, err := NewDeviceByIdent(ident) if d != nil { return d, nil } hasher := sha1.New() hasher.Write([]byte(ident)) sum := hasher.Sum(nil) id, err := gocql.UUIDFromBytes(sum[:16]) if err != nil { return nil, err } node := db.NewRegistryNode(DEVICE_BY_IDENT_NODE_PATH + ident + "/").Create() node.SetValue("id", id.String()) device := NewDeviceById(id) device.Node.Create() device.Node.SetValue("ident", ident) { // We put it in the default domain def, _ := NewDomainByNameCreate("default") device.SetDomain(def) } return device, nil } func (d *Device) Delete() error { if dom := d.Domain(); dom != nil { dom.Node.GetChild("devices").DelValue(d.Id()) } return d.Node.Delete(false) } func (d *Domain) Devices() []*Device { devices := []*Device{} for n, _ := range d.Node.GetChild("devices").Values() { devId, err := gocql.ParseUUID(n) if err == nil { devices = append(devices, NewDeviceById(devId)) } else { // This should never happen log.Print("Invalid device id:", err) } } return devices } func (d *Device) Id() string { return d.Node.Name() } func (d *Device) Name() string { return d.GetServerSettingsPublicNode().Value("name") } func (d *Device) Ident() string { return d.Node.Value("ident") } func (d *Device) SetName(name string) error { return d.GetServerSettingsPublicNode().SetValue("name", name) } func (d *Device) getCommandsNode() *db.RegistryNode { return d.Node.GetChild("commands").Check() } func (d *Device) getCommandsResponseNode() *db.RegistryNode { return d.Node.GetChild("commands-response").Check() } func (d *Device) getSettingsNode() *db.RegistryNode { return d.Node.GetChild("settings").Check() } func (d *Device) getSettingsToSendNode() *db.RegistryNode { return d.Node.GetChild("settings-to-send").Check() } func (d *Device) getSettingsAckTimeNode() *db.RegistryNode { return d.Node.GetChild("settings-ack-time").Check() } func (d *Device) getStatusNode() *db.RegistryNode { return d.Node.GetChild("status").Check() } func (d *Device) getServerSettingsNode() *db.RegistryNode { return d.Node.GetChild("server-settings").Check() } func (d *Device) GetServerSettingsPublicNode() *db.RegistryNode { return d.Node.GetChild("server-settings-public").Check() } // Add a command to send to the device func (d *Device) AddCommand(cmd string) (string, error) { cmdId, err := gocql.RandomUUID() if err != nil { return "", err } err = d.getCommandsNode().SetValue(cmdId.String(), cmd) if err != nil { return "", err } return cmdId.String(), nil } func (d *Device) Status(name string) string { return d.getStatusNode().Value(name) } func (d *Device) SetStatus(name, value string) error { return d.getStatusNode().SetValue(name, value) } func (d *Device) Setting(name string) string { return d.getSettingsNode().Value(name) } // Define a setting func (d *Device) SetSetting(name, value string) (err error) { err = d.getSettingsNode().SetValue(name, value) if err == nil { err = d.getSettingsToSendNode().SetValue(name, value) } if err == nil { err = d.getSettingsAckTimeNode().DelValue(name) } return } // Delete a setting func (d *Device) DelSetting(name string) (err error) { err = d.getSettingsNode().DelValue(name) if err == nil { err = d.getSettingsToSendNode().DelValue(name) } return err } func (d *Device) AckSetting(name, ackedValue string) (err error) { toSend := d.getSettingsToSendNode() defined := d.getSettingsNode() { // Delete the setting to send valueToSend := toSend.Value(name) if ackedValue == valueToSend { err = toSend.DelValue(name) if err == nil { d.getSettingsAckTimeNode().SetValue(name, fmt.Sprintf("%d", time.Now().UnixNano()%1e6/1e3)) } } } // Save the setting (whatever happens) if err == nil { err = defined.SetValue(name, ackedValue) } return } func (d *Device) Settings() map[string]string { return d.getSettingsNode().Values() } func (d *Device) SettingsToSend() map[string]string { return d.getSettingsToSendNode().Values() } func (d *Device) Commands() map[string]string { return d.getCommandsNode().Values() } // Acknowledge a command with its ID func (d *Device) AckCommand(cmdId string) error { return d.getCommandsNode().DelValue(cmdId) } func (d *Device) AckCommandWithResponse(cmdId, response string) error { d.AckCommand(cmdId) return d.getCommandsResponseNode().SetValue(cmdId, response) } func (dev *Device) SetDomain(d *Domain) error { { // We remove it from the previous domain previousDomain := dev.Domain() if previousDomain != nil { previousDomain.Node.GetChild("devices").Check().DelValue(dev.Id()) } } // We set the domain id dev.Node.SetValue("domain", d.Id()) // And add it to the references of the new domain d.Node.GetChild("devices").Check().SetValue(dev.Id(), "") return nil } func (this *Device) Owner() *User { sUserId := this.Node.Value("owner") userId, err := gocql.ParseUUID(sUserId) if err != nil { return nil } return NewUserById(userId) } func (dev *Device) Domain() *Domain { sDomainId := dev.Node.Value("domain") domainId, err := gocql.ParseUUID(sDomainId) if err != nil { return nil } return NewDomainById(domainId) } func (d *Device) TSID() string { return "dev-" + d.Id() } func (d *Device) SaveTSTime(dataType string, time time.Time, data string) error { return db.SaveTSTime(d.TSID(), dataType, time, data) } func (d *Device) SaveTSTimeObj(dataType string, time time.Time, obj interface{}) error { return db.SaveTSTimeObj(d.TSID(), dataType, time, obj) }
package main import ( "errors" "fmt" "log" "sync" "time" "github.com/dgryski/go-tsz" ) var serverStart uint32 var statsPeriod time.Duration func init() { serverStart = uint32(time.Now().Unix()) statsPeriod = time.Duration(1) * time.Second } // AggMetric takes in new values, updates the in-memory data and streams the points to aggregators // it uses a circular buffer of chunks // each chunk starts at their respective t0 // a t0 is a timestamp divisible by chunkSpan without a remainder (e.g. 2 hour boundaries) // firstT0's data is held at index 0, indexes go up and wrap around from numChunks-1 to 0 // in addition, keep in mind that the last chunk is always a work in progress and not useable for aggregation // AggMetric is concurrency-safe type AggMetric struct { sync.Mutex key string firstTs uint32 // first timestamp from which we have seen data. (either a point ts during our first chunk, or the t0 of a chunk if we've had to drop old chunks) lastTs uint32 // last timestamp seen firstT0 uint32 // first t0 seen, even if no longer in range lastT0 uint32 // last t0 seen numChunks uint32 // size of the circular buffer chunkSpan uint32 // span of individual chunks in seconds chunks []*Chunk aggregators []*Aggregator } // NewAggMetric creates a metric with given key, it retains the given number of chunks each chunkSpan seconds long // it optionally also creates aggregations with the given settings func NewAggMetric(key string, chunkSpan, numChunks uint32, aggsetting ...aggSetting) *AggMetric { m := AggMetric{ key: key, chunkSpan: chunkSpan, numChunks: numChunks, chunks: make([]*Chunk, numChunks), } for _, as := range aggsetting { m.aggregators = append(m.aggregators, NewAggregator(key, as.span, as.chunkSpan, as.numChunks)) } go m.stats() go m.trimOldData() return &m } func (a *AggMetric) stats() { for range time.Tick(statsPeriod) { sum := 0 a.Lock() for _, chunk := range a.chunks { if chunk != nil { sum += int(chunk.numPoints) } } a.Unlock() points.Update(int64(sum)) } } func (a *AggMetric) trimOldData() { a.Lock() //for t := range time.Tick(time.Duration(a.chunkSpan) * time.Second) { // Finish // it's ok to re-finish if already finished // } a.Unlock() } // this function must only be called while holding the lock func (a *AggMetric) indexFor(t0 uint32) uint32 { return ((t0 - a.firstT0) / a.chunkSpan) % a.numChunks } // using user input, which has to be verified, and could be any input // from inclusive, to exclusive. just like slices // we also need to be accurately say from which point on we have data. // that way you know if you should also query another datastore // this is trickier than it sounds: // 1) we can't just use server start, because older data may have come in with a bit of a delay // 2) we can't just use oldest point that we still hold, because data may have arrived long after server start, // i.e. after a period of nothingness. and we know we would have had the data after start if it had come in // 3) we can't just compute based on chunks how far back in time we would have had the data, // because this could be before server start, if invoked soon after starting. // so we use a combination of all factors.. // note that this value may lie before the timestamp of actual data returned func (a *AggMetric) GetUnsafe(from, to uint32) (uint32, []*tsz.Iter, error) { if from >= to { return 0, nil, errors.New("invalid request. to must > from") } a.Lock() //log.Printf("GetUnsafe(%d, %d)\n", from, to) firstT0 := from - (from % a.chunkSpan) lastT0 := (to - 1) - ((to - 1) % a.chunkSpan) // we cannot satisfy data older than our retention oldestT0WeMayHave := a.lastT0 - (a.numChunks-1)*a.chunkSpan if firstT0 < oldestT0WeMayHave { firstT0 = oldestT0WeMayHave } // no point in requesting data older then what we have. common shortly after server start if firstT0 < a.firstT0 { firstT0 = a.firstT0 } if lastT0 > a.lastT0 { lastT0 = a.lastT0 } defer a.Unlock() oldest := oldestT0WeMayHave if oldest < serverStart { oldest = serverStart } if oldest > a.firstTs { oldest = a.firstTs } return oldest, a.get(firstT0, lastT0), nil } // using input from our software, which should already be solid. // returns a range that includes the requested range, but typically more. // from inclusive, to exclusive. just like slices func (a *AggMetric) GetSafe(from, to uint32) []*tsz.Iter { if from >= to { panic("invalid request. to must > from") } a.Lock() firstT0 := from - (from % a.chunkSpan) lastT0 := (to - 1) - ((to - 1) % a.chunkSpan) aggFirstT0 := int(a.lastT0) - int(a.numChunks*a.chunkSpan) // this can happen in contrived, testing scenarios that use very low timestamps if aggFirstT0 < 0 { aggFirstT0 = 0 } if int(firstT0) < aggFirstT0 { panic("requested a firstT0 that is too old") } if lastT0 > a.lastT0 { panic(fmt.Sprintf("requested lastT0 %d that doesn't exist yet. last is %d", lastT0, a.lastT0)) } defer a.Unlock() return a.get(firstT0, lastT0) } // remember: firstT0 and lastT0 must be cleanly divisible by chunkSpan! func (a *AggMetric) get(firstT0, lastT0 uint32) []*tsz.Iter { first := a.indexFor(firstT0) last := a.indexFor(lastT0) var data []*Chunk if last >= first { data = a.chunks[first : last+1] } else { numAtSliceEnd := (a.numChunks - first) numAtSliceBegin := last + 1 num := numAtSliceEnd + numAtSliceBegin data = make([]*Chunk, 0, num) // add the values at the end of chunks slice first (they are first in time) for i := first; i < a.numChunks; i++ { data = append(data, a.chunks[i]) } // then the values later in time, which are at the beginning of the slice for i := uint32(0); i <= last; i++ { data = append(data, a.chunks[i]) } } iters := make([]*tsz.Iter, 0, len(data)) for _, chunk := range data { if chunk != nil { iters = append(iters, chunk.Iter()) } } return iters } // this function must only be called while holding the lock func (a *AggMetric) addAggregators(ts uint32, val float64) { for _, agg := range a.aggregators { agg.Add(ts, val) } } func (a *AggMetric) Persist(c *Chunk) { go func() { log.Println("if c* enabled, saving chunk", c) err := InsertMetric(a.key, c.t0, c.Series.Bytes()) a.Lock() defer a.Unlock() if err == nil { c.saved = true log.Println("saved chunk", c) } else { log.Println("ERROR: could not save chunk", c, err) // TODO } }() } // don't ever call with a ts of 0, cause we use 0 to mean not initialized! func (a *AggMetric) Add(ts uint32, val float64) { a.Lock() defer a.Unlock() if ts <= a.lastTs { log.Printf("ERROR: ts %d <= last seen ts %d. can only append newer data", ts, a.lastTs) return } t0 := ts - (ts % a.chunkSpan) log.Println("t0=", TS(t0), "adding", TS(ts), val) if a.lastTs == 0 { // we're adding first point ever.. a.firstT0, a.lastT0 = t0, t0 a.firstTs, a.lastTs = ts, ts a.chunks[0] = NewChunk(t0).Push(ts, val) a.addAggregators(ts, val) return } if t0 == a.lastT0 { // last prior data was in same chunk as new point a.chunks[a.indexFor(t0)].Push(ts, val) } else { // the point needs a newer chunk than points we've seen before prev := a.indexFor(a.lastT0) a.chunks[prev].Finish() a.Persist(a.chunks[prev]) // TODO: create empty series in between, if there's a gap. -> actually no, we may just as well keep the old data // but we have to make sure we don't accidentally return the old data out of order now := a.indexFor(t0) a.chunks[now] = NewChunk(t0).Push(ts, val) // update firstTs to oldest t0 var found *Chunk if now > prev { for i := prev; i <= now && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } } else { for i := prev; i < uint32(len(a.chunks)) && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } for i := uint32(0); i <= now && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } } a.firstTs = found.t0 a.lastT0 = t0 a.lastTs = ts } a.addAggregators(ts, val) } fix set lastTs in all cases package main import ( "errors" "fmt" "log" "sync" "time" "github.com/dgryski/go-tsz" ) var serverStart uint32 var statsPeriod time.Duration func init() { serverStart = uint32(time.Now().Unix()) statsPeriod = time.Duration(1) * time.Second } // AggMetric takes in new values, updates the in-memory data and streams the points to aggregators // it uses a circular buffer of chunks // each chunk starts at their respective t0 // a t0 is a timestamp divisible by chunkSpan without a remainder (e.g. 2 hour boundaries) // firstT0's data is held at index 0, indexes go up and wrap around from numChunks-1 to 0 // in addition, keep in mind that the last chunk is always a work in progress and not useable for aggregation // AggMetric is concurrency-safe type AggMetric struct { sync.Mutex key string firstTs uint32 // first timestamp from which we have seen data. (either a point ts during our first chunk, or the t0 of a chunk if we've had to drop old chunks) lastTs uint32 // last timestamp seen firstT0 uint32 // first t0 seen, even if no longer in range lastT0 uint32 // last t0 seen numChunks uint32 // size of the circular buffer chunkSpan uint32 // span of individual chunks in seconds chunks []*Chunk aggregators []*Aggregator } // NewAggMetric creates a metric with given key, it retains the given number of chunks each chunkSpan seconds long // it optionally also creates aggregations with the given settings func NewAggMetric(key string, chunkSpan, numChunks uint32, aggsetting ...aggSetting) *AggMetric { m := AggMetric{ key: key, chunkSpan: chunkSpan, numChunks: numChunks, chunks: make([]*Chunk, numChunks), } for _, as := range aggsetting { m.aggregators = append(m.aggregators, NewAggregator(key, as.span, as.chunkSpan, as.numChunks)) } go m.stats() go m.trimOldData() return &m } func (a *AggMetric) stats() { for range time.Tick(statsPeriod) { sum := 0 a.Lock() for _, chunk := range a.chunks { if chunk != nil { sum += int(chunk.numPoints) } } a.Unlock() points.Update(int64(sum)) } } func (a *AggMetric) trimOldData() { a.Lock() //for t := range time.Tick(time.Duration(a.chunkSpan) * time.Second) { // Finish // it's ok to re-finish if already finished // } a.Unlock() } // this function must only be called while holding the lock func (a *AggMetric) indexFor(t0 uint32) uint32 { return ((t0 - a.firstT0) / a.chunkSpan) % a.numChunks } // using user input, which has to be verified, and could be any input // from inclusive, to exclusive. just like slices // we also need to be accurately say from which point on we have data. // that way you know if you should also query another datastore // this is trickier than it sounds: // 1) we can't just use server start, because older data may have come in with a bit of a delay // 2) we can't just use oldest point that we still hold, because data may have arrived long after server start, // i.e. after a period of nothingness. and we know we would have had the data after start if it had come in // 3) we can't just compute based on chunks how far back in time we would have had the data, // because this could be before server start, if invoked soon after starting. // so we use a combination of all factors.. // note that this value may lie before the timestamp of actual data returned func (a *AggMetric) GetUnsafe(from, to uint32) (uint32, []*tsz.Iter, error) { if from >= to { return 0, nil, errors.New("invalid request. to must > from") } a.Lock() //log.Printf("GetUnsafe(%d, %d)\n", from, to) firstT0 := from - (from % a.chunkSpan) lastT0 := (to - 1) - ((to - 1) % a.chunkSpan) // we cannot satisfy data older than our retention oldestT0WeMayHave := a.lastT0 - (a.numChunks-1)*a.chunkSpan if firstT0 < oldestT0WeMayHave { firstT0 = oldestT0WeMayHave } // no point in requesting data older then what we have. common shortly after server start if firstT0 < a.firstT0 { firstT0 = a.firstT0 } if lastT0 > a.lastT0 { lastT0 = a.lastT0 } defer a.Unlock() oldest := oldestT0WeMayHave if oldest < serverStart { oldest = serverStart } if oldest > a.firstTs { oldest = a.firstTs } return oldest, a.get(firstT0, lastT0), nil } // using input from our software, which should already be solid. // returns a range that includes the requested range, but typically more. // from inclusive, to exclusive. just like slices func (a *AggMetric) GetSafe(from, to uint32) []*tsz.Iter { if from >= to { panic("invalid request. to must > from") } a.Lock() firstT0 := from - (from % a.chunkSpan) lastT0 := (to - 1) - ((to - 1) % a.chunkSpan) aggFirstT0 := int(a.lastT0) - int(a.numChunks*a.chunkSpan) // this can happen in contrived, testing scenarios that use very low timestamps if aggFirstT0 < 0 { aggFirstT0 = 0 } if int(firstT0) < aggFirstT0 { panic("requested a firstT0 that is too old") } if lastT0 > a.lastT0 { panic(fmt.Sprintf("requested lastT0 %d that doesn't exist yet. last is %d", lastT0, a.lastT0)) } defer a.Unlock() return a.get(firstT0, lastT0) } // remember: firstT0 and lastT0 must be cleanly divisible by chunkSpan! func (a *AggMetric) get(firstT0, lastT0 uint32) []*tsz.Iter { first := a.indexFor(firstT0) last := a.indexFor(lastT0) var data []*Chunk if last >= first { data = a.chunks[first : last+1] } else { numAtSliceEnd := (a.numChunks - first) numAtSliceBegin := last + 1 num := numAtSliceEnd + numAtSliceBegin data = make([]*Chunk, 0, num) // add the values at the end of chunks slice first (they are first in time) for i := first; i < a.numChunks; i++ { data = append(data, a.chunks[i]) } // then the values later in time, which are at the beginning of the slice for i := uint32(0); i <= last; i++ { data = append(data, a.chunks[i]) } } iters := make([]*tsz.Iter, 0, len(data)) for _, chunk := range data { if chunk != nil { iters = append(iters, chunk.Iter()) } } return iters } // this function must only be called while holding the lock func (a *AggMetric) addAggregators(ts uint32, val float64) { for _, agg := range a.aggregators { agg.Add(ts, val) } } func (a *AggMetric) Persist(c *Chunk) { go func() { log.Println("if c* enabled, saving chunk", c) err := InsertMetric(a.key, c.t0, c.Series.Bytes()) a.Lock() defer a.Unlock() if err == nil { c.saved = true log.Println("saved chunk", c) } else { log.Println("ERROR: could not save chunk", c, err) // TODO } }() } // don't ever call with a ts of 0, cause we use 0 to mean not initialized! func (a *AggMetric) Add(ts uint32, val float64) { a.Lock() defer a.Unlock() if ts <= a.lastTs { log.Printf("ERROR: ts %d <= last seen ts %d. can only append newer data", ts, a.lastTs) return } t0 := ts - (ts % a.chunkSpan) log.Println("t0=", TS(t0), "adding", TS(ts), val) if a.lastTs == 0 { // we're adding first point ever.. a.firstT0, a.lastT0 = t0, t0 a.firstTs, a.lastTs = ts, ts a.chunks[0] = NewChunk(t0).Push(ts, val) a.addAggregators(ts, val) return } if t0 == a.lastT0 { // last prior data was in same chunk as new point a.chunks[a.indexFor(t0)].Push(ts, val) } else { // the point needs a newer chunk than points we've seen before prev := a.indexFor(a.lastT0) a.chunks[prev].Finish() a.Persist(a.chunks[prev]) // TODO: create empty series in between, if there's a gap. -> actually no, we may just as well keep the old data // but we have to make sure we don't accidentally return the old data out of order now := a.indexFor(t0) a.chunks[now] = NewChunk(t0).Push(ts, val) // update firstTs to oldest t0 var found *Chunk if now > prev { for i := prev; i <= now && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } } else { for i := prev; i < uint32(len(a.chunks)) && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } for i := uint32(0); i <= now && found == nil; i++ { if a.chunks[i] != nil { found = a.chunks[i] } } } a.firstTs = found.t0 a.lastT0 = t0 } a.lastTs = ts a.addAggregators(ts, val) }
// Copyright 2015 Davis Webb // Copyright 2015 Luke Shumaker // Copyright 2015 Guntas Grewal package store import ( "github.com/jinzhu/gorm" he "httpentity" "httpentity/util" // heutil "io" "jsonpatch" "periwinkle/util" // putil "strings" ) var _ he.Entity = &Group{} var _ he.NetEntity = &Group{} var dirGroups he.Entity = newDirGroups() // Model ///////////////////////////////////////////////////////////// type Group struct { Id string `json:"group_id"` Addresses []GroupAddress `json:"addresses"` } func (o Group) dbSchema(db *gorm.DB) error { return db.CreateTable(&o).Error } type GroupAddress struct { Id int64 `json:"group_address_id"` GroupId string `json:"group_id"` Medium string `json:"medium"` Address string `json:"address"` } func (o GroupAddress) dbSchema(db *gorm.DB) error { return db.CreateTable(&o). AddForeignKey("group_id", "groups(id)", "RESTRICT", "RESTRICT"). AddForeignKey("medium", "media(id)", "RESTRICT", "RESTRICT"). AddUniqueIndex("uniqueness_idx", "medium", "address"). Error } func GetGroupById(db *gorm.DB, id string) *Group { var o Group if result := db.First(&o, "id = ?", id); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetUsersInGroup(db *gorm.DB, groupId string) *[]User { var users []User err := db.Joins("inner join user_addresses on user_addresses.user_id = users.id").Joins( "inner join subscriptions on subscriptions.address_id = user_addresses.id").Where( "subscriptions.group_id = ?", groupId).Find(&users) if err != nil { panic("could not get users in group") } return &users } func GetGroupByAddress(db *gorm.DB, address string) *Group { var o Group if result := db.Joins("inner join groups on group_addresses.group_id = groups.id").Where("group_addresses.address = ?", address).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetGroupAddressesByMediumAndGroupId(db *gorm.DB, medium string, groupId string) *[]GroupAddress { var o []GroupAddress if result := db.Where("medium =? and group_id =?", medium, groupId).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetGroupAddressesByMedium(db *gorm.DB, medium string) *[]GroupAddress { var o []GroupAddress if result := db.Where("medium =?", medium).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func NewGroup(db *gorm.DB, name string) *Group { o := Group{Id: name} if err := db.Create(&o).Error; err != nil { panic(err) } return &o } func (o *Group) Save(db *gorm.DB) { if err := db.Save(o).Error; err != nil { panic(err) } } func (o *Group) Subentity(name string, req he.Request) he.Entity { panic("TODO: API: (*Group).Subentity()") } func (o *Group) Methods() map[string]func(he.Request) he.Response { return map[string]func(he.Request) he.Response{ "GET": func(req he.Request) he.Response { return he.StatusOK(o) }, "PUT": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) sess := req.Things["session"].(*Session) users := GetUsersInGroup(db, o.Id) flag := false for _, user := range *users { if sess.UserId == user.Id { flag = true break } } if !flag { return he.StatusForbidden(heutil.NetString("Unauthorized user")) } var new_group Group err := safeDecodeJSON(req.Entity, &new_group) if err != nil { return err.Response() } if o.Id != new_group.Id { return he.StatusConflict(heutil.NetString("Cannot change group id")) } *o = new_group o.Save(db) return he.StatusOK(o) }, "PATCH": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) sess := req.Things["session"].(*Session) users := GetUsersInGroup(db, o.Id) flag := false for _, user := range *users { if sess.UserId == user.Id { flag = true break } } if !flag { return he.StatusForbidden(heutil.NetString("Unauthorized user")) } patch, ok := req.Entity.(jsonpatch.Patch) if !ok { return putil.HTTPErrorf(415, "PATCH request must have a patch media type").Response() } var new_group Group err := patch.Apply(o, &new_group) if err != nil { return putil.HTTPErrorf(409, "%v", err).Response() } if o.Id != new_group.Id { return he.StatusConflict(heutil.NetString("Cannot change user id")) } *o = new_group o.Save(db) return he.StatusOK(o) }, "DELETE": func(req he.Request) he.Response { panic("TODO: API: (*Group).Methods()[\"DELETE\"]") }, } } // View ////////////////////////////////////////////////////////////// func (o *Group) Encoders() map[string]func(io.Writer) error { return defaultEncoders(o) } // Directory ("Controller") ////////////////////////////////////////// type t_dirGroups struct { methods map[string]func(he.Request) he.Response } func newDirGroups() t_dirGroups { r := t_dirGroups{} r.methods = map[string]func(he.Request) he.Response{ "POST": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) type postfmt struct { Groupname string `json:"grouponame"` } var entity postfmt httperr := safeDecodeJSON(req.Entity, &entity) if httperr != nil { return httperr.Response() } entity.Groupname = strings.ToLower(entity.Groupname) group := NewGroup(db, entity.Groupname) if group == nil { return he.StatusConflict(heutil.NetString("a group with that name already exists")) } else { return he.StatusCreated(r, entity.Groupname, req) } }, } return r } func (d t_dirGroups) Methods() map[string]func(he.Request) he.Response { return d.methods } func (d t_dirGroups) Subentity(name string, req he.Request) he.Entity { db := req.Things["db"].(*gorm.DB) return GetGroupById(db, name) } added subentity check for group post // Copyright 2015 Davis Webb // Copyright 2015 Luke Shumaker // Copyright 2015 Guntas Grewal package store import ( "github.com/jinzhu/gorm" he "httpentity" "httpentity/util" // heutil "io" "jsonpatch" "periwinkle/util" // putil "strings" ) var _ he.Entity = &Group{} var _ he.NetEntity = &Group{} var dirGroups he.Entity = newDirGroups() // Model ///////////////////////////////////////////////////////////// type Group struct { Id string `json:"group_id"` Addresses []GroupAddress `json:"addresses"` } func (o Group) dbSchema(db *gorm.DB) error { return db.CreateTable(&o).Error } type GroupAddress struct { Id int64 `json:"group_address_id"` GroupId string `json:"group_id"` Medium string `json:"medium"` Address string `json:"address"` } func (o GroupAddress) dbSchema(db *gorm.DB) error { return db.CreateTable(&o). AddForeignKey("group_id", "groups(id)", "RESTRICT", "RESTRICT"). AddForeignKey("medium", "media(id)", "RESTRICT", "RESTRICT"). AddUniqueIndex("uniqueness_idx", "medium", "address"). Error } func GetGroupById(db *gorm.DB, id string) *Group { var o Group if result := db.First(&o, "id = ?", id); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetUsersInGroup(db *gorm.DB, groupId string) *[]User { var users []User err := db.Joins("inner join user_addresses on user_addresses.user_id = users.id").Joins( "inner join subscriptions on subscriptions.address_id = user_addresses.id").Where( "subscriptions.group_id = ?", groupId).Find(&users) if err != nil { panic("could not get users in group") } return &users } func GetGroupByAddress(db *gorm.DB, address string) *Group { var o Group if result := db.Joins("inner join groups on group_addresses.group_id = groups.id").Where("group_addresses.address = ?", address).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetGroupAddressesByMediumAndGroupId(db *gorm.DB, medium string, groupId string) *[]GroupAddress { var o []GroupAddress if result := db.Where("medium =? and group_id =?", medium, groupId).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func GetGroupAddressesByMedium(db *gorm.DB, medium string) *[]GroupAddress { var o []GroupAddress if result := db.Where("medium =?", medium).Find(&o); result.Error != nil { if result.RecordNotFound() { return nil } panic(result.Error) } return &o } func NewGroup(db *gorm.DB, name string) *Group { o := Group{Id: name} if err := db.Create(&o).Error; err != nil { panic(err) } return &o } func (o *Group) Save(db *gorm.DB) { if err := db.Save(o).Error; err != nil { panic(err) } } func (o *Group) Subentity(name string, req he.Request) he.Entity { panic("TODO: API: (*Group).Subentity()") } func (o *Group) Methods() map[string]func(he.Request) he.Response { return map[string]func(he.Request) he.Response{ "GET": func(req he.Request) he.Response { return he.StatusOK(o) }, "PUT": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) sess := req.Things["session"].(*Session) users := GetUsersInGroup(db, o.Id) flag := false for _, user := range *users { if sess.UserId == user.Id { flag = true break } } if !flag { return he.StatusForbidden(heutil.NetString("Unauthorized user")) } var new_group Group err := safeDecodeJSON(req.Entity, &new_group) if err != nil { return err.Response() } if o.Id != new_group.Id { return he.StatusConflict(heutil.NetString("Cannot change group id")) } *o = new_group o.Save(db) return he.StatusOK(o) }, "PATCH": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) sess := req.Things["session"].(*Session) users := GetUsersInGroup(db, o.Id) flag := false for _, user := range *users { if sess.UserId == user.Id { flag = true break } } if !flag { return he.StatusForbidden(heutil.NetString("Unauthorized user")) } patch, ok := req.Entity.(jsonpatch.Patch) if !ok { return putil.HTTPErrorf(415, "PATCH request must have a patch media type").Response() } var new_group Group err := patch.Apply(o, &new_group) if err != nil { return putil.HTTPErrorf(409, "%v", err).Response() } if o.Id != new_group.Id { return he.StatusConflict(heutil.NetString("Cannot change user id")) } *o = new_group o.Save(db) return he.StatusOK(o) }, "DELETE": func(req he.Request) he.Response { panic("TODO: API: (*Group).Methods()[\"DELETE\"]") }, } } // View ////////////////////////////////////////////////////////////// func (o *Group) Encoders() map[string]func(io.Writer) error { return defaultEncoders(o) } // Directory ("Controller") ////////////////////////////////////////// type t_dirGroups struct { methods map[string]func(he.Request) he.Response } func newDirGroups() t_dirGroups { r := t_dirGroups{} r.methods = map[string]func(he.Request) he.Response{ "POST": func(req he.Request) he.Response { db := req.Things["db"].(*gorm.DB) type postfmt struct { Groupname string `json:"grouponame"` } var entity postfmt httperr := safeDecodeJSON(req.Entity, &entity) if httperr != nil { return httperr.Response() } entity.Groupname = strings.ToLower(entity.Groupname) group := NewGroup(db, entity.Groupname) if group == nil { return he.StatusConflict(heutil.NetString("a group with that name already exists")) } else { return he.StatusCreated(r, entity.Groupname, req) } }, } return r } func (d t_dirGroups) Methods() map[string]func(he.Request) he.Response { return d.methods } func (d t_dirGroups) Subentity(name string, req he.Request) he.Entity { name = strings.ToLower(name) sess := req.Things["session"].(*Session) if sess == nil && req.Method == "POST" { group, ok := req.Things["group"].(Group) if !ok { return nil } if group.Id == name { return &group } return nil } db := req.Things["db"].(*gorm.DB) return GetGroupById(db, name) }
// +build linux /* directory structure . |-- repositoryName |-- scratch |-- shardNum // the read-only read created on InitRepository, this is where to start branching |-- commitID |-- shardNum // this is where subvolumes are */ package btrfs import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "time" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/drive" "github.com/pachyderm/pachyderm/src/pkg/executil" "github.com/peter-edge/go-google-protobuf" "github.com/satori/go.uuid" ) const ( metadataDir = ".pfs" ) type driver struct { rootDir string namespace string } func newDriver(rootDir string, namespace string) (*driver, error) { if namespace != "" { if err := os.MkdirAll(filepath.Join(rootDir, namespace), 0700); err != nil { return nil, err } } return &driver{rootDir, namespace}, nil } func (d *driver) InitRepository(repository *pfs.Repository, shards map[int]bool) error { if err := execSubvolumeCreate(d.repositoryPath(repository)); err != nil && !execSubvolumeExists(d.repositoryPath(repository)) { return err } return nil } func (d *driver) GetFile(path *pfs.Path, shard int) (drive.ReaderAtCloser, error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } return os.Open(filePath) } func (d *driver) GetFileInfo(path *pfs.Path, shard int) (_ *pfs.FileInfo, ok bool, _ error) { filePath, err := d.stat(path, shard) if err != nil && os.IsNotExist(err) { return nil, false, nil } if err != nil { return nil, false, err } return filePath, true, nil } func (d *driver) MakeDirectory(path *pfs.Path, shards map[int]bool) error { // TODO(pedge): if PutFile fails here or on another shard, the directories // will still exist and be returned from ListFiles, we want to do this // iteratively and with rollback for shard := range shards { if err := d.checkWrite(path.Commit, shard); err != nil { return err } filePath, err := d.filePath(path, shard) if err != nil { return err } if err := os.MkdirAll(filePath, 0700); err != nil { return err } } return nil } func (d *driver) PutFile(path *pfs.Path, shard int, offset int64, reader io.Reader) error { if err := d.checkWrite(path.Commit, shard); err != nil { return err } filePath, err := d.filePath(path, shard) if err != nil { return err } file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0666) if err != nil { return err } defer file.Close() if _, err := file.Seek(offset, 0); err != nil { // 0 means relative to start return err } _, err = bufio.NewReader(reader).WriteTo(file) return err } func (d *driver) ListFiles(path *pfs.Path, shard int) (_ []*pfs.FileInfo, retErr error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } stat, err := os.Stat(filePath) if err != nil { return nil, err } if !stat.IsDir() { return nil, fmt.Errorf("%s is not a directory", filePath) } dir, err := os.Open(filePath) if err != nil { return nil, err } defer func() { if err := dir.Close(); err != nil && retErr == nil { retErr = err } }() var fileInfos []*pfs.FileInfo // TODO(pedge): constant for names, err := dir.Readdirnames(100); err != io.EOF; names, err = dir.Readdirnames(100) { if err != nil { return nil, err } for _, name := range names { if inMetadataDir(name) { continue } fileInfo, err := d.stat( &pfs.Path{ Commit: path.Commit, Path: filepath.Join(path.Path, name), }, shard, ) if err != nil { return nil, err } fileInfos = append(fileInfos, fileInfo) } } return fileInfos, nil } func (d *driver) stat(path *pfs.Path, shard int) (*pfs.FileInfo, error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } stat, err := os.Stat(filePath) if err != nil { return nil, err } fileType := pfs.FileType_FILE_TYPE_OTHER if stat.Mode().IsRegular() { fileType = pfs.FileType_FILE_TYPE_REGULAR } if stat.Mode().IsDir() { fileType = pfs.FileType_FILE_TYPE_DIR } return &pfs.FileInfo{ Path: path, FileType: fileType, SizeBytes: uint64(stat.Size()), Perm: uint32(stat.Mode() & os.ModePerm), LastModified: &google_protobuf.Timestamp{ Seconds: stat.ModTime().UnixNano() / int64(time.Second), Nanos: int32(stat.ModTime().UnixNano() % int64(time.Second)), }, }, nil } func (d *driver) Branch(commit *pfs.Commit, newCommit *pfs.Commit, shards map[int]bool) (*pfs.Commit, error) { if commit == nil && newCommit == nil { return nil, fmt.Errorf("pachyderm: must specify either commit or newCommit") } if newCommit == nil { newCommit = &pfs.Commit{ Repository: commit.Repository, Id: newCommitID(), } } if err := execSubvolumeCreate(d.commitPathNoShard(newCommit)); err != nil && !execSubvolumeExists(d.commitPathNoShard(newCommit)) { return nil, err } for shard := range shards { newCommitPath := d.writeCommitPath(newCommit, shard) if commit != nil { if err := d.checkReadOnly(commit, shard); err != nil { return nil, err } commitPath, err := d.commitPath(commit, shard) if err != nil { return nil, err } if err := execSubvolumeSnapshot(commitPath, newCommitPath, false); err != nil { return nil, err } filePath, err := d.filePath(&pfs.Path{Commit: newCommit, Path: filepath.Join(metadataDir, "parent")}, shard) if err != nil { return nil, err } if err := ioutil.WriteFile(filePath, []byte(commit.Id), 0600); err != nil { return nil, err } } else { if err := execSubvolumeCreate(newCommitPath); err != nil { return nil, err } filePath, err := d.filePath(&pfs.Path{Commit: newCommit, Path: metadataDir}, shard) if err != nil { return nil, err } if err := os.Mkdir(filePath, 0700); err != nil { return nil, err } } } return newCommit, nil } func (d *driver) Commit(commit *pfs.Commit, shards map[int]bool) error { for shard := range shards { if err := execSubvolumeSnapshot(d.writeCommitPath(commit, shard), d.readCommitPath(commit, shard), true); err != nil { return err } if err := execSubvolumeDelete(d.writeCommitPath(commit, shard)); err != nil { return err } } return nil } func (d *driver) PullDiff(commit *pfs.Commit, shard int, diff io.Writer) error { parent, err := d.getParent(commit, shard) if err != nil { return err } if parent == nil { return execSend(d.readCommitPath(commit, shard), "", diff) } return execSend(d.readCommitPath(commit, shard), d.readCommitPath(parent, shard), diff) } func (d *driver) PushDiff(commit *pfs.Commit, diff io.Reader) error { if err := execSubvolumeCreate(d.commitPathNoShard(commit)); err != nil && !execSubvolumeExists(d.commitPathNoShard(commit)) { return err } return execRecv(d.commitPathNoShard(commit), diff) } func (d *driver) GetCommitInfo(commit *pfs.Commit, shard int) (_ *pfs.CommitInfo, ok bool, _ error) { _, readErr := os.Stat(d.readCommitPath(commit, shard)) _, writeErr := os.Stat(d.writeCommitPath(commit, shard)) if readErr != nil && os.IsNotExist(readErr) && writeErr != nil && os.IsNotExist(writeErr) { return nil, false, nil } parent, err := d.getParent(commit, shard) if err != nil { return nil, false, err } readOnly, err := d.getReadOnly(commit, shard) if err != nil { return nil, false, err } commitType := pfs.CommitType_COMMIT_TYPE_WRITE if readOnly { commitType = pfs.CommitType_COMMIT_TYPE_READ } return &pfs.CommitInfo{ Commit: commit, CommitType: commitType, ParentCommit: parent, }, true, nil } func (d *driver) ListCommits(repository *pfs.Repository, shard int) (_ []*pfs.CommitInfo, retErr error) { var commitInfos []*pfs.CommitInfo //TODO this buffer might get too big var buffer bytes.Buffer if err := execSubvolumeList(d.repositoryPath(repository), "", false, &buffer); err != nil { return nil, err } commitScanner := newCommitScanner(&buffer, d.namespace, repository.Name) for commitScanner.Scan() { commitID := commitScanner.Commit() commitInfo, ok, err := d.GetCommitInfo( &pfs.Commit{ Repository: repository, Id: commitID, }, shard, ) if !ok { // This is a really weird error to get since we got this commit // name by listing commits. This is probably indicative of a // race condition. return nil, fmt.Errorf("Commit not found.") } if err != nil { return nil, err } commitInfos = append(commitInfos, commitInfo) } return commitInfos, nil } func (d *driver) getParent(commit *pfs.Commit, shard int) (*pfs.Commit, error) { filePath, err := d.filePath(&pfs.Path{Commit: commit, Path: filepath.Join(metadataDir, "parent")}, shard) if err != nil { return nil, err } data, err := ioutil.ReadFile(filePath) if os.IsNotExist(err) { return nil, nil } if err != nil { return nil, err } return &pfs.Commit{ Repository: commit.Repository, Id: string(data), }, nil } func (d *driver) checkReadOnly(commit *pfs.Commit, shard int) error { ok, err := d.getReadOnly(commit, shard) if err != nil { return err } if !ok { return fmt.Errorf("%+v is not a read only commit", commit) } return nil } func (d *driver) checkWrite(commit *pfs.Commit, shard int) error { ok, err := d.getReadOnly(commit, shard) if err != nil { return err } if ok { return fmt.Errorf("%+v is not a write commit", commit) } return nil } func (d *driver) getReadOnly(commit *pfs.Commit, shard int) (bool, error) { if execSubvolumeExists(d.readCommitPath(commit, shard)) { return true, nil } else if execSubvolumeExists(d.writeCommitPath(commit, shard)) { return false, nil } else { return false, fmt.Errorf("pachyderm: commit %s doesn't exist", commit.Id) } } func (d *driver) repositoryPath(repository *pfs.Repository) string { return filepath.Join(d.rootDir, d.namespace, repository.Name) } func (d *driver) commitPathNoShard(commit *pfs.Commit) string { return filepath.Join(d.repositoryPath(commit.Repository), commit.Id) } func (d *driver) readCommitPath(commit *pfs.Commit, shard int) string { return filepath.Join(d.commitPathNoShard(commit), fmt.Sprint(shard)) } func (d *driver) writeCommitPath(commit *pfs.Commit, shard int) string { return d.readCommitPath(commit, shard) + ".write" } func (d *driver) commitPath(commit *pfs.Commit, shard int) (string, error) { readOnly, err := d.getReadOnly(commit, shard) if err != nil { return "", err } if readOnly { return d.readCommitPath(commit, shard), nil } return d.writeCommitPath(commit, shard), nil } func (d *driver) filePath(path *pfs.Path, shard int) (string, error) { commitPath, err := d.commitPath(path.Commit, shard) if err != nil { return "", err } return filepath.Join(commitPath, path.Path), nil } func newCommitID() string { return strings.Replace(uuid.NewV4().String(), "-", "", -1) } func inMetadataDir(name string) bool { parts := strings.Split(name, "/") return (len(parts) > 0 && parts[0] == metadataDir) } func execSubvolumeCreate(path string) error { return executil.Run("btrfs", "subvolume", "create", path) } func execSubvolumeDelete(path string) error { return executil.Run("btrfs", "subvolume", "delete", path) } func execSubvolumeExists(path string) bool { if err := executil.Run("btrfs", "subvolume", "show", path); err != nil { return false } return true } func execSubvolumeSnapshot(src string, dest string, readOnly bool) error { if readOnly { return executil.Run("btrfs", "subvolume", "snapshot", "-r", src, dest) } return executil.Run("btrfs", "subvolume", "snapshot", src, dest) } func execTransID(path string) (string, error) { // "9223372036854775810" == 2 ** 63 we use a very big number there so that // we get the transid of the from path. According to the internet this is // the nicest way to get it from btrfs. var buffer bytes.Buffer if err := executil.RunStdout(&buffer, "btrfs", "subvolume", "find-new", path, "9223372036854775808"); err != nil { return "", err } scanner := bufio.NewScanner(&buffer) for scanner.Scan() { // scanner.Text() looks like this: // transid marker was 907 // 0 1 2 3 tokens := strings.Split(scanner.Text(), " ") if len(tokens) != 4 { return "", fmt.Errorf("pachyderm: failed to parse find-new output") } // We want to increment the transid because it's inclusive, if we // don't increment we'll get things from the previous commit as // well. return tokens[3], nil } if scanner.Err() != nil { return "", scanner.Err() } return "", fmt.Errorf("pachyderm: empty output from find-new") } func execSubvolumeList(path string, fromCommit string, ascending bool, out io.Writer) error { var sort string if ascending { sort = "+ogen" } else { sort = "-ogen" } if fromCommit == "" { return executil.RunStdout(out, "btrfs", "subvolume", "list", "-a", "--sort", sort, path) } transid, err := execTransID(fromCommit) if err != nil { return err } return executil.RunStdout(out, "btrfs", "subvolume", "list", "-aC", "+"+transid, "--sort", sort, path) } type commitScanner struct { textScanner *bufio.Scanner namespace string repository string } func newCommitScanner(reader io.Reader, namespace string, repository string) *commitScanner { return &commitScanner{bufio.NewScanner(reader), namespace, repository} } func (c *commitScanner) Scan() bool { for { if !c.textScanner.Scan() { return false } if _, ok := c.parseCommit(c.textScanner.Text()); ok { return true } } } func (c *commitScanner) Err() error { return c.textScanner.Err() } func (c *commitScanner) Commit() string { commit, _ := c.parseCommit(c.textScanner.Text()) return commit } func (c *commitScanner) parseCommit(listLine string) (string, bool) { // listLine looks like: // ID 905 gen 865 top level 5 path <FS_TREE>/repo/commit // 0 1 2 3 4 5 6 7 8 tokens := strings.Split(c.textScanner.Text(), " ") if len(tokens) != 9 { return "", false } if strings.HasPrefix(tokens[8], filepath.Join("<FS_TREE>", c.namespace, c.repository)) && len(strings.Split(tokens[8], "/")) == 4 { return strings.Split(tokens[8], "/")[3], true } return "", false } func execSend(path string, parent string, diff io.Writer) error { if parent == "" { return executil.RunStdout(diff, "btrfs", "send", path) } return executil.RunStdout(diff, "btrfs", "send", "-p", parent, path) } func execRecv(path string, diff io.Reader) error { return executil.RunStdin(diff, "btrfs", "receive", path) } Fix commit parsing when there's no namespace. // +build linux /* directory structure . |-- repositoryName |-- scratch |-- shardNum // the read-only read created on InitRepository, this is where to start branching |-- commitID |-- shardNum // this is where subvolumes are */ package btrfs import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "time" "github.com/pachyderm/pachyderm/src/pfs" "github.com/pachyderm/pachyderm/src/pfs/drive" "github.com/pachyderm/pachyderm/src/pkg/executil" "github.com/peter-edge/go-google-protobuf" "github.com/satori/go.uuid" ) const ( metadataDir = ".pfs" ) type driver struct { rootDir string namespace string } func newDriver(rootDir string, namespace string) (*driver, error) { if namespace != "" { if err := os.MkdirAll(filepath.Join(rootDir, namespace), 0700); err != nil { return nil, err } } return &driver{rootDir, namespace}, nil } func (d *driver) InitRepository(repository *pfs.Repository, shards map[int]bool) error { if err := execSubvolumeCreate(d.repositoryPath(repository)); err != nil && !execSubvolumeExists(d.repositoryPath(repository)) { return err } return nil } func (d *driver) GetFile(path *pfs.Path, shard int) (drive.ReaderAtCloser, error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } return os.Open(filePath) } func (d *driver) GetFileInfo(path *pfs.Path, shard int) (_ *pfs.FileInfo, ok bool, _ error) { filePath, err := d.stat(path, shard) if err != nil && os.IsNotExist(err) { return nil, false, nil } if err != nil { return nil, false, err } return filePath, true, nil } func (d *driver) MakeDirectory(path *pfs.Path, shards map[int]bool) error { // TODO(pedge): if PutFile fails here or on another shard, the directories // will still exist and be returned from ListFiles, we want to do this // iteratively and with rollback for shard := range shards { if err := d.checkWrite(path.Commit, shard); err != nil { return err } filePath, err := d.filePath(path, shard) if err != nil { return err } if err := os.MkdirAll(filePath, 0700); err != nil { return err } } return nil } func (d *driver) PutFile(path *pfs.Path, shard int, offset int64, reader io.Reader) error { if err := d.checkWrite(path.Commit, shard); err != nil { return err } filePath, err := d.filePath(path, shard) if err != nil { return err } file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0666) if err != nil { return err } defer file.Close() if _, err := file.Seek(offset, 0); err != nil { // 0 means relative to start return err } _, err = bufio.NewReader(reader).WriteTo(file) return err } func (d *driver) ListFiles(path *pfs.Path, shard int) (_ []*pfs.FileInfo, retErr error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } stat, err := os.Stat(filePath) if err != nil { return nil, err } if !stat.IsDir() { return nil, fmt.Errorf("%s is not a directory", filePath) } dir, err := os.Open(filePath) if err != nil { return nil, err } defer func() { if err := dir.Close(); err != nil && retErr == nil { retErr = err } }() var fileInfos []*pfs.FileInfo // TODO(pedge): constant for names, err := dir.Readdirnames(100); err != io.EOF; names, err = dir.Readdirnames(100) { if err != nil { return nil, err } for _, name := range names { if inMetadataDir(name) { continue } fileInfo, err := d.stat( &pfs.Path{ Commit: path.Commit, Path: filepath.Join(path.Path, name), }, shard, ) if err != nil { return nil, err } fileInfos = append(fileInfos, fileInfo) } } return fileInfos, nil } func (d *driver) stat(path *pfs.Path, shard int) (*pfs.FileInfo, error) { filePath, err := d.filePath(path, shard) if err != nil { return nil, err } stat, err := os.Stat(filePath) if err != nil { return nil, err } fileType := pfs.FileType_FILE_TYPE_OTHER if stat.Mode().IsRegular() { fileType = pfs.FileType_FILE_TYPE_REGULAR } if stat.Mode().IsDir() { fileType = pfs.FileType_FILE_TYPE_DIR } return &pfs.FileInfo{ Path: path, FileType: fileType, SizeBytes: uint64(stat.Size()), Perm: uint32(stat.Mode() & os.ModePerm), LastModified: &google_protobuf.Timestamp{ Seconds: stat.ModTime().UnixNano() / int64(time.Second), Nanos: int32(stat.ModTime().UnixNano() % int64(time.Second)), }, }, nil } func (d *driver) Branch(commit *pfs.Commit, newCommit *pfs.Commit, shards map[int]bool) (*pfs.Commit, error) { if commit == nil && newCommit == nil { return nil, fmt.Errorf("pachyderm: must specify either commit or newCommit") } if newCommit == nil { newCommit = &pfs.Commit{ Repository: commit.Repository, Id: newCommitID(), } } if err := execSubvolumeCreate(d.commitPathNoShard(newCommit)); err != nil && !execSubvolumeExists(d.commitPathNoShard(newCommit)) { return nil, err } for shard := range shards { newCommitPath := d.writeCommitPath(newCommit, shard) if commit != nil { if err := d.checkReadOnly(commit, shard); err != nil { return nil, err } commitPath, err := d.commitPath(commit, shard) if err != nil { return nil, err } if err := execSubvolumeSnapshot(commitPath, newCommitPath, false); err != nil { return nil, err } filePath, err := d.filePath(&pfs.Path{Commit: newCommit, Path: filepath.Join(metadataDir, "parent")}, shard) if err != nil { return nil, err } if err := ioutil.WriteFile(filePath, []byte(commit.Id), 0600); err != nil { return nil, err } } else { if err := execSubvolumeCreate(newCommitPath); err != nil { return nil, err } filePath, err := d.filePath(&pfs.Path{Commit: newCommit, Path: metadataDir}, shard) if err != nil { return nil, err } if err := os.Mkdir(filePath, 0700); err != nil { return nil, err } } } return newCommit, nil } func (d *driver) Commit(commit *pfs.Commit, shards map[int]bool) error { for shard := range shards { if err := execSubvolumeSnapshot(d.writeCommitPath(commit, shard), d.readCommitPath(commit, shard), true); err != nil { return err } if err := execSubvolumeDelete(d.writeCommitPath(commit, shard)); err != nil { return err } } return nil } func (d *driver) PullDiff(commit *pfs.Commit, shard int, diff io.Writer) error { parent, err := d.getParent(commit, shard) if err != nil { return err } if parent == nil { return execSend(d.readCommitPath(commit, shard), "", diff) } return execSend(d.readCommitPath(commit, shard), d.readCommitPath(parent, shard), diff) } func (d *driver) PushDiff(commit *pfs.Commit, diff io.Reader) error { if err := execSubvolumeCreate(d.commitPathNoShard(commit)); err != nil && !execSubvolumeExists(d.commitPathNoShard(commit)) { return err } return execRecv(d.commitPathNoShard(commit), diff) } func (d *driver) GetCommitInfo(commit *pfs.Commit, shard int) (_ *pfs.CommitInfo, ok bool, _ error) { _, readErr := os.Stat(d.readCommitPath(commit, shard)) _, writeErr := os.Stat(d.writeCommitPath(commit, shard)) if readErr != nil && os.IsNotExist(readErr) && writeErr != nil && os.IsNotExist(writeErr) { return nil, false, nil } parent, err := d.getParent(commit, shard) if err != nil { return nil, false, err } readOnly, err := d.getReadOnly(commit, shard) if err != nil { return nil, false, err } commitType := pfs.CommitType_COMMIT_TYPE_WRITE if readOnly { commitType = pfs.CommitType_COMMIT_TYPE_READ } return &pfs.CommitInfo{ Commit: commit, CommitType: commitType, ParentCommit: parent, }, true, nil } func (d *driver) ListCommits(repository *pfs.Repository, shard int) (_ []*pfs.CommitInfo, retErr error) { var commitInfos []*pfs.CommitInfo //TODO this buffer might get too big var buffer bytes.Buffer if err := execSubvolumeList(d.repositoryPath(repository), "", false, &buffer); err != nil { return nil, err } commitScanner := newCommitScanner(&buffer, d.namespace, repository.Name) for commitScanner.Scan() { commitID := commitScanner.Commit() commitInfo, ok, err := d.GetCommitInfo( &pfs.Commit{ Repository: repository, Id: commitID, }, shard, ) if !ok { // This is a really weird error to get since we got this commit // name by listing commits. This is probably indicative of a // race condition. return nil, fmt.Errorf("Commit %s not found.", commitID) } if err != nil { return nil, err } commitInfos = append(commitInfos, commitInfo) } return commitInfos, nil } func (d *driver) getParent(commit *pfs.Commit, shard int) (*pfs.Commit, error) { filePath, err := d.filePath(&pfs.Path{Commit: commit, Path: filepath.Join(metadataDir, "parent")}, shard) if err != nil { return nil, err } data, err := ioutil.ReadFile(filePath) if os.IsNotExist(err) { return nil, nil } if err != nil { return nil, err } return &pfs.Commit{ Repository: commit.Repository, Id: string(data), }, nil } func (d *driver) checkReadOnly(commit *pfs.Commit, shard int) error { ok, err := d.getReadOnly(commit, shard) if err != nil { return err } if !ok { return fmt.Errorf("%+v is not a read only commit", commit) } return nil } func (d *driver) checkWrite(commit *pfs.Commit, shard int) error { ok, err := d.getReadOnly(commit, shard) if err != nil { return err } if ok { return fmt.Errorf("%+v is not a write commit", commit) } return nil } func (d *driver) getReadOnly(commit *pfs.Commit, shard int) (bool, error) { if execSubvolumeExists(d.readCommitPath(commit, shard)) { return true, nil } else if execSubvolumeExists(d.writeCommitPath(commit, shard)) { return false, nil } else { return false, fmt.Errorf("pachyderm: commit %s doesn't exist", commit.Id) } } func (d *driver) repositoryPath(repository *pfs.Repository) string { return filepath.Join(d.rootDir, d.namespace, repository.Name) } func (d *driver) commitPathNoShard(commit *pfs.Commit) string { return filepath.Join(d.repositoryPath(commit.Repository), commit.Id) } func (d *driver) readCommitPath(commit *pfs.Commit, shard int) string { return filepath.Join(d.commitPathNoShard(commit), fmt.Sprint(shard)) } func (d *driver) writeCommitPath(commit *pfs.Commit, shard int) string { return d.readCommitPath(commit, shard) + ".write" } func (d *driver) commitPath(commit *pfs.Commit, shard int) (string, error) { readOnly, err := d.getReadOnly(commit, shard) if err != nil { return "", err } if readOnly { return d.readCommitPath(commit, shard), nil } return d.writeCommitPath(commit, shard), nil } func (d *driver) filePath(path *pfs.Path, shard int) (string, error) { commitPath, err := d.commitPath(path.Commit, shard) if err != nil { return "", err } return filepath.Join(commitPath, path.Path), nil } func newCommitID() string { return strings.Replace(uuid.NewV4().String(), "-", "", -1) } func inMetadataDir(name string) bool { parts := strings.Split(name, "/") return (len(parts) > 0 && parts[0] == metadataDir) } func execSubvolumeCreate(path string) error { return executil.Run("btrfs", "subvolume", "create", path) } func execSubvolumeDelete(path string) error { return executil.Run("btrfs", "subvolume", "delete", path) } func execSubvolumeExists(path string) bool { if err := executil.Run("btrfs", "subvolume", "show", path); err != nil { return false } return true } func execSubvolumeSnapshot(src string, dest string, readOnly bool) error { if readOnly { return executil.Run("btrfs", "subvolume", "snapshot", "-r", src, dest) } return executil.Run("btrfs", "subvolume", "snapshot", src, dest) } func execTransID(path string) (string, error) { // "9223372036854775810" == 2 ** 63 we use a very big number there so that // we get the transid of the from path. According to the internet this is // the nicest way to get it from btrfs. var buffer bytes.Buffer if err := executil.RunStdout(&buffer, "btrfs", "subvolume", "find-new", path, "9223372036854775808"); err != nil { return "", err } scanner := bufio.NewScanner(&buffer) for scanner.Scan() { // scanner.Text() looks like this: // transid marker was 907 // 0 1 2 3 tokens := strings.Split(scanner.Text(), " ") if len(tokens) != 4 { return "", fmt.Errorf("pachyderm: failed to parse find-new output") } // We want to increment the transid because it's inclusive, if we // don't increment we'll get things from the previous commit as // well. return tokens[3], nil } if scanner.Err() != nil { return "", scanner.Err() } return "", fmt.Errorf("pachyderm: empty output from find-new") } func execSubvolumeList(path string, fromCommit string, ascending bool, out io.Writer) error { var sort string if ascending { sort = "+ogen" } else { sort = "-ogen" } if fromCommit == "" { return executil.RunStdout(out, "btrfs", "subvolume", "list", "-a", "--sort", sort, path) } transid, err := execTransID(fromCommit) if err != nil { return err } return executil.RunStdout(out, "btrfs", "subvolume", "list", "-aC", "+"+transid, "--sort", sort, path) } type commitScanner struct { textScanner *bufio.Scanner namespace string repository string } func newCommitScanner(reader io.Reader, namespace string, repository string) *commitScanner { return &commitScanner{bufio.NewScanner(reader), namespace, repository} } func (c *commitScanner) Scan() bool { for { if !c.textScanner.Scan() { return false } if _, ok := c.parseCommit(c.textScanner.Text()); ok { return true } } } func (c *commitScanner) Err() error { return c.textScanner.Err() } func (c *commitScanner) Commit() string { commit, _ := c.parseCommit(c.textScanner.Text()) return commit } func (c *commitScanner) parseCommit(listLine string) (string, bool) { // listLine looks like: // ID 905 gen 865 top level 5 path <FS_TREE>/[namespace/]repo/commit // 0 1 2 3 4 5 6 7 8 tokens := strings.Split(c.textScanner.Text(), " ") if len(tokens) != 9 { return "", false } if c.namespace == "" { if strings.HasPrefix(tokens[8], filepath.Join("<FS_TREE>", c.repository)) && len(strings.Split(tokens[8], "/")) == 3 { return strings.Split(tokens[8], "/")[2], true } } else { if strings.HasPrefix(tokens[8], filepath.Join("<FS_TREE>", c.namespace, c.repository)) && len(strings.Split(tokens[8], "/")) == 4 { return strings.Split(tokens[8], "/")[3], true } } return "", false } func execSend(path string, parent string, diff io.Writer) error { if parent == "" { return executil.RunStdout(diff, "btrfs", "send", path) } return executil.RunStdout(diff, "btrfs", "send", "-p", parent, path) } func execRecv(path string, diff io.Reader) error { return executil.RunStdin(diff, "btrfs", "receive", path) }
package tokay import ( "bytes" "github.com/valyala/fasthttp" ) // RouterGroup represents a group of routes that share the same path prefix. type RouterGroup struct { path string engine *Engine handlers []Handler } // newRouteGroup creates a new RouterGroup with the given path, engine, and handlers. func newRouteGroup(path string, engine *Engine, handlers []Handler) *RouterGroup { return &RouterGroup{ path: path, engine: engine, handlers: handlers, } } // Path returns RouterGroup fullpath func (r *RouterGroup) Path() (path string) { return r.path } // GET adds a GET route to the engine with the given route path and handlers. func (r *RouterGroup) GET(path string, handlers ...Handler) *Route { return newRoute(path, r).GET(handlers...) } // POST adds a POST route to the engine with the given route path and handlers. func (r *RouterGroup) POST(path string, handlers ...Handler) *Route { return newRoute(path, r).POST(handlers...) } // PUT adds a PUT route to the engine with the given route path and handlers. func (r *RouterGroup) PUT(path string, handlers ...Handler) *Route { return newRoute(path, r).PUT(handlers...) } // PATCH adds a PATCH route to the engine with the given route path and handlers. func (r *RouterGroup) PATCH(path string, handlers ...Handler) *Route { return newRoute(path, r).PATCH(handlers...) } // DELETE adds a DELETE route to the engine with the given route path and handlers. func (r *RouterGroup) DELETE(path string, handlers ...Handler) *Route { return newRoute(path, r).DELETE(handlers...) } // CONNECT adds a CONNECT route to the engine with the given route path and handlers. func (r *RouterGroup) CONNECT(path string, handlers ...Handler) *Route { return newRoute(path, r).CONNECT(handlers...) } // HEAD adds a HEAD route to the engine with the given route path and handlers. func (r *RouterGroup) HEAD(path string, handlers ...Handler) *Route { return newRoute(path, r).HEAD(handlers...) } // OPTIONS adds an OPTIONS route to the engine with the given route path and handlers. func (r *RouterGroup) OPTIONS(path string, handlers ...Handler) *Route { return newRoute(path, r).OPTIONS(handlers...) } // TRACE adds a TRACE route to the engine with the given route path and handlers. func (r *RouterGroup) TRACE(path string, handlers ...Handler) *Route { return newRoute(path, r).TRACE(handlers...) } // Any adds a route with the given route, handlers, and the HTTP methods as listed in routing.Methods. func (r *RouterGroup) Any(path string, handlers ...Handler) *Route { route := newRoute(path, r) for _, method := range Methods { route.add(method, handlers) } return route } // To adds a route to the engine with the given HTTP methods, route path, and handlers. // Multiple HTTP methods should be separated by commas (without any surrounding spaces). func (r *RouterGroup) To(methods, path string, handlers ...Handler) *Route { return newRoute(path, r).To(methods, handlers...) } // Group creates a RouterGroup with the given route path and handlers. // The new group will combine the existing path with the new one. // If no handler is provided, the new group will inherit the handlers registered // with the current group. func (r *RouterGroup) Group(path string, handlers ...Handler) *RouterGroup { if len(handlers) == 0 { handlers = make([]Handler, len(r.handlers)) copy(handlers, r.handlers) } if path == "" || path[0] != '/' { path = "/" + path } return newRouteGroup(r.path+path, r.engine, handlers) } // Use registers one or multiple handlers to the current route group. // These handlers will be shared by all routes belong to this group and its subgroups. func (r *RouterGroup) Use(handlers ...Handler) { r.handlers = append(r.handlers, handlers...) } // Static serves files from the given file system root. // Where: // 'path' - relative path from current engine path on site (must be without trailing slash), // 'root' - directory that contains served files. For example: // engine.Static("/static", "/var/www") func (r *RouterGroup) Static(path, root string, compress ...bool) *Route { if len(compress) == 0 { compress = append(compress, true) } if path == "" || path[len(path)-1] != '/' { path += "/" } group := r.Group(path) handler := (&fasthttp.FS{ Root: root, Compress: compress[0], PathRewrite: func(ctx *fasthttp.RequestCtx) []byte { return append([]byte{'/'}, bytes.TrimPrefix(ctx.Request.RequestURI(), []byte(group.path))...) }, }).NewRequestHandler() return newRoute("*", group).To("GET,HEAD", func(c *Context) { handler(c.RequestCtx) }) } Clear get request parameters from file names package tokay import ( "strings" "github.com/valyala/fasthttp" ) // RouterGroup represents a group of routes that share the same path prefix. type RouterGroup struct { path string engine *Engine handlers []Handler } // newRouteGroup creates a new RouterGroup with the given path, engine, and handlers. func newRouteGroup(path string, engine *Engine, handlers []Handler) *RouterGroup { return &RouterGroup{ path: path, engine: engine, handlers: handlers, } } // Path returns RouterGroup fullpath func (r *RouterGroup) Path() (path string) { return r.path } // GET adds a GET route to the engine with the given route path and handlers. func (r *RouterGroup) GET(path string, handlers ...Handler) *Route { return newRoute(path, r).GET(handlers...) } // POST adds a POST route to the engine with the given route path and handlers. func (r *RouterGroup) POST(path string, handlers ...Handler) *Route { return newRoute(path, r).POST(handlers...) } // PUT adds a PUT route to the engine with the given route path and handlers. func (r *RouterGroup) PUT(path string, handlers ...Handler) *Route { return newRoute(path, r).PUT(handlers...) } // PATCH adds a PATCH route to the engine with the given route path and handlers. func (r *RouterGroup) PATCH(path string, handlers ...Handler) *Route { return newRoute(path, r).PATCH(handlers...) } // DELETE adds a DELETE route to the engine with the given route path and handlers. func (r *RouterGroup) DELETE(path string, handlers ...Handler) *Route { return newRoute(path, r).DELETE(handlers...) } // CONNECT adds a CONNECT route to the engine with the given route path and handlers. func (r *RouterGroup) CONNECT(path string, handlers ...Handler) *Route { return newRoute(path, r).CONNECT(handlers...) } // HEAD adds a HEAD route to the engine with the given route path and handlers. func (r *RouterGroup) HEAD(path string, handlers ...Handler) *Route { return newRoute(path, r).HEAD(handlers...) } // OPTIONS adds an OPTIONS route to the engine with the given route path and handlers. func (r *RouterGroup) OPTIONS(path string, handlers ...Handler) *Route { return newRoute(path, r).OPTIONS(handlers...) } // TRACE adds a TRACE route to the engine with the given route path and handlers. func (r *RouterGroup) TRACE(path string, handlers ...Handler) *Route { return newRoute(path, r).TRACE(handlers...) } // Any adds a route with the given route, handlers, and the HTTP methods as listed in routing.Methods. func (r *RouterGroup) Any(path string, handlers ...Handler) *Route { route := newRoute(path, r) for _, method := range Methods { route.add(method, handlers) } return route } // To adds a route to the engine with the given HTTP methods, route path, and handlers. // Multiple HTTP methods should be separated by commas (without any surrounding spaces). func (r *RouterGroup) To(methods, path string, handlers ...Handler) *Route { return newRoute(path, r).To(methods, handlers...) } // Group creates a RouterGroup with the given route path and handlers. // The new group will combine the existing path with the new one. // If no handler is provided, the new group will inherit the handlers registered // with the current group. func (r *RouterGroup) Group(path string, handlers ...Handler) *RouterGroup { if len(handlers) == 0 { handlers = make([]Handler, len(r.handlers)) copy(handlers, r.handlers) } if path == "" || path[0] != '/' { path = "/" + path } return newRouteGroup(r.path+path, r.engine, handlers) } // Use registers one or multiple handlers to the current route group. // These handlers will be shared by all routes belong to this group and its subgroups. func (r *RouterGroup) Use(handlers ...Handler) { r.handlers = append(r.handlers, handlers...) } // Static serves files from the given file system root. // Where: // 'path' - relative path from current engine path on site (must be without trailing slash), // 'root' - directory that contains served files. For example: // engine.Static("/static", "/var/www") func (r *RouterGroup) Static(path, root string, compress ...bool) *Route { if len(compress) == 0 { compress = append(compress, true) } if path == "" || path[len(path)-1] != '/' { path += "/" } group := r.Group(path) handler := (&fasthttp.FS{ Root: root, Compress: compress[0], PathRewrite: func(ctx *fasthttp.RequestCtx) []byte { url := strings.Split(string(ctx.Request.RequestURI()), "?")[0] return []byte("/" + strings.TrimPrefix(url, group.path)) }, }).NewRequestHandler() return newRoute("*", group).To("GET,HEAD", func(c *Context) { handler(c.RequestCtx) }) }
// Copyright 2009 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. // The printer package implements printing of AST nodes. package printer import ( "bytes" "fmt" "go/ast" "go/token" "io" "os" "path" "runtime" "tabwriter" ) const ( debug = false // enable for debugging maxNewlines = 3 // maximum vertical white space ) type whiteSpace int const ( ignore = whiteSpace(0) blank = whiteSpace(' ') vtab = whiteSpace('\v') newline = whiteSpace('\n') formfeed = whiteSpace('\f') indent = whiteSpace('>') unindent = whiteSpace('<') ) var ( esc = []byte{tabwriter.Escape} htab = []byte{'\t'} htabs = []byte("\t\t\t\t\t\t\t\t") newlines = []byte("\n\n\n\n\n\n\n\n") // more than maxNewlines formfeeds = []byte("\f\f\f\f\f\f\f\f") // more than maxNewlines esc_quot = []byte("&#34;") // shorter than "&quot;" esc_apos = []byte("&#39;") // shorter than "&apos;" esc_amp = []byte("&amp;") esc_lt = []byte("&lt;") esc_gt = []byte("&gt;") ) // Special positions var noPos token.Position // use noPos when a position is needed but not known var infinity = 1 << 30 // Use ignoreMultiLine if the multiLine information is not important. var ignoreMultiLine = new(bool) type printer struct { // Configuration (does not change after initialization) output io.Writer Config errors chan os.Error // Current state written int // number of bytes written indent int // current indentation escape bool // true if in escape sequence // Buffered whitespace buffer []whiteSpace // The (possibly estimated) position in the generated output; // in AST space (i.e., pos is set whenever a token position is // known accurately, and updated dependending on what has been // written). pos token.Position // The value of pos immediately after the last item has been // written using writeItem. last token.Position // HTML support lastTaggedLine int // last line for which a line tag was written // The list of all source comments, in order of appearance. comments []*ast.CommentGroup // may be nil cindex int // current comment index useNodeComments bool // if not set, ignore lead and line comments of nodes } func (p *printer) init(output io.Writer, cfg *Config) { p.output = output p.Config = *cfg p.errors = make(chan os.Error) p.buffer = make([]whiteSpace, 0, 16) // whitespace sequences are short } func (p *printer) internalError(msg ...interface{}) { if debug { fmt.Print(p.pos.String() + ": ") fmt.Println(msg) panic() } } // write0 writes raw (uninterpreted) data to p.output and handles errors. // write0 does not indent after newlines, and does not HTML-escape or update p.pos. // func (p *printer) write0(data []byte) { n, err := p.output.Write(data) p.written += n if err != nil { p.errors <- err runtime.Goexit() } } // write interprets data and writes it to p.output. It inserts indentation // after a line break unless in a tabwriter escape sequence, and it HTML- // escapes characters if GenHTML is set. It updates p.pos as a side-effect. // func (p *printer) write(data []byte) { i0 := 0 for i, b := range data { switch b { case '\n', '\f': // write segment ending in b p.write0(data[i0 : i+1]) // update p.pos p.pos.Offset += i + 1 - i0 p.pos.Line++ p.pos.Column = 1 if !p.escape { // write indentation // use "hard" htabs - indentation columns // must not be discarded by the tabwriter j := p.indent for ; j > len(htabs); j -= len(htabs) { p.write0(htabs) } p.write0(htabs[0:j]) // update p.pos p.pos.Offset += p.indent p.pos.Column += p.indent } // next segment start i0 = i + 1 case '"', '\'', '&', '<', '>': if p.Mode&GenHTML != 0 { // write segment ending in b p.write0(data[i0:i]) // write HTML-escaped b var esc []byte switch b { case '"': esc = esc_quot case '\'': esc = esc_apos case '&': esc = esc_amp case '<': esc = esc_lt case '>': esc = esc_gt } p.write0(esc) // update p.pos d := i + 1 - i0 p.pos.Offset += d p.pos.Column += d // next segment start i0 = i + 1 } case tabwriter.Escape: p.escape = !p.escape } } // write remaining segment p.write0(data[i0:]) // update p.pos d := len(data) - i0 p.pos.Offset += d p.pos.Column += d } func (p *printer) writeNewlines(n int, useFF bool) { if n > 0 { if n > maxNewlines { n = maxNewlines } if useFF { p.write(formfeeds[0:n]) } else { p.write(newlines[0:n]) } } } func (p *printer) writeTaggedItem(data []byte, tag HTMLTag) { // write start tag, if any // (no html-escaping and no p.pos update for tags - use write0) if tag.Start != "" { p.write0([]byte(tag.Start)) } p.write(data) // write end tag, if any if tag.End != "" { p.write0([]byte(tag.End)) } } // writeItem writes data at position pos. data is the text corresponding to // a single lexical token, but may also be comment text. pos is the actual // (or at least very accurately estimated) position of the data in the original // source text. If tags are present and GenHTML is set, the tags are written // before and after the data. writeItem updates p.last to the position // immediately following the data. // func (p *printer) writeItem(pos token.Position, data []byte, tag HTMLTag) { fileChanged := false if pos.IsValid() { // continue with previous position if we don't have a valid pos if p.last.IsValid() && p.last.Filename != pos.Filename { // the file has changed - reset state // (used when printing merged ASTs of different files // e.g., the result of ast.MergePackageFiles) p.indent = 0 p.escape = false p.buffer = p.buffer[0:0] fileChanged = true } p.pos = pos } if debug { // do not update p.pos - use write0 _, filename := path.Split(pos.Filename) p.write0([]byte(fmt.Sprintf("[%s:%d:%d]", filename, pos.Line, pos.Column))) } if p.Mode&GenHTML != 0 { // write line tag if on a new line // TODO(gri): should write line tags on each line at the start // will be more useful (e.g. to show line numbers) if p.Styler != nil && (pos.Line != p.lastTaggedLine || fileChanged) { p.writeTaggedItem(p.Styler.LineTag(pos.Line)) p.lastTaggedLine = pos.Line } p.writeTaggedItem(data, tag) } else { p.write(data) } p.last = p.pos } // writeCommentPrefix writes the whitespace before a comment. // If there is any pending whitespace, it consumes as much of // it as is likely to help position the comment nicely. // pos is the comment position, next the position of the item // after all pending comments, isFirst indicates if this is the // first comment in a group of comments, and isKeyword indicates // if the next item is a keyword. // func (p *printer) writeCommentPrefix(pos, next token.Position, isFirst, isKeyword bool) { if !p.last.IsValid() { // there was no preceeding item and the comment is the // first item to be printed - don't write any whitespace return } if pos.IsValid() && pos.Filename != p.last.Filename { // comment in a different file - separate with newlines p.writeNewlines(maxNewlines, true) return } if pos.IsValid() && pos.Line == p.last.Line { // comment on the same line as last item: // separate with at least one separator hasSep := false if isFirst { j := 0 for i, ch := range p.buffer { switch ch { case blank: // ignore any blanks before a comment p.buffer[i] = ignore continue case vtab: // respect existing tabs - important // for proper formatting of commented structs hasSep = true continue case indent: // apply pending indentation continue } j = i break } p.writeWhitespace(j) } // make sure there is at least one separator if !hasSep { if pos.Line == next.Line { // next item is on the same line as the comment // (which must be a /*-style comment): separate // with a blank instead of a tab p.write([]byte{' '}) } else { p.write(htab) } } } else { // comment on a different line: // separate with at least one line break if isFirst { j := 0 for i, ch := range p.buffer { switch ch { case blank, vtab: // ignore any horizontal whitespace before line breaks p.buffer[i] = ignore continue case indent: // apply pending indentation continue case unindent: // if the next token is a keyword, apply the outdent // if it appears that the comment is aligned with the // keyword; otherwise assume the outdent is part of a // closing block and stop (this scenario appears with // comments before a case label where the comments // apply to the next case instead of the current one) if isKeyword && pos.Column == next.Column { continue } case newline, formfeed: // TODO(gri): may want to keep formfeed info in some cases p.buffer[i] = ignore } j = i break } p.writeWhitespace(j) } // use formfeeds to break columns before a comment; // this is analogous to using formfeeds to separate // individual lines of /*-style comments // (if !pos.IsValid(), pos.Line == 0, and this will // print no newlines) p.writeNewlines(pos.Line-p.last.Line, true) } } func (p *printer) writeCommentLine(comment *ast.Comment, pos token.Position, line []byte) { // line must pass through unchanged, bracket it with tabwriter.Escape esc := []byte{tabwriter.Escape} line = bytes.Join([][]byte{esc, line, esc}, nil) // apply styler, if any var tag HTMLTag if p.Styler != nil { line, tag = p.Styler.Comment(comment, line) } p.writeItem(pos, line, tag) } // TODO(gri): Similar (but not quite identical) functionality for // comment processing can be found in go/doc/comment.go. // Perhaps this can be factored eventually. // Split comment text into lines func split(text []byte) [][]byte { // count lines (comment text never ends in a newline) n := 1 for _, c := range text { if c == '\n' { n++ } } // split lines := make([][]byte, n) n = 0 i := 0 for j, c := range text { if c == '\n' { lines[n] = text[i:j] // exclude newline i = j + 1 // discard newline n++ } } lines[n] = text[i:] return lines } func isBlank(s []byte) bool { for _, b := range s { if b > ' ' { return false } } return true } func commonPrefix(a, b []byte) []byte { i := 0 for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') { i++ } return a[0:i] } func stripCommonPrefix(lines [][]byte) { if len(lines) < 2 { return // at most one line - nothing to do } // len(lines) >= 2 // The heuristic in this function tries to handle a few // common patterns of /*-style comments: Comments where // the opening /* and closing */ are aligned and the // rest of the comment text is aligned and indented with // blanks or tabs, cases with a vertical "line of stars" // on the left, and cases where the closing */ is on the // same line as the last comment text. // Compute maximum common white prefix of all but the first, // last, and blank lines, and replace blank lines with empty // lines (the first line starts with /* and has no prefix). // In case of two-line comments, consider the last line for // the prefix computation since otherwise the prefix would // be empty. // // Note that the first and last line are never empty (they // contain the opening /* and closing */ respectively) and // thus they can be ignored by the blank line check. var prefix []byte if len(lines) > 2 { for i, line := range lines[1 : len(lines)-1] { switch { case isBlank(line): lines[i+1] = nil case prefix == nil: prefix = commonPrefix(line, line) default: prefix = commonPrefix(prefix, line) } } } else { // len(lines) == 2 line := lines[1] prefix = commonPrefix(line, line) } /* * Check for vertical "line of stars" and correct prefix accordingly. */ lineOfStars := false if i := bytes.Index(prefix, []byte{'*'}); i >= 0 { // Line of stars present. if i > 0 && prefix[i-1] == ' ' { i-- // remove trailing blank from prefix so stars remain aligned } prefix = prefix[0:i] lineOfStars = true } else { // No line of stars present. // Determine the white space on the first line after the /* // and before the beginning of the comment text, assume two // blanks instead of the /* unless the first character after // the /* is a tab. If the first comment line is empty but // for the opening /*, assume up to 3 blanks or a tab. This // whitespace may be found as suffix in the common prefix. first := lines[0] if isBlank(first[2:]) { // no comment text on the first line: // reduce prefix by up to 3 blanks or a tab // if present - this keeps comment text indented // relative to the /* and */'s if it was indented // in the first place i := len(prefix) for n := 0; n < 3 && i > 0 && prefix[i-1] == ' '; n++ { i-- } if i == len(prefix) && i > 0 && prefix[i-1] == '\t' { i-- } prefix = prefix[0:i] } else { // comment text on the first line suffix := make([]byte, len(first)) n := 2 for n < len(first) && first[n] <= ' ' { suffix[n] = first[n] n++ } if n > 2 && suffix[2] == '\t' { // assume the '\t' compensates for the /* suffix = suffix[2:n] } else { // otherwise assume two blanks suffix[0], suffix[1] = ' ', ' ' suffix = suffix[0:n] } // Shorten the computed common prefix by the length of // suffix, if it is found as suffix of the prefix. if bytes.HasSuffix(prefix, suffix) { prefix = prefix[0 : len(prefix)-len(suffix)] } } } // Handle last line: If it only contains a closing */, align it // with the opening /*, otherwise align the text with the other // lines. last := lines[len(lines)-1] closing := []byte("*/") i := bytes.Index(last, closing) if isBlank(last[0:i]) { // last line only contains closing */ var sep []byte if lineOfStars { // insert an aligning blank sep = []byte{' '} } lines[len(lines)-1] = bytes.Join([][]byte{prefix, closing}, sep) } else { // last line contains more comment text - assume // it is aligned like the other lines prefix = commonPrefix(prefix, last) } // Remove the common prefix from all but the first and empty lines. for i, line := range lines { if i > 0 && len(line) != 0 { lines[i] = line[len(prefix):] } } } func (p *printer) writeComment(comment *ast.Comment) { text := comment.Text // shortcut common case of //-style comments if text[1] == '/' { p.writeCommentLine(comment, comment.Pos(), text) return } // for /*-style comments, print line by line and let the // write function take care of the proper indentation lines := split(text) stripCommonPrefix(lines) // write comment lines, separated by formfeed, // without a line break after the last line linebreak := formfeeds[0:1] pos := comment.Pos() for i, line := range lines { if i > 0 { p.write(linebreak) pos = p.pos } if len(line) > 0 { p.writeCommentLine(comment, pos, line) } } } // writeCommentSuffix writes a line break after a comment if indicated // and processes any leftover indentation information. If a line break // is needed, the kind of break (newline vs formfeed) depends on the // pending whitespace. writeCommentSuffix returns true if a pending // formfeed was dropped from the whitespace buffer. // func (p *printer) writeCommentSuffix(needsLinebreak bool) (droppedFF bool) { for i, ch := range p.buffer { switch ch { case blank, vtab: // ignore trailing whitespace p.buffer[i] = ignore case indent, unindent: // don't loose indentation information case newline, formfeed: // if we need a line break, keep exactly one // but remember if we dropped any formfeeds if needsLinebreak { needsLinebreak = false } else { if ch == formfeed { droppedFF = true } p.buffer[i] = ignore } } } p.writeWhitespace(len(p.buffer)) // make sure we have a line break if needsLinebreak { p.write([]byte{'\n'}) } return } // intersperseComments consumes all comments that appear before the next token // tok and prints it together with the buffered whitespace (i.e., the whitespace // that needs to be written before the next token). A heuristic is used to mix // the comments and whitespace. intersperseComments returns true if a pending // formfeed was dropped from the whitespace buffer. // func (p *printer) intersperseComments(next token.Position, tok token.Token) (droppedFF bool) { var last *ast.Comment for ; p.commentBefore(next); p.cindex++ { for _, c := range p.comments[p.cindex].List { p.writeCommentPrefix(c.Pos(), next, last == nil, tok.IsKeyword()) p.writeComment(c) last = c } } if last != nil { if last.Text[1] == '*' && last.Pos().Line == next.Line { // the last comment is a /*-style comment and the next item // follows on the same line: separate with an extra blank p.write([]byte{' '}) } // ensure that there is a newline after a //-style comment // or if we are before a closing '}' or at the end of a file return p.writeCommentSuffix(last.Text[1] == '/' || tok == token.RBRACE || tok == token.EOF) } // no comment was written - we should never reach here since // intersperseComments should not be called in that case p.internalError("intersperseComments called without pending comments") return false } // whiteWhitespace writes the first n whitespace entries. func (p *printer) writeWhitespace(n int) { // write entries var data [1]byte for i := 0; i < n; i++ { switch ch := p.buffer[i]; ch { case ignore: // ignore! case indent: p.indent++ case unindent: p.indent-- if p.indent < 0 { p.internalError("negative indentation:", p.indent) p.indent = 0 } case newline, formfeed: // A line break immediately followed by a "correcting" // unindent is swapped with the unindent - this permits // proper label positioning. If a comment is between // the line break and the label, the unindent is not // part of the comment whitespace prefix and the comment // will be positioned correctly indented. if i+1 < n && p.buffer[i+1] == unindent { // Use a formfeed to terminate the current section. // Otherwise, a long label name on the next line leading // to a wide column may increase the indentation column // of lines before the label; effectively leading to wrong // indentation. p.buffer[i], p.buffer[i+1] = unindent, formfeed i-- // do it again continue } fallthrough default: data[0] = byte(ch) p.write(&data) } } // shift remaining entries down i := 0 for ; n < len(p.buffer); n++ { p.buffer[i] = p.buffer[n] i++ } p.buffer = p.buffer[0:i] } // ---------------------------------------------------------------------------- // Printing interface // print prints a list of "items" (roughly corresponding to syntactic // tokens, but also including whitespace and formatting information). // It is the only print function that should be called directly from // any of the AST printing functions in nodes.go. // // Whitespace is accumulated until a non-whitespace token appears. Any // comments that need to appear before that token are printed first, // taking into account the amount and structure of any pending white- // space for best comment placement. Then, any leftover whitespace is // printed, followed by the actual token. // func (p *printer) print(args ...interface{}) { for _, f := range args { next := p.pos // estimated position of next item var data []byte var tag HTMLTag var tok token.Token switch x := f.(type) { case whiteSpace: if x == ignore { // don't add ignore's to the buffer; they // may screw up "correcting" unindents (see // LabeledStmt) break } i := len(p.buffer) if i == cap(p.buffer) { // Whitespace sequences are very short so this should // never happen. Handle gracefully (but possibly with // bad comment placement) if it does happen. p.writeWhitespace(i) i = 0 } p.buffer = p.buffer[0 : i+1] p.buffer[i] = x case *ast.Ident: if p.Styler != nil { data, tag = p.Styler.Ident(x) } else { data = []byte(x.Name()) } case *ast.BasicLit: if p.Styler != nil { data, tag = p.Styler.BasicLit(x) } else { data = x.Value } // escape all literals so they pass through unchanged // (note that valid Go programs cannot contain esc ('\xff') // bytes since they do not appear in legal UTF-8 sequences) // TODO(gri): do this more efficiently. data = []byte("\xff" + string(data) + "\xff") case token.Token: if p.Styler != nil { data, tag = p.Styler.Token(x) } else { data = []byte(x.String()) } tok = x case token.Position: if x.IsValid() { next = x // accurate position of next item } default: fmt.Fprintf(os.Stderr, "print: unsupported argument type %T\n", f) panic() } p.pos = next if data != nil { droppedFF := p.flush(next, tok) // intersperse extra newlines if present in the source // (don't do this in flush as it will cause extra newlines // at the end of a file) - use formfeeds if we dropped one // before p.writeNewlines(next.Line-p.pos.Line, droppedFF) p.writeItem(next, data, tag) } } } // commentBefore returns true iff the current comment occurs // before the next position in the source code. // func (p *printer) commentBefore(next token.Position) bool { return p.cindex < len(p.comments) && p.comments[p.cindex].List[0].Pos().Offset < next.Offset } // Flush prints any pending comments and whitespace occuring // textually before the position of the next token tok. Flush // returns true if a pending formfeed character was dropped // from the whitespace buffer as a result of interspersing // comments. // func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) { if p.commentBefore(next) { // if there are comments before the next item, intersperse them droppedFF = p.intersperseComments(next, tok) } else { // otherwise, write any leftover whitespace p.writeWhitespace(len(p.buffer)) } return } // ---------------------------------------------------------------------------- // Trimmer // A trimmer is an io.Writer filter for stripping tabwriter.Escape // characters, trailing blanks and tabs, and for converting formfeed // and vtab characters into newlines and htabs (in case no tabwriter // is used). // type trimmer struct { output io.Writer buf bytes.Buffer } // Design note: It is tempting to eliminate extra blanks occuring in // whitespace in this function as it could simplify some // of the blanks logic in the node printing functions. // However, this would mess up any formatting done by // the tabwriter. func (p *trimmer) Write(data []byte) (n int, err os.Error) { // m < 0: no unwritten data except for whitespace // m >= 0: data[m:n] unwritten and no whitespace m := 0 if p.buf.Len() > 0 { m = -1 } var b byte for n, b = range data { switch b { default: // write any pending whitespace if m < 0 { if _, err = p.output.Write(p.buf.Bytes()); err != nil { return } p.buf.Reset() m = n } case '\v': b = '\t' // convert to htab fallthrough case '\t', ' ', tabwriter.Escape: // write any pending (non-whitespace) data if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } m = -1 } // collect whitespace but discard tabwriter.Escapes. if b != tabwriter.Escape { p.buf.WriteByte(b) // WriteByte returns no errors } case '\f', '\n': // discard whitespace p.buf.Reset() // write any pending (non-whitespace) data if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } m = -1 } // convert formfeed into newline if _, err = p.output.Write(newlines[0:1]); err != nil { return } } } n = len(data) // write any pending non-whitespace if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } } return } // ---------------------------------------------------------------------------- // Public interface // General printing is controlled with these Config.Mode flags. const ( GenHTML uint = 1 << iota // generate HTML RawFormat // do not use a tabwriter; if set, UseSpaces is ignored TabIndent // use tabs for indentation independent of UseSpaces UseSpaces // use spaces instead of tabs for alignment ) // An HTMLTag specifies a start and end tag. type HTMLTag struct { Start, End string // empty if tags are absent } // A Styler specifies formatting of line tags and elementary Go words. // A format consists of text and a (possibly empty) surrounding HTML tag. // type Styler interface { LineTag(line int) ([]byte, HTMLTag) Comment(c *ast.Comment, line []byte) ([]byte, HTMLTag) BasicLit(x *ast.BasicLit) ([]byte, HTMLTag) Ident(id *ast.Ident) ([]byte, HTMLTag) Token(tok token.Token) ([]byte, HTMLTag) } // A Config node controls the output of Fprint. type Config struct { Mode uint // default: 0 Tabwidth int // default: 8 Styler Styler // default: nil } // Fprint "pretty-prints" an AST node to output and returns the number // of bytes written and an error (if any) for a given configuration cfg. // The node type must be *ast.File, or assignment-compatible to ast.Expr, // ast.Decl, or ast.Stmt. // func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) { // redirect output through a trimmer to eliminate trailing whitespace // (Input to a tabwriter must be untrimmed since trailing tabs provide // formatting information. The tabwriter could provide trimming // functionality but no tabwriter is used when RawFormat is set.) output = &trimmer{output: output} // setup tabwriter if needed and redirect output var tw *tabwriter.Writer if cfg.Mode&RawFormat == 0 { minwidth := cfg.Tabwidth padchar := byte('\t') if cfg.Mode&UseSpaces != 0 { padchar = ' ' } twmode := tabwriter.DiscardEmptyColumns if cfg.Mode&GenHTML != 0 { twmode |= tabwriter.FilterHTML } if cfg.Mode&TabIndent != 0 { minwidth = 0 twmode |= tabwriter.TabIndent } tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode) output = tw } // setup printer and print node var p printer p.init(output, cfg) go func() { switch n := node.(type) { case ast.Expr: p.useNodeComments = true p.expr(n, ignoreMultiLine) case ast.Stmt: p.useNodeComments = true // A labeled statement will un-indent to position the // label. Set indent to 1 so we don't get indent "underflow". if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt { p.indent = 1 } p.stmt(n, ignoreMultiLine) case ast.Decl: p.useNodeComments = true p.decl(n, atTop, ignoreMultiLine) case ast.Spec: p.useNodeComments = true p.spec(n, 1, atTop, false, ignoreMultiLine) case *ast.File: p.comments = n.Comments p.useNodeComments = n.Comments == nil p.file(n) default: p.errors <- os.NewError(fmt.Sprintf("printer.Fprint: unsupported node type %T", n)) runtime.Goexit() } p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF) p.errors <- nil // no errors }() err := <-p.errors // wait for completion of goroutine // flush tabwriter, if any if tw != nil { tw.Flush() // ignore errors } return p.written, err } // Fprint "pretty-prints" an AST node to output. // It calls Config.Fprint with default settings. // func Fprint(output io.Writer, node interface{}) os.Error { _, err := (&Config{Tabwidth: 8}).Fprint(output, node) // don't care about number of bytes written return err } go/printer: fix a comment R=rsc CC=golang-dev http://codereview.appspot.com/826042 // Copyright 2009 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. // The printer package implements printing of AST nodes. package printer import ( "bytes" "fmt" "go/ast" "go/token" "io" "os" "path" "runtime" "tabwriter" ) const ( debug = false // enable for debugging maxNewlines = 3 // maximum vertical white space ) type whiteSpace int const ( ignore = whiteSpace(0) blank = whiteSpace(' ') vtab = whiteSpace('\v') newline = whiteSpace('\n') formfeed = whiteSpace('\f') indent = whiteSpace('>') unindent = whiteSpace('<') ) var ( esc = []byte{tabwriter.Escape} htab = []byte{'\t'} htabs = []byte("\t\t\t\t\t\t\t\t") newlines = []byte("\n\n\n\n\n\n\n\n") // more than maxNewlines formfeeds = []byte("\f\f\f\f\f\f\f\f") // more than maxNewlines esc_quot = []byte("&#34;") // shorter than "&quot;" esc_apos = []byte("&#39;") // shorter than "&apos;" esc_amp = []byte("&amp;") esc_lt = []byte("&lt;") esc_gt = []byte("&gt;") ) // Special positions var noPos token.Position // use noPos when a position is needed but not known var infinity = 1 << 30 // Use ignoreMultiLine if the multiLine information is not important. var ignoreMultiLine = new(bool) type printer struct { // Configuration (does not change after initialization) output io.Writer Config errors chan os.Error // Current state written int // number of bytes written indent int // current indentation escape bool // true if in escape sequence // Buffered whitespace buffer []whiteSpace // The (possibly estimated) position in the generated output; // in AST space (i.e., pos is set whenever a token position is // known accurately, and updated dependending on what has been // written). pos token.Position // The value of pos immediately after the last item has been // written using writeItem. last token.Position // HTML support lastTaggedLine int // last line for which a line tag was written // The list of all source comments, in order of appearance. comments []*ast.CommentGroup // may be nil cindex int // current comment index useNodeComments bool // if not set, ignore lead and line comments of nodes } func (p *printer) init(output io.Writer, cfg *Config) { p.output = output p.Config = *cfg p.errors = make(chan os.Error) p.buffer = make([]whiteSpace, 0, 16) // whitespace sequences are short } func (p *printer) internalError(msg ...interface{}) { if debug { fmt.Print(p.pos.String() + ": ") fmt.Println(msg) panic() } } // write0 writes raw (uninterpreted) data to p.output and handles errors. // write0 does not indent after newlines, and does not HTML-escape or update p.pos. // func (p *printer) write0(data []byte) { n, err := p.output.Write(data) p.written += n if err != nil { p.errors <- err runtime.Goexit() } } // write interprets data and writes it to p.output. It inserts indentation // after a line break unless in a tabwriter escape sequence, and it HTML- // escapes characters if GenHTML is set. It updates p.pos as a side-effect. // func (p *printer) write(data []byte) { i0 := 0 for i, b := range data { switch b { case '\n', '\f': // write segment ending in b p.write0(data[i0 : i+1]) // update p.pos p.pos.Offset += i + 1 - i0 p.pos.Line++ p.pos.Column = 1 if !p.escape { // write indentation // use "hard" htabs - indentation columns // must not be discarded by the tabwriter j := p.indent for ; j > len(htabs); j -= len(htabs) { p.write0(htabs) } p.write0(htabs[0:j]) // update p.pos p.pos.Offset += p.indent p.pos.Column += p.indent } // next segment start i0 = i + 1 case '"', '\'', '&', '<', '>': if p.Mode&GenHTML != 0 { // write segment ending in b p.write0(data[i0:i]) // write HTML-escaped b var esc []byte switch b { case '"': esc = esc_quot case '\'': esc = esc_apos case '&': esc = esc_amp case '<': esc = esc_lt case '>': esc = esc_gt } p.write0(esc) // update p.pos d := i + 1 - i0 p.pos.Offset += d p.pos.Column += d // next segment start i0 = i + 1 } case tabwriter.Escape: p.escape = !p.escape } } // write remaining segment p.write0(data[i0:]) // update p.pos d := len(data) - i0 p.pos.Offset += d p.pos.Column += d } func (p *printer) writeNewlines(n int, useFF bool) { if n > 0 { if n > maxNewlines { n = maxNewlines } if useFF { p.write(formfeeds[0:n]) } else { p.write(newlines[0:n]) } } } func (p *printer) writeTaggedItem(data []byte, tag HTMLTag) { // write start tag, if any // (no html-escaping and no p.pos update for tags - use write0) if tag.Start != "" { p.write0([]byte(tag.Start)) } p.write(data) // write end tag, if any if tag.End != "" { p.write0([]byte(tag.End)) } } // writeItem writes data at position pos. data is the text corresponding to // a single lexical token, but may also be comment text. pos is the actual // (or at least very accurately estimated) position of the data in the original // source text. If tags are present and GenHTML is set, the tags are written // before and after the data. writeItem updates p.last to the position // immediately following the data. // func (p *printer) writeItem(pos token.Position, data []byte, tag HTMLTag) { fileChanged := false if pos.IsValid() { // continue with previous position if we don't have a valid pos if p.last.IsValid() && p.last.Filename != pos.Filename { // the file has changed - reset state // (used when printing merged ASTs of different files // e.g., the result of ast.MergePackageFiles) p.indent = 0 p.escape = false p.buffer = p.buffer[0:0] fileChanged = true } p.pos = pos } if debug { // do not update p.pos - use write0 _, filename := path.Split(pos.Filename) p.write0([]byte(fmt.Sprintf("[%s:%d:%d]", filename, pos.Line, pos.Column))) } if p.Mode&GenHTML != 0 { // write line tag if on a new line // TODO(gri): should write line tags on each line at the start // will be more useful (e.g. to show line numbers) if p.Styler != nil && (pos.Line != p.lastTaggedLine || fileChanged) { p.writeTaggedItem(p.Styler.LineTag(pos.Line)) p.lastTaggedLine = pos.Line } p.writeTaggedItem(data, tag) } else { p.write(data) } p.last = p.pos } // writeCommentPrefix writes the whitespace before a comment. // If there is any pending whitespace, it consumes as much of // it as is likely to help position the comment nicely. // pos is the comment position, next the position of the item // after all pending comments, isFirst indicates if this is the // first comment in a group of comments, and isKeyword indicates // if the next item is a keyword. // func (p *printer) writeCommentPrefix(pos, next token.Position, isFirst, isKeyword bool) { if !p.last.IsValid() { // there was no preceeding item and the comment is the // first item to be printed - don't write any whitespace return } if pos.IsValid() && pos.Filename != p.last.Filename { // comment in a different file - separate with newlines p.writeNewlines(maxNewlines, true) return } if pos.IsValid() && pos.Line == p.last.Line { // comment on the same line as last item: // separate with at least one separator hasSep := false if isFirst { j := 0 for i, ch := range p.buffer { switch ch { case blank: // ignore any blanks before a comment p.buffer[i] = ignore continue case vtab: // respect existing tabs - important // for proper formatting of commented structs hasSep = true continue case indent: // apply pending indentation continue } j = i break } p.writeWhitespace(j) } // make sure there is at least one separator if !hasSep { if pos.Line == next.Line { // next item is on the same line as the comment // (which must be a /*-style comment): separate // with a blank instead of a tab p.write([]byte{' '}) } else { p.write(htab) } } } else { // comment on a different line: // separate with at least one line break if isFirst { j := 0 for i, ch := range p.buffer { switch ch { case blank, vtab: // ignore any horizontal whitespace before line breaks p.buffer[i] = ignore continue case indent: // apply pending indentation continue case unindent: // if the next token is a keyword, apply the outdent // if it appears that the comment is aligned with the // keyword; otherwise assume the outdent is part of a // closing block and stop (this scenario appears with // comments before a case label where the comments // apply to the next case instead of the current one) if isKeyword && pos.Column == next.Column { continue } case newline, formfeed: // TODO(gri): may want to keep formfeed info in some cases p.buffer[i] = ignore } j = i break } p.writeWhitespace(j) } // use formfeeds to break columns before a comment; // this is analogous to using formfeeds to separate // individual lines of /*-style comments // (if !pos.IsValid(), pos.Line == 0, and this will // print no newlines) p.writeNewlines(pos.Line-p.last.Line, true) } } func (p *printer) writeCommentLine(comment *ast.Comment, pos token.Position, line []byte) { // line must pass through unchanged, bracket it with tabwriter.Escape esc := []byte{tabwriter.Escape} line = bytes.Join([][]byte{esc, line, esc}, nil) // apply styler, if any var tag HTMLTag if p.Styler != nil { line, tag = p.Styler.Comment(comment, line) } p.writeItem(pos, line, tag) } // TODO(gri): Similar (but not quite identical) functionality for // comment processing can be found in go/doc/comment.go. // Perhaps this can be factored eventually. // Split comment text into lines func split(text []byte) [][]byte { // count lines (comment text never ends in a newline) n := 1 for _, c := range text { if c == '\n' { n++ } } // split lines := make([][]byte, n) n = 0 i := 0 for j, c := range text { if c == '\n' { lines[n] = text[i:j] // exclude newline i = j + 1 // discard newline n++ } } lines[n] = text[i:] return lines } func isBlank(s []byte) bool { for _, b := range s { if b > ' ' { return false } } return true } func commonPrefix(a, b []byte) []byte { i := 0 for i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') { i++ } return a[0:i] } func stripCommonPrefix(lines [][]byte) { if len(lines) < 2 { return // at most one line - nothing to do } // len(lines) >= 2 // The heuristic in this function tries to handle a few // common patterns of /*-style comments: Comments where // the opening /* and closing */ are aligned and the // rest of the comment text is aligned and indented with // blanks or tabs, cases with a vertical "line of stars" // on the left, and cases where the closing */ is on the // same line as the last comment text. // Compute maximum common white prefix of all but the first, // last, and blank lines, and replace blank lines with empty // lines (the first line starts with /* and has no prefix). // In case of two-line comments, consider the last line for // the prefix computation since otherwise the prefix would // be empty. // // Note that the first and last line are never empty (they // contain the opening /* and closing */ respectively) and // thus they can be ignored by the blank line check. var prefix []byte if len(lines) > 2 { for i, line := range lines[1 : len(lines)-1] { switch { case isBlank(line): lines[i+1] = nil case prefix == nil: prefix = commonPrefix(line, line) default: prefix = commonPrefix(prefix, line) } } } else { // len(lines) == 2 line := lines[1] prefix = commonPrefix(line, line) } /* * Check for vertical "line of stars" and correct prefix accordingly. */ lineOfStars := false if i := bytes.Index(prefix, []byte{'*'}); i >= 0 { // Line of stars present. if i > 0 && prefix[i-1] == ' ' { i-- // remove trailing blank from prefix so stars remain aligned } prefix = prefix[0:i] lineOfStars = true } else { // No line of stars present. // Determine the white space on the first line after the /* // and before the beginning of the comment text, assume two // blanks instead of the /* unless the first character after // the /* is a tab. If the first comment line is empty but // for the opening /*, assume up to 3 blanks or a tab. This // whitespace may be found as suffix in the common prefix. first := lines[0] if isBlank(first[2:]) { // no comment text on the first line: // reduce prefix by up to 3 blanks or a tab // if present - this keeps comment text indented // relative to the /* and */'s if it was indented // in the first place i := len(prefix) for n := 0; n < 3 && i > 0 && prefix[i-1] == ' '; n++ { i-- } if i == len(prefix) && i > 0 && prefix[i-1] == '\t' { i-- } prefix = prefix[0:i] } else { // comment text on the first line suffix := make([]byte, len(first)) n := 2 for n < len(first) && first[n] <= ' ' { suffix[n] = first[n] n++ } if n > 2 && suffix[2] == '\t' { // assume the '\t' compensates for the /* suffix = suffix[2:n] } else { // otherwise assume two blanks suffix[0], suffix[1] = ' ', ' ' suffix = suffix[0:n] } // Shorten the computed common prefix by the length of // suffix, if it is found as suffix of the prefix. if bytes.HasSuffix(prefix, suffix) { prefix = prefix[0 : len(prefix)-len(suffix)] } } } // Handle last line: If it only contains a closing */, align it // with the opening /*, otherwise align the text with the other // lines. last := lines[len(lines)-1] closing := []byte("*/") i := bytes.Index(last, closing) if isBlank(last[0:i]) { // last line only contains closing */ var sep []byte if lineOfStars { // insert an aligning blank sep = []byte{' '} } lines[len(lines)-1] = bytes.Join([][]byte{prefix, closing}, sep) } else { // last line contains more comment text - assume // it is aligned like the other lines prefix = commonPrefix(prefix, last) } // Remove the common prefix from all but the first and empty lines. for i, line := range lines { if i > 0 && len(line) != 0 { lines[i] = line[len(prefix):] } } } func (p *printer) writeComment(comment *ast.Comment) { text := comment.Text // shortcut common case of //-style comments if text[1] == '/' { p.writeCommentLine(comment, comment.Pos(), text) return } // for /*-style comments, print line by line and let the // write function take care of the proper indentation lines := split(text) stripCommonPrefix(lines) // write comment lines, separated by formfeed, // without a line break after the last line linebreak := formfeeds[0:1] pos := comment.Pos() for i, line := range lines { if i > 0 { p.write(linebreak) pos = p.pos } if len(line) > 0 { p.writeCommentLine(comment, pos, line) } } } // writeCommentSuffix writes a line break after a comment if indicated // and processes any leftover indentation information. If a line break // is needed, the kind of break (newline vs formfeed) depends on the // pending whitespace. writeCommentSuffix returns true if a pending // formfeed was dropped from the whitespace buffer. // func (p *printer) writeCommentSuffix(needsLinebreak bool) (droppedFF bool) { for i, ch := range p.buffer { switch ch { case blank, vtab: // ignore trailing whitespace p.buffer[i] = ignore case indent, unindent: // don't loose indentation information case newline, formfeed: // if we need a line break, keep exactly one // but remember if we dropped any formfeeds if needsLinebreak { needsLinebreak = false } else { if ch == formfeed { droppedFF = true } p.buffer[i] = ignore } } } p.writeWhitespace(len(p.buffer)) // make sure we have a line break if needsLinebreak { p.write([]byte{'\n'}) } return } // intersperseComments consumes all comments that appear before the next token // tok and prints it together with the buffered whitespace (i.e., the whitespace // that needs to be written before the next token). A heuristic is used to mix // the comments and whitespace. intersperseComments returns true if a pending // formfeed was dropped from the whitespace buffer. // func (p *printer) intersperseComments(next token.Position, tok token.Token) (droppedFF bool) { var last *ast.Comment for ; p.commentBefore(next); p.cindex++ { for _, c := range p.comments[p.cindex].List { p.writeCommentPrefix(c.Pos(), next, last == nil, tok.IsKeyword()) p.writeComment(c) last = c } } if last != nil { if last.Text[1] == '*' && last.Pos().Line == next.Line { // the last comment is a /*-style comment and the next item // follows on the same line: separate with an extra blank p.write([]byte{' '}) } // ensure that there is a newline after a //-style comment // or if we are before a closing '}' or at the end of a file return p.writeCommentSuffix(last.Text[1] == '/' || tok == token.RBRACE || tok == token.EOF) } // no comment was written - we should never reach here since // intersperseComments should not be called in that case p.internalError("intersperseComments called without pending comments") return false } // whiteWhitespace writes the first n whitespace entries. func (p *printer) writeWhitespace(n int) { // write entries var data [1]byte for i := 0; i < n; i++ { switch ch := p.buffer[i]; ch { case ignore: // ignore! case indent: p.indent++ case unindent: p.indent-- if p.indent < 0 { p.internalError("negative indentation:", p.indent) p.indent = 0 } case newline, formfeed: // A line break immediately followed by a "correcting" // unindent is swapped with the unindent - this permits // proper label positioning. If a comment is between // the line break and the label, the unindent is not // part of the comment whitespace prefix and the comment // will be positioned correctly indented. if i+1 < n && p.buffer[i+1] == unindent { // Use a formfeed to terminate the current section. // Otherwise, a long label name on the next line leading // to a wide column may increase the indentation column // of lines before the label; effectively leading to wrong // indentation. p.buffer[i], p.buffer[i+1] = unindent, formfeed i-- // do it again continue } fallthrough default: data[0] = byte(ch) p.write(&data) } } // shift remaining entries down i := 0 for ; n < len(p.buffer); n++ { p.buffer[i] = p.buffer[n] i++ } p.buffer = p.buffer[0:i] } // ---------------------------------------------------------------------------- // Printing interface // print prints a list of "items" (roughly corresponding to syntactic // tokens, but also including whitespace and formatting information). // It is the only print function that should be called directly from // any of the AST printing functions in nodes.go. // // Whitespace is accumulated until a non-whitespace token appears. Any // comments that need to appear before that token are printed first, // taking into account the amount and structure of any pending white- // space for best comment placement. Then, any leftover whitespace is // printed, followed by the actual token. // func (p *printer) print(args ...interface{}) { for _, f := range args { next := p.pos // estimated position of next item var data []byte var tag HTMLTag var tok token.Token switch x := f.(type) { case whiteSpace: if x == ignore { // don't add ignore's to the buffer; they // may screw up "correcting" unindents (see // LabeledStmt) break } i := len(p.buffer) if i == cap(p.buffer) { // Whitespace sequences are very short so this should // never happen. Handle gracefully (but possibly with // bad comment placement) if it does happen. p.writeWhitespace(i) i = 0 } p.buffer = p.buffer[0 : i+1] p.buffer[i] = x case *ast.Ident: if p.Styler != nil { data, tag = p.Styler.Ident(x) } else { data = []byte(x.Name()) } case *ast.BasicLit: if p.Styler != nil { data, tag = p.Styler.BasicLit(x) } else { data = x.Value } // escape all literals so they pass through unchanged // (note that valid Go programs cannot contain esc ('\xff') // bytes since they do not appear in legal UTF-8 sequences) // TODO(gri): do this more efficiently. data = []byte("\xff" + string(data) + "\xff") case token.Token: if p.Styler != nil { data, tag = p.Styler.Token(x) } else { data = []byte(x.String()) } tok = x case token.Position: if x.IsValid() { next = x // accurate position of next item } default: fmt.Fprintf(os.Stderr, "print: unsupported argument type %T\n", f) panic() } p.pos = next if data != nil { droppedFF := p.flush(next, tok) // intersperse extra newlines if present in the source // (don't do this in flush as it will cause extra newlines // at the end of a file) - use formfeeds if we dropped one // before p.writeNewlines(next.Line-p.pos.Line, droppedFF) p.writeItem(next, data, tag) } } } // commentBefore returns true iff the current comment occurs // before the next position in the source code. // func (p *printer) commentBefore(next token.Position) bool { return p.cindex < len(p.comments) && p.comments[p.cindex].List[0].Pos().Offset < next.Offset } // Flush prints any pending comments and whitespace occuring // textually before the position of the next token tok. Flush // returns true if a pending formfeed character was dropped // from the whitespace buffer as a result of interspersing // comments. // func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) { if p.commentBefore(next) { // if there are comments before the next item, intersperse them droppedFF = p.intersperseComments(next, tok) } else { // otherwise, write any leftover whitespace p.writeWhitespace(len(p.buffer)) } return } // ---------------------------------------------------------------------------- // Trimmer // A trimmer is an io.Writer filter for stripping tabwriter.Escape // characters, trailing blanks and tabs, and for converting formfeed // and vtab characters into newlines and htabs (in case no tabwriter // is used). // type trimmer struct { output io.Writer buf bytes.Buffer } // Design note: It is tempting to eliminate extra blanks occuring in // whitespace in this function as it could simplify some // of the blanks logic in the node printing functions. // However, this would mess up any formatting done by // the tabwriter. func (p *trimmer) Write(data []byte) (n int, err os.Error) { // m < 0: no unwritten data except for whitespace // m >= 0: data[m:n] unwritten and no whitespace m := 0 if p.buf.Len() > 0 { m = -1 } var b byte for n, b = range data { switch b { default: // write any pending whitespace if m < 0 { if _, err = p.output.Write(p.buf.Bytes()); err != nil { return } p.buf.Reset() m = n } case '\v': b = '\t' // convert to htab fallthrough case '\t', ' ', tabwriter.Escape: // write any pending (non-whitespace) data if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } m = -1 } // collect whitespace but discard tabwriter.Escapes. if b != tabwriter.Escape { p.buf.WriteByte(b) // WriteByte returns no errors } case '\f', '\n': // discard whitespace p.buf.Reset() // write any pending (non-whitespace) data if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } m = -1 } // convert formfeed into newline if _, err = p.output.Write(newlines[0:1]); err != nil { return } } } n = len(data) // write any pending non-whitespace if m >= 0 { if _, err = p.output.Write(data[m:n]); err != nil { return } } return } // ---------------------------------------------------------------------------- // Public interface // General printing is controlled with these Config.Mode flags. const ( GenHTML uint = 1 << iota // generate HTML RawFormat // do not use a tabwriter; if set, UseSpaces is ignored TabIndent // use tabs for indentation independent of UseSpaces UseSpaces // use spaces instead of tabs for alignment ) // An HTMLTag specifies a start and end tag. type HTMLTag struct { Start, End string // empty if tags are absent } // A Styler specifies formatting of line tags and elementary Go words. // A format consists of text and a (possibly empty) surrounding HTML tag. // type Styler interface { LineTag(line int) ([]byte, HTMLTag) Comment(c *ast.Comment, line []byte) ([]byte, HTMLTag) BasicLit(x *ast.BasicLit) ([]byte, HTMLTag) Ident(id *ast.Ident) ([]byte, HTMLTag) Token(tok token.Token) ([]byte, HTMLTag) } // A Config node controls the output of Fprint. type Config struct { Mode uint // default: 0 Tabwidth int // default: 8 Styler Styler // default: nil } // Fprint "pretty-prints" an AST node to output and returns the number // of bytes written and an error (if any) for a given configuration cfg. // The node type must be *ast.File, or assignment-compatible to ast.Expr, // ast.Decl, ast.Spec, or ast.Stmt. // func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) { // redirect output through a trimmer to eliminate trailing whitespace // (Input to a tabwriter must be untrimmed since trailing tabs provide // formatting information. The tabwriter could provide trimming // functionality but no tabwriter is used when RawFormat is set.) output = &trimmer{output: output} // setup tabwriter if needed and redirect output var tw *tabwriter.Writer if cfg.Mode&RawFormat == 0 { minwidth := cfg.Tabwidth padchar := byte('\t') if cfg.Mode&UseSpaces != 0 { padchar = ' ' } twmode := tabwriter.DiscardEmptyColumns if cfg.Mode&GenHTML != 0 { twmode |= tabwriter.FilterHTML } if cfg.Mode&TabIndent != 0 { minwidth = 0 twmode |= tabwriter.TabIndent } tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode) output = tw } // setup printer and print node var p printer p.init(output, cfg) go func() { switch n := node.(type) { case ast.Expr: p.useNodeComments = true p.expr(n, ignoreMultiLine) case ast.Stmt: p.useNodeComments = true // A labeled statement will un-indent to position the // label. Set indent to 1 so we don't get indent "underflow". if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt { p.indent = 1 } p.stmt(n, ignoreMultiLine) case ast.Decl: p.useNodeComments = true p.decl(n, atTop, ignoreMultiLine) case ast.Spec: p.useNodeComments = true p.spec(n, 1, atTop, false, ignoreMultiLine) case *ast.File: p.comments = n.Comments p.useNodeComments = n.Comments == nil p.file(n) default: p.errors <- os.NewError(fmt.Sprintf("printer.Fprint: unsupported node type %T", n)) runtime.Goexit() } p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF) p.errors <- nil // no errors }() err := <-p.errors // wait for completion of goroutine // flush tabwriter, if any if tw != nil { tw.Flush() // ignore errors } return p.written, err } // Fprint "pretty-prints" an AST node to output. // It calls Config.Fprint with default settings. // func Fprint(output io.Writer, node interface{}) os.Error { _, err := (&Config{Tabwidth: 8}).Fprint(output, node) // don't care about number of bytes written return err }
// Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "errors" "fmt" "io" "log" "net" "net/url" "os" "strings" "sync" "time" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes network connections as needed // and caches them for reuse by subsequent calls. It uses HTTP proxies // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and // $no_proxy) environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { idleMu sync.Mutex idleConn map[connectMethodKey][]*persistConn idleConnCh map[connectMethodKey]chan *persistConn reqMu sync.Mutex reqConn map[*Request]*persistConn altMu sync.RWMutex altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(network, addr string) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config // DisableKeepAlives, if true, prevents re-use of TCP connections // between different HTTP requests. DisableKeepAlives bool // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" // request header when the Request contains no existing // Accept-Encoding value. If the Transport requests gzip on // its own and gets a gzipped response, it's transparently // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int // ResponseHeaderTimeout, if non-zero, specifies the amount of // time to wait for a server's response headers after fully // writing the request (including its body, if any). This // time does not include the time to read the response body. ResponseHeaderTimeout time.Duration // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // An error is returned if the proxy environment is invalid. // A nil URL and nil error are returned if no proxy is defined in the // environment, or a proxy should not be used for the given request. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := httpProxyEnv.Get() if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") { // proxy was bogus. Try prepending "http://" to it and // see if that parses correctly. If not, we fall // through and complain about the original one. if proxyURL, err := url.Parse("http://" + proxy); err == nil { return proxyURL, nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. // // For higher-level HTTP client support (such as handling of cookies // and redirects), see Get, Post, and the Client type. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.altMu.RLock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.altMu.RUnlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } if req.URL.Host == "" { return nil, errors.New("http: no Host in request URL") } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.altMu.Lock() defer t.altMu.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.idleMu.Lock() m := t.idleConn t.idleConn = nil t.idleConnCh = nil t.idleMu.Unlock() if m == nil { return } for _, conns := range m { for _, pconn := range conns { pconn.close() } } } // CancelRequest cancels an in-flight request by closing its // connection. func (t *Transport) CancelRequest(req *Request) { t.reqMu.Lock() pc := t.reqConn[req] t.reqMu.Unlock() if pc != nil { pc.conn.Close() } } // // Private implementation past this point. // var ( httpProxyEnv = &envOnce{ names: []string{"HTTP_PROXY", "http_proxy"}, } noProxyEnv = &envOnce{ names: []string{"NO_PROXY", "no_proxy"}, } ) // envOnce looks up an environment variable (optionally by multiple // names) once. It mitigates expensive lookups on some platforms // (e.g. Windows). type envOnce struct { names []string once sync.Once val string } func (e *envOnce) Get() string { e.once.Do(e.init) return e.val } func (e *envOnce) init() { for _, n := range e.names { e.val = os.Getenv(n) if e.val != "" { return } } } // reset is used by tests func (e *envOnce) reset() { e.once = sync.Once{} e.val = "" } func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) { cm.targetScheme = treq.URL.Scheme cm.targetAddr = canonicalAddr(treq.URL) if t.Proxy != nil { cm.proxyURL, err = t.Proxy(treq.Request) } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { username := u.Username() password, _ := u.Password() return "Basic " + basicAuth(username, password) } return "" } // putIdleConn adds pconn to the list of idle persistent connections awaiting // a new request. // If pconn is no longer needed or not in a good state, putIdleConn // returns false. func (t *Transport) putIdleConn(pconn *persistConn) bool { if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return false } if pconn.isBroken() { return false } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } t.idleMu.Lock() waitingDialer := t.idleConnCh[key] select { case waitingDialer <- pconn: // We're done with this pconn and somebody else is // currently waiting for a conn of this type (they're // actively dialing, but this conn is ready // first). Chrome calls this socket late binding. See // https://insouciant.org/tech/connection-management-in-chromium/ t.idleMu.Unlock() return true default: if waitingDialer != nil { // They had populated this, but their dial won // first, so we can clean up this map entry. delete(t.idleConnCh, key) } } if t.idleConn == nil { t.idleConn = make(map[connectMethodKey][]*persistConn) } if len(t.idleConn[key]) >= max { t.idleMu.Unlock() pconn.close() return false } for _, exist := range t.idleConn[key] { if exist == pconn { log.Fatalf("dup idle pconn %p in freelist", pconn) } } t.idleConn[key] = append(t.idleConn[key], pconn) t.idleMu.Unlock() return true } // getIdleConnCh returns a channel to receive and return idle // persistent connection for the given connectMethod. // It may return nil, if persistent connections are not being used. func (t *Transport) getIdleConnCh(cm connectMethod) chan *persistConn { if t.DisableKeepAlives { return nil } key := cm.key() t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConnCh == nil { t.idleConnCh = make(map[connectMethodKey]chan *persistConn) } ch, ok := t.idleConnCh[key] if !ok { ch = make(chan *persistConn) t.idleConnCh[key] = ch } return ch } func (t *Transport) getIdleConn(cm connectMethod) (pconn *persistConn) { key := cm.key() t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConn == nil { return nil } for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[:len(pconns)-1] } if !pconn.isBroken() { return } } } func (t *Transport) setReqConn(r *Request, pc *persistConn) { t.reqMu.Lock() defer t.reqMu.Unlock() if t.reqConn == nil { t.reqConn = make(map[*Request]*persistConn) } if pc != nil { t.reqConn[r] = pc } else { delete(t.reqConn, r) } } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } type dialRes struct { pc *persistConn err error } dialc := make(chan dialRes) go func() { pc, err := t.dialConn(cm) dialc <- dialRes{pc, err} }() idleConnCh := t.getIdleConnCh(cm) select { case v := <-dialc: // Our dial finished. return v.pc, v.err case pc := <-idleConnCh: // Another request finished first and its net.Conn // became available before our dial. Or somebody // else's dial that they didn't use. // But our dial is still going, so give it away // when it finishes: go func() { if v := <-dialc; v.err == nil { t.putIdleConn(v.pc) } }() return pc, nil } } func (t *Transport) dialConn(cm connectMethod) (*persistConn, error) { conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.key(), conn: conn, reqch: make(chan requestAndChan, 50), writech: make(chan writeRequest, 50), closech: make(chan struct{}), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. cfg := t.TLSClientConfig if cfg == nil || cfg.ServerName == "" { host := cm.tlsHost() if cfg == nil { cfg = &tls.Config{ServerName: host} } else { clone := *cfg // shallow clone clone.ServerName = host cfg = &clone } } conn = tls.Client(conn, cfg) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cfg.ServerName); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() go pconn.writeLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := noProxyEnv.Get() if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // no_proxy ".foo.com" matches "bar.foo.com" or "foo.com" return false } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // no_proxy "foo.com" matches "bar.foo.com" return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // ||http|foo.com http directly to server, no proxy // ||https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (cm *connectMethod) key() connectMethodKey { proxyStr := "" targetAddr := cm.targetAddr if cm.proxyURL != nil { proxyStr = cm.proxyURL.String() if cm.targetScheme == "http" { targetAddr = "" } } return connectMethodKey{ proxy: proxyStr, scheme: cm.targetScheme, addr: targetAddr, } } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // connectMethodKey is the map key version of connectMethod, with a // stringified proxy URL (or the empty string) instead of a pointer to // a URL. type connectMethodKey struct { proxy, scheme, addr string } func (k connectMethodKey) String() string { // Only used by tests. return fmt.Sprintf("%s|%s|%s", k.proxy, k.scheme, k.addr) } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey connectMethodKey conn net.Conn closed bool // whether conn has been closed br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip; read by readLoop writech chan writeRequest // written by roundTrip; read by writeLoop closech chan struct{} // broadcast close when readLoop (TCP connection) closes isProxy bool lk sync.Mutex // guards following 3 fields numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) } func (pc *persistConn) isBroken() bool { pc.lk.Lock() b := pc.broken pc.lk.Unlock() return b } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { defer close(pc.closech) alive := true for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch var resp *Response if err == nil { resp, err = ReadResponse(pc.br, rc.req) if err == nil && resp.StatusCode == 100 { // Skip any 100-continue for now. // TODO(bradfitz): if rc.req had "Expect: 100-continue", // actually block the request body write and signal the // writeLoop now to begin sending it. (Issue 2184) For now we // eat it, since we're never expecting one. resp, err = ReadResponse(pc.br, rc.req) } } hasBody := resp != nil && rc.req.Method != "HEAD" && resp.ContentLength != 0 if err != nil { pc.close() } else { if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readerAndCloser{gzReader, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close || resp.StatusCode <= 199 { // Don't do keep-alive on error if either party requested a close // or we get an unexpected informational (1xx) response. // StatusCode 100 is already handled above. alive = false } var waitForBodyRead chan bool if hasBody { waitForBodyRead = make(chan bool, 2) resp.Body.(*bodyEOFSignal).earlyCloseFn = func() error { // Sending false here sets alive to // false and closes the connection // below. waitForBodyRead <- false return nil } resp.Body.(*bodyEOFSignal).fn = func(err error) { alive1 := alive if err != nil { alive1 = false } if alive1 && !pc.t.putIdleConn(pc) { alive1 = false } if !alive1 || pc.isBroken() { pc.close() } waitForBodyRead <- alive1 } } if alive && !hasBody { if !pc.t.putIdleConn(pc) { alive = false } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { alive = <-waitForBodyRead } pc.t.setReqConn(rc.req, nil) if !alive { pc.close() } } } func (pc *persistConn) writeLoop() { for { select { case wr := <-pc.writech: if pc.isBroken() { wr.ch <- errors.New("http: can't write HTTP request on broken connection") continue } err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra) if err == nil { err = pc.bw.Flush() } if err != nil { pc.markBroken() } wr.ch <- err case <-pc.closech: return } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } // A writeRequest is sent by the readLoop's goroutine to the // writeLoop's goroutine to write a request while the read loop // concurrently waits on both the write response and the server's // reply. type writeRequest struct { req *transportRequest ch chan<- error } type httpError struct { err string timeout bool } func (e *httpError) Error() string { return e.err } func (e *httpError) Timeout() bool { return e.timeout } func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true} var errClosed error = &httpError{err: "net/http: transport closed before response was received"} func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { pc.t.setReqConn(req.Request, pc) pc.lk.Lock() pc.numExpectedResponses++ headerFn := pc.mutateHeaderFunc pc.lk.Unlock() if headerFn != nil { headerFn(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" && req.Method != "HEAD" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 // // Note that we don't request this for HEAD requests, // due to a bug in nginx: // http://trac.nginx.org/nginx/ticket/358 // http://golang.org/issue/5522 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } // Write the request concurrently with waiting for a response, // in case the server decides to reply before reading our full // request body. writeErrCh := make(chan error, 1) pc.writech <- writeRequest{req, writeErrCh} resc := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, resc, requestedGzip} var re responseAndError var pconnDeadCh = pc.closech var failTicker <-chan time.Time var respHeaderTimer <-chan time.Time WaitResponse: for { select { case err := <-writeErrCh: if err != nil { re = responseAndError{nil, err} pc.close() break WaitResponse } if d := pc.t.ResponseHeaderTimeout; d > 0 { respHeaderTimer = time.After(d) } case <-pconnDeadCh: // The persist connection is dead. This shouldn't // usually happen (only with Connection: close responses // with no response bodies), but if it does happen it // means either a) the remote server hung up on us // prematurely, or b) the readLoop sent us a response & // closed its closech at roughly the same time, and we // selected this case first, in which case a response // might still be coming soon. // // We can't avoid the select race in b) by using a unbuffered // resc channel instead, because then goroutines can // leak if we exit due to other errors. pconnDeadCh = nil // avoid spinning failTicker = time.After(100 * time.Millisecond) // arbitrary time to wait for resc case <-failTicker: re = responseAndError{err: errClosed} break WaitResponse case <-respHeaderTimer: pc.close() re = responseAndError{err: errTimeout} break WaitResponse case re = <-resc: break WaitResponse } } pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() if re.err != nil { pc.t.setReqConn(req.Request, nil) } return re.res, re.err } // markBroken marks a connection as broken (so it's not reused). // It differs from close in that it doesn't close the underlying // connection for use when it's still being read. func (pc *persistConn) markBroken() { pc.lk.Lock() defer pc.lk.Unlock() pc.broken = true } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true if !pc.closed { pc.conn.Close() pc.closed = true } pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before its final (error-producing) Read or Close call // returns. If earlyCloseFn is non-nil and Close is called before // io.EOF is seen, earlyCloseFn is called instead of fn, and its // return value is the return value from Close. type bodyEOFSignal struct { body io.ReadCloser mu sync.Mutex // guards following 4 fields closed bool // whether Close has been called rerr error // sticky Read error fn func(error) // error will be nil on Read io.EOF earlyCloseFn func() error // optional alt Close func used if io.EOF not seen } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { es.mu.Lock() closed, rerr := es.closed, es.rerr es.mu.Unlock() if closed { return 0, errors.New("http: read on closed response body") } if rerr != nil { return 0, rerr } n, err = es.body.Read(p) if err != nil { es.mu.Lock() defer es.mu.Unlock() if es.rerr == nil { es.rerr = err } es.condfn(err) } return } func (es *bodyEOFSignal) Close() error { es.mu.Lock() defer es.mu.Unlock() if es.closed { return nil } es.closed = true if es.earlyCloseFn != nil && es.rerr != io.EOF { return es.earlyCloseFn() } err := es.body.Close() es.condfn(err) return err } // caller must hold es.mu. func (es *bodyEOFSignal) condfn(err error) { if es.fn == nil { return } if err == io.EOF { err = nil } es.fn(err) es.fn = nil } type readerAndCloser struct { io.Reader io.Closer } net/http: fix comment in connectMethod's key format LGTM=bradfitz R=golang-codereviews, bradfitz CC=golang-codereviews https://codereview.appspot.com/66990045 Committer: Brad Fitzpatrick <ae9783c0b0efc69cd85ab025ddd17aa44cdc4aa5@golang.org> // Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "errors" "fmt" "io" "log" "net" "net/url" "os" "strings" "sync" "time" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes network connections as needed // and caches them for reuse by subsequent calls. It uses HTTP proxies // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and // $no_proxy) environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { idleMu sync.Mutex idleConn map[connectMethodKey][]*persistConn idleConnCh map[connectMethodKey]chan *persistConn reqMu sync.Mutex reqConn map[*Request]*persistConn altMu sync.RWMutex altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(network, addr string) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config // DisableKeepAlives, if true, prevents re-use of TCP connections // between different HTTP requests. DisableKeepAlives bool // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" // request header when the Request contains no existing // Accept-Encoding value. If the Transport requests gzip on // its own and gets a gzipped response, it's transparently // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int // ResponseHeaderTimeout, if non-zero, specifies the amount of // time to wait for a server's response headers after fully // writing the request (including its body, if any). This // time does not include the time to read the response body. ResponseHeaderTimeout time.Duration // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // An error is returned if the proxy environment is invalid. // A nil URL and nil error are returned if no proxy is defined in the // environment, or a proxy should not be used for the given request. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := httpProxyEnv.Get() if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") { // proxy was bogus. Try prepending "http://" to it and // see if that parses correctly. If not, we fall // through and complain about the original one. if proxyURL, err := url.Parse("http://" + proxy); err == nil { return proxyURL, nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. // // For higher-level HTTP client support (such as handling of cookies // and redirects), see Get, Post, and the Client type. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.altMu.RLock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.altMu.RUnlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } if req.URL.Host == "" { return nil, errors.New("http: no Host in request URL") } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.altMu.Lock() defer t.altMu.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.idleMu.Lock() m := t.idleConn t.idleConn = nil t.idleConnCh = nil t.idleMu.Unlock() if m == nil { return } for _, conns := range m { for _, pconn := range conns { pconn.close() } } } // CancelRequest cancels an in-flight request by closing its // connection. func (t *Transport) CancelRequest(req *Request) { t.reqMu.Lock() pc := t.reqConn[req] t.reqMu.Unlock() if pc != nil { pc.conn.Close() } } // // Private implementation past this point. // var ( httpProxyEnv = &envOnce{ names: []string{"HTTP_PROXY", "http_proxy"}, } noProxyEnv = &envOnce{ names: []string{"NO_PROXY", "no_proxy"}, } ) // envOnce looks up an environment variable (optionally by multiple // names) once. It mitigates expensive lookups on some platforms // (e.g. Windows). type envOnce struct { names []string once sync.Once val string } func (e *envOnce) Get() string { e.once.Do(e.init) return e.val } func (e *envOnce) init() { for _, n := range e.names { e.val = os.Getenv(n) if e.val != "" { return } } } // reset is used by tests func (e *envOnce) reset() { e.once = sync.Once{} e.val = "" } func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) { cm.targetScheme = treq.URL.Scheme cm.targetAddr = canonicalAddr(treq.URL) if t.Proxy != nil { cm.proxyURL, err = t.Proxy(treq.Request) } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { username := u.Username() password, _ := u.Password() return "Basic " + basicAuth(username, password) } return "" } // putIdleConn adds pconn to the list of idle persistent connections awaiting // a new request. // If pconn is no longer needed or not in a good state, putIdleConn // returns false. func (t *Transport) putIdleConn(pconn *persistConn) bool { if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return false } if pconn.isBroken() { return false } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } t.idleMu.Lock() waitingDialer := t.idleConnCh[key] select { case waitingDialer <- pconn: // We're done with this pconn and somebody else is // currently waiting for a conn of this type (they're // actively dialing, but this conn is ready // first). Chrome calls this socket late binding. See // https://insouciant.org/tech/connection-management-in-chromium/ t.idleMu.Unlock() return true default: if waitingDialer != nil { // They had populated this, but their dial won // first, so we can clean up this map entry. delete(t.idleConnCh, key) } } if t.idleConn == nil { t.idleConn = make(map[connectMethodKey][]*persistConn) } if len(t.idleConn[key]) >= max { t.idleMu.Unlock() pconn.close() return false } for _, exist := range t.idleConn[key] { if exist == pconn { log.Fatalf("dup idle pconn %p in freelist", pconn) } } t.idleConn[key] = append(t.idleConn[key], pconn) t.idleMu.Unlock() return true } // getIdleConnCh returns a channel to receive and return idle // persistent connection for the given connectMethod. // It may return nil, if persistent connections are not being used. func (t *Transport) getIdleConnCh(cm connectMethod) chan *persistConn { if t.DisableKeepAlives { return nil } key := cm.key() t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConnCh == nil { t.idleConnCh = make(map[connectMethodKey]chan *persistConn) } ch, ok := t.idleConnCh[key] if !ok { ch = make(chan *persistConn) t.idleConnCh[key] = ch } return ch } func (t *Transport) getIdleConn(cm connectMethod) (pconn *persistConn) { key := cm.key() t.idleMu.Lock() defer t.idleMu.Unlock() if t.idleConn == nil { return nil } for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[:len(pconns)-1] } if !pconn.isBroken() { return } } } func (t *Transport) setReqConn(r *Request, pc *persistConn) { t.reqMu.Lock() defer t.reqMu.Unlock() if t.reqConn == nil { t.reqConn = make(map[*Request]*persistConn) } if pc != nil { t.reqConn[r] = pc } else { delete(t.reqConn, r) } } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } type dialRes struct { pc *persistConn err error } dialc := make(chan dialRes) go func() { pc, err := t.dialConn(cm) dialc <- dialRes{pc, err} }() idleConnCh := t.getIdleConnCh(cm) select { case v := <-dialc: // Our dial finished. return v.pc, v.err case pc := <-idleConnCh: // Another request finished first and its net.Conn // became available before our dial. Or somebody // else's dial that they didn't use. // But our dial is still going, so give it away // when it finishes: go func() { if v := <-dialc; v.err == nil { t.putIdleConn(v.pc) } }() return pc, nil } } func (t *Transport) dialConn(cm connectMethod) (*persistConn, error) { conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.key(), conn: conn, reqch: make(chan requestAndChan, 50), writech: make(chan writeRequest, 50), closech: make(chan struct{}), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. cfg := t.TLSClientConfig if cfg == nil || cfg.ServerName == "" { host := cm.tlsHost() if cfg == nil { cfg = &tls.Config{ServerName: host} } else { clone := *cfg // shallow clone clone.ServerName = host cfg = &clone } } conn = tls.Client(conn, cfg) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cfg.ServerName); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() go pconn.writeLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := noProxyEnv.Get() if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // no_proxy ".foo.com" matches "bar.foo.com" or "foo.com" return false } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // no_proxy "foo.com" matches "bar.foo.com" return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // |http|foo.com http directly to server, no proxy // |https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (cm *connectMethod) key() connectMethodKey { proxyStr := "" targetAddr := cm.targetAddr if cm.proxyURL != nil { proxyStr = cm.proxyURL.String() if cm.targetScheme == "http" { targetAddr = "" } } return connectMethodKey{ proxy: proxyStr, scheme: cm.targetScheme, addr: targetAddr, } } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // connectMethodKey is the map key version of connectMethod, with a // stringified proxy URL (or the empty string) instead of a pointer to // a URL. type connectMethodKey struct { proxy, scheme, addr string } func (k connectMethodKey) String() string { // Only used by tests. return fmt.Sprintf("%s|%s|%s", k.proxy, k.scheme, k.addr) } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey connectMethodKey conn net.Conn closed bool // whether conn has been closed br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip; read by readLoop writech chan writeRequest // written by roundTrip; read by writeLoop closech chan struct{} // broadcast close when readLoop (TCP connection) closes isProxy bool lk sync.Mutex // guards following 3 fields numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) } func (pc *persistConn) isBroken() bool { pc.lk.Lock() b := pc.broken pc.lk.Unlock() return b } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { defer close(pc.closech) alive := true for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch var resp *Response if err == nil { resp, err = ReadResponse(pc.br, rc.req) if err == nil && resp.StatusCode == 100 { // Skip any 100-continue for now. // TODO(bradfitz): if rc.req had "Expect: 100-continue", // actually block the request body write and signal the // writeLoop now to begin sending it. (Issue 2184) For now we // eat it, since we're never expecting one. resp, err = ReadResponse(pc.br, rc.req) } } hasBody := resp != nil && rc.req.Method != "HEAD" && resp.ContentLength != 0 if err != nil { pc.close() } else { if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readerAndCloser{gzReader, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close || resp.StatusCode <= 199 { // Don't do keep-alive on error if either party requested a close // or we get an unexpected informational (1xx) response. // StatusCode 100 is already handled above. alive = false } var waitForBodyRead chan bool if hasBody { waitForBodyRead = make(chan bool, 2) resp.Body.(*bodyEOFSignal).earlyCloseFn = func() error { // Sending false here sets alive to // false and closes the connection // below. waitForBodyRead <- false return nil } resp.Body.(*bodyEOFSignal).fn = func(err error) { alive1 := alive if err != nil { alive1 = false } if alive1 && !pc.t.putIdleConn(pc) { alive1 = false } if !alive1 || pc.isBroken() { pc.close() } waitForBodyRead <- alive1 } } if alive && !hasBody { if !pc.t.putIdleConn(pc) { alive = false } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { alive = <-waitForBodyRead } pc.t.setReqConn(rc.req, nil) if !alive { pc.close() } } } func (pc *persistConn) writeLoop() { for { select { case wr := <-pc.writech: if pc.isBroken() { wr.ch <- errors.New("http: can't write HTTP request on broken connection") continue } err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra) if err == nil { err = pc.bw.Flush() } if err != nil { pc.markBroken() } wr.ch <- err case <-pc.closech: return } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } // A writeRequest is sent by the readLoop's goroutine to the // writeLoop's goroutine to write a request while the read loop // concurrently waits on both the write response and the server's // reply. type writeRequest struct { req *transportRequest ch chan<- error } type httpError struct { err string timeout bool } func (e *httpError) Error() string { return e.err } func (e *httpError) Timeout() bool { return e.timeout } func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true} var errClosed error = &httpError{err: "net/http: transport closed before response was received"} func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { pc.t.setReqConn(req.Request, pc) pc.lk.Lock() pc.numExpectedResponses++ headerFn := pc.mutateHeaderFunc pc.lk.Unlock() if headerFn != nil { headerFn(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" && req.Method != "HEAD" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 // // Note that we don't request this for HEAD requests, // due to a bug in nginx: // http://trac.nginx.org/nginx/ticket/358 // http://golang.org/issue/5522 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } // Write the request concurrently with waiting for a response, // in case the server decides to reply before reading our full // request body. writeErrCh := make(chan error, 1) pc.writech <- writeRequest{req, writeErrCh} resc := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, resc, requestedGzip} var re responseAndError var pconnDeadCh = pc.closech var failTicker <-chan time.Time var respHeaderTimer <-chan time.Time WaitResponse: for { select { case err := <-writeErrCh: if err != nil { re = responseAndError{nil, err} pc.close() break WaitResponse } if d := pc.t.ResponseHeaderTimeout; d > 0 { respHeaderTimer = time.After(d) } case <-pconnDeadCh: // The persist connection is dead. This shouldn't // usually happen (only with Connection: close responses // with no response bodies), but if it does happen it // means either a) the remote server hung up on us // prematurely, or b) the readLoop sent us a response & // closed its closech at roughly the same time, and we // selected this case first, in which case a response // might still be coming soon. // // We can't avoid the select race in b) by using a unbuffered // resc channel instead, because then goroutines can // leak if we exit due to other errors. pconnDeadCh = nil // avoid spinning failTicker = time.After(100 * time.Millisecond) // arbitrary time to wait for resc case <-failTicker: re = responseAndError{err: errClosed} break WaitResponse case <-respHeaderTimer: pc.close() re = responseAndError{err: errTimeout} break WaitResponse case re = <-resc: break WaitResponse } } pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() if re.err != nil { pc.t.setReqConn(req.Request, nil) } return re.res, re.err } // markBroken marks a connection as broken (so it's not reused). // It differs from close in that it doesn't close the underlying // connection for use when it's still being read. func (pc *persistConn) markBroken() { pc.lk.Lock() defer pc.lk.Unlock() pc.broken = true } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true if !pc.closed { pc.conn.Close() pc.closed = true } pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before its final (error-producing) Read or Close call // returns. If earlyCloseFn is non-nil and Close is called before // io.EOF is seen, earlyCloseFn is called instead of fn, and its // return value is the return value from Close. type bodyEOFSignal struct { body io.ReadCloser mu sync.Mutex // guards following 4 fields closed bool // whether Close has been called rerr error // sticky Read error fn func(error) // error will be nil on Read io.EOF earlyCloseFn func() error // optional alt Close func used if io.EOF not seen } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { es.mu.Lock() closed, rerr := es.closed, es.rerr es.mu.Unlock() if closed { return 0, errors.New("http: read on closed response body") } if rerr != nil { return 0, rerr } n, err = es.body.Read(p) if err != nil { es.mu.Lock() defer es.mu.Unlock() if es.rerr == nil { es.rerr = err } es.condfn(err) } return } func (es *bodyEOFSignal) Close() error { es.mu.Lock() defer es.mu.Unlock() if es.closed { return nil } es.closed = true if es.earlyCloseFn != nil && es.rerr != io.EOF { return es.earlyCloseFn() } err := es.body.Close() es.condfn(err) return err } // caller must hold es.mu. func (es *bodyEOFSignal) condfn(err error) { if es.fn == nil { return } if err == io.EOF { err = nil } es.fn(err) es.fn = nil } type readerAndCloser struct { io.Reader io.Closer }
// Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "log" "net" "net/url" "os" "strings" "sync" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes a new network connection for // each call to Do and uses HTTP proxies as directed by the // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) // environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { lk sync.Mutex idleConn map[string][]*persistConn altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections // TODO: optional pipelining // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(net, addr string) (c net.Conn, err error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config DisableKeepAlives bool DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // Either URL or an error is returned. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := getenvEitherCase("HTTP_PROXY") if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.ParseRequest(proxy) if err != nil { return nil, errors.New("invalid proxy address") } if proxyURL.Host == "" { proxyURL, err = url.ParseRequest("http://" + proxy) if err != nil { return nil, errors.New("invalid proxy address") } } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.lk.Lock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.lk.Unlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.lk.Lock() defer t.lk.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.lk.Lock() defer t.lk.Unlock() if t.idleConn == nil { return } for _, conns := range t.idleConn { for _, pconn := range conns { pconn.close() } } t.idleConn = nil } // // Private implementation past this point. // func getenvEitherCase(k string) string { if v := os.Getenv(strings.ToUpper(k)); v != "" { return v } return os.Getenv(strings.ToLower(k)) } func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) { cm := &connectMethod{ targetScheme: treq.URL.Scheme, targetAddr: canonicalAddr(treq.URL), } if t.Proxy != nil { var err error cm.proxyURL, err = t.Proxy(treq.Request) if err != nil { return nil, err } } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String())) } return "" } func (t *Transport) putIdleConn(pconn *persistConn) { t.lk.Lock() defer t.lk.Unlock() if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return } if pconn.isBroken() { return } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } if len(t.idleConn[key]) >= max { pconn.close() return } t.idleConn[key] = append(t.idleConn[key], pconn) } func (t *Transport) getIdleConn(cm *connectMethod) (pconn *persistConn) { t.lk.Lock() defer t.lk.Unlock() if t.idleConn == nil { t.idleConn = make(map[string][]*persistConn) } key := cm.String() for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[0 : len(pconns)-1] } if !pconn.isBroken() { return } } return } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.String(), conn: conn, reqch: make(chan requestAndChan, 50), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. conn = tls.Client(conn, t.TLSClientConfig) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if t.TLSClientConfig == nil || !t.TLSClientConfig.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cm.tlsHost()); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := getenvEitherCase("NO_PROXY") if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) { return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // ||http|foo.com http directly to server, no proxy // ||https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (ck *connectMethod) String() string { proxyStr := "" if ck.proxyURL != nil { proxyStr = ck.proxyURL.String() } return strings.Join([]string{proxyStr, ck.targetScheme, ck.targetAddr}, "|") } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey string // its connectMethod.String() conn net.Conn br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip(); read by readLoop() isProxy bool // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) lk sync.Mutex // guards numExpectedResponses and broken numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. } func (pc *persistConn) isBroken() bool { pc.lk.Lock() defer pc.lk.Unlock() return pc.broken } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { alive := true var lastbody io.ReadCloser // last response body, if any, read on this connection for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch // Advance past the previous response's body, if the // caller hasn't done so. if lastbody != nil { lastbody.Close() // assumed idempotent lastbody = nil } resp, err := ReadResponse(pc.br, rc.req) if err != nil { pc.close() } else { hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readFirstCloseBoth{&discardOnCloseReadCloser{gzReader}, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close { alive = false } hasBody := resp != nil && resp.ContentLength != 0 var waitForBodyRead chan bool if alive { if hasBody { lastbody = resp.Body waitForBodyRead = make(chan bool) resp.Body.(*bodyEOFSignal).fn = func() { pc.t.putIdleConn(pc) waitForBodyRead <- true } } else { // When there's no response body, we immediately // reuse the TCP connection (putIdleConn), but // we need to prevent ClientConn.Read from // closing the Response.Body on the next // loop, otherwise it might close the body // before the client code has had a chance to // read it (even though it'll just be 0, EOF). lastbody = nil pc.t.putIdleConn(pc) } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { <-waitForBodyRead } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { if pc.mutateHeaderFunc != nil { pc.mutateHeaderFunc(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } pc.lk.Lock() pc.numExpectedResponses++ pc.lk.Unlock() err = req.Request.write(pc.bw, pc.isProxy, req.extra) if err != nil { pc.close() return } pc.bw.Flush() ch := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, ch, requestedGzip} re := <-ch pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() return re.res, re.err } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true pc.conn.Close() pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } func responseIsKeepAlive(res *Response) bool { // TODO: implement. for now just always shutting down the connection. return false } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before the final Read() or Close() call returns, but after // EOF has been seen. type bodyEOFSignal struct { body io.ReadCloser fn func() isClosed bool } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { n, err = es.body.Read(p) if es.isClosed && n > 0 { panic("http: unexpected bodyEOFSignal Read after Close; see issue 1725") } if err == io.EOF && es.fn != nil { es.fn() es.fn = nil } return } func (es *bodyEOFSignal) Close() (err error) { if es.isClosed { return nil } es.isClosed = true err = es.body.Close() if err == nil && es.fn != nil { es.fn() es.fn = nil } return } type readFirstCloseBoth struct { io.ReadCloser io.Closer } func (r *readFirstCloseBoth) Close() error { if err := r.ReadCloser.Close(); err != nil { r.Closer.Close() return err } if err := r.Closer.Close(); err != nil { return err } return nil } // discardOnCloseReadCloser consumes all its input on Close. type discardOnCloseReadCloser struct { io.ReadCloser } func (d *discardOnCloseReadCloser) Close() error { io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed return d.ReadCloser.Close() } net/http: fix http_proxy parsing Fixes issue 2919. R=golang-dev, bradfitz CC=golang-dev http://codereview.appspot.com/5645089 // Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "log" "net" "net/url" "os" "strings" "sync" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes a new network connection for // each call to Do and uses HTTP proxies as directed by the // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) // environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { lk sync.Mutex idleConn map[string][]*persistConn altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections // TODO: optional pipelining // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(net, addr string) (c net.Conn, err error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config DisableKeepAlives bool DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // Either URL or an error is returned. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := getenvEitherCase("HTTP_PROXY") if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil { if u, err := url.Parse("http://" + proxy); err == nil { proxyURL = u err = nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.lk.Lock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.lk.Unlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.lk.Lock() defer t.lk.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.lk.Lock() defer t.lk.Unlock() if t.idleConn == nil { return } for _, conns := range t.idleConn { for _, pconn := range conns { pconn.close() } } t.idleConn = nil } // // Private implementation past this point. // func getenvEitherCase(k string) string { if v := os.Getenv(strings.ToUpper(k)); v != "" { return v } return os.Getenv(strings.ToLower(k)) } func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) { cm := &connectMethod{ targetScheme: treq.URL.Scheme, targetAddr: canonicalAddr(treq.URL), } if t.Proxy != nil { var err error cm.proxyURL, err = t.Proxy(treq.Request) if err != nil { return nil, err } } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String())) } return "" } func (t *Transport) putIdleConn(pconn *persistConn) { t.lk.Lock() defer t.lk.Unlock() if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return } if pconn.isBroken() { return } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } if len(t.idleConn[key]) >= max { pconn.close() return } t.idleConn[key] = append(t.idleConn[key], pconn) } func (t *Transport) getIdleConn(cm *connectMethod) (pconn *persistConn) { t.lk.Lock() defer t.lk.Unlock() if t.idleConn == nil { t.idleConn = make(map[string][]*persistConn) } key := cm.String() for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[0 : len(pconns)-1] } if !pconn.isBroken() { return } } return } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.String(), conn: conn, reqch: make(chan requestAndChan, 50), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. conn = tls.Client(conn, t.TLSClientConfig) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if t.TLSClientConfig == nil || !t.TLSClientConfig.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cm.tlsHost()); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := getenvEitherCase("NO_PROXY") if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) { return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // ||http|foo.com http directly to server, no proxy // ||https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (ck *connectMethod) String() string { proxyStr := "" if ck.proxyURL != nil { proxyStr = ck.proxyURL.String() } return strings.Join([]string{proxyStr, ck.targetScheme, ck.targetAddr}, "|") } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey string // its connectMethod.String() conn net.Conn br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip(); read by readLoop() isProxy bool // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) lk sync.Mutex // guards numExpectedResponses and broken numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. } func (pc *persistConn) isBroken() bool { pc.lk.Lock() defer pc.lk.Unlock() return pc.broken } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { alive := true var lastbody io.ReadCloser // last response body, if any, read on this connection for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch // Advance past the previous response's body, if the // caller hasn't done so. if lastbody != nil { lastbody.Close() // assumed idempotent lastbody = nil } resp, err := ReadResponse(pc.br, rc.req) if err != nil { pc.close() } else { hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readFirstCloseBoth{&discardOnCloseReadCloser{gzReader}, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close { alive = false } hasBody := resp != nil && resp.ContentLength != 0 var waitForBodyRead chan bool if alive { if hasBody { lastbody = resp.Body waitForBodyRead = make(chan bool) resp.Body.(*bodyEOFSignal).fn = func() { pc.t.putIdleConn(pc) waitForBodyRead <- true } } else { // When there's no response body, we immediately // reuse the TCP connection (putIdleConn), but // we need to prevent ClientConn.Read from // closing the Response.Body on the next // loop, otherwise it might close the body // before the client code has had a chance to // read it (even though it'll just be 0, EOF). lastbody = nil pc.t.putIdleConn(pc) } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { <-waitForBodyRead } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { if pc.mutateHeaderFunc != nil { pc.mutateHeaderFunc(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } pc.lk.Lock() pc.numExpectedResponses++ pc.lk.Unlock() err = req.Request.write(pc.bw, pc.isProxy, req.extra) if err != nil { pc.close() return } pc.bw.Flush() ch := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, ch, requestedGzip} re := <-ch pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() return re.res, re.err } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true pc.conn.Close() pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } func responseIsKeepAlive(res *Response) bool { // TODO: implement. for now just always shutting down the connection. return false } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before the final Read() or Close() call returns, but after // EOF has been seen. type bodyEOFSignal struct { body io.ReadCloser fn func() isClosed bool } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { n, err = es.body.Read(p) if es.isClosed && n > 0 { panic("http: unexpected bodyEOFSignal Read after Close; see issue 1725") } if err == io.EOF && es.fn != nil { es.fn() es.fn = nil } return } func (es *bodyEOFSignal) Close() (err error) { if es.isClosed { return nil } es.isClosed = true err = es.body.Close() if err == nil && es.fn != nil { es.fn() es.fn = nil } return } type readFirstCloseBoth struct { io.ReadCloser io.Closer } func (r *readFirstCloseBoth) Close() error { if err := r.ReadCloser.Close(); err != nil { r.Closer.Close() return err } if err := r.Closer.Close(); err != nil { return err } return nil } // discardOnCloseReadCloser consumes all its input on Close. type discardOnCloseReadCloser struct { io.ReadCloser } func (d *discardOnCloseReadCloser) Close() error { io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed return d.ReadCloser.Close() }
// Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "log" "net" "net/url" "os" "strings" "sync" "time" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes a new network connection for // each call to Do and uses HTTP proxies as directed by the // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) // environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { idleLk sync.Mutex idleConn map[string][]*persistConn altLk sync.RWMutex altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections // TODO: optional pipelining // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(net, addr string) (c net.Conn, err error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config DisableKeepAlives bool DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // An error is returned if the proxy environment is invalid. // A nil URL and nil error are returned if no proxy is defined in the // environment, or a proxy should not be used for the given request. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := getenvEitherCase("HTTP_PROXY") if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || proxyURL.Scheme == "" { if u, err := url.Parse("http://" + proxy); err == nil { proxyURL = u err = nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.altLk.RLock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.altLk.RUnlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.altLk.Lock() defer t.altLk.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.idleLk.Lock() m := t.idleConn t.idleConn = nil t.idleLk.Unlock() if m == nil { return } for _, conns := range m { for _, pconn := range conns { pconn.close() } } } // // Private implementation past this point. // func getenvEitherCase(k string) string { if v := os.Getenv(strings.ToUpper(k)); v != "" { return v } return os.Getenv(strings.ToLower(k)) } func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) { cm := &connectMethod{ targetScheme: treq.URL.Scheme, targetAddr: canonicalAddr(treq.URL), } if t.Proxy != nil { var err error cm.proxyURL, err = t.Proxy(treq.Request) if err != nil { return nil, err } } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String())) } return "" } // putIdleConn adds pconn to the list of idle persistent connections awaiting // a new request. // If pconn is no longer needed or not in a good state, putIdleConn // returns false. func (t *Transport) putIdleConn(pconn *persistConn) bool { if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return false } if pconn.isBroken() { return false } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } t.idleLk.Lock() if t.idleConn == nil { t.idleConn = make(map[string][]*persistConn) } if len(t.idleConn[key]) >= max { t.idleLk.Unlock() pconn.close() return false } for _, exist := range t.idleConn[key] { if exist == pconn { log.Fatalf("dup idle pconn %p in freelist", pconn) } } t.idleConn[key] = append(t.idleConn[key], pconn) t.idleLk.Unlock() return true } func (t *Transport) getIdleConn(cm *connectMethod) (pconn *persistConn) { key := cm.String() t.idleLk.Lock() defer t.idleLk.Unlock() if t.idleConn == nil { return nil } for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[0 : len(pconns)-1] } if !pconn.isBroken() { return } } panic("unreachable") } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.String(), conn: conn, reqch: make(chan requestAndChan, 50), writech: make(chan writeRequest, 50), closech: make(chan struct{}), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. cfg := t.TLSClientConfig if cfg == nil || cfg.ServerName == "" { host := cm.tlsHost() if cfg == nil { cfg = &tls.Config{ServerName: host} } else { clone := *cfg // shallow clone clone.ServerName = host cfg = &clone } } conn = tls.Client(conn, cfg) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if t.TLSClientConfig == nil || !t.TLSClientConfig.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cm.tlsHost()); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() go pconn.writeLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := getenvEitherCase("NO_PROXY") if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) { return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // ||http|foo.com http directly to server, no proxy // ||https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (ck *connectMethod) String() string { proxyStr := "" targetAddr := ck.targetAddr if ck.proxyURL != nil { proxyStr = ck.proxyURL.String() if ck.targetScheme == "http" { targetAddr = "" } } return strings.Join([]string{proxyStr, ck.targetScheme, targetAddr}, "|") } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey string // its connectMethod.String() conn net.Conn closed bool // whether conn has been closed br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip; read by readLoop writech chan writeRequest // written by roundTrip; read by writeLoop closech chan struct{} // broadcast close when readLoop (TCP connection) closes isProxy bool // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) lk sync.Mutex // guards numExpectedResponses and broken numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. } func (pc *persistConn) isBroken() bool { pc.lk.Lock() b := pc.broken pc.lk.Unlock() return b } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { defer close(pc.closech) alive := true var lastbody io.ReadCloser // last response body, if any, read on this connection for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch // Advance past the previous response's body, if the // caller hasn't done so. if lastbody != nil { lastbody.Close() // assumed idempotent lastbody = nil } var resp *Response if err == nil { resp, err = ReadResponse(pc.br, rc.req) } if err != nil { pc.close() } else { hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readFirstCloseBoth{&discardOnCloseReadCloser{gzReader}, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close { alive = false } // TODO(bradfitz): this hasBody conflicts with the defition // above which excludes HEAD requests. Is this one // incomplete? hasBody := resp != nil && resp.ContentLength != 0 var waitForBodyRead chan bool if hasBody { lastbody = resp.Body waitForBodyRead = make(chan bool, 1) resp.Body.(*bodyEOFSignal).fn = func(err error) { alive1 := alive if err != nil { alive1 = false } if alive1 && !pc.t.putIdleConn(pc) { alive1 = false } if !alive1 || pc.isBroken() { pc.close() } waitForBodyRead <- alive1 } } if alive && !hasBody { // When there's no response body, we immediately // reuse the TCP connection (putIdleConn), but // we need to prevent ClientConn.Read from // closing the Response.Body on the next // loop, otherwise it might close the body // before the client code has had a chance to // read it (even though it'll just be 0, EOF). lastbody = nil if !pc.t.putIdleConn(pc) { alive = false } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { alive = <-waitForBodyRead } if !alive { pc.close() } } } func (pc *persistConn) writeLoop() { for { select { case wr := <-pc.writech: if pc.isBroken() { wr.ch <- errors.New("http: can't write HTTP request on broken connection") continue } err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra) if err == nil { err = pc.bw.Flush() } if err != nil { pc.markBroken() } wr.ch <- err case <-pc.closech: return } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } // A writeRequest is sent by the readLoop's goroutine to the // writeLoop's goroutine to write a request while the read loop // concurrently waits on both the write response and the server's // reply. type writeRequest struct { req *transportRequest ch chan<- error } func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { if pc.mutateHeaderFunc != nil { pc.mutateHeaderFunc(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } pc.lk.Lock() pc.numExpectedResponses++ pc.lk.Unlock() // Write the request concurrently with waiting for a response, // in case the server decides to reply before reading our full // request body. writeErrCh := make(chan error, 1) pc.writech <- writeRequest{req, writeErrCh} resc := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, resc, requestedGzip} var re responseAndError var pconnDeadCh = pc.closech var failTicker <-chan time.Time WaitResponse: for { select { case err := <-writeErrCh: if err != nil { re = responseAndError{nil, err} break WaitResponse } case <-pconnDeadCh: // The persist connection is dead. This shouldn't // usually happen (only with Connection: close responses // with no response bodies), but if it does happen it // means either a) the remote server hung up on us // prematurely, or b) the readLoop sent us a response & // closed its closech at roughly the same time, and we // selected this case first, in which case a response // might still be coming soon. // // We can't avoid the select race in b) by using a unbuffered // resc channel instead, because then goroutines can // leak if we exit due to other errors. pconnDeadCh = nil // avoid spinning failTicker = time.After(100 * time.Millisecond) // arbitrary time to wait for resc case <-failTicker: re = responseAndError{nil, errors.New("net/http: transport closed before response was received")} break WaitResponse case re = <-resc: break WaitResponse } } pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() return re.res, re.err } // markBroken marks a connection as broken (so it's not reused). // It differs from close in that it doesn't close the underlying // connection for use when it's still being read. func (pc *persistConn) markBroken() { pc.lk.Lock() defer pc.lk.Unlock() pc.broken = true } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true if !pc.closed { pc.conn.Close() pc.closed = true } pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before its final (error-producing) Read or Close call // returns. type bodyEOFSignal struct { body io.ReadCloser mu sync.Mutex // guards closed, rerr and fn closed bool // whether Close has been called rerr error // sticky Read error fn func(error) // error will be nil on Read io.EOF } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { es.mu.Lock() closed, rerr := es.closed, es.rerr es.mu.Unlock() if closed { return 0, errors.New("http: read on closed response body") } if rerr != nil { return 0, rerr } n, err = es.body.Read(p) if err != nil { es.mu.Lock() defer es.mu.Unlock() if es.rerr == nil { es.rerr = err } es.condfn(err) } return } func (es *bodyEOFSignal) Close() error { es.mu.Lock() defer es.mu.Unlock() if es.closed { return nil } es.closed = true err := es.body.Close() es.condfn(err) return err } // caller must hold es.mu. func (es *bodyEOFSignal) condfn(err error) { if es.fn == nil { return } if err == io.EOF { err = nil } es.fn(err) es.fn = nil } type readFirstCloseBoth struct { io.ReadCloser io.Closer } func (r *readFirstCloseBoth) Close() error { if err := r.ReadCloser.Close(); err != nil { r.Closer.Close() return err } if err := r.Closer.Close(); err != nil { return err } return nil } // discardOnCloseReadCloser consumes all its input on Close. type discardOnCloseReadCloser struct { io.ReadCloser } func (d *discardOnCloseReadCloser) Close() error { io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed return d.ReadCloser.Close() } net/http: clarify DefaultTransport docs Fixes issue 4281 R=golang-dev, adg CC=golang-dev https://codereview.appspot.com/6872053 // Copyright 2011 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. // HTTP client implementation. See RFC 2616. // // This is the low-level Transport implementation of RoundTripper. // The high-level interface is in client.go. package http import ( "bufio" "compress/gzip" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "log" "net" "net/url" "os" "strings" "sync" "time" ) // DefaultTransport is the default implementation of Transport and is // used by DefaultClient. It establishes network connections as needed // and caches them for reuse by subsequent calls. It uses HTTP proxies // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and // $no_proxy) environment variables. var DefaultTransport RoundTripper = &Transport{Proxy: ProxyFromEnvironment} // DefaultMaxIdleConnsPerHost is the default value of Transport's // MaxIdleConnsPerHost. const DefaultMaxIdleConnsPerHost = 2 // Transport is an implementation of RoundTripper that supports http, // https, and http proxies (for either http or https with CONNECT). // Transport can also cache connections for future re-use. type Transport struct { idleLk sync.Mutex idleConn map[string][]*persistConn altLk sync.RWMutex altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper // TODO: tunable on global max cached connections // TODO: tunable on timeout on cached connections // TODO: optional pipelining // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*Request) (*url.URL, error) // Dial specifies the dial function for creating TCP // connections. // If Dial is nil, net.Dial is used. Dial func(net, addr string) (c net.Conn, err error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. TLSClientConfig *tls.Config DisableKeepAlives bool DisableCompression bool // MaxIdleConnsPerHost, if non-zero, controls the maximum idle // (keep-alive) to keep per-host. If zero, // DefaultMaxIdleConnsPerHost is used. MaxIdleConnsPerHost int } // ProxyFromEnvironment returns the URL of the proxy to use for a // given request, as indicated by the environment variables // $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy). // An error is returned if the proxy environment is invalid. // A nil URL and nil error are returned if no proxy is defined in the // environment, or a proxy should not be used for the given request. func ProxyFromEnvironment(req *Request) (*url.URL, error) { proxy := getenvEitherCase("HTTP_PROXY") if proxy == "" { return nil, nil } if !useProxy(canonicalAddr(req.URL)) { return nil, nil } proxyURL, err := url.Parse(proxy) if err != nil || proxyURL.Scheme == "" { if u, err := url.Parse("http://" + proxy); err == nil { proxyURL = u err = nil } } if err != nil { return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err) } return proxyURL, nil } // ProxyURL returns a proxy function (for use in a Transport) // that always returns the same URL. func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) { return func(*Request) (*url.URL, error) { return fixedURL, nil } } // transportRequest is a wrapper around a *Request that adds // optional extra headers to write. type transportRequest struct { *Request // original request, not to be mutated extra Header // extra headers to write, or nil } func (tr *transportRequest) extraHeaders() Header { if tr.extra == nil { tr.extra = make(Header) } return tr.extra } // RoundTrip implements the RoundTripper interface. func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) { if req.URL == nil { return nil, errors.New("http: nil Request.URL") } if req.Header == nil { return nil, errors.New("http: nil Request.Header") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { t.altLk.RLock() var rt RoundTripper if t.altProto != nil { rt = t.altProto[req.URL.Scheme] } t.altLk.RUnlock() if rt == nil { return nil, &badStringError{"unsupported protocol scheme", req.URL.Scheme} } return rt.RoundTrip(req) } treq := &transportRequest{Request: req} cm, err := t.connectMethodForRequest(treq) if err != nil { return nil, err } // Get the cached or newly-created connection to either the // host (for http or https), the http proxy, or the http proxy // pre-CONNECTed to https server. In any case, we'll be ready // to send it requests. pconn, err := t.getConn(cm) if err != nil { return nil, err } return pconn.roundTrip(treq) } // RegisterProtocol registers a new protocol with scheme. // The Transport will pass requests using the given scheme to rt. // It is rt's responsibility to simulate HTTP request semantics. // // RegisterProtocol can be used by other packages to provide // implementations of protocol schemes like "ftp" or "file". func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) { if scheme == "http" || scheme == "https" { panic("protocol " + scheme + " already registered") } t.altLk.Lock() defer t.altLk.Unlock() if t.altProto == nil { t.altProto = make(map[string]RoundTripper) } if _, exists := t.altProto[scheme]; exists { panic("protocol " + scheme + " already registered") } t.altProto[scheme] = rt } // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle in // a "keep-alive" state. It does not interrupt any connections currently // in use. func (t *Transport) CloseIdleConnections() { t.idleLk.Lock() m := t.idleConn t.idleConn = nil t.idleLk.Unlock() if m == nil { return } for _, conns := range m { for _, pconn := range conns { pconn.close() } } } // // Private implementation past this point. // func getenvEitherCase(k string) string { if v := os.Getenv(strings.ToUpper(k)); v != "" { return v } return os.Getenv(strings.ToLower(k)) } func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) { cm := &connectMethod{ targetScheme: treq.URL.Scheme, targetAddr: canonicalAddr(treq.URL), } if t.Proxy != nil { var err error cm.proxyURL, err = t.Proxy(treq.Request) if err != nil { return nil, err } } return cm, nil } // proxyAuth returns the Proxy-Authorization header to set // on requests, if applicable. func (cm *connectMethod) proxyAuth() string { if cm.proxyURL == nil { return "" } if u := cm.proxyURL.User; u != nil { return "Basic " + base64.URLEncoding.EncodeToString([]byte(u.String())) } return "" } // putIdleConn adds pconn to the list of idle persistent connections awaiting // a new request. // If pconn is no longer needed or not in a good state, putIdleConn // returns false. func (t *Transport) putIdleConn(pconn *persistConn) bool { if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 { pconn.close() return false } if pconn.isBroken() { return false } key := pconn.cacheKey max := t.MaxIdleConnsPerHost if max == 0 { max = DefaultMaxIdleConnsPerHost } t.idleLk.Lock() if t.idleConn == nil { t.idleConn = make(map[string][]*persistConn) } if len(t.idleConn[key]) >= max { t.idleLk.Unlock() pconn.close() return false } for _, exist := range t.idleConn[key] { if exist == pconn { log.Fatalf("dup idle pconn %p in freelist", pconn) } } t.idleConn[key] = append(t.idleConn[key], pconn) t.idleLk.Unlock() return true } func (t *Transport) getIdleConn(cm *connectMethod) (pconn *persistConn) { key := cm.String() t.idleLk.Lock() defer t.idleLk.Unlock() if t.idleConn == nil { return nil } for { pconns, ok := t.idleConn[key] if !ok { return nil } if len(pconns) == 1 { pconn = pconns[0] delete(t.idleConn, key) } else { // 2 or more cached connections; pop last // TODO: queue? pconn = pconns[len(pconns)-1] t.idleConn[key] = pconns[0 : len(pconns)-1] } if !pconn.isBroken() { return } } panic("unreachable") } func (t *Transport) dial(network, addr string) (c net.Conn, err error) { if t.Dial != nil { return t.Dial(network, addr) } return net.Dial(network, addr) } // getConn dials and creates a new persistConn to the target as // specified in the connectMethod. This includes doing a proxy CONNECT // and/or setting up TLS. If this doesn't return an error, the persistConn // is ready to write requests to. func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) { if pc := t.getIdleConn(cm); pc != nil { return pc, nil } conn, err := t.dial("tcp", cm.addr()) if err != nil { if cm.proxyURL != nil { err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err) } return nil, err } pa := cm.proxyAuth() pconn := &persistConn{ t: t, cacheKey: cm.String(), conn: conn, reqch: make(chan requestAndChan, 50), writech: make(chan writeRequest, 50), closech: make(chan struct{}), } switch { case cm.proxyURL == nil: // Do nothing. case cm.targetScheme == "http": pconn.isProxy = true if pa != "" { pconn.mutateHeaderFunc = func(h Header) { h.Set("Proxy-Authorization", pa) } } case cm.targetScheme == "https": connectReq := &Request{ Method: "CONNECT", URL: &url.URL{Opaque: cm.targetAddr}, Host: cm.targetAddr, Header: make(Header), } if pa != "" { connectReq.Header.Set("Proxy-Authorization", pa) } connectReq.Write(conn) // Read response. // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err := ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { f := strings.SplitN(resp.Status, " ", 2) conn.Close() return nil, errors.New(f[1]) } } if cm.targetScheme == "https" { // Initiate TLS and check remote host name against certificate. cfg := t.TLSClientConfig if cfg == nil || cfg.ServerName == "" { host := cm.tlsHost() if cfg == nil { cfg = &tls.Config{ServerName: host} } else { clone := *cfg // shallow clone clone.ServerName = host cfg = &clone } } conn = tls.Client(conn, cfg) if err = conn.(*tls.Conn).Handshake(); err != nil { return nil, err } if t.TLSClientConfig == nil || !t.TLSClientConfig.InsecureSkipVerify { if err = conn.(*tls.Conn).VerifyHostname(cm.tlsHost()); err != nil { return nil, err } } pconn.conn = conn } pconn.br = bufio.NewReader(pconn.conn) pconn.bw = bufio.NewWriter(pconn.conn) go pconn.readLoop() go pconn.writeLoop() return pconn, nil } // useProxy returns true if requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool { if len(addr) == 0 { return true } host, _, err := net.SplitHostPort(addr) if err != nil { return false } if host == "localhost" { return false } if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() { return false } } no_proxy := getenvEitherCase("NO_PROXY") if no_proxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(no_proxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p || (p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:])) { return false } } return true } // connectMethod is the map key (in its String form) for keeping persistent // TCP connections alive for subsequent HTTP requests. // // A connect method may be of the following types: // // Cache key form Description // ----------------- ------------------------- // ||http|foo.com http directly to server, no proxy // ||https|foo.com https directly to server, no proxy // http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com // http://proxy.com|http http to proxy, http to anywhere after that // // Note: no support to https to the proxy yet. // type connectMethod struct { proxyURL *url.URL // nil for no proxy, else full proxy URL targetScheme string // "http" or "https" targetAddr string // Not used if proxy + http targetScheme (4th example in table) } func (ck *connectMethod) String() string { proxyStr := "" targetAddr := ck.targetAddr if ck.proxyURL != nil { proxyStr = ck.proxyURL.String() if ck.targetScheme == "http" { targetAddr = "" } } return strings.Join([]string{proxyStr, ck.targetScheme, targetAddr}, "|") } // addr returns the first hop "host:port" to which we need to TCP connect. func (cm *connectMethod) addr() string { if cm.proxyURL != nil { return canonicalAddr(cm.proxyURL) } return cm.targetAddr } // tlsHost returns the host name to match against the peer's // TLS certificate. func (cm *connectMethod) tlsHost() string { h := cm.targetAddr if hasPort(h) { h = h[:strings.LastIndex(h, ":")] } return h } // persistConn wraps a connection, usually a persistent one // (but may be used for non-keep-alive requests as well) type persistConn struct { t *Transport cacheKey string // its connectMethod.String() conn net.Conn closed bool // whether conn has been closed br *bufio.Reader // from conn bw *bufio.Writer // to conn reqch chan requestAndChan // written by roundTrip; read by readLoop writech chan writeRequest // written by roundTrip; read by writeLoop closech chan struct{} // broadcast close when readLoop (TCP connection) closes isProxy bool // mutateHeaderFunc is an optional func to modify extra // headers on each outbound request before it's written. (the // original Request given to RoundTrip is not modified) mutateHeaderFunc func(Header) lk sync.Mutex // guards numExpectedResponses and broken numExpectedResponses int broken bool // an error has happened on this connection; marked broken so it's not reused. } func (pc *persistConn) isBroken() bool { pc.lk.Lock() b := pc.broken pc.lk.Unlock() return b } var remoteSideClosedFunc func(error) bool // or nil to use default func remoteSideClosed(err error) bool { if err == io.EOF { return true } if remoteSideClosedFunc != nil { return remoteSideClosedFunc(err) } return false } func (pc *persistConn) readLoop() { defer close(pc.closech) alive := true var lastbody io.ReadCloser // last response body, if any, read on this connection for alive { pb, err := pc.br.Peek(1) pc.lk.Lock() if pc.numExpectedResponses == 0 { pc.closeLocked() pc.lk.Unlock() if len(pb) > 0 { log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", string(pb), err) } return } pc.lk.Unlock() rc := <-pc.reqch // Advance past the previous response's body, if the // caller hasn't done so. if lastbody != nil { lastbody.Close() // assumed idempotent lastbody = nil } var resp *Response if err == nil { resp, err = ReadResponse(pc.br, rc.req) } if err != nil { pc.close() } else { hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0 if rc.addedGzip && hasBody && resp.Header.Get("Content-Encoding") == "gzip" { resp.Header.Del("Content-Encoding") resp.Header.Del("Content-Length") resp.ContentLength = -1 gzReader, zerr := gzip.NewReader(resp.Body) if zerr != nil { pc.close() err = zerr } else { resp.Body = &readFirstCloseBoth{&discardOnCloseReadCloser{gzReader}, resp.Body} } } resp.Body = &bodyEOFSignal{body: resp.Body} } if err != nil || resp.Close || rc.req.Close { alive = false } // TODO(bradfitz): this hasBody conflicts with the defition // above which excludes HEAD requests. Is this one // incomplete? hasBody := resp != nil && resp.ContentLength != 0 var waitForBodyRead chan bool if hasBody { lastbody = resp.Body waitForBodyRead = make(chan bool, 1) resp.Body.(*bodyEOFSignal).fn = func(err error) { alive1 := alive if err != nil { alive1 = false } if alive1 && !pc.t.putIdleConn(pc) { alive1 = false } if !alive1 || pc.isBroken() { pc.close() } waitForBodyRead <- alive1 } } if alive && !hasBody { // When there's no response body, we immediately // reuse the TCP connection (putIdleConn), but // we need to prevent ClientConn.Read from // closing the Response.Body on the next // loop, otherwise it might close the body // before the client code has had a chance to // read it (even though it'll just be 0, EOF). lastbody = nil if !pc.t.putIdleConn(pc) { alive = false } } rc.ch <- responseAndError{resp, err} // Wait for the just-returned response body to be fully consumed // before we race and peek on the underlying bufio reader. if waitForBodyRead != nil { alive = <-waitForBodyRead } if !alive { pc.close() } } } func (pc *persistConn) writeLoop() { for { select { case wr := <-pc.writech: if pc.isBroken() { wr.ch <- errors.New("http: can't write HTTP request on broken connection") continue } err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra) if err == nil { err = pc.bw.Flush() } if err != nil { pc.markBroken() } wr.ch <- err case <-pc.closech: return } } } type responseAndError struct { res *Response err error } type requestAndChan struct { req *Request ch chan responseAndError // did the Transport (as opposed to the client code) add an // Accept-Encoding gzip header? only if it we set it do // we transparently decode the gzip. addedGzip bool } // A writeRequest is sent by the readLoop's goroutine to the // writeLoop's goroutine to write a request while the read loop // concurrently waits on both the write response and the server's // reply. type writeRequest struct { req *transportRequest ch chan<- error } func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) { if pc.mutateHeaderFunc != nil { pc.mutateHeaderFunc(req.extraHeaders()) } // Ask for a compressed version if the caller didn't set their // own value for Accept-Encoding. We only attempted to // uncompress the gzip stream if we were the layer that // requested it. requestedGzip := false if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" { // Request gzip only, not deflate. Deflate is ambiguous and // not as universally supported anyway. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 requestedGzip = true req.extraHeaders().Set("Accept-Encoding", "gzip") } pc.lk.Lock() pc.numExpectedResponses++ pc.lk.Unlock() // Write the request concurrently with waiting for a response, // in case the server decides to reply before reading our full // request body. writeErrCh := make(chan error, 1) pc.writech <- writeRequest{req, writeErrCh} resc := make(chan responseAndError, 1) pc.reqch <- requestAndChan{req.Request, resc, requestedGzip} var re responseAndError var pconnDeadCh = pc.closech var failTicker <-chan time.Time WaitResponse: for { select { case err := <-writeErrCh: if err != nil { re = responseAndError{nil, err} break WaitResponse } case <-pconnDeadCh: // The persist connection is dead. This shouldn't // usually happen (only with Connection: close responses // with no response bodies), but if it does happen it // means either a) the remote server hung up on us // prematurely, or b) the readLoop sent us a response & // closed its closech at roughly the same time, and we // selected this case first, in which case a response // might still be coming soon. // // We can't avoid the select race in b) by using a unbuffered // resc channel instead, because then goroutines can // leak if we exit due to other errors. pconnDeadCh = nil // avoid spinning failTicker = time.After(100 * time.Millisecond) // arbitrary time to wait for resc case <-failTicker: re = responseAndError{nil, errors.New("net/http: transport closed before response was received")} break WaitResponse case re = <-resc: break WaitResponse } } pc.lk.Lock() pc.numExpectedResponses-- pc.lk.Unlock() return re.res, re.err } // markBroken marks a connection as broken (so it's not reused). // It differs from close in that it doesn't close the underlying // connection for use when it's still being read. func (pc *persistConn) markBroken() { pc.lk.Lock() defer pc.lk.Unlock() pc.broken = true } func (pc *persistConn) close() { pc.lk.Lock() defer pc.lk.Unlock() pc.closeLocked() } func (pc *persistConn) closeLocked() { pc.broken = true if !pc.closed { pc.conn.Close() pc.closed = true } pc.mutateHeaderFunc = nil } var portMap = map[string]string{ "http": "80", "https": "443", } // canonicalAddr returns url.Host but always with a ":port" suffix func canonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr } // bodyEOFSignal wraps a ReadCloser but runs fn (if non-nil) at most // once, right before its final (error-producing) Read or Close call // returns. type bodyEOFSignal struct { body io.ReadCloser mu sync.Mutex // guards closed, rerr and fn closed bool // whether Close has been called rerr error // sticky Read error fn func(error) // error will be nil on Read io.EOF } func (es *bodyEOFSignal) Read(p []byte) (n int, err error) { es.mu.Lock() closed, rerr := es.closed, es.rerr es.mu.Unlock() if closed { return 0, errors.New("http: read on closed response body") } if rerr != nil { return 0, rerr } n, err = es.body.Read(p) if err != nil { es.mu.Lock() defer es.mu.Unlock() if es.rerr == nil { es.rerr = err } es.condfn(err) } return } func (es *bodyEOFSignal) Close() error { es.mu.Lock() defer es.mu.Unlock() if es.closed { return nil } es.closed = true err := es.body.Close() es.condfn(err) return err } // caller must hold es.mu. func (es *bodyEOFSignal) condfn(err error) { if es.fn == nil { return } if err == io.EOF { err = nil } es.fn(err) es.fn = nil } type readFirstCloseBoth struct { io.ReadCloser io.Closer } func (r *readFirstCloseBoth) Close() error { if err := r.ReadCloser.Close(); err != nil { r.Closer.Close() return err } if err := r.Closer.Close(); err != nil { return err } return nil } // discardOnCloseReadCloser consumes all its input on Close. type discardOnCloseReadCloser struct { io.ReadCloser } func (d *discardOnCloseReadCloser) Close() error { io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed return d.ReadCloser.Close() }
package nvim import ( "bytes" "errors" "fmt" "log" "os" "os/exec" "path/filepath" "reflect" "runtime" "sort" "strconv" "strings" "sync/atomic" "testing" ) type version struct { Major int Minor int Patch int } var ( channelID int64 nvimVersion version ) func parseVersion(tb testing.TB, version string) (major, minor, patch int) { tb.Helper() version = strings.TrimPrefix(version, "v") vpair := strings.Split(version, ".") if len(vpair) != 3 { tb.Fatal("could not parse neovim version") } var err error major, err = strconv.Atoi(vpair[0]) if err != nil { tb.Fatal(err) } minor, err = strconv.Atoi(vpair[1]) if err != nil { tb.Fatal(err) } patch, err = strconv.Atoi(vpair[2]) if err != nil { tb.Fatal(err) } return major, minor, patch } func skipVersion(tb testing.TB, version string) { major, minor, patch := parseVersion(tb, version) const skipFmt = "SKIP: current neovim version v%d.%d.%d but expected version %s" if nvimVersion.Major < major || nvimVersion.Minor < minor || nvimVersion.Patch < patch { tb.Skipf(skipFmt, nvimVersion.Major, nvimVersion.Minor, nvimVersion.Patch, version) } } // clearBuffer clears the buffer lines. func clearBuffer(tb testing.TB, v *Nvim, buffer Buffer) { tb.Helper() if err := v.SetBufferLines(buffer, 0, -1, true, bytes.Fields(nil)); err != nil { tb.Fatal(err) } } func TestAPI(t *testing.T) { t.Parallel() v, cleanup := newChildProcess(t) t.Cleanup(func() { cleanup() }) apiInfo, err := v.APIInfo() if err != nil { t.Fatal(err) } if len(apiInfo) != 2 { t.Fatalf("unknown APIInfo: %#v", apiInfo) } var ok bool channelID, ok = apiInfo[0].(int64) if !ok { t.Fatalf("apiInfo[0] is not int64 type: %T", apiInfo[0]) } info, ok := apiInfo[1].(map[string]interface{}) if !ok { t.Fatalf("apiInfo[1] is not map[string]interface{} type: %T", apiInfo[1]) } infoV := info["version"].(map[string]interface{}) nvimVersion.Major = int(infoV["major"].(int64)) nvimVersion.Minor = int(infoV["minor"].(int64)) nvimVersion.Patch = int(infoV["patch"].(int64)) t.Run("BufAttach", testBufAttach(v)) t.Run("APIInfo", testAPIInfo(v)) t.Run("SimpleHandler", testSimpleHandler(v)) t.Run("Buffer", testBuffer(v)) t.Run("Window", testWindow(v)) t.Run("Tabpage", testTabpage(v)) t.Run("Lines", testLines(v)) t.Run("Commands", testCommands(v)) t.Run("Var", testVar(v)) t.Run("Message", testMessage(v)) t.Run("Key", testKey(v)) t.Run("Eval", testEval(v)) t.Run("Batch", testBatch(v)) t.Run("Mode", testMode(v)) t.Run("ExecLua", testExecLua(v)) t.Run("Highlight", testHighlight(v)) t.Run("VirtualText", testVirtualText(v)) t.Run("FloatingWindow", testFloatingWindow(v)) t.Run("Context", testContext(v)) t.Run("Extmarks", testExtmarks(v)) t.Run("Runtime", testRuntime(v)) t.Run("Namespace", testNamespace(v)) t.Run("PutPaste", testPutPaste(v)) t.Run("Options", testOptions(v)) t.Run("AllOptionsInfo", testAllOptionsInfo(v)) t.Run("OptionsInfo", testOptionsInfo(v)) t.Run("OpenTerm", testTerm(v)) t.Run("ChannelClientInfo", testChannelClientInfo(v)) t.Run("UI", testUI(v)) t.Run("Proc", testProc(v)) } func testBufAttach(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text changedtickChan := make(chan *ChangedtickEvent) v.RegisterHandler(EventBufChangedtick, func(changedtickEvent ...interface{}) { ev := &ChangedtickEvent{ Buffer: changedtickEvent[0].(Buffer), Changetick: changedtickEvent[1].(int64), } changedtickChan <- ev }) bufLinesChan := make(chan *BufLinesEvent) v.RegisterHandler(EventBufLines, func(bufLinesEvent ...interface{}) { ev := &BufLinesEvent{ Buffer: bufLinesEvent[0].(Buffer), Changetick: bufLinesEvent[1].(int64), FirstLine: bufLinesEvent[2].(int64), LastLine: bufLinesEvent[3].(int64), IsMultipart: bufLinesEvent[5].(bool), } for _, line := range bufLinesEvent[4].([]interface{}) { ev.LineData = append(ev.LineData, line.(string)) } bufLinesChan <- ev }) bufDetachChan := make(chan *BufDetachEvent) v.RegisterHandler(EventBufDetach, func(bufDetachEvent ...interface{}) { ev := &BufDetachEvent{ Buffer: bufDetachEvent[0].(Buffer), } bufDetachChan <- ev }) ok, err := v.AttachBuffer(0, false, make(map[string]interface{})) // first 0 arg refers to the current buffer if err != nil { t.Fatal(err) } if !ok { t.Fatal(errors.New("could not attach buffer")) } changedtickExpected := &ChangedtickEvent{ Buffer: Buffer(1), Changetick: 3, } bufLinesEventExpected := &BufLinesEvent{ Buffer: Buffer(1), Changetick: 4, FirstLine: 0, LastLine: 1, LineData: []string{"foo", "bar", "baz", "qux", "quux", "quuz"}, IsMultipart: false, } bufDetachEventExpected := &BufDetachEvent{ Buffer: Buffer(1), } var numEvent int64 // add and load should be atomically errc := make(chan error) done := make(chan struct{}) go func() { for { select { default: if atomic.LoadInt64(&numEvent) == 3 { // end buf_attach test when handle 2 event done <- struct{}{} return } case changedtick := <-changedtickChan: if !reflect.DeepEqual(changedtick, changedtickExpected) { errc <- fmt.Errorf("changedtick = %+v, want %+v", changedtick, changedtickExpected) } atomic.AddInt64(&numEvent, 1) case bufLines := <-bufLinesChan: if expected := bufLinesEventExpected; !reflect.DeepEqual(bufLines, expected) { errc <- fmt.Errorf("bufLines = %+v, want %+v", bufLines, expected) } atomic.AddInt64(&numEvent, 1) case detach := <-bufDetachChan: if expected := bufDetachEventExpected; !reflect.DeepEqual(detach, expected) { errc <- fmt.Errorf("bufDetach = %+v, want %+v", detach, expected) } atomic.AddInt64(&numEvent, 1) } } }() go func() { <-done close(errc) }() test := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz"), []byte("qux"), []byte("quux"), []byte("quuz")} if err := v.SetBufferLines(Buffer(0), 0, -1, true, test); err != nil { // first 0 arg refers to the current buffer t.Fatal(err) } if detached, err := v.DetachBuffer(Buffer(0)); err != nil || !detached { t.Fatal(err) } for err := range errc { if err != nil { t.Fatal(err) } } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text changedtickChan := make(chan *ChangedtickEvent) v.RegisterHandler(EventBufChangedtick, func(changedtickEvent ...interface{}) { ev := &ChangedtickEvent{ Buffer: changedtickEvent[0].(Buffer), Changetick: changedtickEvent[1].(int64), } changedtickChan <- ev }) bufLinesChan := make(chan *BufLinesEvent) v.RegisterHandler(EventBufLines, func(bufLinesEvent ...interface{}) { ev := &BufLinesEvent{ Buffer: bufLinesEvent[0].(Buffer), Changetick: bufLinesEvent[1].(int64), FirstLine: bufLinesEvent[2].(int64), LastLine: bufLinesEvent[3].(int64), IsMultipart: bufLinesEvent[5].(bool), } for _, line := range bufLinesEvent[4].([]interface{}) { ev.LineData = append(ev.LineData, line.(string)) } bufLinesChan <- ev }) bufDetachChan := make(chan *BufDetachEvent) v.RegisterHandler(EventBufDetach, func(bufDetachEvent ...interface{}) { ev := &BufDetachEvent{ Buffer: bufDetachEvent[0].(Buffer), } bufDetachChan <- ev }) b := v.NewBatch() var attached bool b.AttachBuffer(0, false, make(map[string]interface{}), &attached) // first 0 arg refers to the current buffer if err := b.Execute(); err != nil { t.Fatal(err) } if !attached { t.Fatal(errors.New("could not attach buffer")) } changedtickExpected := &ChangedtickEvent{ Buffer: Buffer(1), Changetick: 5, } bufLinesEventExpected := &BufLinesEvent{ Buffer: Buffer(1), Changetick: 6, FirstLine: 0, LastLine: 1, LineData: []string{"foo", "bar", "baz", "qux", "quux", "quuz"}, IsMultipart: false, } bufDetachEventExpected := &BufDetachEvent{ Buffer: Buffer(1), } var numEvent int64 // add and load should be atomically errc := make(chan error) done := make(chan struct{}) go func() { for { select { default: if atomic.LoadInt64(&numEvent) == 3 { // end buf_attach test when handle 2 event done <- struct{}{} return } case changedtick := <-changedtickChan: if !reflect.DeepEqual(changedtick, changedtickExpected) { errc <- fmt.Errorf("changedtick = %+v, want %+v", changedtick, changedtickExpected) } atomic.AddInt64(&numEvent, 1) case bufLines := <-bufLinesChan: if expected := bufLinesEventExpected; !reflect.DeepEqual(bufLines, expected) { errc <- fmt.Errorf("bufLines = %+v, want %+v", bufLines, expected) } atomic.AddInt64(&numEvent, 1) case detach := <-bufDetachChan: if expected := bufDetachEventExpected; !reflect.DeepEqual(detach, expected) { errc <- fmt.Errorf("bufDetach = %+v, want %+v", detach, expected) } atomic.AddInt64(&numEvent, 1) } } }() go func() { <-done close(errc) }() test := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz"), []byte("qux"), []byte("quux"), []byte("quuz")} if err := v.SetBufferLines(Buffer(0), 0, -1, true, test); err != nil { // first 0 arg refers to the current buffer t.Fatal(err) } var detached bool b.DetachBuffer(Buffer(0), &detached) if err := b.Execute(); err != nil { t.Fatal(err) } for err := range errc { if err != nil { t.Fatal(err) } } }) } } func testAPIInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { apiinfo, err := v.APIInfo() if err != nil { t.Fatal(err) } if len(apiinfo) == 0 { t.Fatal("expected apiinfo is non-nil") } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var apiinfo []interface{} b.APIInfo(&apiinfo) if err := b.Execute(); err != nil { t.Fatal(err) } if len(apiinfo) == 0 { t.Fatal("expected apiinfo is non-nil") } }) } } func testSimpleHandler(v *Nvim) func(*testing.T) { return func(t *testing.T) { cid := v.ChannelID() if cid <= 0 { t.Fatal("could not get channel id") } helloHandler := func(s string) (string, error) { return "Hello, " + s, nil } errorHandler := func() error { return errors.New("ouch") } if err := v.RegisterHandler("hello", helloHandler); err != nil { t.Fatal(err) } if err := v.RegisterHandler("error", errorHandler); err != nil { t.Fatal(err) } var result string if err := v.Call("rpcrequest", &result, cid, "hello", "world"); err != nil { t.Fatal(err) } if expected := "Hello, world"; result != expected { t.Fatalf("hello returned %q, want %q", result, expected) } // Test errors. if err := v.Call("execute", &result, fmt.Sprintf("silent! call rpcrequest(%d, 'error')", cid)); err != nil { t.Fatal(err) } if expected := "\nError invoking 'error' on channel 1:\nouch"; result != expected { t.Fatalf("got error %q, want %q", result, expected) } } } func testBuffer(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("BufferName", func(t *testing.T) { cwd, _ := os.Getwd() // buffer name is full path wantBufName := filepath.Join(cwd, "/test_buffer") if err := v.SetBufferName(Buffer(0), wantBufName); err != nil { t.Fatal(err) } bufName, err := v.BufferName(Buffer(0)) if err != nil { t.Fatal(err) } if bufName != wantBufName { t.Fatalf("want %s buffer name but got %s", wantBufName, bufName) } t.Cleanup(func() { // cleanup cindent option if err := v.SetBufferName(Buffer(0), ""); err != nil { t.Fatal(err) } }) }) t.Run("Buffers", func(t *testing.T) { bufs, err := v.Buffers() if err != nil { t.Fatal(err) } if len(bufs) != 2 { t.Fatalf("expected one buf, found %d bufs", len(bufs)) } if bufs[0] == 0 { t.Fatalf("bufs[0] is not %q: %q", bufs[0], Buffer(0)) } buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } if buf != bufs[0] { t.Fatalf("buf is not bufs[0]: buf %v, bufs[0]: %v", buf, bufs[0]) } const want = "Buffer:1" if got := buf.String(); got != want { t.Fatalf("buf.String() = %s, want %s", got, want) } if err := v.SetCurrentBuffer(buf); err != nil { t.Fatal(err) } }) t.Run("Var", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } const ( varkey = "bvar" varVal = "bval" ) if err := v.SetBufferVar(buf, varkey, varVal); err != nil { t.Fatal(err) } var s string if err := v.BufferVar(buf, varkey, &s); err != nil { t.Fatal(err) } if s != "bval" { t.Fatalf("expected %s=%s, got %s", s, varkey, varVal) } if err := v.DeleteBufferVar(buf, varkey); err != nil { t.Fatal(err) } s = "" // reuse if err := v.BufferVar(buf, varkey, &s); err == nil { t.Fatalf("expected %s not found but error is nil: err: %#v", varkey, err) } }) t.Run("Delete", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) t.Run("ChangeTick", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } // 1 changedtick lines := [][]byte{[]byte("hello"), []byte("world")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } // 2 changedtick const wantChangedTick = 2 changedTick, err := v.BufferChangedTick(buf) if err != nil { t.Fatal(err) } if changedTick != wantChangedTick { t.Fatalf("got %d changedTick but want %d", changedTick, wantChangedTick) } // cleanup buffer deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) t.Run("SetCurrentDirectory", func(t *testing.T) { wantDir, err := os.UserHomeDir() if err != nil { t.Fatal(err) } if err := v.SetCurrentDirectory(wantDir); err != nil { t.Fatal(err) } var got string if err := v.Eval(`getcwd()`, &got); err != nil { t.Fatal(err) } if got != wantDir { t.Fatalf("SetCurrentDirectory(%s) = %s, want: %s", wantDir, got, wantDir) } }) t.Run("BufferCommands", func(t *testing.T) { commands, err := v.BufferCommands(Buffer(0), make(map[string]interface{})) if err != nil { t.Fatal(err) } if len(commands) > 0 { t.Fatalf("expected commands empty but non-zero: %#v", commands) } }) t.Run("BufferOption", func(t *testing.T) { var cindent bool if err := v.BufferOption(Buffer(0), "cindent", &cindent); err != nil { t.Fatal(err) } if cindent { t.Fatalf("expected cindent is false but got %t", cindent) } if err := v.SetBufferOption(Buffer(0), "cindent", true); err != nil { t.Fatal(err) } if err := v.BufferOption(Buffer(0), "cindent", &cindent); err != nil { t.Fatal(err) } if !cindent { t.Fatalf("expected cindent is true but got %t", cindent) } t.Cleanup(func() { // cleanup cindent option if err := v.SetBufferOption(Buffer(0), "cindent", false); err != nil { t.Fatal(err) } }) }) t.Run("IsBufferLoaded", func(t *testing.T) { loaded, err := v.IsBufferLoaded(Buffer(0)) if err != nil { t.Fatal(err) } if !loaded { t.Fatalf("expected buffer is loaded but got %t", loaded) } }) t.Run("IsBufferValid", func(t *testing.T) { valid, err := v.IsBufferValid(Buffer(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected buffer is valid but got %t", valid) } }) t.Run("BufferMark", func(t *testing.T) { lines := [][]byte{ []byte("a"), []byte("bit of"), []byte("text"), } if err := v.SetBufferLines(Buffer(0), -1, -1, true, lines); err != nil { t.Fatal(err) } if err := v.SetWindowCursor(Window(0), [2]int{3, 4}); err != nil { t.Fatal(err) } if err := v.Command("mark v"); err != nil { t.Fatal(err) } const ( wantLine = 3 wantCol = 0 ) pos, err := v.BufferMark(Buffer(0), "v") if err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) }) }) }) t.Run("Batch", func(t *testing.T) { t.Run("BufferName", func(t *testing.T) { b := v.NewBatch() cwd, _ := os.Getwd() // buffer name is full path wantBufName := filepath.Join(cwd, "/test_buffer") b.SetBufferName(Buffer(0), wantBufName) if err := b.Execute(); err != nil { t.Fatal(err) } var bufName string b.BufferName(Buffer(0), &bufName) if err := b.Execute(); err != nil { t.Fatal(err) } if bufName != wantBufName { t.Fatalf("want %s buffer name but got %s", wantBufName, bufName) } t.Cleanup(func() { // cleanup cindent option b.SetBufferName(Buffer(0), "") if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("Buffers", func(t *testing.T) { b := v.NewBatch() var bufs []Buffer b.Buffers(&bufs) if err := b.Execute(); err != nil { t.Fatal(err) } if len(bufs) != 2 { t.Fatalf("expected one buf, found %d bufs", len(bufs)) } if bufs[0] == Buffer(0) { t.Fatalf("bufs[0] is not %q: %q", bufs[0], Buffer(0)) } var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } if buf != bufs[0] { t.Fatalf("buf is not bufs[0]: buf %v, bufs[0]: %v", buf, bufs[0]) } const want = "Buffer:1" if got := buf.String(); got != want { t.Fatalf("buf.String() = %s, want %s", got, want) } b.SetCurrentBuffer(buf) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("Var", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } const ( varkey = "bvar" varVal = "bval" ) b.SetBufferVar(buf, varkey, varVal) var s string b.BufferVar(buf, varkey, &s) if err := b.Execute(); err != nil { t.Fatal(err) } if s != varVal { t.Fatalf("expected bvar=bval, got %s", s) } b.DeleteBufferVar(buf, varkey) if err := b.Execute(); err != nil { t.Fatal(err) } s = "" // reuse b.BufferVar(buf, varkey, &s) if err := b.Execute(); err == nil { t.Fatalf("expected %s not found but error is nil: err: %#v", varkey, err) } }) t.Run("Delete", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("ChangeTick", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } // 1 changedtick lines := [][]byte{[]byte("hello"), []byte("world")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // 2 changedtick const wantChangedTick = 2 var changedTick int b.BufferChangedTick(buf, &changedTick) if err := b.Execute(); err != nil { t.Fatal(err) } if changedTick != wantChangedTick { t.Fatalf("got %d changedTick but want %d", changedTick, wantChangedTick) } // cleanup buffer deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("SetCurrentDirectory", func(t *testing.T) { wantDir, err := os.UserHomeDir() if err != nil { t.Fatal(err) } b := v.NewBatch() b.SetCurrentDirectory(wantDir) if err := b.Execute(); err != nil { t.Fatal(err) } var got string if err := v.Eval(`getcwd()`, &got); err != nil { t.Fatal(err) } if got != wantDir { t.Fatalf("SetCurrentDirectory(%s) = %s, want: %s", wantDir, got, wantDir) } }) t.Run("BufferCommands", func(t *testing.T) { b := v.NewBatch() var commands map[string]*Command b.BufferCommands(Buffer(0), make(map[string]interface{}), &commands) if err := b.Execute(); err != nil { t.Fatal(err) } if len(commands) > 0 { t.Fatalf("expected commands empty but non-zero: %#v", commands) } }) t.Run("BufferOption", func(t *testing.T) { b := v.NewBatch() var cindent bool b.BufferOption(Buffer(0), "cindent", &cindent) if err := b.Execute(); err != nil { t.Fatal(err) } if cindent { t.Fatalf("expected cindent is false but got %t", cindent) } b.SetBufferOption(Buffer(0), "cindent", true) if err := b.Execute(); err != nil { t.Fatal(err) } b.BufferOption(Buffer(0), "cindent", &cindent) if err := b.Execute(); err != nil { t.Fatal(err) } if !cindent { t.Fatalf("expected cindent is true but got %t", cindent) } t.Cleanup(func() { // cleanup cindent option b.SetBufferOption(Buffer(0), "cindent", false) if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("IsBufferLoaded", func(t *testing.T) { b := v.NewBatch() var loaded bool b.IsBufferLoaded(Buffer(0), &loaded) if err := b.Execute(); err != nil { t.Fatal(err) } if !loaded { t.Fatalf("expected buffer is loaded but got %t", loaded) } }) t.Run("IsBufferValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsBufferValid(Buffer(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected buffer is valid but got %t", valid) } }) t.Run("BufferMark", func(t *testing.T) { b := v.NewBatch() lines := [][]byte{ []byte("a"), []byte("bit of"), []byte("text"), } b.SetBufferLines(Buffer(0), -1, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetWindowCursor(Window(0), [2]int{3, 4}) b.Command("mark v") if err := b.Execute(); err != nil { t.Fatal(err) } const ( wantLine = 3 wantCol = 0 ) var pos [2]int b.BufferMark(Buffer(0), "v", &pos) if err := b.Execute(); err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) }) }) }) } } func testWindow(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { wins, err := v.Windows() if err != nil { t.Fatal(err) } if len(wins) != 1 { for i := 0; i < len(wins); i++ { t.Logf("wins[%d]: %v", i, wins[i]) } t.Fatalf("expected one win, found %d wins", len(wins)) } if wins[0] == 0 { t.Fatalf("wins[0] == 0") } win, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if win != wins[0] { t.Fatalf("win is not wins[0]: win: %v wins[0]: %v", win, wins[0]) } const want = "Window:1000" if got := win.String(); got != want { t.Fatalf("got %s but want %s", got, want) } win, err = v.CurrentWindow() if err != nil { t.Fatal(err) } if err := v.Command("split"); err != nil { t.Fatal(err) } win2, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if err := v.SetCurrentWindow(win); err != nil { t.Fatal(err) } gotwin, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if gotwin != win { t.Fatalf("expected current window %s but got %s", win, gotwin) } if err := v.HideWindow(win2); err != nil { t.Fatalf("failed to HideWindow(%v)", win2) } wins2, err := v.Windows() if err != nil { t.Fatal(err) } if len(wins2) != 1 { for i := 0; i < len(wins2); i++ { t.Logf("wins[%d]: %v", i, wins2[i]) } t.Fatalf("expected one win, found %d wins", len(wins2)) } if wins2[0] == 0 { t.Fatalf("wins[0] == 0") } if win != wins2[0] { t.Fatalf("win2 is not wins2[0]: want: %v, win2: %v ", wins2[0], win) } t.Run("WindowBuffer", func(t *testing.T) { skipVersion(t, "v0.6.0") gotBuf, err := v.WindowBuffer(Window(0)) if err != nil { t.Fatal(err) } wantBuffer := Buffer(1) if gotBuf != wantBuffer { t.Fatalf("want %s buffer but got %s", wantBuffer, gotBuf) } buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } if err := v.SetBufferToWindow(Window(0), buf); err != nil { t.Fatal(err) } gotBuf2, err := v.WindowBuffer(Window(0)) if err != nil { t.Fatal(err) } if gotBuf2 != buf { t.Fatalf("want %s buffer but got %s", buf, gotBuf2) } t.Cleanup(func() { if err := v.SetBufferToWindow(Window(0), gotBuf); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) }) t.Run("WindowCursor", func(t *testing.T) { wantLine := []byte("hello world") if err := v.SetCurrentLine(wantLine); err != nil { t.Fatal(err) } t.Cleanup(func() { if err := v.DeleteCurrentLine(); err != nil { t.Fatal(err) } }) wantPos := [2]int{1, 5} if err := v.SetWindowCursor(Window(0), wantPos); err != nil { t.Fatal(err) } gotPos, err := v.WindowCursor(Window(0)) if err != nil { t.Fatal(err) } if wantPos != gotPos { t.Fatalf("want %#v position buf got %#v", wantPos, gotPos) } }) t.Run("WindowVar", func(t *testing.T) { wantValue := []int{1, 2} if err := v.SetWindowVar(Window(0), "lua", wantValue); err != nil { t.Fatal(err) } var gotValue []int if err := v.WindowVar(Window(0), "lua", &gotValue); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } if err := v.DeleteWindowVar(Window(0), "lua"); err != nil { t.Fatal(err) } if err := v.WindowVar(Window(0), "lua", nil); err == nil { t.Fatalf("expect Key not found but fonud key") } }) t.Run("WindowOption", func(t *testing.T) { wantValue := "+1" if err := v.SetWindowOption(Window(0), "colorcolumn", &wantValue); err != nil { t.Fatal(err) } var gotValue string if err := v.WindowOption(Window(0), "colorcolumn", &gotValue); err != nil { t.Fatal(err) } if gotValue != wantValue { t.Fatalf("expected %s but got %s", wantValue, gotValue) } t.Cleanup(func() { if err := v.SetWindowOption(Window(0), "colorcolumn", ""); err != nil { t.Fatal(err) } }) }) t.Run("WindowPosition", func(t *testing.T) { gotPos, err := v.WindowPosition(Window(0)) if err != nil { t.Fatal(err) } wantPos := [2]int{0, 0} if gotPos != wantPos { t.Fatalf("expected %v but got %v", wantPos, gotPos) } }) t.Run("WindowTabpage", func(t *testing.T) { gotTabpage, err := v.WindowTabpage(Window(0)) if err != nil { t.Fatal(err) } wantTabpage := Tabpage(1) if gotTabpage != wantTabpage { t.Fatalf("expected %v but got %v", wantTabpage, gotTabpage) } }) t.Run("WindowNumber", func(t *testing.T) { gotWinNum, err := v.WindowNumber(Window(0)) if err != nil { t.Fatal(err) } wantWinNum := 1 if gotWinNum != wantWinNum { t.Fatalf("expected %v but got %v", wantWinNum, gotWinNum) } }) t.Run("IsWindowValid", func(t *testing.T) { valid, err := v.IsWindowValid(Window(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var wins []Window b.Windows(&wins) if err := b.Execute(); err != nil { t.Fatal(err) } if len(wins) != 1 { t.Fatalf("expected one win, found %d wins", len(wins)) } if wins[0] == 0 { t.Fatalf("wins[0] == 0") } var win Window b.CurrentWindow(&win) if err := b.Execute(); err != nil { t.Fatal(err) } if win != wins[0] { t.Fatalf("win is not wins[0]: win: %v wins[0]: %v", win, wins[0]) } const want = "Window:1000" if got := win.String(); got != want { t.Fatalf("got %s but want %s", got, want) } b.CurrentWindow(&win) if err := b.Execute(); err != nil { t.Fatal(err) } b.Command("split") var win2 Window b.CurrentWindow(&win2) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetCurrentWindow(win) var gotwin Window b.CurrentWindow(&gotwin) if err := b.Execute(); err != nil { t.Fatal(err) } if gotwin != win { t.Fatalf("expected current window %s but got %s", win, gotwin) } b.HideWindow(win2) var wins2 []Window b.Windows(&wins2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(wins2) != 1 { for i := 0; i < len(wins2); i++ { t.Logf("wins[%d]: %v", i, wins2[i]) } t.Fatalf("expected one win, found %d wins", len(wins2)) } if wins2[0] == 0 { t.Fatalf("wins[0] == 0") } if win != wins2[0] { t.Fatalf("win2 is not wins2[0]: want: %v, win2: %v ", wins2[0], win) } t.Run("WindowBuffer", func(t *testing.T) { skipVersion(t, "v0.6.0") b := v.NewBatch() var gotBuf Buffer b.WindowBuffer(Window(0), &gotBuf) if err := b.Execute(); err != nil { t.Fatal(err) } wantBuffer := Buffer(1) if gotBuf != wantBuffer { t.Fatalf("want %s buffer but got %s", wantBuffer, gotBuf) } var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetBufferToWindow(Window(0), buf) if err := b.Execute(); err != nil { t.Fatal(err) } var gotBuf2 Buffer b.WindowBuffer(Window(0), &gotBuf2) if err := b.Execute(); err != nil { t.Fatal(err) } if gotBuf2 != buf { t.Fatalf("want %s buffer but got %s", buf, gotBuf2) } t.Cleanup(func() { b.SetBufferToWindow(Window(0), gotBuf) if err := b.Execute(); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("WindowCursor", func(t *testing.T) { b := v.NewBatch() wantLine := []byte("hello world") b.SetCurrentLine(wantLine) if err := b.Execute(); err != nil { t.Fatal(err) } t.Cleanup(func() { b.DeleteCurrentLine() if err := b.Execute(); err != nil { t.Fatal(err) } }) wantPos := [2]int{1, 5} b.SetWindowCursor(Window(0), wantPos) if err := b.Execute(); err != nil { t.Fatal(err) } var gotPos [2]int b.WindowCursor(Window(0), &gotPos) if err := b.Execute(); err != nil { t.Fatal(err) } if wantPos != gotPos { t.Fatalf("want %#v position buf got %#v", wantPos, gotPos) } }) t.Run("WindowVar", func(t *testing.T) { b := v.NewBatch() wantValue := []int{1, 2} b.SetWindowVar(Window(0), "lua", wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue []int b.WindowVar(Window(0), "lua", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } b.DeleteWindowVar(Window(0), "lua") if err := b.Execute(); err != nil { t.Fatal(err) } b.WindowVar(Window(0), "lua", nil) if err := b.Execute(); err == nil { t.Fatalf("expect Key not found but fonud key") } }) t.Run("WindowOption", func(t *testing.T) { b := v.NewBatch() wantValue := "+1" b.SetWindowOption(Window(0), "colorcolumn", &wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue string b.WindowOption(Window(0), "colorcolumn", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if gotValue != wantValue { t.Fatalf("expected %s but got %s", wantValue, gotValue) } t.Cleanup(func() { b.SetWindowOption(Window(0), "colorcolumn", "") if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("WindowPosition", func(t *testing.T) { b := v.NewBatch() var gotPos [2]int b.WindowPosition(Window(0), &gotPos) if err := b.Execute(); err != nil { t.Fatal(err) } wantPos := [2]int{0, 0} if gotPos != wantPos { t.Fatalf("expected %v but got %v", wantPos, gotPos) } }) t.Run("WindowTabpage", func(t *testing.T) { b := v.NewBatch() var gotTabpage Tabpage b.WindowTabpage(Window(0), &gotTabpage) if err := b.Execute(); err != nil { t.Fatal(err) } wantTabpage := Tabpage(1) if gotTabpage != wantTabpage { t.Fatalf("expected %v but got %v", wantTabpage, gotTabpage) } }) t.Run("WindowNumber", func(t *testing.T) { b := v.NewBatch() var gotWinNum int b.WindowNumber(Window(0), &gotWinNum) if err := b.Execute(); err != nil { t.Fatal(err) } wantWinNum := 1 if gotWinNum != wantWinNum { t.Fatalf("expected %v but got %v", wantWinNum, gotWinNum) } }) t.Run("IsWindowValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsWindowValid(Window(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) }) } } func testTabpage(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { pages, err := v.Tabpages() if err != nil { t.Fatal(err) } if len(pages) != 1 { t.Fatalf("expected one page, found %d pages", len(pages)) } if pages[0] == 0 { t.Fatalf("pages[0] is not 0: %d", pages[0]) } page, err := v.CurrentTabpage() if err != nil { t.Fatal(err) } if page != pages[0] { t.Fatalf("page is not pages[0]: page: %v pages[0]: %v", page, pages[0]) } const want = "Tabpage:1" if got := page.String(); got != want { t.Fatalf("got %s but want %s", got, want) } if err := v.SetCurrentTabpage(page); err != nil { t.Fatal(err) } t.Run("TabpageWindow", func(t *testing.T) { gotWin, err := v.TabpageWindow(Tabpage(0)) if err != nil { t.Fatal(err) } wantWin := Window(1000) if !reflect.DeepEqual(gotWin, wantWin) { t.Fatalf("expected %v but got %v", wantWin, gotWin) } }) t.Run("TabpageWindows", func(t *testing.T) { gotWins, err := v.TabpageWindows(Tabpage(0)) if err != nil { t.Fatal(err) } wantWins := []Window{Window(1000)} if !reflect.DeepEqual(gotWins, wantWins) { t.Fatalf("expected %v but got %v", wantWins, gotWins) } }) t.Run("TabpageNumber", func(t *testing.T) { gotTabpageNum, err := v.TabpageNumber(Tabpage(0)) if err != nil { t.Fatal(err) } wantTabpageNum := 1 if gotTabpageNum != wantTabpageNum { t.Fatalf("expected %v but got %v", wantTabpageNum, gotTabpageNum) } }) t.Run("IsTabpageValid", func(t *testing.T) { valid, err := v.IsTabpageValid(Tabpage(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) t.Run("TabpageVar", func(t *testing.T) { wantValue := []int{1, 2} if err := v.SetTabpageVar(Tabpage(0), "lua", wantValue); err != nil { t.Fatal(err) } var gotValue []int if err := v.TabpageVar(Tabpage(0), "lua", &gotValue); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } if err := v.DeleteTabpageVar(Tabpage(0), "lua"); err != nil { t.Fatal(err) } if err := v.TabpageVar(Tabpage(0), "lua", nil); err == nil { t.Fatalf("expect Key not found but fonud key") } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var pages []Tabpage b.Tabpages(&pages) if err := b.Execute(); err != nil { t.Fatal(err) } if len(pages) != 1 { t.Fatalf("expected one page, found %d pages", len(pages)) } if pages[0] == 0 { t.Fatalf("pages[0] is not 0: %d", pages[0]) } var page Tabpage b.CurrentTabpage(&page) if err := b.Execute(); err != nil { t.Fatal(err) } if page != pages[0] { t.Fatalf("page is not pages[0]: page: %v pages[0]: %v", page, pages[0]) } const want = "Tabpage:1" if got := page.String(); got != want { t.Fatalf("got %s but want %s", got, want) } b.SetCurrentTabpage(page) if err := b.Execute(); err != nil { t.Fatal(err) } t.Run("TabpageWindow", func(t *testing.T) { b := v.NewBatch() var gotWin Window b.TabpageWindow(Tabpage(0), &gotWin) if err := b.Execute(); err != nil { t.Fatal(err) } wantWin := Window(1000) if gotWin != wantWin { t.Fatalf("expected %v but got %v", wantWin, gotWin) } }) t.Run("TabpageWindows", func(t *testing.T) { b := v.NewBatch() var gotWins []Window b.TabpageWindows(Tabpage(0), &gotWins) if err := b.Execute(); err != nil { t.Fatal(err) } wantWins := []Window{Window(1000)} if !reflect.DeepEqual(gotWins, wantWins) { t.Fatalf("expected %v but got %v", wantWins, gotWins) } }) t.Run("TabpageNumber", func(t *testing.T) { b := v.NewBatch() var gotTabpageNum int b.TabpageNumber(Tabpage(0), &gotTabpageNum) if err := b.Execute(); err != nil { t.Fatal(err) } wantTabpageNum := 1 if gotTabpageNum != wantTabpageNum { t.Fatalf("expected %v but got %v", wantTabpageNum, gotTabpageNum) } }) t.Run("IsWindowValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsTabpageValid(Tabpage(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) t.Run("TabpageVar", func(t *testing.T) { b := v.NewBatch() wantValue := []int{1, 2} b.SetTabpageVar(Tabpage(0), "lua", wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue []int b.TabpageVar(Tabpage(0), "lua", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } b.DeleteTabpageVar(Tabpage(0), "lua") if err := b.Execute(); err != nil { t.Fatal(err) } b.TabpageVar(Tabpage(0), "lua", nil) if err := b.Execute(); err == nil { t.Fatalf("expect Key not found but fonud key") } }) }) } } func testLines(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("CurrentLine", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) beforeLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } wantLine := []byte("hello world") if err := v.SetCurrentLine(wantLine); err != nil { t.Fatal(err) } afterLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } if bytes.EqualFold(beforeLine, afterLine) { t.Fatalf("current line not change: before: %v, after: %v", beforeLine, afterLine) } if err := v.DeleteCurrentLine(); err != nil { t.Fatal(err) } deletedLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } if len(deletedLine) != 0 { t.Fatal("DeleteCurrentLine not deleted") } }) t.Run("BufferLines", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. lines := [][]byte{[]byte("hello"), []byte("world")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } lines2, err := v.BufferLines(buf, 0, -1, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(lines2, lines) { t.Fatalf("lines = %+v, want %+v", lines2, lines) } const wantCount = 2 count, err := v.BufferLineCount(buf) if err != nil { t.Fatal(err) } if count != wantCount { t.Fatalf("got count %d but want %d", count, wantCount) } const wantOffset = 12 // [][]byte{[]byte("hello"), []byte("\n"), []byte("world"), []byte("\n")} offset, err := v.BufferOffset(buf, count) if err != nil { t.Fatal(err) } if offset != wantOffset { t.Fatalf("got offset %d but want %d", offset, wantOffset) } }) t.Run("SetBufferText", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. // sets test buffer text. lines := [][]byte{[]byte("Vim is the"), []byte("Nvim-fork? focused on extensibility and usability")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } // Replace `Vim is the` to `Neovim is the` if err := v.SetBufferText(buf, 0, 0, 0, 3, [][]byte{[]byte("Neovim")}); err != nil { t.Fatal(err) } // Replace `Nvim-fork?` to `Vim-fork` if err := v.SetBufferText(buf, 1, 0, 1, 10, [][]byte{[]byte("Vim-fork")}); err != nil { t.Fatal(err) } want := [2][]byte{ []byte("Neovim is the"), []byte("Vim-fork focused on extensibility and usability"), } got, err := v.BufferLines(buf, 0, -1, true) if err != nil { t.Fatal(err) } // assert buffer lines count. const wantCount = 2 if len(got) != wantCount { t.Fatalf("expected buffer lines rows is %d: got %d", wantCount, len(got)) } // assert row 1 buffer text. if !bytes.EqualFold(want[0], got[0]) { t.Fatalf("row 1 is not equal: want: %q, got: %q", string(want[0]), string(got[0])) } // assert row 2 buffer text. if !bytes.EqualFold(want[1], got[1]) { t.Fatalf("row 2 is not equal: want: %q, got: %q", string(want[1]), string(got[1])) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("CurrentLine", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) b := v.NewBatch() var beforeLine []byte b.CurrentLine(&beforeLine) if err := b.Execute(); err != nil { t.Fatal(err) } wantLine := []byte("hello world") b.SetCurrentLine(wantLine) if err := b.Execute(); err != nil { t.Fatal(err) } var afterLine []byte b.CurrentLine(&afterLine) if err := b.Execute(); err != nil { t.Fatal(err) } if bytes.EqualFold(beforeLine, afterLine) { t.Fatalf("current line not change: before: %v, after: %v", beforeLine, afterLine) } b.DeleteCurrentLine() if err := b.Execute(); err != nil { t.Fatal(err) } var deletedLine []byte b.CurrentLine(&deletedLine) if err := b.Execute(); err != nil { t.Fatal(err) } if len(deletedLine) != 0 { t.Fatal("DeleteCurrentLine not deleted") } }) t.Run("BufferLines", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. lines := [][]byte{[]byte("hello"), []byte("world")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } var lines2 [][]byte b.BufferLines(buf, 0, -1, true, &lines2) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(lines2, lines) { t.Fatalf("lines = %+v, want %+v", lines2, lines) } const wantCount = 2 var count int b.BufferLineCount(buf, &count) if err := b.Execute(); err != nil { t.Fatal(err) } if count != wantCount { t.Fatalf("count is not 2 %d", count) } const wantOffset = 12 // [][]byte{[]byte("hello"), []byte("\n"), []byte("world"), []byte("\n")} var offset int b.BufferOffset(buf, count, &offset) if err := b.Execute(); err != nil { t.Fatal(err) } if offset != wantOffset { t.Fatalf("got offset %d but want %d", offset, wantOffset) } }) t.Run("SetBufferText", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. // sets test buffer text. lines := [][]byte{[]byte("Vim is the"), []byte("Nvim-fork? focused on extensibility and usability")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // Replace `Vim is the` to `Neovim is the` b.SetBufferText(buf, 0, 0, 0, 3, [][]byte{[]byte("Neovim")}) // Replace `Nvim-fork?` to `Vim-fork` b.SetBufferText(buf, 1, 0, 1, 10, [][]byte{[]byte("Vim-fork")}) if err := b.Execute(); err != nil { t.Fatal(err) } want := [2][]byte{ []byte("Neovim is the"), []byte("Vim-fork focused on extensibility and usability"), } var got [][]byte b.BufferLines(buf, 0, -1, true, &got) if err := b.Execute(); err != nil { t.Fatal(err) } // assert buffer lines count. const wantCount = 2 if len(got) != wantCount { t.Fatalf("expected buffer lines rows is %d: got %d", wantCount, len(got)) } // assert row 1 buffer text. if !bytes.EqualFold(want[0], got[0]) { t.Fatalf("row 1 is not equal: want: %q, got: %q", string(want[0]), string(got[0])) } // assert row 1 buffer text. if !bytes.EqualFold(want[1], got[1]) { t.Fatalf("row 2 is not equal: want: %q, got: %q", string(want[1]), string(got[1])) } }) }) } } func testCommands(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { opts := map[string]interface{}{ "builtin": false, } cmds, err := v.Commands(opts) if err != nil { t.Fatal(err) } if len(cmds) > 0 { t.Fatalf("expected 0 length but got %#v", cmds) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() opts := map[string]interface{}{ "builtin": false, } var cmds map[string]*Command b.Commands(opts, &cmds) if err := b.Execute(); err != nil { t.Fatal(err) } if len(cmds) > 0 { t.Fatalf("expected 0 length but got %#v", cmds) } }) } } func testVar(v *Nvim) func(*testing.T) { return func(t *testing.T) { const ( varKey = `gvar` varVal = `gval` ) const ( vvarKey = "statusmsg" wantVvar = "test" ) t.Run("Nvim", func(t *testing.T) { t.Run("Var", func(t *testing.T) { if err := v.SetVar(varKey, varVal); err != nil { t.Fatal(err) } var value interface{} if err := v.Var(varKey, &value); err != nil { t.Fatal(err) } if value != varVal { t.Fatalf("got %v, want %q", value, varVal) } if err := v.SetVar(varKey, ""); err != nil { t.Fatal(err) } value = nil if err := v.Var(varKey, &value); err != nil { t.Fatal(err) } if value != "" { t.Fatalf("got %v, want %q", value, "") } if err := v.DeleteVar(varKey); err != nil && !strings.Contains(err.Error(), "Key not found") { t.Fatal(err) } }) t.Run("VVar", func(t *testing.T) { if err := v.SetVVar(vvarKey, wantVvar); err != nil { t.Fatalf("failed to SetVVar: %v", err) } var vvar string if err := v.VVar(vvarKey, &vvar); err != nil { t.Fatalf("failed to SetVVar: %v", err) } if vvar != wantVvar { t.Fatalf("VVar(%s, %s) = %s, want: %s", vvarKey, wantVvar, vvar, wantVvar) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Var", func(t *testing.T) { b := v.NewBatch() b.SetVar(varKey, varVal) var value interface{} b.Var(varKey, &value) if err := b.Execute(); err != nil { t.Fatal(err) } if value != varVal { t.Fatalf("got %v, want %q", value, varVal) } b.SetVar(varKey, "") value = nil b.Var(varKey, &value) if err := b.Execute(); err != nil { t.Fatal(err) } if value != "" { t.Fatalf("got %v, want %q", value, "") } b.DeleteVar(varKey) if err := b.Execute(); err != nil && !strings.Contains(err.Error(), "Key not found") { t.Fatal(err) } }) t.Run("VVar", func(t *testing.T) { b := v.NewBatch() b.SetVVar(vvarKey, wantVvar) if err := b.Execute(); err != nil { t.Fatal(err) } var vvar string b.VVar(vvarKey, &vvar) if err := b.Execute(); err != nil { t.Fatal(err) } if vvar != wantVvar { t.Fatalf("VVar(%s, %s) = %s, want: %s", vvarKey, wantVvar, vvar, wantVvar) } }) }) } } func testMessage(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("Echo", func(t *testing.T) { const wantEcho = `hello Echo` chunk := []TextChunk{ { Text: wantEcho, }, } if err := v.Echo(chunk, true, make(map[string]interface{})); err != nil { t.Fatalf("failed to Echo: %v", err) } gotEcho, err := v.Exec("message", true) if err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotEcho != wantEcho { t.Fatalf("Echo(%q) = %q, want: %q", wantEcho, gotEcho, wantEcho) } }) t.Run("WriteOut", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWriteOut = `hello WriteOut` if err := v.WriteOut(wantWriteOut + "\n"); err != nil { t.Fatalf("failed to WriteOut: %v", err) } var gotWriteOut string if err := v.VVar("statusmsg", &gotWriteOut); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteOut != wantWriteOut { t.Fatalf("WriteOut(%q) = %q, want: %q", wantWriteOut, gotWriteOut, wantWriteOut) } }) t.Run("WriteErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWriteErr = `hello WriteErr` if err := v.WriteErr(wantWriteErr + "\n"); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWriteErr string if err := v.VVar("errmsg", &gotWriteErr); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteErr != wantWriteErr { t.Fatalf("WriteErr(%q) = %q, want: %q", wantWriteErr, gotWriteErr, wantWriteErr) } }) t.Run("WritelnErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWritelnErr = `hello WritelnErr` if err := v.WritelnErr(wantWritelnErr); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWritelnErr string if err := v.VVar("errmsg", &gotWritelnErr); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWritelnErr != wantWritelnErr { t.Fatalf("WritelnErr(%q) = %q, want: %q", wantWritelnErr, gotWritelnErr, wantWritelnErr) } }) t.Run("Notify", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantNotifyMsg = `hello Notify` if err := v.Notify(wantNotifyMsg, LogInfoLevel, make(map[string]interface{})); err != nil { t.Fatalf("failed to Notify: %v", err) } gotNotifyMsg, err := v.Exec(":messages", true) if err != nil { t.Fatalf("failed to messages command: %v", err) } if wantNotifyMsg != gotNotifyMsg { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyMsg, LogInfoLevel, gotNotifyMsg) } }) t.Run("Notify/Error", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantNotifyErr = `hello Notify Error` if err := v.Notify(wantNotifyErr, LogErrorLevel, make(map[string]interface{})); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyErr string if err := v.VVar("errmsg", &gotNotifyErr); err != nil { t.Fatalf("could not get v:errmsg nvim variable: %v", err) } if wantNotifyErr != gotNotifyErr { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyErr, LogErrorLevel, gotNotifyErr) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Echo", func(t *testing.T) { b := v.NewBatch() const wantEcho = `hello Echo` chunk := []TextChunk{ { Text: wantEcho, }, } b.Echo(chunk, true, make(map[string]interface{})) var gotEcho string b.Exec("message", true, &gotEcho) if err := b.Execute(); err != nil { t.Fatalf("failed to Execute: %v", err) } if gotEcho != wantEcho { t.Fatalf("Echo(%q) = %q, want: %q", wantEcho, gotEcho, wantEcho) } }) t.Run("WriteOut", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWriteOut = `hello WriteOut` b.WriteOut(wantWriteOut + "\n") if err := b.Execute(); err != nil { t.Fatalf("failed to WriteOut: %v", err) } var gotWriteOut string b.VVar("statusmsg", &gotWriteOut) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteOut != wantWriteOut { t.Fatalf("b.WriteOut(%q) = %q, want: %q", wantWriteOut, gotWriteOut, wantWriteOut) } }) t.Run("WriteErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWriteErr = `hello WriteErr` b.WriteErr(wantWriteErr + "\n") if err := b.Execute(); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWriteErr string b.VVar("errmsg", &gotWriteErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteErr != wantWriteErr { t.Fatalf("b.WriteErr(%q) = %q, want: %q", wantWriteErr, gotWriteErr, wantWriteErr) } }) t.Run("WritelnErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWritelnErr = `hello WritelnErr` b.WritelnErr(wantWritelnErr) if err := b.Execute(); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWritelnErr string b.VVar("errmsg", &gotWritelnErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWritelnErr != wantWritelnErr { t.Fatalf("b.WritelnErr(%q) = %q, want: %q", wantWritelnErr, gotWritelnErr, wantWritelnErr) } }) t.Run("Notify", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantNotifyMsg = `hello Notify` b.Notify(wantNotifyMsg, LogInfoLevel, make(map[string]interface{})) if err := b.Execute(); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyMsg string b.Exec(":messages", true, &gotNotifyMsg) if err := b.Execute(); err != nil { t.Fatalf("failed to \":messages\" command: %v", err) } if wantNotifyMsg != gotNotifyMsg { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyMsg, LogInfoLevel, gotNotifyMsg) } }) t.Run("Notify/Error", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantNotifyErr = `hello Notify Error` b.Notify(wantNotifyErr, LogErrorLevel, make(map[string]interface{})) if err := b.Execute(); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyErr string b.VVar("errmsg", &gotNotifyErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:errmsg nvim variable: %v", err) } if wantNotifyErr != gotNotifyErr { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyErr, LogErrorLevel, gotNotifyErr) } }) }) } } func testKey(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("FeedKeys", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) input, err := v.ReplaceTermcodes(keys, true, true, true) if err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) if err := v.FeedKeys(input, mode, escapeCSI); err != nil { t.Fatal(err) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("Input", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) input, err := v.ReplaceTermcodes(keys, true, true, true) if err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) written, err := v.Input(input) if err != nil { t.Fatal(err) } if written != len(input) { t.Fatalf("Input(%s) = %d: want: %d", input, written, len(input)) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("InputMouse", func(t *testing.T) { defer func() { // cleanup current Buffer after tests. clearBuffer(t, v, Buffer(0)) input, err := v.ReplaceTermcodes(`<ESC>`, true, true, true) if err != nil { t.Fatal(err) } if err := v.FeedKeys(input, `n`, true); err != nil { t.Fatal(err) } }() // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) lines := [][]byte{ []byte("foo bar baz"), []byte("qux quux quuz"), []byte("corge grault garply"), []byte("waldo fred plugh"), []byte("xyzzy thud"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } const ( button = `left` firestAction = `press` secondAction = `release` modifier = "" ) const ( wantGrid = 20 wantRow = 2 wantCol = 5 ) if err := v.InputMouse(button, firestAction, modifier, wantGrid, wantRow, wantCol); err != nil { t.Fatal(err) } // TODO(zchee): assertion }) t.Run("StringWidth", func(t *testing.T) { const str = "hello\t" got, err := v.StringWidth(str) if err != nil { t.Fatal(err) } if got != len(str) { t.Fatalf("StringWidth(%s) = %d, want: %d", str, got, len(str)) } }) t.Run("KeyMap", func(t *testing.T) { mode := "n" if err := v.SetKeyMap(mode, "y", "yy", make(map[string]bool)); err != nil { t.Fatal(err) } wantMaps := []*Mapping{ { LHS: "y", RHS: "yy", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, } wantMapsLen := 0 if nvimVersion.Minor >= 6 { lastMap := wantMaps[0] wantMaps = []*Mapping{ { LHS: "<C-L>", RHS: "<Cmd>nohlsearch|diffupdate<CR><C-L>", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, { LHS: "Y", RHS: "y$", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, lastMap, } wantMapsLen = 2 } got, err := v.KeyMap(mode) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, wantMaps) { for i, gotmap := range got { t.Logf(" got[%d]: %#v", i, gotmap) } for i, wantmap := range wantMaps { t.Logf("want[%d]: %#v", i, wantmap) } t.Fatalf("KeyMap(%s) = %#v, want: %#v", mode, got, wantMaps) } if err := v.DeleteKeyMap(mode, "y"); err != nil { t.Fatal(err) } got2, err := v.KeyMap(mode) if err != nil { t.Fatal(err) } if len(got2) != wantMapsLen { t.Fatalf("expected %d but got %#v", wantMapsLen, got2) } }) t.Run("BufferKeyMap", func(t *testing.T) { mode := "n" buffer := Buffer(0) if err := v.SetBufferKeyMap(buffer, mode, "x", "xx", make(map[string]bool)); err != nil { t.Fatal(err) } wantMap := []*Mapping{ { LHS: "x", RHS: "xx", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 1, SID: 0, NoWait: 0, }, } got, err := v.BufferKeyMap(buffer, mode) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(wantMap, got) { t.Fatalf("KeyMap(n) = %#v, want: %#v", got[0], wantMap[0]) } if err := v.DeleteBufferKeyMap(buffer, mode, "x"); err != nil { t.Fatal(err) } got2, err := v.BufferKeyMap(buffer, mode) if err != nil { t.Fatal(err) } if wantLen := 0; len(got2) != wantLen { t.Fatalf("expected %d but got %#v", wantLen, got2) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("FeedKeys", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) b := v.NewBatch() const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) var input string b.ReplaceTermcodes(keys, true, true, true, &input) if err := b.Execute(); err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) b.FeedKeys(input, mode, escapeCSI) if err := b.Execute(); err != nil { t.Fatal(err) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", keys, mode, escapeCSI, gotLines, wantLines) } }) t.Run("Input", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) b := v.NewBatch() const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) var input string b.ReplaceTermcodes(keys, true, true, true, &input) if err := b.Execute(); err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) var written int b.Input(input, &written) if err := b.Execute(); err != nil { t.Fatal(err) } if written != len(input) { t.Fatalf("Input(%s) = %d: want: %d", input, written, len(input)) } wantLines := []byte{'a', 'b', 'c'} var gotLines []byte b.CurrentLine(&gotLines) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("InputMouse", func(t *testing.T) { defer func() { // cleanup current Buffer after tests. clearBuffer(t, v, Buffer(0)) input, err := v.ReplaceTermcodes(`<ESC>`, true, true, true) if err != nil { t.Fatal(err) } if err := v.FeedKeys(input, `n`, true); err != nil { t.Fatal(err) } }() // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) lines := [][]byte{ []byte("foo bar baz"), []byte("qux quux quuz"), []byte("corge grault garply"), []byte("waldo fred plugh"), []byte("xyzzy thud"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } const ( button = `left` firestAction = `press` secondAction = `release` modifier = "" ) const ( wantGrid = 20 wantRow = 2 wantCol = 5 ) b := v.NewBatch() b.InputMouse(button, firestAction, modifier, wantGrid, wantRow, wantCol) if err := b.Execute(); err != nil { t.Fatal(err) } b.InputMouse(button, secondAction, modifier, wantGrid, wantRow, wantCol) if err := b.Execute(); err != nil { t.Fatal(err) } // TODO(zchee): assertion }) t.Run("StringWidth", func(t *testing.T) { b := v.NewBatch() const str = "hello\t" var got int b.StringWidth(str, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if got != len(str) { t.Fatalf("StringWidth(%s) = %d, want: %d", str, got, len(str)) } }) t.Run("KeyMap", func(t *testing.T) { b := v.NewBatch() mode := "n" b.SetKeyMap(mode, "y", "yy", make(map[string]bool)) if err := b.Execute(); err != nil { t.Fatal(err) } wantMaps := []*Mapping{ { LHS: "y", RHS: "yy", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, } wantMapsLen := 0 if nvimVersion.Minor >= 6 { lastMap := wantMaps[0] wantMaps = []*Mapping{ { LHS: "<C-L>", RHS: "<Cmd>nohlsearch|diffupdate<CR><C-L>", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, { LHS: "Y", RHS: "y$", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, lastMap, } wantMapsLen = 2 } var got []*Mapping b.KeyMap(mode, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, wantMaps) { for i, gotmap := range got { t.Logf(" got[%d]: %#v", i, gotmap) } for i, wantmap := range wantMaps { t.Logf("want[%d]: %#v", i, wantmap) } t.Fatalf("KeyMap(%s) = %#v, want: %#v", mode, got, wantMaps) } b.DeleteKeyMap(mode, "y") if err := b.Execute(); err != nil { t.Fatal(err) } var got2 []*Mapping b.KeyMap(mode, &got2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(got2) != wantMapsLen { t.Fatalf("expected %d but got %#v", wantMapsLen, got2) } }) t.Run("BufferKeyMap", func(t *testing.T) { mode := "n" b := v.NewBatch() buffer := Buffer(0) b.SetBufferKeyMap(buffer, mode, "x", "xx", make(map[string]bool)) if err := b.Execute(); err != nil { t.Fatal(err) } wantMap := []*Mapping{ { LHS: "x", RHS: "xx", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 1, SID: 0, NoWait: 0, }, } var got []*Mapping b.BufferKeyMap(buffer, mode, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(wantMap, got) { t.Fatalf("KeyMap(n) = %#v, want: %#v", got[0], wantMap[0]) } b.DeleteBufferKeyMap(buffer, mode, "x") if err := b.Execute(); err != nil { t.Fatal(err) } var got2 []*Mapping b.BufferKeyMap(buffer, mode, &got2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(got2) > 0 { t.Fatalf("expected 0 but got %#v", got2) } }) }) } } func testEval(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { var a, b string if err := v.Eval(`["hello", "world"]`, []*string{&a, &b}); err != nil { t.Fatal(err) } if a != "hello" || b != "world" { t.Fatalf("a=%q b=%q, want a=hello b=world", a, b) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var x, y string b.Eval(`["hello", "world"]`, []*string{&x, &y}) if err := b.Execute(); err != nil { t.Fatal(err) } if x != "hello" || y != "world" { t.Fatalf("a=%q b=%q, want a=hello b=world", x, y) } }) } } func testBatch(v *Nvim) func(*testing.T) { return func(t *testing.T) { b := v.NewBatch() results := make([]int, 128) for i := range results { b.SetVar(fmt.Sprintf("batch%d", i), i) } for i := range results { b.Var(fmt.Sprintf("batch%d", i), &results[i]) } if err := b.Execute(); err != nil { t.Fatal(err) } for i := range results { if results[i] != i { t.Fatalf("result[i] = %d, want %d", results[i], i) } } // Reuse batch var i int b.Var("batch3", &i) if err := b.Execute(); err != nil { log.Fatal(err) } if i != 3 { t.Fatalf("i = %d, want %d", i, 3) } // Check for *BatchError const errorIndex = 3 for i := range results { results[i] = -1 } for i := range results { if i == errorIndex { b.Var("batch_bad_var", &results[i]) } else { b.Var(fmt.Sprintf("batch%d", i), &results[i]) } } err := b.Execute() if e, ok := err.(*BatchError); !ok || e.Index != errorIndex { t.Fatalf("unxpected error %T %v", e, e) } // Expect results proceeding error. for i := 0; i < errorIndex; i++ { if results[i] != i { t.Fatalf("result[i] = %d, want %d", results[i], i) break } } // No results after error. for i := errorIndex; i < len(results); i++ { if results[i] != -1 { t.Fatalf("result[i] = %d, want %d", results[i], -1) break } } // Execute should return marshal error for argument that cannot be marshaled. b.SetVar("batch0", make(chan bool)) if err := b.Execute(); err == nil || !strings.Contains(err.Error(), "chan bool") { t.Fatalf("err = nil, expect error containing text 'chan bool'") } // Test call with empty argument list. var buf Buffer b.CurrentBuffer(&buf) if err = b.Execute(); err != nil { t.Fatalf("GetCurrentBuffer returns err %s: %#v", err, err) } } } func testMode(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { m, err := v.Mode() if err != nil { t.Fatal(err) } if m.Mode != "n" { t.Fatalf("Mode() returned %s, want n", m.Mode) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var m Mode b.Mode(&m) if err := b.Execute(); err != nil { t.Fatal(err) } if m.Mode != "n" { t.Fatalf("Mode() returned %s, want n", m.Mode) } }) } } func testExecLua(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { var n int err := v.ExecLua("local a, b = ... return a + b", &n, 1, 2) if err != nil { t.Fatal(err) } if n != 3 { t.Fatalf("Mode() returned %v, want 3", n) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var n int b.ExecLua("local a, b = ... return a + b", &n, 1, 2) if err := b.Execute(); err != nil { t.Fatal(err) } if n != 3 { t.Fatalf("Mode() returned %v, want 3", n) } }) } } func testHighlight(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { cm, err := v.ColorMap() if err != nil { t.Fatal(err) } const cmd = `highlight NewHighlight cterm=underline ctermbg=green guifg=red guibg=yellow guisp=blue gui=bold` if err := v.Command(cmd); err != nil { t.Fatal(err) } wantCTerm := &HLAttrs{ Underline: true, Foreground: -1, Background: 10, Special: -1, } wantGUI := &HLAttrs{ Bold: true, Foreground: cm["Red"], Background: cm["Yellow"], Special: cm["Blue"], } var nsID int if err := v.Eval(`hlID('NewHighlight')`, &nsID); err != nil { t.Fatal(err) } const HLIDName = `Error` var wantErrorHLID = 64 if nvimVersion.Minor >= 7 { wantErrorHLID = 66 } goHLID, err := v.HLIDByName(HLIDName) if err != nil { t.Fatal(err) } if goHLID != wantErrorHLID { t.Fatalf("HLByID(%s)\n got %+v,\nwant %+v", HLIDName, goHLID, wantErrorHLID) } gotCTermHL, err := v.HLByID(nsID, false) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotCTermHL, wantCTerm) { t.Fatalf("HLByID(id, false)\n got %+v,\nwant %+v", gotCTermHL, wantCTerm) } gotGUIHL, err := v.HLByID(nsID, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotGUIHL, wantGUI) { t.Fatalf("HLByID(id, true)\n got %+v,\nwant %+v", gotGUIHL, wantGUI) } errorMsgHL, err := v.HLByName(`ErrorMsg`, true) if err != nil { t.Fatal(err) } errorMsgHL.Bold = true errorMsgHL.Underline = true errorMsgHL.Italic = true if err := v.SetHighlight(nsID, "ErrorMsg", errorMsgHL); err != nil { t.Fatal(err) } wantErrorMsgEHL := &HLAttrs{ Bold: true, Underline: true, Italic: true, Foreground: 16777215, Background: 16711680, Special: -1, } if !reflect.DeepEqual(wantErrorMsgEHL, errorMsgHL) { t.Fatalf("SetHighlight:\nwant %#v\n got %#v", wantErrorMsgEHL, errorMsgHL) } const cmd2 = `hi NewHighlight2 guifg=yellow guibg=red gui=bold` if err := v.Command(cmd2); err != nil { t.Fatal(err) } var nsID2 int if err := v.Eval(`hlID('NewHighlight2')`, &nsID2); err != nil { t.Fatal(err) } if err := v.SetHighlightNameSpace(nsID2); err != nil { t.Fatal(err) } want := &HLAttrs{ Bold: true, Underline: false, Undercurl: false, Italic: false, Reverse: false, Foreground: 16776960, Background: 16711680, Special: -1, } got, err := v.HLByID(nsID2, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, got) { t.Fatalf("SetHighlight:\nwant %#v\n got %#v", want, got) } const wantRedColor = 16711680 gotColor, err := v.ColorByName("red") if err != nil { t.Fatal(err) } if wantRedColor != gotColor { t.Fatalf("expected red color %d but got %d", wantRedColor, gotColor) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var cm map[string]int b.ColorMap(&cm) const cmd = `highlight NewHighlight cterm=underline ctermbg=green guifg=red guibg=yellow guisp=blue gui=bold` b.Command(cmd) if err := b.Execute(); err != nil { t.Fatal(err) } wantCTerm := &HLAttrs{ Underline: true, Foreground: -1, Background: 10, Special: -1, } wantGUI := &HLAttrs{ Bold: true, Foreground: cm[`Red`], Background: cm[`Yellow`], Special: cm[`Blue`], } var nsID int b.Eval("hlID('NewHighlight')", &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } const HLIDName = `Error` var wantErrorHLID = 64 if nvimVersion.Minor >= 7 { wantErrorHLID = 66 } var goHLID int b.HLIDByName(HLIDName, &goHLID) if err := b.Execute(); err != nil { t.Fatal(err) } if goHLID != wantErrorHLID { t.Fatalf("HLByID(%s)\n got %+v,\nwant %+v", HLIDName, goHLID, wantErrorHLID) } var gotCTermHL HLAttrs b.HLByID(nsID, false, &gotCTermHL) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotCTermHL, wantCTerm) { t.Fatalf("HLByID(id, false)\n got %+v,\nwant %+v", &gotCTermHL, wantCTerm) } var gotGUIHL HLAttrs b.HLByID(nsID, true, &gotGUIHL) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotGUIHL, wantGUI) { t.Fatalf("HLByID(id, true)\n got %+v,\nwant %+v", &gotGUIHL, wantGUI) } var errorMsgHL HLAttrs b.HLByName(`ErrorMsg`, true, &errorMsgHL) if err := b.Execute(); err != nil { t.Fatal(err) } errorMsgHL.Bold = true errorMsgHL.Underline = true errorMsgHL.Italic = true b.SetHighlight(nsID, `ErrorMsg`, &errorMsgHL) if err := b.Execute(); err != nil { t.Fatal(err) } wantErrorMsgEHL := &HLAttrs{ Bold: true, Underline: true, Italic: true, Foreground: 16777215, Background: 16711680, Special: -1, } if !reflect.DeepEqual(&errorMsgHL, wantErrorMsgEHL) { t.Fatalf("SetHighlight:\ngot %#v\nwant %#v", &errorMsgHL, wantErrorMsgEHL) } const cmd2 = `hi NewHighlight2 guifg=yellow guibg=red gui=bold` b.Command(cmd2) if err := b.Execute(); err != nil { t.Fatal(err) } var nsID2 int b.Eval("hlID('NewHighlight2')", &nsID2) b.SetHighlightNameSpace(nsID2) if err := b.Execute(); err != nil { t.Fatal(err) } want := &HLAttrs{ Bold: true, Underline: false, Undercurl: false, Italic: false, Reverse: false, Foreground: 16776960, Background: 16711680, Special: -1, } var got HLAttrs b.HLByID(nsID2, true, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&got, want) { t.Fatalf("SetHighlight:\n got %#v\nwant %#v", &got, want) } const wantRedColor = 16711680 var gotColor int b.ColorByName("red", &gotColor) if err := b.Execute(); err != nil { t.Fatal(err) } if wantRedColor != gotColor { t.Fatalf("expected red color %d but got %d", wantRedColor, gotColor) } }) } } func testVirtualText(v *Nvim) func(*testing.T) { return func(t *testing.T) { clearBuffer(t, v, Buffer(0)) // clear curret buffer text nsID, err := v.CreateNamespace("test_virtual_text") if err != nil { t.Fatal(err) } lines := []byte("ping") if err := v.SetBufferLines(Buffer(0), 0, -1, true, bytes.Fields(lines)); err != nil { t.Fatal(err) } chunks := []TextChunk{ { Text: "pong", HLGroup: "String", }, } nsID2, err := v.SetBufferVirtualText(Buffer(0), nsID, 0, chunks, make(map[string]interface{})) if err != nil { t.Fatal(err) } if got := nsID2; got != nsID { t.Fatalf("namespaceID: got %d, want %d", got, nsID) } if err := v.ClearBufferNamespace(Buffer(0), nsID, 0, -1); err != nil { t.Fatal(err) } } } func testFloatingWindow(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text curwin, err := v.CurrentWindow() if err != nil { t.Fatal(err) } wantWidth := 50 wantHeight := 20 cfg := &WindowConfig{ Relative: "cursor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Col: 0, Focusable: true, Style: "minimal", } w, err := v.OpenWindow(Buffer(0), true, cfg) if err != nil { t.Fatal(err) } if curwin == w { t.Fatal("same window number: floating window not focused") } if err := v.SetWindowWidth(w, wantWidth); err != nil { t.Fatal(err) } if err := v.SetWindowHeight(w, wantHeight); err != nil { t.Fatal(err) } gotWidth, err := v.WindowWidth(w) if err != nil { t.Fatal(err) } if gotWidth != wantWidth { t.Fatalf("got %d width but want %d", gotWidth, wantWidth) } gotHeight, err := v.WindowHeight(w) if err != nil { t.Fatal(err) } if gotHeight != wantHeight { t.Fatalf("got %d height but want %d", gotHeight, wantHeight) } wantWinConfig := &WindowConfig{ Relative: "editor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Focusable: false, } if err := v.SetWindowConfig(w, wantWinConfig); err != nil { t.Fatal(err) } gotWinConfig, err := v.WindowConfig(w) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotWinConfig, wantWinConfig) { t.Fatalf("want %#v but got %#v", wantWinConfig, gotWinConfig) } var ( numberOpt bool relativenumberOpt bool cursorlineOpt bool cursorcolumnOpt bool spellOpt bool listOpt bool signcolumnOpt string colorcolumnOpt string ) if err := v.WindowOption(w, "number", &numberOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "relativenumber", &relativenumberOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "cursorline", &cursorlineOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "cursorcolumn", &cursorcolumnOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "spell", &spellOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "list", &listOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "signcolumn", &signcolumnOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "colorcolumn", &colorcolumnOpt); err != nil { t.Fatal(err) } if numberOpt || relativenumberOpt || cursorlineOpt || cursorcolumnOpt || spellOpt || listOpt || signcolumnOpt != "auto" || colorcolumnOpt != "" { t.Fatal("expected minimal style") } if err := v.CloseWindow(w, true); err != nil { t.Fatal(err) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() var curwin Window b.CurrentWindow(&curwin) if err := b.Execute(); err != nil { t.Fatal(err) } wantWidth := 50 wantHeight := 20 cfg := &WindowConfig{ Relative: "cursor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Col: 0, Focusable: true, Style: "minimal", } var w Window b.OpenWindow(Buffer(0), true, cfg, &w) if err := b.Execute(); err != nil { t.Fatal(err) } if curwin == w { t.Fatal("same window number: floating window not focused") } b.SetWindowWidth(w, wantWidth) b.SetWindowHeight(w, wantHeight) if err := b.Execute(); err != nil { t.Fatal(err) } var gotWidth int b.WindowWidth(w, &gotWidth) var gotHeight int b.WindowHeight(w, &gotHeight) if err := b.Execute(); err != nil { t.Fatal(err) } if gotWidth != wantWidth { t.Fatalf("got %d width but want %d", gotWidth, wantWidth) } if gotHeight != wantHeight { t.Fatalf("got %d height but want %d", gotHeight, wantHeight) } wantWinConfig := &WindowConfig{ Relative: "editor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Focusable: false, } b.SetWindowConfig(w, wantWinConfig) if err := b.Execute(); err != nil { t.Fatal(err) } gotWinConfig := new(WindowConfig) b.WindowConfig(w, gotWinConfig) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotWinConfig, wantWinConfig) { t.Fatalf("want %#v but got %#v", wantWinConfig, gotWinConfig) } var ( numberOpt bool relativenumberOpt bool cursorlineOpt bool cursorcolumnOpt bool spellOpt bool listOpt bool signcolumnOpt string colorcolumnOpt string ) b.WindowOption(w, "number", &numberOpt) b.WindowOption(w, "relativenumber", &relativenumberOpt) b.WindowOption(w, "cursorline", &cursorlineOpt) b.WindowOption(w, "cursorcolumn", &cursorcolumnOpt) b.WindowOption(w, "spell", &spellOpt) b.WindowOption(w, "list", &listOpt) b.WindowOption(w, "signcolumn", &signcolumnOpt) b.WindowOption(w, "colorcolumn", &colorcolumnOpt) if err := b.Execute(); err != nil { t.Fatal(err) } if numberOpt || relativenumberOpt || cursorlineOpt || cursorcolumnOpt || spellOpt || listOpt || signcolumnOpt != "auto" || colorcolumnOpt != "" { t.Fatal("expected minimal style") } b.CloseWindow(w, true) if err := b.Execute(); err != nil { t.Fatal(err) } }) } } func testContext(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { ctxt, err := v.Context(make(map[string][]string)) if err != nil { t.Fatal(err) } var result interface{} if err := v.LoadContext(ctxt, &result); err != nil { t.Fatal(err) } if result != nil { t.Fatal("expected result to nil") } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var ctxt map[string]interface{} b.Context(make(map[string][]string), &ctxt) if err := b.Execute(); err != nil { t.Fatal(err) } var result interface{} b.LoadContext(ctxt, &result) if err := b.Execute(); err != nil { t.Fatal(err) } if result != nil { t.Fatal("expected result to nil") } }) } } func testExtmarks(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { // setup buffer lines lines := [][]byte{ []byte("hello"), []byte("world"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } // create namespace for test extmarks const extMarkName = "test_extmarks" nsID, err := v.CreateNamespace(extMarkName) if err != nil { t.Fatal(err) } const ( wantExtMarkID = 1 wantLine = 1 wantCol = 3 ) gotExtMarkID, err := v.SetBufferExtmark(Buffer(0), nsID, wantLine, wantCol, make(map[string]interface{})) if err != nil { t.Fatal(err) } if gotExtMarkID != wantExtMarkID { t.Fatalf("got %d extMarkID but want %d", gotExtMarkID, wantExtMarkID) } extmarks, err := v.BufferExtmarks(Buffer(0), nsID, 0, -1, make(map[string]interface{})) if err != nil { t.Fatal(err) } if len(extmarks) > 1 { t.Fatalf("expected extmarks length to 1 but got %d", len(extmarks)) } if extmarks[0].ID != gotExtMarkID { t.Fatalf("got %d extMarkID but want %d", extmarks[0].ID, wantExtMarkID) } if extmarks[0].Row != wantLine { t.Fatalf("got %d extmarks Row but want %d", extmarks[0].Row, wantLine) } if extmarks[0].Col != wantCol { t.Fatalf("got %d extmarks Col but want %d", extmarks[0].Col, wantCol) } pos, err := v.BufferExtmarkByID(Buffer(0), nsID, gotExtMarkID, make(map[string]interface{})) if err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } deleted, err := v.DeleteBufferExtmark(Buffer(0), nsID, gotExtMarkID) if err != nil { t.Fatal(err) } if !deleted { t.Fatalf("expected deleted but got %t", deleted) } if err := v.ClearBufferNamespace(Buffer(0), nsID, 0, -1); err != nil { t.Fatal(err) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) // clear curret buffer text }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() // setup buffer lines lines := [][]byte{ []byte("hello"), []byte("world"), } b.SetBufferLines(Buffer(0), 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // create namespace for test extmarks const extMarkName = "test_extmarks" var nsID int b.CreateNamespace(extMarkName, &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } const ( wantExtMarkID = 2 wantLine = 1 wantCol = 3 ) var gotExtMarkID int b.SetBufferExtmark(Buffer(0), nsID, wantLine, wantCol, make(map[string]interface{}), &gotExtMarkID) if err := b.Execute(); err != nil { t.Fatal(err) } if gotExtMarkID != wantExtMarkID { t.Fatalf("got %d extMarkID but want %d", gotExtMarkID, wantExtMarkID) } var extmarks []ExtMark b.BufferExtmarks(Buffer(0), nsID, 0, -1, make(map[string]interface{}), &extmarks) if err := b.Execute(); err != nil { t.Fatal(err) } if len(extmarks) > 1 { t.Fatalf("expected extmarks length to 1 but got %d", len(extmarks)) } if extmarks[0].ID != gotExtMarkID { t.Fatalf("got %d extMarkID but want %d", extmarks[0].ID, wantExtMarkID) } if extmarks[0].Row != wantLine { t.Fatalf("got %d extmarks Row but want %d", extmarks[0].Row, wantLine) } if extmarks[0].Col != wantCol { t.Fatalf("got %d extmarks Col but want %d", extmarks[0].Col, wantCol) } var pos []int b.BufferExtmarkByID(Buffer(0), nsID, gotExtMarkID, make(map[string]interface{}), &pos) if err := b.Execute(); err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } var deleted bool b.DeleteBufferExtmark(Buffer(0), nsID, gotExtMarkID, &deleted) if err := b.Execute(); err != nil { t.Fatal(err) } if !deleted { t.Fatalf("expected deleted but got %t", deleted) } b.ClearBufferNamespace(Buffer(0), nsID, 0, -1) if err := b.Execute(); err != nil { t.Fatal(err) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) // clear curret buffer text }) }) } } func testRuntime(v *Nvim) func(*testing.T) { return func(t *testing.T) { var runtimePath string if err := v.Eval("$VIMRUNTIME", &runtimePath); err != nil { t.Fatal(err) } viDiff := filepath.Join(runtimePath, "doc", "vi_diff.txt") vimDiff := filepath.Join(runtimePath, "doc", "vim_diff.txt") want := fmt.Sprintf("%s,%s", viDiff, vimDiff) binaryPath, err := exec.LookPath(BinaryName) if err != nil { t.Fatal(err) } nvimPrefix := filepath.Dir(filepath.Dir(binaryPath)) wantPaths := []string{ filepath.Join(nvimPrefix, "share", "nvim", "runtime"), filepath.Join(nvimPrefix, "lib", "nvim"), } switch runtime.GOOS { case "linux", "darwin": if nvimVersion.Minor <= 5 { oldRuntimePaths := []string{ filepath.Join("/etc", "xdg", "nvim"), filepath.Join("/etc", "xdg", "nvim", "after"), filepath.Join("/usr", "local", "share", "nvim", "site"), filepath.Join("/usr", "local", "share", "nvim", "site", "after"), filepath.Join("/usr", "share", "nvim", "site"), filepath.Join("/usr", "share", "nvim", "site", "after"), } wantPaths = append(wantPaths, oldRuntimePaths...) } case "windows": if nvimVersion.Minor <= 5 { localAppDataDir := os.Getenv("LocalAppData") oldRuntimePaths := []string{ filepath.Join(localAppDataDir, "nvim"), filepath.Join(localAppDataDir, "nvim", "after"), filepath.Join(localAppDataDir, "nvim-data", "site"), filepath.Join(localAppDataDir, "nvim-data", "site", "after"), } wantPaths = append(wantPaths, oldRuntimePaths...) } } sort.Strings(wantPaths) argName := filepath.Join("doc", "*_diff.txt") argAll := true t.Run("Nvim", func(t *testing.T) { t.Run("RuntimeFiles", func(t *testing.T) { files, err := v.RuntimeFiles(argName, argAll) if err != nil { t.Fatal(err) } sort.Strings(files) if len(files) != 2 { t.Fatalf("expected 2 length but got %d", len(files)) } if got := strings.Join(files, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimeFiles(%s, %t): got %s but want %s", argName, argAll, got, want) } }) t.Run("RuntimePaths", func(t *testing.T) { paths, err := v.RuntimePaths() if err != nil { t.Fatal(err) } sort.Strings(paths) if got, want := strings.Join(paths, ","), strings.Join(wantPaths, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimePaths():\n got %v\nwant %v", paths, wantPaths) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("RuntimeFiles", func(t *testing.T) { b := v.NewBatch() var files []string b.RuntimeFiles(argName, true, &files) if err := b.Execute(); err != nil { t.Fatal(err) } sort.Strings(files) if len(files) != 2 { t.Fatalf("expected 2 length but got %d", len(files)) } if got := strings.Join(files, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimeFiles(%s, %t): got %s but want %s", argName, argAll, got, want) } }) t.Run("RuntimePaths", func(t *testing.T) { b := v.NewBatch() var paths []string b.RuntimePaths(&paths) if err := b.Execute(); err != nil { t.Fatal(err) } sort.Strings(paths) if got, want := strings.Join(paths, ","), strings.Join(wantPaths, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimePaths():\n got %v\nwant %v", paths, wantPaths) } }) }) } } func testPutPaste(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Put", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) // clear curret buffer text replacement := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} if err := v.SetBufferText(Buffer(0), 0, 0, 0, 0, replacement); err != nil { t.Fatal(err) } const putText = "qux" putLines := []string{putText} if err := v.Put(putLines, "l", true, true); err != nil { t.Fatal(err) } want := append(replacement, []byte(putText)) lines, err := v.BufferLines(Buffer(0), 0, -1, true) if err != nil { t.Fatal(err) } wantLines := bytes.Join(want, []byte("\n")) gotLines := bytes.Join(lines, []byte("\n")) if !bytes.Equal(wantLines, gotLines) { t.Fatalf("expected %s but got %s", string(wantLines), string(gotLines)) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() replacement := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} b.SetBufferText(Buffer(0), 0, 0, 0, 0, replacement) if err := b.Execute(); err != nil { t.Fatal(err) } const putText = "qux" putLines := []string{putText} b.Put(putLines, "l", true, true) if err := b.Execute(); err != nil { t.Fatal(err) } want := append(replacement, []byte(putText)) var lines [][]byte b.BufferLines(Buffer(0), 0, -1, true, &lines) if err := b.Execute(); err != nil { t.Fatal(err) } wantLines := bytes.Join(want, []byte("\n")) gotLines := bytes.Join(lines, []byte("\n")) if !bytes.Equal(wantLines, gotLines) { t.Fatalf("expected %s but got %s", string(wantLines), string(gotLines)) } }) }) t.Run("Paste", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text state, err := v.Paste("!!", true, 1) // starts the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("foo", true, 2) // continues the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("bar", true, 2) // continues the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("baz", true, 3) // ends the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect not canceled") } lines, err := v.CurrentLine() if err != nil { t.Fatal(err) } const want = "!foobarbaz!" if want != string(lines) { t.Fatalf("got %s current lines but want %s", string(lines), want) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() var state, state2, state3, state4 bool b.Paste("!!", true, 1, &state) // starts the paste b.Paste("foo", true, 2, &state2) // starts the paste b.Paste("bar", true, 2, &state3) // starts the paste b.Paste("baz", true, 3, &state4) // ends the paste if err := b.Execute(); err != nil { t.Fatal(err) } if !state || !state2 || !state3 || !state4 { t.Fatal("expect continue to pasting") } var lines []byte b.CurrentLine(&lines) if err := b.Execute(); err != nil { t.Fatal(err) } const want = "!foobarbaz!" if want != string(lines) { t.Fatalf("got %s current lines but want %s", string(lines), want) } }) }) } } func testNamespace(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Namespace", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { const nsName = "test-nvim" nsID, err := v.CreateNamespace(nsName) if err != nil { t.Fatal(err) } nsIDs, err := v.Namespaces() if err != nil { t.Fatal(err) } gotID, ok := nsIDs[nsName] if !ok { t.Fatalf("not fount %s namespace ID", nsName) } if gotID != nsID { t.Fatalf("nsID mismatched: got: %d want: %d", gotID, nsID) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() const nsName = "test-batch" var nsID int b.CreateNamespace(nsName, &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } var nsIDs map[string]int b.Namespaces(&nsIDs) if err := b.Execute(); err != nil { t.Fatal(err) } gotID, ok := nsIDs[nsName] if !ok { t.Fatalf("not fount %s namespace ID", nsName) } if gotID != nsID { t.Fatalf("nsID mismatched: got: %d want: %d", gotID, nsID) } }) }) } } func testOptions(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Option", func(t *testing.T) { tests := map[string]struct { name string want interface{} }{ "background": { name: "background", want: "dark", }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { var got interface{} if err := v.Option(tt.name, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { b := v.NewBatch() var got interface{} b.Option(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } }) t.Run("SetOption", func(t *testing.T) { tests := map[string]struct { name string value interface{} want interface{} }{ "background": { name: "background", want: "light", }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if err := v.SetOption(tt.name, tt.want); err != nil { t.Fatal(err) } var got interface{} if err := v.Option(tt.name, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { b := v.NewBatch() b.SetOption(tt.name, tt.want) if err := b.Execute(); err != nil { t.Fatal(err) } var got interface{} b.Option(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } }) t.Run("OptionInfo", func(t *testing.T) { tests := map[string]struct { name string want *OptionInfo }{ "filetype": { name: "filetype", want: &OptionInfo{ Name: "filetype", ShortName: "ft", Type: "string", Default: "", WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "buf", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "cmdheight": { name: "cmdheight", want: &OptionInfo{ Name: "cmdheight", ShortName: "ch", Type: "number", Default: int64(1), WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "hidden": { name: "hidden", want: &OptionInfo{ Name: "hidden", ShortName: "hid", Type: "boolean", Default: true, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } got, err := v.OptionInfo(tt.name) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } b := v.NewBatch() var got OptionInfo b.OptionInfo(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, &got) { t.Fatalf("got %#v but want %#v", &got, tt.want) } }) } }) } } func testAllOptionsInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { want := &OptionInfo{ Name: "", ShortName: "", Type: "", Default: nil, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "", GlobalLocal: false, CommaList: false, FlagList: false, } got, err := v.AllOptionsInfo() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, got) { t.Fatalf("got %v but want %v", got, want) } b := v.NewBatch() var got2 OptionInfo b.AllOptionsInfo(&got2) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, &got2) { t.Fatalf("got %v but want %v", got2, want) } } } func testOptionsInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { tests := map[string]struct { name string want *OptionInfo }{ "filetype": { name: "filetype", want: &OptionInfo{ Name: "filetype", ShortName: "ft", Type: "string", Default: "", WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "buf", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "cmdheight": { name: "cmdheight", want: &OptionInfo{ Name: "cmdheight", ShortName: "ch", Type: "number", Default: int64(1), WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "hidden": { name: "hidden", want: &OptionInfo{ Name: "hidden", ShortName: "hid", Type: "boolean", Default: true, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } got, err := v.OptionInfo(tt.name) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } b := v.NewBatch() var got OptionInfo b.OptionInfo(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, &got) { t.Fatalf("got %#v but want %#v", &got, tt.want) } }) } } } // TODO(zchee): correct testcase func testTerm(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } cfg := &WindowConfig{ Relative: "editor", Width: 79, Height: 31, Row: 1, Col: 1, } if _, err := v.OpenWindow(buf, false, cfg); err != nil { t.Fatal(err) } termID, err := v.OpenTerm(buf, make(map[string]interface{})) if err != nil { t.Fatal(err) } data := "\x1b[38;2;00;00;255mTRUECOLOR\x1b[0m" if err := v.Call("chansend", nil, termID, data); err != nil { t.Fatal(err) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } cfg := &WindowConfig{ Relative: "editor", Width: 79, Height: 31, Row: 1, Col: 1, } var win Window b.OpenWindow(buf, false, cfg, &win) var termID int b.OpenTerm(buf, make(map[string]interface{}), &termID) if err := b.Execute(); err != nil { t.Fatal(err) } data := "\x1b[38;2;00;00;255mTRUECOLOR\x1b[0m" b.Call("chansend", nil, termID, data) if err := b.Execute(); err != nil { t.Fatal(err) } }) } } func testChannelClientInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { const clientNamePrefix = "testClient" var ( clientVersion = ClientVersion{ Major: 1, Minor: 2, Patch: 3, Prerelease: "-dev", Commit: "e07b9dde387bc817d36176bbe1ce58acd3c81921", } clientType = RemoteClientType clientMethods = map[string]*ClientMethod{ "foo": { Async: true, NArgs: ClientMethodNArgs{ Min: 0, Max: 1, }, }, "bar": { Async: false, NArgs: ClientMethodNArgs{ Min: 0, Max: 0, }, }, } clientAttributes = ClientAttributes{ ClientAttributeKeyLicense: "Apache-2.0", } ) t.Run("Nvim", func(t *testing.T) { clientName := clientNamePrefix + "Nvim" t.Run("SetClientInfo", func(t *testing.T) { if err := v.SetClientInfo(clientName, clientVersion, clientType, clientMethods, clientAttributes); err != nil { t.Fatal(err) } }) t.Run("ChannelInfo", func(t *testing.T) { wantClient := &Client{ Name: clientName, Version: clientVersion, Type: clientType, Methods: clientMethods, Attributes: clientAttributes, } wantChannel := &Channel{ Stream: "stdio", Mode: "rpc", Client: wantClient, } gotChannel, err := v.ChannelInfo(int(channelID)) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotChannel, wantChannel) { t.Fatalf("got %#v channel but want %#v channel", gotChannel, wantChannel) } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() clientName := clientNamePrefix + "Batch" t.Run("SetClientInfo", func(t *testing.T) { b.SetClientInfo(clientName, clientVersion, clientType, clientMethods, clientAttributes) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("ChannelInfo", func(t *testing.T) { wantClient := &Client{ Name: clientName, Version: clientVersion, Type: clientType, Methods: clientMethods, Attributes: clientAttributes, } wantChannel := &Channel{ Stream: "stdio", Mode: "rpc", Client: wantClient, } var gotChannel Channel b.ChannelInfo(int(channelID), &gotChannel) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotChannel, wantChannel) { t.Fatalf("got %#v channel but want %#v channel", &gotChannel, wantChannel) } }) }) } } func testUI(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("UIs", func(t *testing.T) { gotUIs, err := v.UIs() if err != nil { t.Fatal(err) } if len(gotUIs) > 0 || gotUIs != nil { t.Fatalf("expected ui empty but non-zero: %#v", gotUIs) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("UIs", func(t *testing.T) { b := v.NewBatch() var gotUIs []*UI b.UIs(&gotUIs) if err := b.Execute(); err != nil { t.Fatal(err) } if len(gotUIs) > 0 || gotUIs != nil { t.Fatalf("expected ui empty but non-zero: %#v", gotUIs) } }) }) } } func testProc(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("Proc", func(t *testing.T) { pid := os.Getpid() ppid := os.Getppid() wantProcess := &Process{ Name: "nvim.test", PID: pid, PPID: ppid, } if runtime.GOOS == "windows" { wantProcess.Name = "nvim.test.exe" } gotProc, err := v.Proc(pid) if err != nil { t.Fatal(err) } if gotProc.Name != wantProcess.Name { t.Fatalf("got %s Process.Name but want %s", gotProc.Name, wantProcess.Name) } if gotProc.PID != wantProcess.PID { t.Fatalf("got %d Process.PID but want %d", gotProc.PID, wantProcess.PID) } if gotProc.PPID != wantProcess.PPID { t.Fatalf("got %d Process.PPID but want %d", gotProc.PPID, wantProcess.PPID) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Proc", func(t *testing.T) { b := v.NewBatch() pid := os.Getpid() ppid := os.Getppid() wantProcess := &Process{ Name: "nvim.test", PID: pid, PPID: ppid, } if runtime.GOOS == "windows" { wantProcess.Name = "nvim.test.exe" } var gotProc Process b.Proc(pid, &gotProc) if err := b.Execute(); err != nil { t.Fatal(err) } if gotProc.Name != wantProcess.Name { t.Fatalf("got %s Process.Name but want %s", gotProc.Name, wantProcess.Name) } if gotProc.PID != wantProcess.PID { t.Fatalf("got %d Process.PID but want %d", gotProc.PID, wantProcess.PID) } if gotProc.PPID != wantProcess.PPID { t.Fatalf("got %d Process.PPID but want %d", gotProc.PPID, wantProcess.PPID) } }) }) } } nvim: add AddBufferHighlight testcase Signed-off-by: Koichi Shiraishi <2e5bdfebde234ed3509bcfc18121c70b6631e207@gmail.com> package nvim import ( "bytes" "errors" "fmt" "log" "os" "os/exec" "path/filepath" "reflect" "runtime" "sort" "strconv" "strings" "sync/atomic" "testing" ) type version struct { Major int Minor int Patch int } var ( channelID int64 nvimVersion version ) func parseVersion(tb testing.TB, version string) (major, minor, patch int) { tb.Helper() version = strings.TrimPrefix(version, "v") vpair := strings.Split(version, ".") if len(vpair) != 3 { tb.Fatal("could not parse neovim version") } var err error major, err = strconv.Atoi(vpair[0]) if err != nil { tb.Fatal(err) } minor, err = strconv.Atoi(vpair[1]) if err != nil { tb.Fatal(err) } patch, err = strconv.Atoi(vpair[2]) if err != nil { tb.Fatal(err) } return major, minor, patch } func skipVersion(tb testing.TB, version string) { major, minor, patch := parseVersion(tb, version) const skipFmt = "SKIP: current neovim version v%d.%d.%d but expected version %s" if nvimVersion.Major < major || nvimVersion.Minor < minor || nvimVersion.Patch < patch { tb.Skipf(skipFmt, nvimVersion.Major, nvimVersion.Minor, nvimVersion.Patch, version) } } // clearBuffer clears the buffer lines. func clearBuffer(tb testing.TB, v *Nvim, buffer Buffer) { tb.Helper() if err := v.SetBufferLines(buffer, 0, -1, true, bytes.Fields(nil)); err != nil { tb.Fatal(err) } } func TestAPI(t *testing.T) { t.Parallel() v, cleanup := newChildProcess(t) t.Cleanup(func() { cleanup() }) apiInfo, err := v.APIInfo() if err != nil { t.Fatal(err) } if len(apiInfo) != 2 { t.Fatalf("unknown APIInfo: %#v", apiInfo) } var ok bool channelID, ok = apiInfo[0].(int64) if !ok { t.Fatalf("apiInfo[0] is not int64 type: %T", apiInfo[0]) } info, ok := apiInfo[1].(map[string]interface{}) if !ok { t.Fatalf("apiInfo[1] is not map[string]interface{} type: %T", apiInfo[1]) } infoV := info["version"].(map[string]interface{}) nvimVersion.Major = int(infoV["major"].(int64)) nvimVersion.Minor = int(infoV["minor"].(int64)) nvimVersion.Patch = int(infoV["patch"].(int64)) t.Run("BufAttach", testBufAttach(v)) t.Run("APIInfo", testAPIInfo(v)) t.Run("SimpleHandler", testSimpleHandler(v)) t.Run("Buffer", testBuffer(v)) t.Run("Window", testWindow(v)) t.Run("Tabpage", testTabpage(v)) t.Run("Lines", testLines(v)) t.Run("Commands", testCommands(v)) t.Run("Var", testVar(v)) t.Run("Message", testMessage(v)) t.Run("Key", testKey(v)) t.Run("Eval", testEval(v)) t.Run("Batch", testBatch(v)) t.Run("Mode", testMode(v)) t.Run("ExecLua", testExecLua(v)) t.Run("Highlight", testHighlight(v)) t.Run("VirtualText", testVirtualText(v)) t.Run("FloatingWindow", testFloatingWindow(v)) t.Run("Context", testContext(v)) t.Run("Extmarks", testExtmarks(v)) t.Run("Runtime", testRuntime(v)) t.Run("Namespace", testNamespace(v)) t.Run("PutPaste", testPutPaste(v)) t.Run("Options", testOptions(v)) t.Run("AllOptionsInfo", testAllOptionsInfo(v)) t.Run("OptionsInfo", testOptionsInfo(v)) t.Run("OpenTerm", testTerm(v)) t.Run("ChannelClientInfo", testChannelClientInfo(v)) t.Run("UI", testUI(v)) t.Run("Proc", testProc(v)) } func testBufAttach(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text changedtickChan := make(chan *ChangedtickEvent) v.RegisterHandler(EventBufChangedtick, func(changedtickEvent ...interface{}) { ev := &ChangedtickEvent{ Buffer: changedtickEvent[0].(Buffer), Changetick: changedtickEvent[1].(int64), } changedtickChan <- ev }) bufLinesChan := make(chan *BufLinesEvent) v.RegisterHandler(EventBufLines, func(bufLinesEvent ...interface{}) { ev := &BufLinesEvent{ Buffer: bufLinesEvent[0].(Buffer), Changetick: bufLinesEvent[1].(int64), FirstLine: bufLinesEvent[2].(int64), LastLine: bufLinesEvent[3].(int64), IsMultipart: bufLinesEvent[5].(bool), } for _, line := range bufLinesEvent[4].([]interface{}) { ev.LineData = append(ev.LineData, line.(string)) } bufLinesChan <- ev }) bufDetachChan := make(chan *BufDetachEvent) v.RegisterHandler(EventBufDetach, func(bufDetachEvent ...interface{}) { ev := &BufDetachEvent{ Buffer: bufDetachEvent[0].(Buffer), } bufDetachChan <- ev }) ok, err := v.AttachBuffer(0, false, make(map[string]interface{})) // first 0 arg refers to the current buffer if err != nil { t.Fatal(err) } if !ok { t.Fatal(errors.New("could not attach buffer")) } changedtickExpected := &ChangedtickEvent{ Buffer: Buffer(1), Changetick: 3, } bufLinesEventExpected := &BufLinesEvent{ Buffer: Buffer(1), Changetick: 4, FirstLine: 0, LastLine: 1, LineData: []string{"foo", "bar", "baz", "qux", "quux", "quuz"}, IsMultipart: false, } bufDetachEventExpected := &BufDetachEvent{ Buffer: Buffer(1), } var numEvent int64 // add and load should be atomically errc := make(chan error) done := make(chan struct{}) go func() { for { select { default: if atomic.LoadInt64(&numEvent) == 3 { // end buf_attach test when handle 2 event done <- struct{}{} return } case changedtick := <-changedtickChan: if !reflect.DeepEqual(changedtick, changedtickExpected) { errc <- fmt.Errorf("changedtick = %+v, want %+v", changedtick, changedtickExpected) } atomic.AddInt64(&numEvent, 1) case bufLines := <-bufLinesChan: if expected := bufLinesEventExpected; !reflect.DeepEqual(bufLines, expected) { errc <- fmt.Errorf("bufLines = %+v, want %+v", bufLines, expected) } atomic.AddInt64(&numEvent, 1) case detach := <-bufDetachChan: if expected := bufDetachEventExpected; !reflect.DeepEqual(detach, expected) { errc <- fmt.Errorf("bufDetach = %+v, want %+v", detach, expected) } atomic.AddInt64(&numEvent, 1) } } }() go func() { <-done close(errc) }() test := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz"), []byte("qux"), []byte("quux"), []byte("quuz")} if err := v.SetBufferLines(Buffer(0), 0, -1, true, test); err != nil { // first 0 arg refers to the current buffer t.Fatal(err) } if detached, err := v.DetachBuffer(Buffer(0)); err != nil || !detached { t.Fatal(err) } for err := range errc { if err != nil { t.Fatal(err) } } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text changedtickChan := make(chan *ChangedtickEvent) v.RegisterHandler(EventBufChangedtick, func(changedtickEvent ...interface{}) { ev := &ChangedtickEvent{ Buffer: changedtickEvent[0].(Buffer), Changetick: changedtickEvent[1].(int64), } changedtickChan <- ev }) bufLinesChan := make(chan *BufLinesEvent) v.RegisterHandler(EventBufLines, func(bufLinesEvent ...interface{}) { ev := &BufLinesEvent{ Buffer: bufLinesEvent[0].(Buffer), Changetick: bufLinesEvent[1].(int64), FirstLine: bufLinesEvent[2].(int64), LastLine: bufLinesEvent[3].(int64), IsMultipart: bufLinesEvent[5].(bool), } for _, line := range bufLinesEvent[4].([]interface{}) { ev.LineData = append(ev.LineData, line.(string)) } bufLinesChan <- ev }) bufDetachChan := make(chan *BufDetachEvent) v.RegisterHandler(EventBufDetach, func(bufDetachEvent ...interface{}) { ev := &BufDetachEvent{ Buffer: bufDetachEvent[0].(Buffer), } bufDetachChan <- ev }) b := v.NewBatch() var attached bool b.AttachBuffer(0, false, make(map[string]interface{}), &attached) // first 0 arg refers to the current buffer if err := b.Execute(); err != nil { t.Fatal(err) } if !attached { t.Fatal(errors.New("could not attach buffer")) } changedtickExpected := &ChangedtickEvent{ Buffer: Buffer(1), Changetick: 5, } bufLinesEventExpected := &BufLinesEvent{ Buffer: Buffer(1), Changetick: 6, FirstLine: 0, LastLine: 1, LineData: []string{"foo", "bar", "baz", "qux", "quux", "quuz"}, IsMultipart: false, } bufDetachEventExpected := &BufDetachEvent{ Buffer: Buffer(1), } var numEvent int64 // add and load should be atomically errc := make(chan error) done := make(chan struct{}) go func() { for { select { default: if atomic.LoadInt64(&numEvent) == 3 { // end buf_attach test when handle 2 event done <- struct{}{} return } case changedtick := <-changedtickChan: if !reflect.DeepEqual(changedtick, changedtickExpected) { errc <- fmt.Errorf("changedtick = %+v, want %+v", changedtick, changedtickExpected) } atomic.AddInt64(&numEvent, 1) case bufLines := <-bufLinesChan: if expected := bufLinesEventExpected; !reflect.DeepEqual(bufLines, expected) { errc <- fmt.Errorf("bufLines = %+v, want %+v", bufLines, expected) } atomic.AddInt64(&numEvent, 1) case detach := <-bufDetachChan: if expected := bufDetachEventExpected; !reflect.DeepEqual(detach, expected) { errc <- fmt.Errorf("bufDetach = %+v, want %+v", detach, expected) } atomic.AddInt64(&numEvent, 1) } } }() go func() { <-done close(errc) }() test := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz"), []byte("qux"), []byte("quux"), []byte("quuz")} if err := v.SetBufferLines(Buffer(0), 0, -1, true, test); err != nil { // first 0 arg refers to the current buffer t.Fatal(err) } var detached bool b.DetachBuffer(Buffer(0), &detached) if err := b.Execute(); err != nil { t.Fatal(err) } for err := range errc { if err != nil { t.Fatal(err) } } }) } } func testAPIInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { apiinfo, err := v.APIInfo() if err != nil { t.Fatal(err) } if len(apiinfo) == 0 { t.Fatal("expected apiinfo is non-nil") } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var apiinfo []interface{} b.APIInfo(&apiinfo) if err := b.Execute(); err != nil { t.Fatal(err) } if len(apiinfo) == 0 { t.Fatal("expected apiinfo is non-nil") } }) } } func testSimpleHandler(v *Nvim) func(*testing.T) { return func(t *testing.T) { cid := v.ChannelID() if cid <= 0 { t.Fatal("could not get channel id") } helloHandler := func(s string) (string, error) { return "Hello, " + s, nil } errorHandler := func() error { return errors.New("ouch") } if err := v.RegisterHandler("hello", helloHandler); err != nil { t.Fatal(err) } if err := v.RegisterHandler("error", errorHandler); err != nil { t.Fatal(err) } var result string if err := v.Call("rpcrequest", &result, cid, "hello", "world"); err != nil { t.Fatal(err) } if expected := "Hello, world"; result != expected { t.Fatalf("hello returned %q, want %q", result, expected) } // Test errors. if err := v.Call("execute", &result, fmt.Sprintf("silent! call rpcrequest(%d, 'error')", cid)); err != nil { t.Fatal(err) } if expected := "\nError invoking 'error' on channel 1:\nouch"; result != expected { t.Fatalf("got error %q, want %q", result, expected) } } } func testBuffer(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("BufferName", func(t *testing.T) { cwd, _ := os.Getwd() // buffer name is full path wantBufName := filepath.Join(cwd, "/test_buffer") if err := v.SetBufferName(Buffer(0), wantBufName); err != nil { t.Fatal(err) } bufName, err := v.BufferName(Buffer(0)) if err != nil { t.Fatal(err) } if bufName != wantBufName { t.Fatalf("want %s buffer name but got %s", wantBufName, bufName) } t.Cleanup(func() { // cleanup cindent option if err := v.SetBufferName(Buffer(0), ""); err != nil { t.Fatal(err) } }) }) t.Run("Buffers", func(t *testing.T) { bufs, err := v.Buffers() if err != nil { t.Fatal(err) } if len(bufs) != 2 { t.Fatalf("expected one buf, found %d bufs", len(bufs)) } if bufs[0] == 0 { t.Fatalf("bufs[0] is not %q: %q", bufs[0], Buffer(0)) } buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } if buf != bufs[0] { t.Fatalf("buf is not bufs[0]: buf %v, bufs[0]: %v", buf, bufs[0]) } const want = "Buffer:1" if got := buf.String(); got != want { t.Fatalf("buf.String() = %s, want %s", got, want) } if err := v.SetCurrentBuffer(buf); err != nil { t.Fatal(err) } }) t.Run("Var", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } const ( varkey = "bvar" varVal = "bval" ) if err := v.SetBufferVar(buf, varkey, varVal); err != nil { t.Fatal(err) } var s string if err := v.BufferVar(buf, varkey, &s); err != nil { t.Fatal(err) } if s != "bval" { t.Fatalf("expected %s=%s, got %s", s, varkey, varVal) } if err := v.DeleteBufferVar(buf, varkey); err != nil { t.Fatal(err) } s = "" // reuse if err := v.BufferVar(buf, varkey, &s); err == nil { t.Fatalf("expected %s not found but error is nil: err: %#v", varkey, err) } }) t.Run("Delete", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) t.Run("ChangeTick", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } // 1 changedtick lines := [][]byte{[]byte("hello"), []byte("world")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } // 2 changedtick const wantChangedTick = 2 changedTick, err := v.BufferChangedTick(buf) if err != nil { t.Fatal(err) } if changedTick != wantChangedTick { t.Fatalf("got %d changedTick but want %d", changedTick, wantChangedTick) } // cleanup buffer deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) t.Run("SetCurrentDirectory", func(t *testing.T) { wantDir, err := os.UserHomeDir() if err != nil { t.Fatal(err) } if err := v.SetCurrentDirectory(wantDir); err != nil { t.Fatal(err) } var got string if err := v.Eval(`getcwd()`, &got); err != nil { t.Fatal(err) } if got != wantDir { t.Fatalf("SetCurrentDirectory(%s) = %s, want: %s", wantDir, got, wantDir) } }) t.Run("BufferCommands", func(t *testing.T) { commands, err := v.BufferCommands(Buffer(0), make(map[string]interface{})) if err != nil { t.Fatal(err) } if len(commands) > 0 { t.Fatalf("expected commands empty but non-zero: %#v", commands) } }) t.Run("BufferOption", func(t *testing.T) { var cindent bool if err := v.BufferOption(Buffer(0), "cindent", &cindent); err != nil { t.Fatal(err) } if cindent { t.Fatalf("expected cindent is false but got %t", cindent) } if err := v.SetBufferOption(Buffer(0), "cindent", true); err != nil { t.Fatal(err) } if err := v.BufferOption(Buffer(0), "cindent", &cindent); err != nil { t.Fatal(err) } if !cindent { t.Fatalf("expected cindent is true but got %t", cindent) } t.Cleanup(func() { // cleanup cindent option if err := v.SetBufferOption(Buffer(0), "cindent", false); err != nil { t.Fatal(err) } }) }) t.Run("IsBufferLoaded", func(t *testing.T) { loaded, err := v.IsBufferLoaded(Buffer(0)) if err != nil { t.Fatal(err) } if !loaded { t.Fatalf("expected buffer is loaded but got %t", loaded) } }) t.Run("IsBufferValid", func(t *testing.T) { valid, err := v.IsBufferValid(Buffer(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected buffer is valid but got %t", valid) } }) t.Run("BufferMark", func(t *testing.T) { lines := [][]byte{ []byte("a"), []byte("bit of"), []byte("text"), } if err := v.SetBufferLines(Buffer(0), -1, -1, true, lines); err != nil { t.Fatal(err) } if err := v.SetWindowCursor(Window(0), [2]int{3, 4}); err != nil { t.Fatal(err) } if err := v.Command("mark v"); err != nil { t.Fatal(err) } const ( wantLine = 3 wantCol = 0 ) pos, err := v.BufferMark(Buffer(0), "v") if err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) }) }) }) t.Run("Batch", func(t *testing.T) { t.Run("BufferName", func(t *testing.T) { b := v.NewBatch() cwd, _ := os.Getwd() // buffer name is full path wantBufName := filepath.Join(cwd, "/test_buffer") b.SetBufferName(Buffer(0), wantBufName) if err := b.Execute(); err != nil { t.Fatal(err) } var bufName string b.BufferName(Buffer(0), &bufName) if err := b.Execute(); err != nil { t.Fatal(err) } if bufName != wantBufName { t.Fatalf("want %s buffer name but got %s", wantBufName, bufName) } t.Cleanup(func() { // cleanup cindent option b.SetBufferName(Buffer(0), "") if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("Buffers", func(t *testing.T) { b := v.NewBatch() var bufs []Buffer b.Buffers(&bufs) if err := b.Execute(); err != nil { t.Fatal(err) } if len(bufs) != 2 { t.Fatalf("expected one buf, found %d bufs", len(bufs)) } if bufs[0] == Buffer(0) { t.Fatalf("bufs[0] is not %q: %q", bufs[0], Buffer(0)) } var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } if buf != bufs[0] { t.Fatalf("buf is not bufs[0]: buf %v, bufs[0]: %v", buf, bufs[0]) } const want = "Buffer:1" if got := buf.String(); got != want { t.Fatalf("buf.String() = %s, want %s", got, want) } b.SetCurrentBuffer(buf) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("Var", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } const ( varkey = "bvar" varVal = "bval" ) b.SetBufferVar(buf, varkey, varVal) var s string b.BufferVar(buf, varkey, &s) if err := b.Execute(); err != nil { t.Fatal(err) } if s != varVal { t.Fatalf("expected bvar=bval, got %s", s) } b.DeleteBufferVar(buf, varkey) if err := b.Execute(); err != nil { t.Fatal(err) } s = "" // reuse b.BufferVar(buf, varkey, &s) if err := b.Execute(); err == nil { t.Fatalf("expected %s not found but error is nil: err: %#v", varkey, err) } }) t.Run("Delete", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("ChangeTick", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } // 1 changedtick lines := [][]byte{[]byte("hello"), []byte("world")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // 2 changedtick const wantChangedTick = 2 var changedTick int b.BufferChangedTick(buf, &changedTick) if err := b.Execute(); err != nil { t.Fatal(err) } if changedTick != wantChangedTick { t.Fatalf("got %d changedTick but want %d", changedTick, wantChangedTick) } // cleanup buffer deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("SetCurrentDirectory", func(t *testing.T) { wantDir, err := os.UserHomeDir() if err != nil { t.Fatal(err) } b := v.NewBatch() b.SetCurrentDirectory(wantDir) if err := b.Execute(); err != nil { t.Fatal(err) } var got string if err := v.Eval(`getcwd()`, &got); err != nil { t.Fatal(err) } if got != wantDir { t.Fatalf("SetCurrentDirectory(%s) = %s, want: %s", wantDir, got, wantDir) } }) t.Run("BufferCommands", func(t *testing.T) { b := v.NewBatch() var commands map[string]*Command b.BufferCommands(Buffer(0), make(map[string]interface{}), &commands) if err := b.Execute(); err != nil { t.Fatal(err) } if len(commands) > 0 { t.Fatalf("expected commands empty but non-zero: %#v", commands) } }) t.Run("BufferOption", func(t *testing.T) { b := v.NewBatch() var cindent bool b.BufferOption(Buffer(0), "cindent", &cindent) if err := b.Execute(); err != nil { t.Fatal(err) } if cindent { t.Fatalf("expected cindent is false but got %t", cindent) } b.SetBufferOption(Buffer(0), "cindent", true) if err := b.Execute(); err != nil { t.Fatal(err) } b.BufferOption(Buffer(0), "cindent", &cindent) if err := b.Execute(); err != nil { t.Fatal(err) } if !cindent { t.Fatalf("expected cindent is true but got %t", cindent) } t.Cleanup(func() { // cleanup cindent option b.SetBufferOption(Buffer(0), "cindent", false) if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("IsBufferLoaded", func(t *testing.T) { b := v.NewBatch() var loaded bool b.IsBufferLoaded(Buffer(0), &loaded) if err := b.Execute(); err != nil { t.Fatal(err) } if !loaded { t.Fatalf("expected buffer is loaded but got %t", loaded) } }) t.Run("IsBufferValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsBufferValid(Buffer(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected buffer is valid but got %t", valid) } }) t.Run("BufferMark", func(t *testing.T) { b := v.NewBatch() lines := [][]byte{ []byte("a"), []byte("bit of"), []byte("text"), } b.SetBufferLines(Buffer(0), -1, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetWindowCursor(Window(0), [2]int{3, 4}) b.Command("mark v") if err := b.Execute(); err != nil { t.Fatal(err) } const ( wantLine = 3 wantCol = 0 ) var pos [2]int b.BufferMark(Buffer(0), "v", &pos) if err := b.Execute(); err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) }) }) }) } } func testWindow(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { wins, err := v.Windows() if err != nil { t.Fatal(err) } if len(wins) != 1 { for i := 0; i < len(wins); i++ { t.Logf("wins[%d]: %v", i, wins[i]) } t.Fatalf("expected one win, found %d wins", len(wins)) } if wins[0] == 0 { t.Fatalf("wins[0] == 0") } win, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if win != wins[0] { t.Fatalf("win is not wins[0]: win: %v wins[0]: %v", win, wins[0]) } const want = "Window:1000" if got := win.String(); got != want { t.Fatalf("got %s but want %s", got, want) } win, err = v.CurrentWindow() if err != nil { t.Fatal(err) } if err := v.Command("split"); err != nil { t.Fatal(err) } win2, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if err := v.SetCurrentWindow(win); err != nil { t.Fatal(err) } gotwin, err := v.CurrentWindow() if err != nil { t.Fatal(err) } if gotwin != win { t.Fatalf("expected current window %s but got %s", win, gotwin) } if err := v.HideWindow(win2); err != nil { t.Fatalf("failed to HideWindow(%v)", win2) } wins2, err := v.Windows() if err != nil { t.Fatal(err) } if len(wins2) != 1 { for i := 0; i < len(wins2); i++ { t.Logf("wins[%d]: %v", i, wins2[i]) } t.Fatalf("expected one win, found %d wins", len(wins2)) } if wins2[0] == 0 { t.Fatalf("wins[0] == 0") } if win != wins2[0] { t.Fatalf("win2 is not wins2[0]: want: %v, win2: %v ", wins2[0], win) } t.Run("WindowBuffer", func(t *testing.T) { skipVersion(t, "v0.6.0") gotBuf, err := v.WindowBuffer(Window(0)) if err != nil { t.Fatal(err) } wantBuffer := Buffer(1) if gotBuf != wantBuffer { t.Fatalf("want %s buffer but got %s", wantBuffer, gotBuf) } buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } if err := v.SetBufferToWindow(Window(0), buf); err != nil { t.Fatal(err) } gotBuf2, err := v.WindowBuffer(Window(0)) if err != nil { t.Fatal(err) } if gotBuf2 != buf { t.Fatalf("want %s buffer but got %s", buf, gotBuf2) } t.Cleanup(func() { if err := v.SetBufferToWindow(Window(0), gotBuf); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } if err := v.DeleteBuffer(buf, deleteBufferOpts); err != nil { t.Fatal(err) } }) }) t.Run("WindowCursor", func(t *testing.T) { wantLine := []byte("hello world") if err := v.SetCurrentLine(wantLine); err != nil { t.Fatal(err) } t.Cleanup(func() { if err := v.DeleteCurrentLine(); err != nil { t.Fatal(err) } }) wantPos := [2]int{1, 5} if err := v.SetWindowCursor(Window(0), wantPos); err != nil { t.Fatal(err) } gotPos, err := v.WindowCursor(Window(0)) if err != nil { t.Fatal(err) } if wantPos != gotPos { t.Fatalf("want %#v position buf got %#v", wantPos, gotPos) } }) t.Run("WindowVar", func(t *testing.T) { wantValue := []int{1, 2} if err := v.SetWindowVar(Window(0), "lua", wantValue); err != nil { t.Fatal(err) } var gotValue []int if err := v.WindowVar(Window(0), "lua", &gotValue); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } if err := v.DeleteWindowVar(Window(0), "lua"); err != nil { t.Fatal(err) } if err := v.WindowVar(Window(0), "lua", nil); err == nil { t.Fatalf("expect Key not found but fonud key") } }) t.Run("WindowOption", func(t *testing.T) { wantValue := "+1" if err := v.SetWindowOption(Window(0), "colorcolumn", &wantValue); err != nil { t.Fatal(err) } var gotValue string if err := v.WindowOption(Window(0), "colorcolumn", &gotValue); err != nil { t.Fatal(err) } if gotValue != wantValue { t.Fatalf("expected %s but got %s", wantValue, gotValue) } t.Cleanup(func() { if err := v.SetWindowOption(Window(0), "colorcolumn", ""); err != nil { t.Fatal(err) } }) }) t.Run("WindowPosition", func(t *testing.T) { gotPos, err := v.WindowPosition(Window(0)) if err != nil { t.Fatal(err) } wantPos := [2]int{0, 0} if gotPos != wantPos { t.Fatalf("expected %v but got %v", wantPos, gotPos) } }) t.Run("WindowTabpage", func(t *testing.T) { gotTabpage, err := v.WindowTabpage(Window(0)) if err != nil { t.Fatal(err) } wantTabpage := Tabpage(1) if gotTabpage != wantTabpage { t.Fatalf("expected %v but got %v", wantTabpage, gotTabpage) } }) t.Run("WindowNumber", func(t *testing.T) { gotWinNum, err := v.WindowNumber(Window(0)) if err != nil { t.Fatal(err) } wantWinNum := 1 if gotWinNum != wantWinNum { t.Fatalf("expected %v but got %v", wantWinNum, gotWinNum) } }) t.Run("IsWindowValid", func(t *testing.T) { valid, err := v.IsWindowValid(Window(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var wins []Window b.Windows(&wins) if err := b.Execute(); err != nil { t.Fatal(err) } if len(wins) != 1 { t.Fatalf("expected one win, found %d wins", len(wins)) } if wins[0] == 0 { t.Fatalf("wins[0] == 0") } var win Window b.CurrentWindow(&win) if err := b.Execute(); err != nil { t.Fatal(err) } if win != wins[0] { t.Fatalf("win is not wins[0]: win: %v wins[0]: %v", win, wins[0]) } const want = "Window:1000" if got := win.String(); got != want { t.Fatalf("got %s but want %s", got, want) } b.CurrentWindow(&win) if err := b.Execute(); err != nil { t.Fatal(err) } b.Command("split") var win2 Window b.CurrentWindow(&win2) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetCurrentWindow(win) var gotwin Window b.CurrentWindow(&gotwin) if err := b.Execute(); err != nil { t.Fatal(err) } if gotwin != win { t.Fatalf("expected current window %s but got %s", win, gotwin) } b.HideWindow(win2) var wins2 []Window b.Windows(&wins2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(wins2) != 1 { for i := 0; i < len(wins2); i++ { t.Logf("wins[%d]: %v", i, wins2[i]) } t.Fatalf("expected one win, found %d wins", len(wins2)) } if wins2[0] == 0 { t.Fatalf("wins[0] == 0") } if win != wins2[0] { t.Fatalf("win2 is not wins2[0]: want: %v, win2: %v ", wins2[0], win) } t.Run("WindowBuffer", func(t *testing.T) { skipVersion(t, "v0.6.0") b := v.NewBatch() var gotBuf Buffer b.WindowBuffer(Window(0), &gotBuf) if err := b.Execute(); err != nil { t.Fatal(err) } wantBuffer := Buffer(1) if gotBuf != wantBuffer { t.Fatalf("want %s buffer but got %s", wantBuffer, gotBuf) } var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } b.SetBufferToWindow(Window(0), buf) if err := b.Execute(); err != nil { t.Fatal(err) } var gotBuf2 Buffer b.WindowBuffer(Window(0), &gotBuf2) if err := b.Execute(); err != nil { t.Fatal(err) } if gotBuf2 != buf { t.Fatalf("want %s buffer but got %s", buf, gotBuf2) } t.Cleanup(func() { b.SetBufferToWindow(Window(0), gotBuf) if err := b.Execute(); err != nil { t.Fatal(err) } deleteBufferOpts := map[string]bool{ "force": true, "unload": false, } b.DeleteBuffer(buf, deleteBufferOpts) if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("WindowCursor", func(t *testing.T) { b := v.NewBatch() wantLine := []byte("hello world") b.SetCurrentLine(wantLine) if err := b.Execute(); err != nil { t.Fatal(err) } t.Cleanup(func() { b.DeleteCurrentLine() if err := b.Execute(); err != nil { t.Fatal(err) } }) wantPos := [2]int{1, 5} b.SetWindowCursor(Window(0), wantPos) if err := b.Execute(); err != nil { t.Fatal(err) } var gotPos [2]int b.WindowCursor(Window(0), &gotPos) if err := b.Execute(); err != nil { t.Fatal(err) } if wantPos != gotPos { t.Fatalf("want %#v position buf got %#v", wantPos, gotPos) } }) t.Run("WindowVar", func(t *testing.T) { b := v.NewBatch() wantValue := []int{1, 2} b.SetWindowVar(Window(0), "lua", wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue []int b.WindowVar(Window(0), "lua", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } b.DeleteWindowVar(Window(0), "lua") if err := b.Execute(); err != nil { t.Fatal(err) } b.WindowVar(Window(0), "lua", nil) if err := b.Execute(); err == nil { t.Fatalf("expect Key not found but fonud key") } }) t.Run("WindowOption", func(t *testing.T) { b := v.NewBatch() wantValue := "+1" b.SetWindowOption(Window(0), "colorcolumn", &wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue string b.WindowOption(Window(0), "colorcolumn", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if gotValue != wantValue { t.Fatalf("expected %s but got %s", wantValue, gotValue) } t.Cleanup(func() { b.SetWindowOption(Window(0), "colorcolumn", "") if err := b.Execute(); err != nil { t.Fatal(err) } }) }) t.Run("WindowPosition", func(t *testing.T) { b := v.NewBatch() var gotPos [2]int b.WindowPosition(Window(0), &gotPos) if err := b.Execute(); err != nil { t.Fatal(err) } wantPos := [2]int{0, 0} if gotPos != wantPos { t.Fatalf("expected %v but got %v", wantPos, gotPos) } }) t.Run("WindowTabpage", func(t *testing.T) { b := v.NewBatch() var gotTabpage Tabpage b.WindowTabpage(Window(0), &gotTabpage) if err := b.Execute(); err != nil { t.Fatal(err) } wantTabpage := Tabpage(1) if gotTabpage != wantTabpage { t.Fatalf("expected %v but got %v", wantTabpage, gotTabpage) } }) t.Run("WindowNumber", func(t *testing.T) { b := v.NewBatch() var gotWinNum int b.WindowNumber(Window(0), &gotWinNum) if err := b.Execute(); err != nil { t.Fatal(err) } wantWinNum := 1 if gotWinNum != wantWinNum { t.Fatalf("expected %v but got %v", wantWinNum, gotWinNum) } }) t.Run("IsWindowValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsWindowValid(Window(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) }) } } func testTabpage(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { pages, err := v.Tabpages() if err != nil { t.Fatal(err) } if len(pages) != 1 { t.Fatalf("expected one page, found %d pages", len(pages)) } if pages[0] == 0 { t.Fatalf("pages[0] is not 0: %d", pages[0]) } page, err := v.CurrentTabpage() if err != nil { t.Fatal(err) } if page != pages[0] { t.Fatalf("page is not pages[0]: page: %v pages[0]: %v", page, pages[0]) } const want = "Tabpage:1" if got := page.String(); got != want { t.Fatalf("got %s but want %s", got, want) } if err := v.SetCurrentTabpage(page); err != nil { t.Fatal(err) } t.Run("TabpageWindow", func(t *testing.T) { gotWin, err := v.TabpageWindow(Tabpage(0)) if err != nil { t.Fatal(err) } wantWin := Window(1000) if !reflect.DeepEqual(gotWin, wantWin) { t.Fatalf("expected %v but got %v", wantWin, gotWin) } }) t.Run("TabpageWindows", func(t *testing.T) { gotWins, err := v.TabpageWindows(Tabpage(0)) if err != nil { t.Fatal(err) } wantWins := []Window{Window(1000)} if !reflect.DeepEqual(gotWins, wantWins) { t.Fatalf("expected %v but got %v", wantWins, gotWins) } }) t.Run("TabpageNumber", func(t *testing.T) { gotTabpageNum, err := v.TabpageNumber(Tabpage(0)) if err != nil { t.Fatal(err) } wantTabpageNum := 1 if gotTabpageNum != wantTabpageNum { t.Fatalf("expected %v but got %v", wantTabpageNum, gotTabpageNum) } }) t.Run("IsTabpageValid", func(t *testing.T) { valid, err := v.IsTabpageValid(Tabpage(0)) if err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) t.Run("TabpageVar", func(t *testing.T) { wantValue := []int{1, 2} if err := v.SetTabpageVar(Tabpage(0), "lua", wantValue); err != nil { t.Fatal(err) } var gotValue []int if err := v.TabpageVar(Tabpage(0), "lua", &gotValue); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } if err := v.DeleteTabpageVar(Tabpage(0), "lua"); err != nil { t.Fatal(err) } if err := v.TabpageVar(Tabpage(0), "lua", nil); err == nil { t.Fatalf("expect Key not found but fonud key") } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var pages []Tabpage b.Tabpages(&pages) if err := b.Execute(); err != nil { t.Fatal(err) } if len(pages) != 1 { t.Fatalf("expected one page, found %d pages", len(pages)) } if pages[0] == 0 { t.Fatalf("pages[0] is not 0: %d", pages[0]) } var page Tabpage b.CurrentTabpage(&page) if err := b.Execute(); err != nil { t.Fatal(err) } if page != pages[0] { t.Fatalf("page is not pages[0]: page: %v pages[0]: %v", page, pages[0]) } const want = "Tabpage:1" if got := page.String(); got != want { t.Fatalf("got %s but want %s", got, want) } b.SetCurrentTabpage(page) if err := b.Execute(); err != nil { t.Fatal(err) } t.Run("TabpageWindow", func(t *testing.T) { b := v.NewBatch() var gotWin Window b.TabpageWindow(Tabpage(0), &gotWin) if err := b.Execute(); err != nil { t.Fatal(err) } wantWin := Window(1000) if gotWin != wantWin { t.Fatalf("expected %v but got %v", wantWin, gotWin) } }) t.Run("TabpageWindows", func(t *testing.T) { b := v.NewBatch() var gotWins []Window b.TabpageWindows(Tabpage(0), &gotWins) if err := b.Execute(); err != nil { t.Fatal(err) } wantWins := []Window{Window(1000)} if !reflect.DeepEqual(gotWins, wantWins) { t.Fatalf("expected %v but got %v", wantWins, gotWins) } }) t.Run("TabpageNumber", func(t *testing.T) { b := v.NewBatch() var gotTabpageNum int b.TabpageNumber(Tabpage(0), &gotTabpageNum) if err := b.Execute(); err != nil { t.Fatal(err) } wantTabpageNum := 1 if gotTabpageNum != wantTabpageNum { t.Fatalf("expected %v but got %v", wantTabpageNum, gotTabpageNum) } }) t.Run("IsWindowValid", func(t *testing.T) { b := v.NewBatch() var valid bool b.IsTabpageValid(Tabpage(0), &valid) if err := b.Execute(); err != nil { t.Fatal(err) } if !valid { t.Fatalf("expected valid but got %t", valid) } }) t.Run("TabpageVar", func(t *testing.T) { b := v.NewBatch() wantValue := []int{1, 2} b.SetTabpageVar(Tabpage(0), "lua", wantValue) if err := b.Execute(); err != nil { t.Fatal(err) } var gotValue []int b.TabpageVar(Tabpage(0), "lua", &gotValue) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotValue, wantValue) { t.Fatalf("want %#v but got %#v", wantValue, gotValue) } b.DeleteTabpageVar(Tabpage(0), "lua") if err := b.Execute(); err != nil { t.Fatal(err) } b.TabpageVar(Tabpage(0), "lua", nil) if err := b.Execute(); err == nil { t.Fatalf("expect Key not found but fonud key") } }) }) } } func testLines(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("CurrentLine", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) beforeLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } wantLine := []byte("hello world") if err := v.SetCurrentLine(wantLine); err != nil { t.Fatal(err) } afterLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } if bytes.EqualFold(beforeLine, afterLine) { t.Fatalf("current line not change: before: %v, after: %v", beforeLine, afterLine) } if err := v.DeleteCurrentLine(); err != nil { t.Fatal(err) } deletedLine, err := v.CurrentLine() if err != nil { t.Fatal(err) } if len(deletedLine) != 0 { t.Fatal("DeleteCurrentLine not deleted") } }) t.Run("BufferLines", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. lines := [][]byte{[]byte("hello"), []byte("world")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } lines2, err := v.BufferLines(buf, 0, -1, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(lines2, lines) { t.Fatalf("lines = %+v, want %+v", lines2, lines) } const wantCount = 2 count, err := v.BufferLineCount(buf) if err != nil { t.Fatal(err) } if count != wantCount { t.Fatalf("got count %d but want %d", count, wantCount) } const wantOffset = 12 // [][]byte{[]byte("hello"), []byte("\n"), []byte("world"), []byte("\n")} offset, err := v.BufferOffset(buf, count) if err != nil { t.Fatal(err) } if offset != wantOffset { t.Fatalf("got offset %d but want %d", offset, wantOffset) } }) t.Run("SetBufferText", func(t *testing.T) { buf, err := v.CurrentBuffer() if err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. // sets test buffer text. lines := [][]byte{[]byte("Vim is the"), []byte("Nvim-fork? focused on extensibility and usability")} if err := v.SetBufferLines(buf, 0, -1, true, lines); err != nil { t.Fatal(err) } // Replace `Vim is the` to `Neovim is the` if err := v.SetBufferText(buf, 0, 0, 0, 3, [][]byte{[]byte("Neovim")}); err != nil { t.Fatal(err) } // Replace `Nvim-fork?` to `Vim-fork` if err := v.SetBufferText(buf, 1, 0, 1, 10, [][]byte{[]byte("Vim-fork")}); err != nil { t.Fatal(err) } want := [2][]byte{ []byte("Neovim is the"), []byte("Vim-fork focused on extensibility and usability"), } got, err := v.BufferLines(buf, 0, -1, true) if err != nil { t.Fatal(err) } // assert buffer lines count. const wantCount = 2 if len(got) != wantCount { t.Fatalf("expected buffer lines rows is %d: got %d", wantCount, len(got)) } // assert row 1 buffer text. if !bytes.EqualFold(want[0], got[0]) { t.Fatalf("row 1 is not equal: want: %q, got: %q", string(want[0]), string(got[0])) } // assert row 2 buffer text. if !bytes.EqualFold(want[1], got[1]) { t.Fatalf("row 2 is not equal: want: %q, got: %q", string(want[1]), string(got[1])) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("CurrentLine", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) b := v.NewBatch() var beforeLine []byte b.CurrentLine(&beforeLine) if err := b.Execute(); err != nil { t.Fatal(err) } wantLine := []byte("hello world") b.SetCurrentLine(wantLine) if err := b.Execute(); err != nil { t.Fatal(err) } var afterLine []byte b.CurrentLine(&afterLine) if err := b.Execute(); err != nil { t.Fatal(err) } if bytes.EqualFold(beforeLine, afterLine) { t.Fatalf("current line not change: before: %v, after: %v", beforeLine, afterLine) } b.DeleteCurrentLine() if err := b.Execute(); err != nil { t.Fatal(err) } var deletedLine []byte b.CurrentLine(&deletedLine) if err := b.Execute(); err != nil { t.Fatal(err) } if len(deletedLine) != 0 { t.Fatal("DeleteCurrentLine not deleted") } }) t.Run("BufferLines", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. lines := [][]byte{[]byte("hello"), []byte("world")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } var lines2 [][]byte b.BufferLines(buf, 0, -1, true, &lines2) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(lines2, lines) { t.Fatalf("lines = %+v, want %+v", lines2, lines) } const wantCount = 2 var count int b.BufferLineCount(buf, &count) if err := b.Execute(); err != nil { t.Fatal(err) } if count != wantCount { t.Fatalf("count is not 2 %d", count) } const wantOffset = 12 // [][]byte{[]byte("hello"), []byte("\n"), []byte("world"), []byte("\n")} var offset int b.BufferOffset(buf, count, &offset) if err := b.Execute(); err != nil { t.Fatal(err) } if offset != wantOffset { t.Fatalf("got offset %d but want %d", offset, wantOffset) } }) t.Run("SetBufferText", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CurrentBuffer(&buf) if err := b.Execute(); err != nil { t.Fatal(err) } defer clearBuffer(t, v, buf) // clear buffer after run sub-test. // sets test buffer text. lines := [][]byte{[]byte("Vim is the"), []byte("Nvim-fork? focused on extensibility and usability")} b.SetBufferLines(buf, 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // Replace `Vim is the` to `Neovim is the` b.SetBufferText(buf, 0, 0, 0, 3, [][]byte{[]byte("Neovim")}) // Replace `Nvim-fork?` to `Vim-fork` b.SetBufferText(buf, 1, 0, 1, 10, [][]byte{[]byte("Vim-fork")}) if err := b.Execute(); err != nil { t.Fatal(err) } want := [2][]byte{ []byte("Neovim is the"), []byte("Vim-fork focused on extensibility and usability"), } var got [][]byte b.BufferLines(buf, 0, -1, true, &got) if err := b.Execute(); err != nil { t.Fatal(err) } // assert buffer lines count. const wantCount = 2 if len(got) != wantCount { t.Fatalf("expected buffer lines rows is %d: got %d", wantCount, len(got)) } // assert row 1 buffer text. if !bytes.EqualFold(want[0], got[0]) { t.Fatalf("row 1 is not equal: want: %q, got: %q", string(want[0]), string(got[0])) } // assert row 1 buffer text. if !bytes.EqualFold(want[1], got[1]) { t.Fatalf("row 2 is not equal: want: %q, got: %q", string(want[1]), string(got[1])) } }) }) } } func testCommands(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { opts := map[string]interface{}{ "builtin": false, } cmds, err := v.Commands(opts) if err != nil { t.Fatal(err) } if len(cmds) > 0 { t.Fatalf("expected 0 length but got %#v", cmds) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() opts := map[string]interface{}{ "builtin": false, } var cmds map[string]*Command b.Commands(opts, &cmds) if err := b.Execute(); err != nil { t.Fatal(err) } if len(cmds) > 0 { t.Fatalf("expected 0 length but got %#v", cmds) } }) } } func testVar(v *Nvim) func(*testing.T) { return func(t *testing.T) { const ( varKey = `gvar` varVal = `gval` ) const ( vvarKey = "statusmsg" wantVvar = "test" ) t.Run("Nvim", func(t *testing.T) { t.Run("Var", func(t *testing.T) { if err := v.SetVar(varKey, varVal); err != nil { t.Fatal(err) } var value interface{} if err := v.Var(varKey, &value); err != nil { t.Fatal(err) } if value != varVal { t.Fatalf("got %v, want %q", value, varVal) } if err := v.SetVar(varKey, ""); err != nil { t.Fatal(err) } value = nil if err := v.Var(varKey, &value); err != nil { t.Fatal(err) } if value != "" { t.Fatalf("got %v, want %q", value, "") } if err := v.DeleteVar(varKey); err != nil && !strings.Contains(err.Error(), "Key not found") { t.Fatal(err) } }) t.Run("VVar", func(t *testing.T) { if err := v.SetVVar(vvarKey, wantVvar); err != nil { t.Fatalf("failed to SetVVar: %v", err) } var vvar string if err := v.VVar(vvarKey, &vvar); err != nil { t.Fatalf("failed to SetVVar: %v", err) } if vvar != wantVvar { t.Fatalf("VVar(%s, %s) = %s, want: %s", vvarKey, wantVvar, vvar, wantVvar) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Var", func(t *testing.T) { b := v.NewBatch() b.SetVar(varKey, varVal) var value interface{} b.Var(varKey, &value) if err := b.Execute(); err != nil { t.Fatal(err) } if value != varVal { t.Fatalf("got %v, want %q", value, varVal) } b.SetVar(varKey, "") value = nil b.Var(varKey, &value) if err := b.Execute(); err != nil { t.Fatal(err) } if value != "" { t.Fatalf("got %v, want %q", value, "") } b.DeleteVar(varKey) if err := b.Execute(); err != nil && !strings.Contains(err.Error(), "Key not found") { t.Fatal(err) } }) t.Run("VVar", func(t *testing.T) { b := v.NewBatch() b.SetVVar(vvarKey, wantVvar) if err := b.Execute(); err != nil { t.Fatal(err) } var vvar string b.VVar(vvarKey, &vvar) if err := b.Execute(); err != nil { t.Fatal(err) } if vvar != wantVvar { t.Fatalf("VVar(%s, %s) = %s, want: %s", vvarKey, wantVvar, vvar, wantVvar) } }) }) } } func testMessage(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("Echo", func(t *testing.T) { const wantEcho = `hello Echo` chunk := []TextChunk{ { Text: wantEcho, }, } if err := v.Echo(chunk, true, make(map[string]interface{})); err != nil { t.Fatalf("failed to Echo: %v", err) } gotEcho, err := v.Exec("message", true) if err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotEcho != wantEcho { t.Fatalf("Echo(%q) = %q, want: %q", wantEcho, gotEcho, wantEcho) } }) t.Run("WriteOut", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWriteOut = `hello WriteOut` if err := v.WriteOut(wantWriteOut + "\n"); err != nil { t.Fatalf("failed to WriteOut: %v", err) } var gotWriteOut string if err := v.VVar("statusmsg", &gotWriteOut); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteOut != wantWriteOut { t.Fatalf("WriteOut(%q) = %q, want: %q", wantWriteOut, gotWriteOut, wantWriteOut) } }) t.Run("WriteErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWriteErr = `hello WriteErr` if err := v.WriteErr(wantWriteErr + "\n"); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWriteErr string if err := v.VVar("errmsg", &gotWriteErr); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteErr != wantWriteErr { t.Fatalf("WriteErr(%q) = %q, want: %q", wantWriteErr, gotWriteErr, wantWriteErr) } }) t.Run("WritelnErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantWritelnErr = `hello WritelnErr` if err := v.WritelnErr(wantWritelnErr); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWritelnErr string if err := v.VVar("errmsg", &gotWritelnErr); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWritelnErr != wantWritelnErr { t.Fatalf("WritelnErr(%q) = %q, want: %q", wantWritelnErr, gotWritelnErr, wantWritelnErr) } }) t.Run("Notify", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantNotifyMsg = `hello Notify` if err := v.Notify(wantNotifyMsg, LogInfoLevel, make(map[string]interface{})); err != nil { t.Fatalf("failed to Notify: %v", err) } gotNotifyMsg, err := v.Exec(":messages", true) if err != nil { t.Fatalf("failed to messages command: %v", err) } if wantNotifyMsg != gotNotifyMsg { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyMsg, LogInfoLevel, gotNotifyMsg) } }) t.Run("Notify/Error", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() const wantNotifyErr = `hello Notify Error` if err := v.Notify(wantNotifyErr, LogErrorLevel, make(map[string]interface{})); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyErr string if err := v.VVar("errmsg", &gotNotifyErr); err != nil { t.Fatalf("could not get v:errmsg nvim variable: %v", err) } if wantNotifyErr != gotNotifyErr { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyErr, LogErrorLevel, gotNotifyErr) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Echo", func(t *testing.T) { b := v.NewBatch() const wantEcho = `hello Echo` chunk := []TextChunk{ { Text: wantEcho, }, } b.Echo(chunk, true, make(map[string]interface{})) var gotEcho string b.Exec("message", true, &gotEcho) if err := b.Execute(); err != nil { t.Fatalf("failed to Execute: %v", err) } if gotEcho != wantEcho { t.Fatalf("Echo(%q) = %q, want: %q", wantEcho, gotEcho, wantEcho) } }) t.Run("WriteOut", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWriteOut = `hello WriteOut` b.WriteOut(wantWriteOut + "\n") if err := b.Execute(); err != nil { t.Fatalf("failed to WriteOut: %v", err) } var gotWriteOut string b.VVar("statusmsg", &gotWriteOut) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteOut != wantWriteOut { t.Fatalf("b.WriteOut(%q) = %q, want: %q", wantWriteOut, gotWriteOut, wantWriteOut) } }) t.Run("WriteErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWriteErr = `hello WriteErr` b.WriteErr(wantWriteErr + "\n") if err := b.Execute(); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWriteErr string b.VVar("errmsg", &gotWriteErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWriteErr != wantWriteErr { t.Fatalf("b.WriteErr(%q) = %q, want: %q", wantWriteErr, gotWriteErr, wantWriteErr) } }) t.Run("WritelnErr", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantWritelnErr = `hello WritelnErr` b.WritelnErr(wantWritelnErr) if err := b.Execute(); err != nil { t.Fatalf("failed to WriteErr: %v", err) } var gotWritelnErr string b.VVar("errmsg", &gotWritelnErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:statusmsg nvim variable: %v", err) } if gotWritelnErr != wantWritelnErr { t.Fatalf("b.WritelnErr(%q) = %q, want: %q", wantWritelnErr, gotWritelnErr, wantWritelnErr) } }) t.Run("Notify", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantNotifyMsg = `hello Notify` b.Notify(wantNotifyMsg, LogInfoLevel, make(map[string]interface{})) if err := b.Execute(); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyMsg string b.Exec(":messages", true, &gotNotifyMsg) if err := b.Execute(); err != nil { t.Fatalf("failed to \":messages\" command: %v", err) } if wantNotifyMsg != gotNotifyMsg { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyMsg, LogInfoLevel, gotNotifyMsg) } }) t.Run("Notify/Error", func(t *testing.T) { defer func() { // cleanup v:statusmsg if err := v.SetVVar("statusmsg", ""); err != nil { t.Fatalf("failed to SetVVar: %v", err) } // clear messages if _, err := v.Exec(":messages clear", false); err != nil { t.Fatalf("failed to SetVVar: %v", err) } }() b := v.NewBatch() const wantNotifyErr = `hello Notify Error` b.Notify(wantNotifyErr, LogErrorLevel, make(map[string]interface{})) if err := b.Execute(); err != nil { t.Fatalf("failed to Notify: %v", err) } var gotNotifyErr string b.VVar("errmsg", &gotNotifyErr) if err := b.Execute(); err != nil { t.Fatalf("could not get v:errmsg nvim variable: %v", err) } if wantNotifyErr != gotNotifyErr { t.Fatalf("Notify(%[1]q, %[2]q) = %[3]q, want: %[1]q", wantNotifyErr, LogErrorLevel, gotNotifyErr) } }) }) } } func testKey(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("FeedKeys", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) input, err := v.ReplaceTermcodes(keys, true, true, true) if err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) if err := v.FeedKeys(input, mode, escapeCSI); err != nil { t.Fatal(err) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("Input", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) input, err := v.ReplaceTermcodes(keys, true, true, true) if err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) written, err := v.Input(input) if err != nil { t.Fatal(err) } if written != len(input) { t.Fatalf("Input(%s) = %d: want: %d", input, written, len(input)) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("InputMouse", func(t *testing.T) { defer func() { // cleanup current Buffer after tests. clearBuffer(t, v, Buffer(0)) input, err := v.ReplaceTermcodes(`<ESC>`, true, true, true) if err != nil { t.Fatal(err) } if err := v.FeedKeys(input, `n`, true); err != nil { t.Fatal(err) } }() // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) lines := [][]byte{ []byte("foo bar baz"), []byte("qux quux quuz"), []byte("corge grault garply"), []byte("waldo fred plugh"), []byte("xyzzy thud"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } const ( button = `left` firestAction = `press` secondAction = `release` modifier = "" ) const ( wantGrid = 20 wantRow = 2 wantCol = 5 ) if err := v.InputMouse(button, firestAction, modifier, wantGrid, wantRow, wantCol); err != nil { t.Fatal(err) } // TODO(zchee): assertion }) t.Run("StringWidth", func(t *testing.T) { const str = "hello\t" got, err := v.StringWidth(str) if err != nil { t.Fatal(err) } if got != len(str) { t.Fatalf("StringWidth(%s) = %d, want: %d", str, got, len(str)) } }) t.Run("KeyMap", func(t *testing.T) { mode := "n" if err := v.SetKeyMap(mode, "y", "yy", make(map[string]bool)); err != nil { t.Fatal(err) } wantMaps := []*Mapping{ { LHS: "y", RHS: "yy", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, } wantMapsLen := 0 if nvimVersion.Minor >= 6 { lastMap := wantMaps[0] wantMaps = []*Mapping{ { LHS: "<C-L>", RHS: "<Cmd>nohlsearch|diffupdate<CR><C-L>", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, { LHS: "Y", RHS: "y$", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, lastMap, } wantMapsLen = 2 } got, err := v.KeyMap(mode) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, wantMaps) { for i, gotmap := range got { t.Logf(" got[%d]: %#v", i, gotmap) } for i, wantmap := range wantMaps { t.Logf("want[%d]: %#v", i, wantmap) } t.Fatalf("KeyMap(%s) = %#v, want: %#v", mode, got, wantMaps) } if err := v.DeleteKeyMap(mode, "y"); err != nil { t.Fatal(err) } got2, err := v.KeyMap(mode) if err != nil { t.Fatal(err) } if len(got2) != wantMapsLen { t.Fatalf("expected %d but got %#v", wantMapsLen, got2) } }) t.Run("BufferKeyMap", func(t *testing.T) { mode := "n" buffer := Buffer(0) if err := v.SetBufferKeyMap(buffer, mode, "x", "xx", make(map[string]bool)); err != nil { t.Fatal(err) } wantMap := []*Mapping{ { LHS: "x", RHS: "xx", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 1, SID: 0, NoWait: 0, }, } got, err := v.BufferKeyMap(buffer, mode) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(wantMap, got) { t.Fatalf("KeyMap(n) = %#v, want: %#v", got[0], wantMap[0]) } if err := v.DeleteBufferKeyMap(buffer, mode, "x"); err != nil { t.Fatal(err) } got2, err := v.BufferKeyMap(buffer, mode) if err != nil { t.Fatal(err) } if wantLen := 0; len(got2) != wantLen { t.Fatalf("expected %d but got %#v", wantLen, got2) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("FeedKeys", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) b := v.NewBatch() const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) var input string b.ReplaceTermcodes(keys, true, true, true, &input) if err := b.Execute(); err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) b.FeedKeys(input, mode, escapeCSI) if err := b.Execute(); err != nil { t.Fatal(err) } wantLines := []byte{'a', 'b', 'c'} gotLines, err := v.CurrentLine() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", keys, mode, escapeCSI, gotLines, wantLines) } }) t.Run("Input", func(t *testing.T) { // cleanup current Buffer after tests. defer clearBuffer(t, v, Buffer(0)) b := v.NewBatch() const ( keys = `iabc<ESC>` mode = `n` escapeCSI = false ) var input string b.ReplaceTermcodes(keys, true, true, true, &input) if err := b.Execute(); err != nil { t.Fatal(err) } // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) var written int b.Input(input, &written) if err := b.Execute(); err != nil { t.Fatal(err) } if written != len(input) { t.Fatalf("Input(%s) = %d: want: %d", input, written, len(input)) } wantLines := []byte{'a', 'b', 'c'} var gotLines []byte b.CurrentLine(&gotLines) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotLines, wantLines) { t.Fatalf("FeedKeys(%s, %s, %t): got %v, want %v", input, mode, escapeCSI, gotLines, wantLines) } }) t.Run("InputMouse", func(t *testing.T) { defer func() { // cleanup current Buffer after tests. clearBuffer(t, v, Buffer(0)) input, err := v.ReplaceTermcodes(`<ESC>`, true, true, true) if err != nil { t.Fatal(err) } if err := v.FeedKeys(input, `n`, true); err != nil { t.Fatal(err) } }() // clear current Buffer before run FeedKeys. clearBuffer(t, v, Buffer(0)) lines := [][]byte{ []byte("foo bar baz"), []byte("qux quux quuz"), []byte("corge grault garply"), []byte("waldo fred plugh"), []byte("xyzzy thud"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } const ( button = `left` firestAction = `press` secondAction = `release` modifier = "" ) const ( wantGrid = 20 wantRow = 2 wantCol = 5 ) b := v.NewBatch() b.InputMouse(button, firestAction, modifier, wantGrid, wantRow, wantCol) if err := b.Execute(); err != nil { t.Fatal(err) } b.InputMouse(button, secondAction, modifier, wantGrid, wantRow, wantCol) if err := b.Execute(); err != nil { t.Fatal(err) } // TODO(zchee): assertion }) t.Run("StringWidth", func(t *testing.T) { b := v.NewBatch() const str = "hello\t" var got int b.StringWidth(str, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if got != len(str) { t.Fatalf("StringWidth(%s) = %d, want: %d", str, got, len(str)) } }) t.Run("KeyMap", func(t *testing.T) { b := v.NewBatch() mode := "n" b.SetKeyMap(mode, "y", "yy", make(map[string]bool)) if err := b.Execute(); err != nil { t.Fatal(err) } wantMaps := []*Mapping{ { LHS: "y", RHS: "yy", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, } wantMapsLen := 0 if nvimVersion.Minor >= 6 { lastMap := wantMaps[0] wantMaps = []*Mapping{ { LHS: "<C-L>", RHS: "<Cmd>nohlsearch|diffupdate<CR><C-L>", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, { LHS: "Y", RHS: "y$", Silent: 0, NoRemap: 1, Expr: 0, Buffer: 0, SID: 0, NoWait: 0, }, lastMap, } wantMapsLen = 2 } var got []*Mapping b.KeyMap(mode, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, wantMaps) { for i, gotmap := range got { t.Logf(" got[%d]: %#v", i, gotmap) } for i, wantmap := range wantMaps { t.Logf("want[%d]: %#v", i, wantmap) } t.Fatalf("KeyMap(%s) = %#v, want: %#v", mode, got, wantMaps) } b.DeleteKeyMap(mode, "y") if err := b.Execute(); err != nil { t.Fatal(err) } var got2 []*Mapping b.KeyMap(mode, &got2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(got2) != wantMapsLen { t.Fatalf("expected %d but got %#v", wantMapsLen, got2) } }) t.Run("BufferKeyMap", func(t *testing.T) { mode := "n" b := v.NewBatch() buffer := Buffer(0) b.SetBufferKeyMap(buffer, mode, "x", "xx", make(map[string]bool)) if err := b.Execute(); err != nil { t.Fatal(err) } wantMap := []*Mapping{ { LHS: "x", RHS: "xx", Silent: 0, NoRemap: 0, Expr: 0, Buffer: 1, SID: 0, NoWait: 0, }, } var got []*Mapping b.BufferKeyMap(buffer, mode, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(wantMap, got) { t.Fatalf("KeyMap(n) = %#v, want: %#v", got[0], wantMap[0]) } b.DeleteBufferKeyMap(buffer, mode, "x") if err := b.Execute(); err != nil { t.Fatal(err) } var got2 []*Mapping b.BufferKeyMap(buffer, mode, &got2) if err := b.Execute(); err != nil { t.Fatal(err) } if len(got2) > 0 { t.Fatalf("expected 0 but got %#v", got2) } }) }) } } func testEval(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { var a, b string if err := v.Eval(`["hello", "world"]`, []*string{&a, &b}); err != nil { t.Fatal(err) } if a != "hello" || b != "world" { t.Fatalf("a=%q b=%q, want a=hello b=world", a, b) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var x, y string b.Eval(`["hello", "world"]`, []*string{&x, &y}) if err := b.Execute(); err != nil { t.Fatal(err) } if x != "hello" || y != "world" { t.Fatalf("a=%q b=%q, want a=hello b=world", x, y) } }) } } func testBatch(v *Nvim) func(*testing.T) { return func(t *testing.T) { b := v.NewBatch() results := make([]int, 128) for i := range results { b.SetVar(fmt.Sprintf("batch%d", i), i) } for i := range results { b.Var(fmt.Sprintf("batch%d", i), &results[i]) } if err := b.Execute(); err != nil { t.Fatal(err) } for i := range results { if results[i] != i { t.Fatalf("result[i] = %d, want %d", results[i], i) } } // Reuse batch var i int b.Var("batch3", &i) if err := b.Execute(); err != nil { log.Fatal(err) } if i != 3 { t.Fatalf("i = %d, want %d", i, 3) } // Check for *BatchError const errorIndex = 3 for i := range results { results[i] = -1 } for i := range results { if i == errorIndex { b.Var("batch_bad_var", &results[i]) } else { b.Var(fmt.Sprintf("batch%d", i), &results[i]) } } err := b.Execute() if e, ok := err.(*BatchError); !ok || e.Index != errorIndex { t.Fatalf("unxpected error %T %v", e, e) } // Expect results proceeding error. for i := 0; i < errorIndex; i++ { if results[i] != i { t.Fatalf("result[i] = %d, want %d", results[i], i) break } } // No results after error. for i := errorIndex; i < len(results); i++ { if results[i] != -1 { t.Fatalf("result[i] = %d, want %d", results[i], -1) break } } // Execute should return marshal error for argument that cannot be marshaled. b.SetVar("batch0", make(chan bool)) if err := b.Execute(); err == nil || !strings.Contains(err.Error(), "chan bool") { t.Fatalf("err = nil, expect error containing text 'chan bool'") } // Test call with empty argument list. var buf Buffer b.CurrentBuffer(&buf) if err = b.Execute(); err != nil { t.Fatalf("GetCurrentBuffer returns err %s: %#v", err, err) } } } func testMode(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { m, err := v.Mode() if err != nil { t.Fatal(err) } if m.Mode != "n" { t.Fatalf("Mode() returned %s, want n", m.Mode) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var m Mode b.Mode(&m) if err := b.Execute(); err != nil { t.Fatal(err) } if m.Mode != "n" { t.Fatalf("Mode() returned %s, want n", m.Mode) } }) } } func testExecLua(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { var n int err := v.ExecLua("local a, b = ... return a + b", &n, 1, 2) if err != nil { t.Fatal(err) } if n != 3 { t.Fatalf("Mode() returned %v, want 3", n) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var n int b.ExecLua("local a, b = ... return a + b", &n, 1, 2) if err := b.Execute(); err != nil { t.Fatal(err) } if n != 3 { t.Fatalf("Mode() returned %v, want 3", n) } }) } } func testHighlight(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { cm, err := v.ColorMap() if err != nil { t.Fatal(err) } const cmd = `highlight NewHighlight cterm=underline ctermbg=green guifg=red guibg=yellow guisp=blue gui=bold` if err := v.Command(cmd); err != nil { t.Fatal(err) } wantCTerm := &HLAttrs{ Underline: true, Foreground: -1, Background: 10, Special: -1, } wantGUI := &HLAttrs{ Bold: true, Foreground: cm["Red"], Background: cm["Yellow"], Special: cm["Blue"], } var nsID int if err := v.Eval(`hlID('NewHighlight')`, &nsID); err != nil { t.Fatal(err) } const HLIDName = `Error` var wantErrorHLID = 64 if nvimVersion.Minor >= 7 { wantErrorHLID = 66 } goHLID, err := v.HLIDByName(HLIDName) if err != nil { t.Fatal(err) } if goHLID != wantErrorHLID { t.Fatalf("HLByID(%s)\n got %+v,\nwant %+v", HLIDName, goHLID, wantErrorHLID) } gotCTermHL, err := v.HLByID(nsID, false) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotCTermHL, wantCTerm) { t.Fatalf("HLByID(id, false)\n got %+v,\nwant %+v", gotCTermHL, wantCTerm) } gotGUIHL, err := v.HLByID(nsID, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotGUIHL, wantGUI) { t.Fatalf("HLByID(id, true)\n got %+v,\nwant %+v", gotGUIHL, wantGUI) } errorMsgHL, err := v.HLByName(`ErrorMsg`, true) if err != nil { t.Fatal(err) } errorMsgHL.Bold = true errorMsgHL.Underline = true errorMsgHL.Italic = true if err := v.SetHighlight(nsID, "ErrorMsg", errorMsgHL); err != nil { t.Fatal(err) } wantErrorMsgEHL := &HLAttrs{ Bold: true, Underline: true, Italic: true, Foreground: 16777215, Background: 16711680, Special: -1, } if !reflect.DeepEqual(wantErrorMsgEHL, errorMsgHL) { t.Fatalf("SetHighlight:\nwant %#v\n got %#v", wantErrorMsgEHL, errorMsgHL) } const cmd2 = `hi NewHighlight2 guifg=yellow guibg=red gui=bold` if err := v.Command(cmd2); err != nil { t.Fatal(err) } var nsID2 int if err := v.Eval(`hlID('NewHighlight2')`, &nsID2); err != nil { t.Fatal(err) } if err := v.SetHighlightNameSpace(nsID2); err != nil { t.Fatal(err) } want := &HLAttrs{ Bold: true, Underline: false, Undercurl: false, Italic: false, Reverse: false, Foreground: 16776960, Background: 16711680, Special: -1, } got, err := v.HLByID(nsID2, true) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, got) { t.Fatalf("SetHighlight:\nwant %#v\n got %#v", want, got) } const wantRedColor = 16711680 gotColor, err := v.ColorByName("red") if err != nil { t.Fatal(err) } if wantRedColor != gotColor { t.Fatalf("expected red color %d but got %d", wantRedColor, gotColor) } id, err := v.AddBufferHighlight(Buffer(0), 0, `NewHighlight2`, 0, 0, -1) if err != nil { t.Fatal(err) } if id < 0 { t.Fatalf("want id is not negative but got %d", id) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var cm map[string]int b.ColorMap(&cm) const cmd = `highlight NewHighlight cterm=underline ctermbg=green guifg=red guibg=yellow guisp=blue gui=bold` b.Command(cmd) if err := b.Execute(); err != nil { t.Fatal(err) } wantCTerm := &HLAttrs{ Underline: true, Foreground: -1, Background: 10, Special: -1, } wantGUI := &HLAttrs{ Bold: true, Foreground: cm[`Red`], Background: cm[`Yellow`], Special: cm[`Blue`], } var nsID int b.Eval("hlID('NewHighlight')", &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } const HLIDName = `Error` var wantErrorHLID = 64 if nvimVersion.Minor >= 7 { wantErrorHLID = 66 } var goHLID int b.HLIDByName(HLIDName, &goHLID) if err := b.Execute(); err != nil { t.Fatal(err) } if goHLID != wantErrorHLID { t.Fatalf("HLByID(%s)\n got %+v,\nwant %+v", HLIDName, goHLID, wantErrorHLID) } var gotCTermHL HLAttrs b.HLByID(nsID, false, &gotCTermHL) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotCTermHL, wantCTerm) { t.Fatalf("HLByID(id, false)\n got %+v,\nwant %+v", &gotCTermHL, wantCTerm) } var gotGUIHL HLAttrs b.HLByID(nsID, true, &gotGUIHL) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotGUIHL, wantGUI) { t.Fatalf("HLByID(id, true)\n got %+v,\nwant %+v", &gotGUIHL, wantGUI) } var errorMsgHL HLAttrs b.HLByName(`ErrorMsg`, true, &errorMsgHL) if err := b.Execute(); err != nil { t.Fatal(err) } errorMsgHL.Bold = true errorMsgHL.Underline = true errorMsgHL.Italic = true b.SetHighlight(nsID, `ErrorMsg`, &errorMsgHL) if err := b.Execute(); err != nil { t.Fatal(err) } wantErrorMsgEHL := &HLAttrs{ Bold: true, Underline: true, Italic: true, Foreground: 16777215, Background: 16711680, Special: -1, } if !reflect.DeepEqual(&errorMsgHL, wantErrorMsgEHL) { t.Fatalf("SetHighlight:\ngot %#v\nwant %#v", &errorMsgHL, wantErrorMsgEHL) } const cmd2 = `hi NewHighlight2 guifg=yellow guibg=red gui=bold` b.Command(cmd2) if err := b.Execute(); err != nil { t.Fatal(err) } var nsID2 int b.Eval("hlID('NewHighlight2')", &nsID2) b.SetHighlightNameSpace(nsID2) if err := b.Execute(); err != nil { t.Fatal(err) } want := &HLAttrs{ Bold: true, Underline: false, Undercurl: false, Italic: false, Reverse: false, Foreground: 16776960, Background: 16711680, Special: -1, } var got HLAttrs b.HLByID(nsID2, true, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&got, want) { t.Fatalf("SetHighlight:\n got %#v\nwant %#v", &got, want) } const wantRedColor = 16711680 var gotColor int b.ColorByName("red", &gotColor) if err := b.Execute(); err != nil { t.Fatal(err) } if wantRedColor != gotColor { t.Fatalf("expected red color %d but got %d", wantRedColor, gotColor) } var id int b.AddBufferHighlight(Buffer(0), 0, `NewHighlight2`, 0, 0, -1, &id) if err := b.Execute(); err != nil { t.Fatal(err) } if id < 0 { t.Fatalf("want id is not negative but got %d", id) } }) } } func testVirtualText(v *Nvim) func(*testing.T) { return func(t *testing.T) { clearBuffer(t, v, Buffer(0)) // clear curret buffer text nsID, err := v.CreateNamespace("test_virtual_text") if err != nil { t.Fatal(err) } lines := []byte("ping") if err := v.SetBufferLines(Buffer(0), 0, -1, true, bytes.Fields(lines)); err != nil { t.Fatal(err) } chunks := []TextChunk{ { Text: "pong", HLGroup: "String", }, } nsID2, err := v.SetBufferVirtualText(Buffer(0), nsID, 0, chunks, make(map[string]interface{})) if err != nil { t.Fatal(err) } if got := nsID2; got != nsID { t.Fatalf("namespaceID: got %d, want %d", got, nsID) } if err := v.ClearBufferNamespace(Buffer(0), nsID, 0, -1); err != nil { t.Fatal(err) } } } func testFloatingWindow(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text curwin, err := v.CurrentWindow() if err != nil { t.Fatal(err) } wantWidth := 50 wantHeight := 20 cfg := &WindowConfig{ Relative: "cursor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Col: 0, Focusable: true, Style: "minimal", } w, err := v.OpenWindow(Buffer(0), true, cfg) if err != nil { t.Fatal(err) } if curwin == w { t.Fatal("same window number: floating window not focused") } if err := v.SetWindowWidth(w, wantWidth); err != nil { t.Fatal(err) } if err := v.SetWindowHeight(w, wantHeight); err != nil { t.Fatal(err) } gotWidth, err := v.WindowWidth(w) if err != nil { t.Fatal(err) } if gotWidth != wantWidth { t.Fatalf("got %d width but want %d", gotWidth, wantWidth) } gotHeight, err := v.WindowHeight(w) if err != nil { t.Fatal(err) } if gotHeight != wantHeight { t.Fatalf("got %d height but want %d", gotHeight, wantHeight) } wantWinConfig := &WindowConfig{ Relative: "editor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Focusable: false, } if err := v.SetWindowConfig(w, wantWinConfig); err != nil { t.Fatal(err) } gotWinConfig, err := v.WindowConfig(w) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotWinConfig, wantWinConfig) { t.Fatalf("want %#v but got %#v", wantWinConfig, gotWinConfig) } var ( numberOpt bool relativenumberOpt bool cursorlineOpt bool cursorcolumnOpt bool spellOpt bool listOpt bool signcolumnOpt string colorcolumnOpt string ) if err := v.WindowOption(w, "number", &numberOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "relativenumber", &relativenumberOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "cursorline", &cursorlineOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "cursorcolumn", &cursorcolumnOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "spell", &spellOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "list", &listOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "signcolumn", &signcolumnOpt); err != nil { t.Fatal(err) } if err := v.WindowOption(w, "colorcolumn", &colorcolumnOpt); err != nil { t.Fatal(err) } if numberOpt || relativenumberOpt || cursorlineOpt || cursorcolumnOpt || spellOpt || listOpt || signcolumnOpt != "auto" || colorcolumnOpt != "" { t.Fatal("expected minimal style") } if err := v.CloseWindow(w, true); err != nil { t.Fatal(err) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() var curwin Window b.CurrentWindow(&curwin) if err := b.Execute(); err != nil { t.Fatal(err) } wantWidth := 50 wantHeight := 20 cfg := &WindowConfig{ Relative: "cursor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Col: 0, Focusable: true, Style: "minimal", } var w Window b.OpenWindow(Buffer(0), true, cfg, &w) if err := b.Execute(); err != nil { t.Fatal(err) } if curwin == w { t.Fatal("same window number: floating window not focused") } b.SetWindowWidth(w, wantWidth) b.SetWindowHeight(w, wantHeight) if err := b.Execute(); err != nil { t.Fatal(err) } var gotWidth int b.WindowWidth(w, &gotWidth) var gotHeight int b.WindowHeight(w, &gotHeight) if err := b.Execute(); err != nil { t.Fatal(err) } if gotWidth != wantWidth { t.Fatalf("got %d width but want %d", gotWidth, wantWidth) } if gotHeight != wantHeight { t.Fatalf("got %d height but want %d", gotHeight, wantHeight) } wantWinConfig := &WindowConfig{ Relative: "editor", Anchor: "NW", Width: 40, Height: 10, Row: 1, Focusable: false, } b.SetWindowConfig(w, wantWinConfig) if err := b.Execute(); err != nil { t.Fatal(err) } gotWinConfig := new(WindowConfig) b.WindowConfig(w, gotWinConfig) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotWinConfig, wantWinConfig) { t.Fatalf("want %#v but got %#v", wantWinConfig, gotWinConfig) } var ( numberOpt bool relativenumberOpt bool cursorlineOpt bool cursorcolumnOpt bool spellOpt bool listOpt bool signcolumnOpt string colorcolumnOpt string ) b.WindowOption(w, "number", &numberOpt) b.WindowOption(w, "relativenumber", &relativenumberOpt) b.WindowOption(w, "cursorline", &cursorlineOpt) b.WindowOption(w, "cursorcolumn", &cursorcolumnOpt) b.WindowOption(w, "spell", &spellOpt) b.WindowOption(w, "list", &listOpt) b.WindowOption(w, "signcolumn", &signcolumnOpt) b.WindowOption(w, "colorcolumn", &colorcolumnOpt) if err := b.Execute(); err != nil { t.Fatal(err) } if numberOpt || relativenumberOpt || cursorlineOpt || cursorcolumnOpt || spellOpt || listOpt || signcolumnOpt != "auto" || colorcolumnOpt != "" { t.Fatal("expected minimal style") } b.CloseWindow(w, true) if err := b.Execute(); err != nil { t.Fatal(err) } }) } } func testContext(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { ctxt, err := v.Context(make(map[string][]string)) if err != nil { t.Fatal(err) } var result interface{} if err := v.LoadContext(ctxt, &result); err != nil { t.Fatal(err) } if result != nil { t.Fatal("expected result to nil") } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var ctxt map[string]interface{} b.Context(make(map[string][]string), &ctxt) if err := b.Execute(); err != nil { t.Fatal(err) } var result interface{} b.LoadContext(ctxt, &result) if err := b.Execute(); err != nil { t.Fatal(err) } if result != nil { t.Fatal("expected result to nil") } }) } } func testExtmarks(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { // setup buffer lines lines := [][]byte{ []byte("hello"), []byte("world"), } if err := v.SetBufferLines(Buffer(0), 0, -1, true, lines); err != nil { t.Fatal(err) } // create namespace for test extmarks const extMarkName = "test_extmarks" nsID, err := v.CreateNamespace(extMarkName) if err != nil { t.Fatal(err) } const ( wantExtMarkID = 1 wantLine = 1 wantCol = 3 ) gotExtMarkID, err := v.SetBufferExtmark(Buffer(0), nsID, wantLine, wantCol, make(map[string]interface{})) if err != nil { t.Fatal(err) } if gotExtMarkID != wantExtMarkID { t.Fatalf("got %d extMarkID but want %d", gotExtMarkID, wantExtMarkID) } extmarks, err := v.BufferExtmarks(Buffer(0), nsID, 0, -1, make(map[string]interface{})) if err != nil { t.Fatal(err) } if len(extmarks) > 1 { t.Fatalf("expected extmarks length to 1 but got %d", len(extmarks)) } if extmarks[0].ID != gotExtMarkID { t.Fatalf("got %d extMarkID but want %d", extmarks[0].ID, wantExtMarkID) } if extmarks[0].Row != wantLine { t.Fatalf("got %d extmarks Row but want %d", extmarks[0].Row, wantLine) } if extmarks[0].Col != wantCol { t.Fatalf("got %d extmarks Col but want %d", extmarks[0].Col, wantCol) } pos, err := v.BufferExtmarkByID(Buffer(0), nsID, gotExtMarkID, make(map[string]interface{})) if err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } deleted, err := v.DeleteBufferExtmark(Buffer(0), nsID, gotExtMarkID) if err != nil { t.Fatal(err) } if !deleted { t.Fatalf("expected deleted but got %t", deleted) } if err := v.ClearBufferNamespace(Buffer(0), nsID, 0, -1); err != nil { t.Fatal(err) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) // clear curret buffer text }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() // setup buffer lines lines := [][]byte{ []byte("hello"), []byte("world"), } b.SetBufferLines(Buffer(0), 0, -1, true, lines) if err := b.Execute(); err != nil { t.Fatal(err) } // create namespace for test extmarks const extMarkName = "test_extmarks" var nsID int b.CreateNamespace(extMarkName, &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } const ( wantExtMarkID = 2 wantLine = 1 wantCol = 3 ) var gotExtMarkID int b.SetBufferExtmark(Buffer(0), nsID, wantLine, wantCol, make(map[string]interface{}), &gotExtMarkID) if err := b.Execute(); err != nil { t.Fatal(err) } if gotExtMarkID != wantExtMarkID { t.Fatalf("got %d extMarkID but want %d", gotExtMarkID, wantExtMarkID) } var extmarks []ExtMark b.BufferExtmarks(Buffer(0), nsID, 0, -1, make(map[string]interface{}), &extmarks) if err := b.Execute(); err != nil { t.Fatal(err) } if len(extmarks) > 1 { t.Fatalf("expected extmarks length to 1 but got %d", len(extmarks)) } if extmarks[0].ID != gotExtMarkID { t.Fatalf("got %d extMarkID but want %d", extmarks[0].ID, wantExtMarkID) } if extmarks[0].Row != wantLine { t.Fatalf("got %d extmarks Row but want %d", extmarks[0].Row, wantLine) } if extmarks[0].Col != wantCol { t.Fatalf("got %d extmarks Col but want %d", extmarks[0].Col, wantCol) } var pos []int b.BufferExtmarkByID(Buffer(0), nsID, gotExtMarkID, make(map[string]interface{}), &pos) if err := b.Execute(); err != nil { t.Fatal(err) } if pos[0] != wantLine { t.Fatalf("got %d extMark line but want %d", pos[0], wantLine) } if pos[1] != wantCol { t.Fatalf("got %d extMark col but want %d", pos[1], wantCol) } var deleted bool b.DeleteBufferExtmark(Buffer(0), nsID, gotExtMarkID, &deleted) if err := b.Execute(); err != nil { t.Fatal(err) } if !deleted { t.Fatalf("expected deleted but got %t", deleted) } b.ClearBufferNamespace(Buffer(0), nsID, 0, -1) if err := b.Execute(); err != nil { t.Fatal(err) } t.Cleanup(func() { clearBuffer(t, v, Buffer(0)) // clear curret buffer text }) }) } } func testRuntime(v *Nvim) func(*testing.T) { return func(t *testing.T) { var runtimePath string if err := v.Eval("$VIMRUNTIME", &runtimePath); err != nil { t.Fatal(err) } viDiff := filepath.Join(runtimePath, "doc", "vi_diff.txt") vimDiff := filepath.Join(runtimePath, "doc", "vim_diff.txt") want := fmt.Sprintf("%s,%s", viDiff, vimDiff) binaryPath, err := exec.LookPath(BinaryName) if err != nil { t.Fatal(err) } nvimPrefix := filepath.Dir(filepath.Dir(binaryPath)) wantPaths := []string{ filepath.Join(nvimPrefix, "share", "nvim", "runtime"), filepath.Join(nvimPrefix, "lib", "nvim"), } switch runtime.GOOS { case "linux", "darwin": if nvimVersion.Minor <= 5 { oldRuntimePaths := []string{ filepath.Join("/etc", "xdg", "nvim"), filepath.Join("/etc", "xdg", "nvim", "after"), filepath.Join("/usr", "local", "share", "nvim", "site"), filepath.Join("/usr", "local", "share", "nvim", "site", "after"), filepath.Join("/usr", "share", "nvim", "site"), filepath.Join("/usr", "share", "nvim", "site", "after"), } wantPaths = append(wantPaths, oldRuntimePaths...) } case "windows": if nvimVersion.Minor <= 5 { localAppDataDir := os.Getenv("LocalAppData") oldRuntimePaths := []string{ filepath.Join(localAppDataDir, "nvim"), filepath.Join(localAppDataDir, "nvim", "after"), filepath.Join(localAppDataDir, "nvim-data", "site"), filepath.Join(localAppDataDir, "nvim-data", "site", "after"), } wantPaths = append(wantPaths, oldRuntimePaths...) } } sort.Strings(wantPaths) argName := filepath.Join("doc", "*_diff.txt") argAll := true t.Run("Nvim", func(t *testing.T) { t.Run("RuntimeFiles", func(t *testing.T) { files, err := v.RuntimeFiles(argName, argAll) if err != nil { t.Fatal(err) } sort.Strings(files) if len(files) != 2 { t.Fatalf("expected 2 length but got %d", len(files)) } if got := strings.Join(files, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimeFiles(%s, %t): got %s but want %s", argName, argAll, got, want) } }) t.Run("RuntimePaths", func(t *testing.T) { paths, err := v.RuntimePaths() if err != nil { t.Fatal(err) } sort.Strings(paths) if got, want := strings.Join(paths, ","), strings.Join(wantPaths, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimePaths():\n got %v\nwant %v", paths, wantPaths) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("RuntimeFiles", func(t *testing.T) { b := v.NewBatch() var files []string b.RuntimeFiles(argName, true, &files) if err := b.Execute(); err != nil { t.Fatal(err) } sort.Strings(files) if len(files) != 2 { t.Fatalf("expected 2 length but got %d", len(files)) } if got := strings.Join(files, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimeFiles(%s, %t): got %s but want %s", argName, argAll, got, want) } }) t.Run("RuntimePaths", func(t *testing.T) { b := v.NewBatch() var paths []string b.RuntimePaths(&paths) if err := b.Execute(); err != nil { t.Fatal(err) } sort.Strings(paths) if got, want := strings.Join(paths, ","), strings.Join(wantPaths, ","); !strings.EqualFold(got, want) { t.Fatalf("RuntimePaths():\n got %v\nwant %v", paths, wantPaths) } }) }) } } func testPutPaste(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Put", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, Buffer(0)) // clear curret buffer text replacement := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} if err := v.SetBufferText(Buffer(0), 0, 0, 0, 0, replacement); err != nil { t.Fatal(err) } const putText = "qux" putLines := []string{putText} if err := v.Put(putLines, "l", true, true); err != nil { t.Fatal(err) } want := append(replacement, []byte(putText)) lines, err := v.BufferLines(Buffer(0), 0, -1, true) if err != nil { t.Fatal(err) } wantLines := bytes.Join(want, []byte("\n")) gotLines := bytes.Join(lines, []byte("\n")) if !bytes.Equal(wantLines, gotLines) { t.Fatalf("expected %s but got %s", string(wantLines), string(gotLines)) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() replacement := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} b.SetBufferText(Buffer(0), 0, 0, 0, 0, replacement) if err := b.Execute(); err != nil { t.Fatal(err) } const putText = "qux" putLines := []string{putText} b.Put(putLines, "l", true, true) if err := b.Execute(); err != nil { t.Fatal(err) } want := append(replacement, []byte(putText)) var lines [][]byte b.BufferLines(Buffer(0), 0, -1, true, &lines) if err := b.Execute(); err != nil { t.Fatal(err) } wantLines := bytes.Join(want, []byte("\n")) gotLines := bytes.Join(lines, []byte("\n")) if !bytes.Equal(wantLines, gotLines) { t.Fatalf("expected %s but got %s", string(wantLines), string(gotLines)) } }) }) t.Run("Paste", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text state, err := v.Paste("!!", true, 1) // starts the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("foo", true, 2) // continues the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("bar", true, 2) // continues the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect continue to pasting") } state, err = v.Paste("baz", true, 3) // ends the paste if err != nil { t.Fatal(err) } if !state { t.Fatal("expect not canceled") } lines, err := v.CurrentLine() if err != nil { t.Fatal(err) } const want = "!foobarbaz!" if want != string(lines) { t.Fatalf("got %s current lines but want %s", string(lines), want) } }) t.Run("Batch", func(t *testing.T) { clearBuffer(t, v, 0) // clear curret buffer text b := v.NewBatch() var state, state2, state3, state4 bool b.Paste("!!", true, 1, &state) // starts the paste b.Paste("foo", true, 2, &state2) // starts the paste b.Paste("bar", true, 2, &state3) // starts the paste b.Paste("baz", true, 3, &state4) // ends the paste if err := b.Execute(); err != nil { t.Fatal(err) } if !state || !state2 || !state3 || !state4 { t.Fatal("expect continue to pasting") } var lines []byte b.CurrentLine(&lines) if err := b.Execute(); err != nil { t.Fatal(err) } const want = "!foobarbaz!" if want != string(lines) { t.Fatalf("got %s current lines but want %s", string(lines), want) } }) }) } } func testNamespace(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Namespace", func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { const nsName = "test-nvim" nsID, err := v.CreateNamespace(nsName) if err != nil { t.Fatal(err) } nsIDs, err := v.Namespaces() if err != nil { t.Fatal(err) } gotID, ok := nsIDs[nsName] if !ok { t.Fatalf("not fount %s namespace ID", nsName) } if gotID != nsID { t.Fatalf("nsID mismatched: got: %d want: %d", gotID, nsID) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() const nsName = "test-batch" var nsID int b.CreateNamespace(nsName, &nsID) if err := b.Execute(); err != nil { t.Fatal(err) } var nsIDs map[string]int b.Namespaces(&nsIDs) if err := b.Execute(); err != nil { t.Fatal(err) } gotID, ok := nsIDs[nsName] if !ok { t.Fatalf("not fount %s namespace ID", nsName) } if gotID != nsID { t.Fatalf("nsID mismatched: got: %d want: %d", gotID, nsID) } }) }) } } func testOptions(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Option", func(t *testing.T) { tests := map[string]struct { name string want interface{} }{ "background": { name: "background", want: "dark", }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { var got interface{} if err := v.Option(tt.name, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { b := v.NewBatch() var got interface{} b.Option(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } }) t.Run("SetOption", func(t *testing.T) { tests := map[string]struct { name string value interface{} want interface{} }{ "background": { name: "background", want: "light", }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if err := v.SetOption(tt.name, tt.want); err != nil { t.Fatal(err) } var got interface{} if err := v.Option(tt.name, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { b := v.NewBatch() b.SetOption(tt.name, tt.want) if err := b.Execute(); err != nil { t.Fatal(err) } var got interface{} b.Option(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } }) t.Run("OptionInfo", func(t *testing.T) { tests := map[string]struct { name string want *OptionInfo }{ "filetype": { name: "filetype", want: &OptionInfo{ Name: "filetype", ShortName: "ft", Type: "string", Default: "", WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "buf", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "cmdheight": { name: "cmdheight", want: &OptionInfo{ Name: "cmdheight", ShortName: "ch", Type: "number", Default: int64(1), WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "hidden": { name: "hidden", want: &OptionInfo{ Name: "hidden", ShortName: "hid", Type: "boolean", Default: true, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } got, err := v.OptionInfo(tt.name) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } b := v.NewBatch() var got OptionInfo b.OptionInfo(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, &got) { t.Fatalf("got %#v but want %#v", &got, tt.want) } }) } }) } } func testAllOptionsInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { want := &OptionInfo{ Name: "", ShortName: "", Type: "", Default: nil, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "", GlobalLocal: false, CommaList: false, FlagList: false, } got, err := v.AllOptionsInfo() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, got) { t.Fatalf("got %v but want %v", got, want) } b := v.NewBatch() var got2 OptionInfo b.AllOptionsInfo(&got2) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(want, &got2) { t.Fatalf("got %v but want %v", got2, want) } } } func testOptionsInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { tests := map[string]struct { name string want *OptionInfo }{ "filetype": { name: "filetype", want: &OptionInfo{ Name: "filetype", ShortName: "ft", Type: "string", Default: "", WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "buf", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "cmdheight": { name: "cmdheight", want: &OptionInfo{ Name: "cmdheight", ShortName: "ch", Type: "number", Default: int64(1), WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, "hidden": { name: "hidden", want: &OptionInfo{ Name: "hidden", ShortName: "hid", Type: "boolean", Default: true, WasSet: false, LastSetSid: 0, LastSetLinenr: 0, LastSetChan: 0, Scope: "global", GlobalLocal: false, CommaList: false, FlagList: false, }, }, } for name, tt := range tests { t.Run("Nvim/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } got, err := v.OptionInfo(tt.name) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, got) { t.Fatalf("got %#v but want %#v", got, tt.want) } }) } for name, tt := range tests { t.Run("Batch/"+name, func(t *testing.T) { if name == "hidden" { skipVersion(t, "v0.6.0") } b := v.NewBatch() var got OptionInfo b.OptionInfo(tt.name, &got) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(tt.want, &got) { t.Fatalf("got %#v but want %#v", &got, tt.want) } }) } } } // TODO(zchee): correct testcase func testTerm(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { buf, err := v.CreateBuffer(true, true) if err != nil { t.Fatal(err) } cfg := &WindowConfig{ Relative: "editor", Width: 79, Height: 31, Row: 1, Col: 1, } if _, err := v.OpenWindow(buf, false, cfg); err != nil { t.Fatal(err) } termID, err := v.OpenTerm(buf, make(map[string]interface{})) if err != nil { t.Fatal(err) } data := "\x1b[38;2;00;00;255mTRUECOLOR\x1b[0m" if err := v.Call("chansend", nil, termID, data); err != nil { t.Fatal(err) } }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() var buf Buffer b.CreateBuffer(true, true, &buf) if err := b.Execute(); err != nil { t.Fatal(err) } cfg := &WindowConfig{ Relative: "editor", Width: 79, Height: 31, Row: 1, Col: 1, } var win Window b.OpenWindow(buf, false, cfg, &win) var termID int b.OpenTerm(buf, make(map[string]interface{}), &termID) if err := b.Execute(); err != nil { t.Fatal(err) } data := "\x1b[38;2;00;00;255mTRUECOLOR\x1b[0m" b.Call("chansend", nil, termID, data) if err := b.Execute(); err != nil { t.Fatal(err) } }) } } func testChannelClientInfo(v *Nvim) func(*testing.T) { return func(t *testing.T) { const clientNamePrefix = "testClient" var ( clientVersion = ClientVersion{ Major: 1, Minor: 2, Patch: 3, Prerelease: "-dev", Commit: "e07b9dde387bc817d36176bbe1ce58acd3c81921", } clientType = RemoteClientType clientMethods = map[string]*ClientMethod{ "foo": { Async: true, NArgs: ClientMethodNArgs{ Min: 0, Max: 1, }, }, "bar": { Async: false, NArgs: ClientMethodNArgs{ Min: 0, Max: 0, }, }, } clientAttributes = ClientAttributes{ ClientAttributeKeyLicense: "Apache-2.0", } ) t.Run("Nvim", func(t *testing.T) { clientName := clientNamePrefix + "Nvim" t.Run("SetClientInfo", func(t *testing.T) { if err := v.SetClientInfo(clientName, clientVersion, clientType, clientMethods, clientAttributes); err != nil { t.Fatal(err) } }) t.Run("ChannelInfo", func(t *testing.T) { wantClient := &Client{ Name: clientName, Version: clientVersion, Type: clientType, Methods: clientMethods, Attributes: clientAttributes, } wantChannel := &Channel{ Stream: "stdio", Mode: "rpc", Client: wantClient, } gotChannel, err := v.ChannelInfo(int(channelID)) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotChannel, wantChannel) { t.Fatalf("got %#v channel but want %#v channel", gotChannel, wantChannel) } }) }) t.Run("Batch", func(t *testing.T) { b := v.NewBatch() clientName := clientNamePrefix + "Batch" t.Run("SetClientInfo", func(t *testing.T) { b.SetClientInfo(clientName, clientVersion, clientType, clientMethods, clientAttributes) if err := b.Execute(); err != nil { t.Fatal(err) } }) t.Run("ChannelInfo", func(t *testing.T) { wantClient := &Client{ Name: clientName, Version: clientVersion, Type: clientType, Methods: clientMethods, Attributes: clientAttributes, } wantChannel := &Channel{ Stream: "stdio", Mode: "rpc", Client: wantClient, } var gotChannel Channel b.ChannelInfo(int(channelID), &gotChannel) if err := b.Execute(); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&gotChannel, wantChannel) { t.Fatalf("got %#v channel but want %#v channel", &gotChannel, wantChannel) } }) }) } } func testUI(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("UIs", func(t *testing.T) { gotUIs, err := v.UIs() if err != nil { t.Fatal(err) } if len(gotUIs) > 0 || gotUIs != nil { t.Fatalf("expected ui empty but non-zero: %#v", gotUIs) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("UIs", func(t *testing.T) { b := v.NewBatch() var gotUIs []*UI b.UIs(&gotUIs) if err := b.Execute(); err != nil { t.Fatal(err) } if len(gotUIs) > 0 || gotUIs != nil { t.Fatalf("expected ui empty but non-zero: %#v", gotUIs) } }) }) } } func testProc(v *Nvim) func(*testing.T) { return func(t *testing.T) { t.Run("Nvim", func(t *testing.T) { t.Run("Proc", func(t *testing.T) { pid := os.Getpid() ppid := os.Getppid() wantProcess := &Process{ Name: "nvim.test", PID: pid, PPID: ppid, } if runtime.GOOS == "windows" { wantProcess.Name = "nvim.test.exe" } gotProc, err := v.Proc(pid) if err != nil { t.Fatal(err) } if gotProc.Name != wantProcess.Name { t.Fatalf("got %s Process.Name but want %s", gotProc.Name, wantProcess.Name) } if gotProc.PID != wantProcess.PID { t.Fatalf("got %d Process.PID but want %d", gotProc.PID, wantProcess.PID) } if gotProc.PPID != wantProcess.PPID { t.Fatalf("got %d Process.PPID but want %d", gotProc.PPID, wantProcess.PPID) } }) }) t.Run("Batch", func(t *testing.T) { t.Run("Proc", func(t *testing.T) { b := v.NewBatch() pid := os.Getpid() ppid := os.Getppid() wantProcess := &Process{ Name: "nvim.test", PID: pid, PPID: ppid, } if runtime.GOOS == "windows" { wantProcess.Name = "nvim.test.exe" } var gotProc Process b.Proc(pid, &gotProc) if err := b.Execute(); err != nil { t.Fatal(err) } if gotProc.Name != wantProcess.Name { t.Fatalf("got %s Process.Name but want %s", gotProc.Name, wantProcess.Name) } if gotProc.PID != wantProcess.PID { t.Fatalf("got %d Process.PID but want %d", gotProc.PID, wantProcess.PID) } if gotProc.PPID != wantProcess.PPID { t.Fatalf("got %d Process.PPID but want %d", gotProc.PPID, wantProcess.PPID) } }) }) } }
// Copyright 2017 The Serulian 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 grok import ( "fmt" "log" "github.com/serulian/compiler/compilercommon" "github.com/serulian/compiler/compilerutil" "github.com/serulian/compiler/formatter" "github.com/serulian/compiler/packageloader" "github.com/serulian/compiler/parser" "github.com/serulian/compiler/vcs" ) const shortSHALength = 7 // AllActions defines the set of all actions supported by Grok. var AllActions = []string{string(NoAction), string(FreezeImport), string(UnfreezeImport)} // ExecuteAction executes an action as defined by GetContextActions. func (gh Handle) ExecuteAction(action Action, params map[string]interface{}, source compilercommon.InputSource) error { switch action { case NoAction: return nil case FreezeImport: importSource, hasImportSource := params["import-source"] if !hasImportSource { return fmt.Errorf("Missing import source") } tag, hasTag := params["tag"] commit, hasCommit := params["commit"] commitOrTag := formatter.Tag("0.0.0") if hasTag { commitOrTag = formatter.Tag(tag.(string)) } else if hasCommit { commitOrTag = formatter.Commit(commit.(string)) } else { return fmt.Errorf("Missing commit or tag") } if !formatter.FreezeAt(string(source), importSource.(string), commitOrTag, gh.groker.vcsDevelopmentDirectories, false) { return fmt.Errorf("Could not freeze import") } return nil case UnfreezeImport: importSource, hasImportSource := params["import-source"] if !hasImportSource { return fmt.Errorf("Missing import source") } if !formatter.UnfreezeAt(string(source), importSource.(string), gh.groker.vcsDevelopmentDirectories, false) { return fmt.Errorf("Could not unfreeze import") } return nil default: return fmt.Errorf("Unknown action: %v", action) } } // GetActionsForPosition returns all asynchronous code actions for the given source position. Unlike GetContextActions, the // returns items must *all* be actions, and should be displayed in a selector menu, rather than inline in the code. func (gh Handle) GetActionsForPosition(source compilercommon.InputSource, lineNumber int, colPosition int) ([]ContextOrAction, error) { // Note: We cannot use PositionFromLineAndColumn here, as it will lookup the position in the *tracked* source, which // may be different than the current live source. liveRune, err := gh.scopeResult.SourceTracker.LineAndColToRunePosition(lineNumber, colPosition, source, compilercommon.SourceMapCurrent) if err != nil { return []ContextOrAction{}, err } sourcePosition := source.PositionForRunePosition(liveRune, gh.scopeResult.SourceTracker) return gh.GetPositionalActions(sourcePosition) } // GetPositionalActions returns all asynchronous code actions for the given source position. Unlike GetContextActions, the // returns items must *all* be actions, and should be displayed in a selector menu, rather than inline in the code. func (gh Handle) GetPositionalActions(sourcePosition compilercommon.SourcePosition) ([]ContextOrAction, error) { updatedPosition, err := gh.scopeResult.SourceTracker.GetPositionOffset(sourcePosition, packageloader.CurrentFilePosition) if err != nil { return []ContextOrAction{}, err } // Create a set of async actions for every import statement in the file that comes from VCS. source := sourcePosition.Source() module, found := gh.scopeResult.Graph.SourceGraph().FindModuleBySource(source) if !found { return []ContextOrAction{}, fmt.Errorf("Invalid or non-SRG source file") } imports := module.GetImports() actions := make([]ContextOrAction, 0, len(imports)) for _, srgImport := range imports { // Make sure the import has a valid source range. sourceRange, hasSourceRange := srgImport.SourceRange() if !hasSourceRange { continue } // Make sure the import's range contains the position. containsPosition, err := sourceRange.ContainsPosition(updatedPosition) if err != nil || !containsPosition { continue } // Parse the import's source and its source kind from the import string. importSource, kind, err := srgImport.ParsedSource() if err != nil { continue } // Make sure this import is pulling from VCS. if kind != parser.ParsedImportTypeVCS { continue } // Parse the VCS path to determine if this import is a HEAD reference, a branch/commit, or a tag. parsed, err := vcs.ParseVCSPath(importSource) if err != nil { log.Printf("Got error when parsing VCS path `%s`: %v", importSource, err) continue } // Inspect the VCS source to determine the commit information and tags available. inspectInfo, err := gh.getInspectInfo(importSource, source) if err != nil { log.Printf("Got error when inspecting VCS path `%s`: %v", importSource, err) continue } // Add an upgrade/update command (if applicable) updateTitle := "Update" updateVersion, err := compilerutil.SemanticUpdateVersion(parsed.Tag(), inspectInfo.Tags, compilerutil.UpdateVersionMinor) if err != nil { updateTitle = "Upgrade" updateVersion, err = compilerutil.SemanticUpdateVersion("0.0.0", inspectInfo.Tags, compilerutil.UpdateVersionMajor) } if err == nil && updateVersion != "" && updateVersion != "0.0.0" { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: fmt.Sprintf("%s import to %s", updateTitle, updateVersion), Action: FreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), "tag": updateVersion, }, }) } // Add a freeze/unfreeze command. if parsed.Tag() != "" || parsed.BranchOrCommit() != "" { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: "Unfreeze import to HEAD", Action: UnfreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), }, }) } else if len(inspectInfo.CommitSHA) >= shortSHALength { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: "Freeze import at " + inspectInfo.CommitSHA[0:shortSHALength], Action: FreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), "commit": inspectInfo.CommitSHA, }, }) } } return actions, nil } // GetContextActions returns all context actions for the given source file. func (gh Handle) GetContextActions(source compilercommon.InputSource) ([]CodeContextOrAction, error) { module, found := gh.scopeResult.Graph.SourceGraph().FindModuleBySource(source) if !found { return []CodeContextOrAction{}, fmt.Errorf("Invalid or non-SRG source file") } // Create a CodeContextOrAction for every import statement in the file that comes from VCS. imports := module.GetImports() cca := make([]CodeContextOrAction, 0, len(imports)) for _, srgImport := range imports { // Make sure the import has a valid source range. sourceRange, hasSourceRange := srgImport.SourceRange() if !hasSourceRange { continue } // Parse the import's source and its source kind from the import string. importSource, kind, err := srgImport.ParsedSource() if err != nil { continue } // Make sure this import is pulling from VCS. if kind != parser.ParsedImportTypeVCS { continue } // Add Context to show the current commit SHA. cca = append(cca, CodeContextOrAction{ Range: sourceRange, Resolve: func() (ContextOrAction, bool) { inspectInfo, err := gh.getInspectInfo(importSource, source) if err != nil { return ContextOrAction{}, false } if len(inspectInfo.CommitSHA) < shortSHALength { return ContextOrAction{}, false } return ContextOrAction{ Range: sourceRange, Title: inspectInfo.CommitSHA[0:shortSHALength] + " (" + inspectInfo.Engine + ")", Action: NoAction, ActionParams: map[string]interface{}{}, }, true }, }) } // Create a CodeContextOrAction for every type member that overrides that composed from an agent. for _, srgTypeDecl := range module.GetTypes() { if !srgTypeDecl.HasComposedAgents() { continue } // Find the type in the type graph. typeDecl, hasTypeDecl := gh.scopeResult.Graph.TypeGraph().GetTypeOrModuleForSourceNode(srgTypeDecl.GraphNode) if !hasTypeDecl { continue } for _, member := range typeDecl.Members() { sourceRange, hasSourceRange := member.SourceRange() if !hasSourceRange { continue } shadowsMembers := member.ShadowsMembers() if len(shadowsMembers) == 0 { continue } cca = append(cca, CodeContextOrAction{ Range: sourceRange.AtStartPosition(), Resolve: func() (ContextOrAction, bool) { return ContextOrAction{ Range: sourceRange.AtStartPosition(), Title: fmt.Sprintf("Shadows %v members", len(shadowsMembers)), Action: NoAction, ActionParams: map[string]interface{}{}, }, true }, }) } } return cca, nil } // getInspectInfo returns the VCS inspection information for the given import source, referenced under the given // source file. func (gh Handle) getInspectInfo(importSource string, source compilercommon.InputSource) (vcs.InspectInfo, error) { // First check the cache, indexed by the import source. cached, hasCached := gh.importInspectCache.Get(importSource) if hasCached { return cached.(vcs.InspectInfo), nil } // If not found, retrieve it via the VCS engine. dirPath := gh.groker.pathLoader.VCSPackageDirectory(gh.groker.entrypoint) inspectInfo, _, err := vcs.PerformVCSCheckoutAndInspect(importSource, dirPath, vcs.VCSAlwaysUseCache) if err != nil { return vcs.InspectInfo{}, nil } gh.importInspectCache.Set(importSource, inspectInfo) return inspectInfo, nil } Always return a command for SHA inspection We encapsulate the error into the returned command, to ensure better user experience // Copyright 2017 The Serulian 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 grok import ( "fmt" "log" "github.com/serulian/compiler/compilercommon" "github.com/serulian/compiler/compilerutil" "github.com/serulian/compiler/formatter" "github.com/serulian/compiler/packageloader" "github.com/serulian/compiler/parser" "github.com/serulian/compiler/vcs" ) const shortSHALength = 7 // AllActions defines the set of all actions supported by Grok. var AllActions = []string{string(NoAction), string(FreezeImport), string(UnfreezeImport)} // ExecuteAction executes an action as defined by GetContextActions. func (gh Handle) ExecuteAction(action Action, params map[string]interface{}, source compilercommon.InputSource) error { switch action { case NoAction: return nil case FreezeImport: importSource, hasImportSource := params["import-source"] if !hasImportSource { return fmt.Errorf("Missing import source") } tag, hasTag := params["tag"] commit, hasCommit := params["commit"] commitOrTag := formatter.Tag("0.0.0") if hasTag { commitOrTag = formatter.Tag(tag.(string)) } else if hasCommit { commitOrTag = formatter.Commit(commit.(string)) } else { return fmt.Errorf("Missing commit or tag") } if !formatter.FreezeAt(string(source), importSource.(string), commitOrTag, gh.groker.vcsDevelopmentDirectories, false) { return fmt.Errorf("Could not freeze import") } return nil case UnfreezeImport: importSource, hasImportSource := params["import-source"] if !hasImportSource { return fmt.Errorf("Missing import source") } if !formatter.UnfreezeAt(string(source), importSource.(string), gh.groker.vcsDevelopmentDirectories, false) { return fmt.Errorf("Could not unfreeze import") } return nil default: return fmt.Errorf("Unknown action: %v", action) } } // GetActionsForPosition returns all asynchronous code actions for the given source position. Unlike GetContextActions, the // returns items must *all* be actions, and should be displayed in a selector menu, rather than inline in the code. func (gh Handle) GetActionsForPosition(source compilercommon.InputSource, lineNumber int, colPosition int) ([]ContextOrAction, error) { // Note: We cannot use PositionFromLineAndColumn here, as it will lookup the position in the *tracked* source, which // may be different than the current live source. liveRune, err := gh.scopeResult.SourceTracker.LineAndColToRunePosition(lineNumber, colPosition, source, compilercommon.SourceMapCurrent) if err != nil { return []ContextOrAction{}, err } sourcePosition := source.PositionForRunePosition(liveRune, gh.scopeResult.SourceTracker) return gh.GetPositionalActions(sourcePosition) } // GetPositionalActions returns all asynchronous code actions for the given source position. Unlike GetContextActions, the // returns items must *all* be actions, and should be displayed in a selector menu, rather than inline in the code. func (gh Handle) GetPositionalActions(sourcePosition compilercommon.SourcePosition) ([]ContextOrAction, error) { updatedPosition, err := gh.scopeResult.SourceTracker.GetPositionOffset(sourcePosition, packageloader.CurrentFilePosition) if err != nil { return []ContextOrAction{}, err } // Create a set of async actions for every import statement in the file that comes from VCS. source := sourcePosition.Source() module, found := gh.scopeResult.Graph.SourceGraph().FindModuleBySource(source) if !found { return []ContextOrAction{}, fmt.Errorf("Invalid or non-SRG source file") } imports := module.GetImports() actions := make([]ContextOrAction, 0, len(imports)) for _, srgImport := range imports { // Make sure the import has a valid source range. sourceRange, hasSourceRange := srgImport.SourceRange() if !hasSourceRange { continue } // Make sure the import's range contains the position. containsPosition, err := sourceRange.ContainsPosition(updatedPosition) if err != nil || !containsPosition { continue } // Parse the import's source and its source kind from the import string. importSource, kind, err := srgImport.ParsedSource() if err != nil { continue } // Make sure this import is pulling from VCS. if kind != parser.ParsedImportTypeVCS { continue } // Parse the VCS path to determine if this import is a HEAD reference, a branch/commit, or a tag. parsed, err := vcs.ParseVCSPath(importSource) if err != nil { log.Printf("Got error when parsing VCS path `%s`: %v", importSource, err) continue } // Inspect the VCS source to determine the commit information and tags available. inspectInfo, err := gh.getInspectInfo(importSource, source) if err != nil { log.Printf("Got error when inspecting VCS path `%s`: %v", importSource, err) continue } // Add an upgrade/update command (if applicable) updateTitle := "Update" updateVersion, err := compilerutil.SemanticUpdateVersion(parsed.Tag(), inspectInfo.Tags, compilerutil.UpdateVersionMinor) if err != nil { updateTitle = "Upgrade" updateVersion, err = compilerutil.SemanticUpdateVersion("0.0.0", inspectInfo.Tags, compilerutil.UpdateVersionMajor) } if err == nil && updateVersion != "" && updateVersion != "0.0.0" { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: fmt.Sprintf("%s import to %s", updateTitle, updateVersion), Action: FreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), "tag": updateVersion, }, }) } // Add a freeze/unfreeze command. if parsed.Tag() != "" || parsed.BranchOrCommit() != "" { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: "Unfreeze import to HEAD", Action: UnfreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), }, }) } else if len(inspectInfo.CommitSHA) >= shortSHALength { actions = append(actions, ContextOrAction{ Range: sourceRange, Title: "Freeze import at " + inspectInfo.CommitSHA[0:shortSHALength], Action: FreezeImport, ActionParams: map[string]interface{}{ "source": string(source), "import-source": parsed.URL(), "commit": inspectInfo.CommitSHA, }, }) } } return actions, nil } // GetContextActions returns all context actions for the given source file. func (gh Handle) GetContextActions(source compilercommon.InputSource) ([]CodeContextOrAction, error) { module, found := gh.scopeResult.Graph.SourceGraph().FindModuleBySource(source) if !found { return []CodeContextOrAction{}, fmt.Errorf("Invalid or non-SRG source file") } // Create a CodeContextOrAction for every import statement in the file that comes from VCS. imports := module.GetImports() cca := make([]CodeContextOrAction, 0, len(imports)) for _, srgImport := range imports { // Make sure the import has a valid source range. sourceRange, hasSourceRange := srgImport.SourceRange() if !hasSourceRange { continue } // Parse the import's source and its source kind from the import string. importSource, kind, err := srgImport.ParsedSource() if err != nil { continue } // Make sure this import is pulling from VCS. if kind != parser.ParsedImportTypeVCS { continue } // Add Context to show the current commit SHA. cca = append(cca, CodeContextOrAction{ Range: sourceRange, Resolve: func() (ContextOrAction, bool) { inspectInfo, err := gh.getInspectInfo(importSource, source) if err != nil { return ContextOrAction{ Range: sourceRange, Title: "(Unable to load current commit)", Action: NoAction, ActionParams: map[string]interface{}{}, }, true } if len(inspectInfo.CommitSHA) < shortSHALength { return ContextOrAction{ Range: sourceRange, Title: "(Unable to load current commit)", Action: NoAction, ActionParams: map[string]interface{}{}, }, true } return ContextOrAction{ Range: sourceRange, Title: inspectInfo.CommitSHA[0:shortSHALength] + " (" + inspectInfo.Engine + ")", Action: NoAction, ActionParams: map[string]interface{}{}, }, true }, }) } // Create a CodeContextOrAction for every type member that overrides that composed from an agent. for _, srgTypeDecl := range module.GetTypes() { if !srgTypeDecl.HasComposedAgents() { continue } // Find the type in the type graph. typeDecl, hasTypeDecl := gh.scopeResult.Graph.TypeGraph().GetTypeOrModuleForSourceNode(srgTypeDecl.GraphNode) if !hasTypeDecl { continue } for _, member := range typeDecl.Members() { sourceRange, hasSourceRange := member.SourceRange() if !hasSourceRange { continue } shadowsMembers := member.ShadowsMembers() if len(shadowsMembers) == 0 { continue } cca = append(cca, CodeContextOrAction{ Range: sourceRange.AtStartPosition(), Resolve: func() (ContextOrAction, bool) { return ContextOrAction{ Range: sourceRange.AtStartPosition(), Title: fmt.Sprintf("Shadows %v members", len(shadowsMembers)), Action: NoAction, ActionParams: map[string]interface{}{}, }, true }, }) } } return cca, nil } // getInspectInfo returns the VCS inspection information for the given import source, referenced under the given // source file. func (gh Handle) getInspectInfo(importSource string, source compilercommon.InputSource) (vcs.InspectInfo, error) { // First check the cache, indexed by the import source. cached, hasCached := gh.importInspectCache.Get(importSource) if hasCached { return cached.(vcs.InspectInfo), nil } // If not found, retrieve it via the VCS engine. dirPath := gh.groker.pathLoader.VCSPackageDirectory(gh.groker.entrypoint) inspectInfo, _, err := vcs.PerformVCSCheckoutAndInspect(importSource, dirPath, vcs.VCSAlwaysUseCache) if err != nil { return vcs.InspectInfo{}, nil } gh.importInspectCache.Set(importSource, inspectInfo) return inspectInfo, nil }
package bundlecollection import boshsys "bosh/system" // e.g. Job, Package type BundleDefinition interface { BundleName() string BundleVersion() string } // BundleCollection is responsible for managing multiple bundles // where bundles can be installed and then enabled. // e.g. Used to manage currently installed/enabled jobs and packages. type BundleCollectionOld interface { // Instead of returning filesys/path it would be nice // to return a Directory object that would really represent // some location (s3 bucket, fs, etc.) Install(defintion BundleDefinition) (boshsys.FileSystem, string, error) GetDir(defintion BundleDefinition) (fs boshsys.FileSystem, path string, err error) Enable(defintion BundleDefinition) error } type BundleCollection interface { Get(defintion BundleDefinition) (bundle Bundle, err error) } type Bundle interface { Install() (fs boshsys.FileSystem, path string, err error) GetInstallPath() (fs boshsys.FileSystem, path string, err error) Enable() (fs boshsys.FileSystem, path string, err error) Disable() (err error) } remove BundleCollectionOld package bundlecollection import boshsys "bosh/system" // e.g. Job, Package type BundleDefinition interface { BundleName() string BundleVersion() string } type BundleCollection interface { Get(defintion BundleDefinition) (bundle Bundle, err error) } type Bundle interface { Install() (fs boshsys.FileSystem, path string, err error) GetInstallPath() (fs boshsys.FileSystem, path string, err error) Enable() (fs boshsys.FileSystem, path string, err error) Disable() (err error) }
// Package b2 provides an interface to the Backblaze B2 object storage system package b2 // FIXME should we remove sha1 checks from here as rclone now supports // checking SHA1s? import ( "bufio" "bytes" "crypto/sha1" "fmt" gohash "hash" "io" "net/http" "path" "regexp" "strconv" "strings" "sync" "time" "github.com/ncw/rclone/backend/b2/api" "github.com/ncw/rclone/fs" "github.com/ncw/rclone/fs/accounting" "github.com/ncw/rclone/fs/config/configmap" "github.com/ncw/rclone/fs/config/configstruct" "github.com/ncw/rclone/fs/fserrors" "github.com/ncw/rclone/fs/fshttp" "github.com/ncw/rclone/fs/hash" "github.com/ncw/rclone/fs/walk" "github.com/ncw/rclone/lib/pacer" "github.com/ncw/rclone/lib/rest" "github.com/pkg/errors" ) const ( defaultEndpoint = "https://api.backblazeb2.com" headerPrefix = "x-bz-info-" // lower case as that is what the server returns timeKey = "src_last_modified_millis" timeHeader = headerPrefix + timeKey sha1Key = "large_file_sha1" sha1Header = "X-Bz-Content-Sha1" sha1InfoHeader = headerPrefix + sha1Key testModeHeader = "X-Bz-Test-Mode" retryAfterHeader = "Retry-After" minSleep = 10 * time.Millisecond maxSleep = 5 * time.Minute decayConstant = 1 // bigger for slower decay, exponential maxParts = 10000 maxVersions = 100 // maximum number of versions we search in --b2-versions mode minChunkSize = 5 * fs.MebiByte defaultChunkSize = 96 * fs.MebiByte defaultUploadCutoff = 200 * fs.MebiByte ) // Globals var ( errNotWithVersions = errors.New("can't modify or delete files in --b2-versions mode") ) // Register with Fs func init() { fs.Register(&fs.RegInfo{ Name: "b2", Description: "Backblaze B2", NewFs: NewFs, Options: []fs.Option{{ Name: "account", Help: "Account ID or Application Key ID", Required: true, }, { Name: "key", Help: "Application Key", Required: true, }, { Name: "endpoint", Help: "Endpoint for the service.\nLeave blank normally.", Advanced: true, }, { Name: "test_mode", Help: `A flag string for X-Bz-Test-Mode header for debugging. This is for debugging purposes only. Setting it to one of the strings below will cause b2 to return specific errors: * "fail_some_uploads" * "expire_some_account_authorization_tokens" * "force_cap_exceeded" These will be set in the "X-Bz-Test-Mode" header which is documented in the [b2 integrations checklist](https://www.backblaze.com/b2/docs/integration_checklist.html).`, Default: "", Hide: fs.OptionHideConfigurator, Advanced: true, }, { Name: "versions", Help: "Include old versions in directory listings.\nNote that when using this no file write operations are permitted,\nso you can't upload files or delete them.", Default: false, Advanced: true, }, { Name: "hard_delete", Help: "Permanently delete files on remote removal, otherwise hide files.", Default: false, }, { Name: "upload_cutoff", Help: `Cutoff for switching to chunked upload. Files above this size will be uploaded in chunks of "--b2-chunk-size". This value should be set no larger than 4.657GiB (== 5GB).`, Default: defaultUploadCutoff, Advanced: true, }, { Name: "chunk_size", Help: `Upload chunk size. Must fit in memory. When uploading large files, chunk the file into this size. Note that these chunks are buffered in memory and there might a maximum of "--transfers" chunks in progress at once. 5,000,000 Bytes is the minimum size.`, Default: defaultChunkSize, Advanced: true, }, { Name: "disable_checksum", Help: `Disable checksums for large (> upload cutoff) files`, Default: false, Advanced: true, }, { Name: "download_url", Help: `Custom endpoint for downloads. This is usually set to a Cloudflare CDN URL as Backblaze offers free egress for data downloaded through the Cloudflare network. Leave blank if you want to use the endpoint provided by Backblaze.`, Advanced: true, }}, }) } // Options defines the configuration for this backend type Options struct { Account string `config:"account"` Key string `config:"key"` Endpoint string `config:"endpoint"` TestMode string `config:"test_mode"` Versions bool `config:"versions"` HardDelete bool `config:"hard_delete"` UploadCutoff fs.SizeSuffix `config:"upload_cutoff"` ChunkSize fs.SizeSuffix `config:"chunk_size"` DisableCheckSum bool `config:"disable_checksum"` DownloadURL string `config:"download_url"` } // Fs represents a remote b2 server type Fs struct { name string // name of this remote root string // the path we are working on if any opt Options // parsed config options features *fs.Features // optional features srv *rest.Client // the connection to the b2 server bucket string // the bucket we are working on bucketOKMu sync.Mutex // mutex to protect bucket OK bucketOK bool // true if we have created the bucket bucketIDMutex sync.Mutex // mutex to protect _bucketID _bucketID string // the ID of the bucket we are working on info api.AuthorizeAccountResponse // result of authorize call uploadMu sync.Mutex // lock for upload variable uploads []*api.GetUploadURLResponse // result of get upload URL calls authMu sync.Mutex // lock for authorizing the account pacer *fs.Pacer // To pace and retry the API calls bufferTokens chan []byte // control concurrency of multipart uploads } // Object describes a b2 object type Object struct { fs *Fs // what this object is part of remote string // The remote path id string // b2 id of the file modTime time.Time // The modified time of the object if known sha1 string // SHA-1 hash if known size int64 // Size of the object mimeType string // Content-Type of the object } // ------------------------------------------------------------ // Name of the remote (as passed into NewFs) func (f *Fs) Name() string { return f.name } // Root of the remote (as passed into NewFs) func (f *Fs) Root() string { if f.root == "" { return f.bucket } return f.bucket + "/" + f.root } // String converts this Fs to a string func (f *Fs) String() string { if f.root == "" { return fmt.Sprintf("B2 bucket %s", f.bucket) } return fmt.Sprintf("B2 bucket %s path %s", f.bucket, f.root) } // Features returns the optional features of this Fs func (f *Fs) Features() *fs.Features { return f.features } // Pattern to match a b2 path var matcher = regexp.MustCompile(`^/*([^/]*)(.*)$`) // parseParse parses a b2 'url' func parsePath(path string) (bucket, directory string, err error) { parts := matcher.FindStringSubmatch(path) if parts == nil { err = errors.Errorf("couldn't find bucket in b2 path %q", path) } else { bucket, directory = parts[1], parts[2] directory = strings.Trim(directory, "/") } return } // retryErrorCodes is a slice of error codes that we will retry var retryErrorCodes = []int{ 401, // Unauthorized (eg "Token has expired") 408, // Request Timeout 429, // Rate exceeded. 500, // Get occasional 500 Internal Server Error 503, // Service Unavailable 504, // Gateway Time-out } // shouldRetryNoAuth returns a boolean as to whether this resp and err // deserve to be retried. It returns the err as a convenience func (f *Fs) shouldRetryNoReauth(resp *http.Response, err error) (bool, error) { // For 429 or 503 errors look at the Retry-After: header and // set the retry appropriately, starting with a minimum of 1 // second if it isn't set. if resp != nil && (resp.StatusCode == 429 || resp.StatusCode == 503) { var retryAfter = 1 retryAfterString := resp.Header.Get(retryAfterHeader) if retryAfterString != "" { var err error retryAfter, err = strconv.Atoi(retryAfterString) if err != nil { fs.Errorf(f, "Malformed %s header %q: %v", retryAfterHeader, retryAfterString, err) } } return true, pacer.RetryAfterError(err, time.Duration(retryAfter)*time.Second) } return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err } // shouldRetry returns a boolean as to whether this resp and err // deserve to be retried. It returns the err as a convenience func (f *Fs) shouldRetry(resp *http.Response, err error) (bool, error) { if resp != nil && resp.StatusCode == 401 { fs.Debugf(f, "Unauthorized: %v", err) // Reauth authErr := f.authorizeAccount() if authErr != nil { err = authErr } return true, err } return f.shouldRetryNoReauth(resp, err) } // errorHandler parses a non 2xx error response into an error func errorHandler(resp *http.Response) error { // Decode error response errResponse := new(api.Error) err := rest.DecodeJSON(resp, &errResponse) if err != nil { fs.Debugf(nil, "Couldn't decode error response: %v", err) } if errResponse.Code == "" { errResponse.Code = "unknown" } if errResponse.Status == 0 { errResponse.Status = resp.StatusCode } if errResponse.Message == "" { errResponse.Message = "Unknown " + resp.Status } return errResponse } func checkUploadChunkSize(cs fs.SizeSuffix) error { if cs < minChunkSize { return errors.Errorf("%s is less than %s", cs, minChunkSize) } return nil } func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) { err = checkUploadChunkSize(cs) if err == nil { old, f.opt.ChunkSize = f.opt.ChunkSize, cs f.fillBufferTokens() // reset the buffer tokens } return } func checkUploadCutoff(opt *Options, cs fs.SizeSuffix) error { if cs < opt.ChunkSize { return errors.Errorf("%v is less than chunk size %v", cs, opt.ChunkSize) } return nil } func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) { err = checkUploadCutoff(&f.opt, cs) if err == nil { old, f.opt.UploadCutoff = f.opt.UploadCutoff, cs } return } // NewFs constructs an Fs from the path, bucket:path func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } err = checkUploadCutoff(opt, opt.UploadCutoff) if err != nil { return nil, errors.Wrap(err, "b2: upload cutoff") } err = checkUploadChunkSize(opt.ChunkSize) if err != nil { return nil, errors.Wrap(err, "b2: chunk size") } bucket, directory, err := parsePath(root) if err != nil { return nil, err } if opt.Account == "" { return nil, errors.New("account not found") } if opt.Key == "" { return nil, errors.New("key not found") } if opt.Endpoint == "" { opt.Endpoint = defaultEndpoint } f := &Fs{ name: name, opt: *opt, bucket: bucket, root: directory, srv: rest.NewClient(fshttp.NewClient(fs.Config)).SetErrorHandler(errorHandler), pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))), } f.features = (&fs.Features{ ReadMimeType: true, WriteMimeType: true, BucketBased: true, }).Fill(f) // Set the test flag if required if opt.TestMode != "" { testMode := strings.TrimSpace(opt.TestMode) f.srv.SetHeader(testModeHeader, testMode) fs.Debugf(f, "Setting test header \"%s: %s\"", testModeHeader, testMode) } f.fillBufferTokens() err = f.authorizeAccount() if err != nil { return nil, errors.Wrap(err, "failed to authorize account") } // If this is a key limited to a single bucket, it must exist already if f.bucket != "" && f.info.Allowed.BucketID != "" { allowedBucket := f.info.Allowed.BucketName if allowedBucket == "" { return nil, errors.New("bucket that application key is restricted to no longer exists") } if allowedBucket != f.bucket { return nil, errors.Errorf("you must use bucket %q with this application key", allowedBucket) } f.markBucketOK() f.setBucketID(f.info.Allowed.BucketID) } if f.root != "" { f.root += "/" // Check to see if the (bucket,directory) is actually an existing file oldRoot := f.root remote := path.Base(directory) f.root = path.Dir(directory) if f.root == "." { f.root = "" } else { f.root += "/" } _, err := f.NewObject(remote) if err != nil { if err == fs.ErrorObjectNotFound { // File doesn't exist so return old f f.root = oldRoot return f, nil } return nil, err } // return an error with an fs which points to the parent return f, fs.ErrorIsFile } return f, nil } // authorizeAccount gets the API endpoint and auth token. Can be used // for reauthentication too. func (f *Fs) authorizeAccount() error { f.authMu.Lock() defer f.authMu.Unlock() opts := rest.Opts{ Method: "GET", Path: "/b2api/v1/b2_authorize_account", RootURL: f.opt.Endpoint, UserName: f.opt.Account, Password: f.opt.Key, ExtraHeaders: map[string]string{"Authorization": ""}, // unset the Authorization for this request } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, nil, &f.info) return f.shouldRetryNoReauth(resp, err) }) if err != nil { return errors.Wrap(err, "failed to authenticate") } f.srv.SetRoot(f.info.APIURL+"/b2api/v1").SetHeader("Authorization", f.info.AuthorizationToken) return nil } // getUploadURL returns the upload info with the UploadURL and the AuthorizationToken // // This should be returned with returnUploadURL when finished func (f *Fs) getUploadURL() (upload *api.GetUploadURLResponse, err error) { f.uploadMu.Lock() defer f.uploadMu.Unlock() bucketID, err := f.getBucketID() if err != nil { return nil, err } if len(f.uploads) == 0 { opts := rest.Opts{ Method: "POST", Path: "/b2_get_upload_url", } var request = api.GetUploadURLRequest{ BucketID: bucketID, } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &upload) return f.shouldRetry(resp, err) }) if err != nil { return nil, errors.Wrap(err, "failed to get upload URL") } } else { upload, f.uploads = f.uploads[0], f.uploads[1:] } return upload, nil } // returnUploadURL returns the UploadURL to the cache func (f *Fs) returnUploadURL(upload *api.GetUploadURLResponse) { if upload == nil { return } f.uploadMu.Lock() f.uploads = append(f.uploads, upload) f.uploadMu.Unlock() } // clearUploadURL clears the current UploadURL and the AuthorizationToken func (f *Fs) clearUploadURL() { f.uploadMu.Lock() f.uploads = nil f.uploadMu.Unlock() } // Fill up (or reset) the buffer tokens func (f *Fs) fillBufferTokens() { f.bufferTokens = make(chan []byte, fs.Config.Transfers) for i := 0; i < fs.Config.Transfers; i++ { f.bufferTokens <- nil } } // getUploadBlock gets a block from the pool of size chunkSize func (f *Fs) getUploadBlock() []byte { buf := <-f.bufferTokens if buf == nil { buf = make([]byte, f.opt.ChunkSize) } // fs.Debugf(f, "Getting upload block %p", buf) return buf } // putUploadBlock returns a block to the pool of size chunkSize func (f *Fs) putUploadBlock(buf []byte) { buf = buf[:cap(buf)] if len(buf) != int(f.opt.ChunkSize) { panic("bad blocksize returned to pool") } // fs.Debugf(f, "Returning upload block %p", buf) f.bufferTokens <- buf } // Return an Object from a path // // If it can't be found it returns the error fs.ErrorObjectNotFound. func (f *Fs) newObjectWithInfo(remote string, info *api.File) (fs.Object, error) { o := &Object{ fs: f, remote: remote, } if info != nil { err := o.decodeMetaData(info) if err != nil { return nil, err } } else { err := o.readMetaData() // reads info and headers, returning an error if err != nil { return nil, err } } return o, nil } // NewObject finds the Object at remote. If it can't be found // it returns the error fs.ErrorObjectNotFound. func (f *Fs) NewObject(remote string) (fs.Object, error) { return f.newObjectWithInfo(remote, nil) } // listFn is called from list to handle an object type listFn func(remote string, object *api.File, isDirectory bool) error // errEndList is a sentinel used to end the list iteration now. // listFn should return it to end the iteration with no errors. var errEndList = errors.New("end list") // list lists the objects into the function supplied from // the bucket and root supplied // // dir is the starting directory, "" for root // // level is the depth to search to // // If prefix is set then startFileName is used as a prefix which all // files must have // // If limit is > 0 then it limits to that many files (must be less // than 1000) // // If hidden is set then it will list the hidden (deleted) files too. func (f *Fs) list(dir string, recurse bool, prefix string, limit int, hidden bool, fn listFn) error { root := f.root if dir != "" { root += dir + "/" } delimiter := "" if !recurse { delimiter = "/" } bucketID, err := f.getBucketID() if err != nil { return err } chunkSize := 1000 if limit > 0 { chunkSize = limit } var request = api.ListFileNamesRequest{ BucketID: bucketID, MaxFileCount: chunkSize, Prefix: root, Delimiter: delimiter, } prefix = root + prefix if prefix != "" { request.StartFileName = prefix } opts := rest.Opts{ Method: "POST", Path: "/b2_list_file_names", } if hidden { opts.Path = "/b2_list_file_versions" } for { var response api.ListFileNamesResponse err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return err } for i := range response.Files { file := &response.Files[i] // Finish if file name no longer has prefix if prefix != "" && !strings.HasPrefix(file.Name, prefix) { return nil } if !strings.HasPrefix(file.Name, f.root) { fs.Debugf(f, "Odd name received %q", file.Name) continue } remote := file.Name[len(f.root):] // Check for directory isDirectory := strings.HasSuffix(remote, "/") if isDirectory { remote = remote[:len(remote)-1] } // Send object err = fn(remote, file, isDirectory) if err != nil { if err == errEndList { return nil } return err } } // end if no NextFileName if response.NextFileName == nil { break } request.StartFileName = *response.NextFileName if response.NextFileID != nil { request.StartFileID = *response.NextFileID } } return nil } // Convert a list item into a DirEntry func (f *Fs) itemToDirEntry(remote string, object *api.File, isDirectory bool, last *string) (fs.DirEntry, error) { if isDirectory { d := fs.NewDir(remote, time.Time{}) return d, nil } if remote == *last { remote = object.UploadTimestamp.AddVersion(remote) } else { *last = remote } // hide objects represent deleted files which we don't list if object.Action == "hide" { return nil, nil } o, err := f.newObjectWithInfo(remote, object) if err != nil { return nil, err } return o, nil } // mark the bucket as being OK func (f *Fs) markBucketOK() { if f.bucket != "" { f.bucketOKMu.Lock() f.bucketOK = true f.bucketOKMu.Unlock() } } // listDir lists a single directory func (f *Fs) listDir(dir string) (entries fs.DirEntries, err error) { last := "" err = f.list(dir, false, "", 0, f.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { entry, err := f.itemToDirEntry(remote, object, isDirectory, &last) if err != nil { return err } if entry != nil { entries = append(entries, entry) } return nil }) if err != nil { return nil, err } // bucket must be present if listing succeeded f.markBucketOK() return entries, nil } // listBuckets returns all the buckets to out func (f *Fs) listBuckets(dir string) (entries fs.DirEntries, err error) { if dir != "" { return nil, fs.ErrorListBucketRequired } err = f.listBucketsToFn(func(bucket *api.Bucket) error { d := fs.NewDir(bucket.Name, time.Time{}) entries = append(entries, d) return nil }) if err != nil { return nil, err } return entries, nil } // List the objects and directories in dir into entries. The // entries can be returned in any order but should be for a // complete directory. // // dir should be "" to list the root, and should not have // trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. func (f *Fs) List(dir string) (entries fs.DirEntries, err error) { if f.bucket == "" { return f.listBuckets(dir) } return f.listDir(dir) } // ListR lists the objects and directories of the Fs starting // from dir recursively into out. // // dir should be "" to start from the root, and should not // have trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. // // It should call callback for each tranche of entries read. // These need not be returned in any particular order. If // callback returns an error then the listing will stop // immediately. // // Don't implement this unless you have a more efficient way // of listing recursively that doing a directory traversal. func (f *Fs) ListR(dir string, callback fs.ListRCallback) (err error) { if f.bucket == "" { return fs.ErrorListBucketRequired } list := walk.NewListRHelper(callback) last := "" err = f.list(dir, true, "", 0, f.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { entry, err := f.itemToDirEntry(remote, object, isDirectory, &last) if err != nil { return err } return list.Add(entry) }) if err != nil { return err } // bucket must be present if listing succeeded f.markBucketOK() return list.Flush() } // listBucketFn is called from listBucketsToFn to handle a bucket type listBucketFn func(*api.Bucket) error // listBucketsToFn lists the buckets to the function supplied func (f *Fs) listBucketsToFn(fn listBucketFn) error { var account = api.ListBucketsRequest{ AccountID: f.info.AccountID, BucketID: f.info.Allowed.BucketID, } var response api.ListBucketsResponse opts := rest.Opts{ Method: "POST", Path: "/b2_list_buckets", } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &account, &response) return f.shouldRetry(resp, err) }) if err != nil { return err } for i := range response.Buckets { err = fn(&response.Buckets[i]) if err != nil { return err } } return nil } // getBucketID finds the ID for the current bucket name func (f *Fs) getBucketID() (bucketID string, err error) { f.bucketIDMutex.Lock() defer f.bucketIDMutex.Unlock() if f._bucketID != "" { return f._bucketID, nil } err = f.listBucketsToFn(func(bucket *api.Bucket) error { if bucket.Name == f.bucket { bucketID = bucket.ID } return nil }) if bucketID == "" { err = fs.ErrorDirNotFound } f._bucketID = bucketID return bucketID, err } // setBucketID sets the ID for the current bucket name func (f *Fs) setBucketID(ID string) { f.bucketIDMutex.Lock() f._bucketID = ID f.bucketIDMutex.Unlock() } // clearBucketID clears the ID for the current bucket name func (f *Fs) clearBucketID() { f.bucketIDMutex.Lock() f._bucketID = "" f.bucketIDMutex.Unlock() } // Put the object into the bucket // // Copy the reader in to the new object which is returned // // The new object may have been created if an error is returned func (f *Fs) Put(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { // Temporary Object under construction fs := &Object{ fs: f, remote: src.Remote(), } return fs, fs.Update(in, src, options...) } // PutStream uploads to the remote path with the modTime given of indeterminate size func (f *Fs) PutStream(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.Put(in, src, options...) } // Mkdir creates the bucket if it doesn't exist func (f *Fs) Mkdir(dir string) error { f.bucketOKMu.Lock() defer f.bucketOKMu.Unlock() if f.bucketOK { return nil } opts := rest.Opts{ Method: "POST", Path: "/b2_create_bucket", } var request = api.CreateBucketRequest{ AccountID: f.info.AccountID, Name: f.bucket, Type: "allPrivate", } var response api.Bucket err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { if apiErr, ok := err.(*api.Error); ok { if apiErr.Code == "duplicate_bucket_name" { // Check this is our bucket - buckets are globally unique and this // might be someone elses. _, getBucketErr := f.getBucketID() if getBucketErr == nil { // found so it is our bucket f.bucketOK = true return nil } if getBucketErr != fs.ErrorDirNotFound { fs.Debugf(f, "Error checking bucket exists: %v", getBucketErr) } } } return errors.Wrap(err, "failed to create bucket") } f.setBucketID(response.ID) f.bucketOK = true return nil } // Rmdir deletes the bucket if the fs is at the root // // Returns an error if it isn't empty func (f *Fs) Rmdir(dir string) error { f.bucketOKMu.Lock() defer f.bucketOKMu.Unlock() if f.root != "" || dir != "" { return nil } opts := rest.Opts{ Method: "POST", Path: "/b2_delete_bucket", } bucketID, err := f.getBucketID() if err != nil { return err } var request = api.DeleteBucketRequest{ ID: bucketID, AccountID: f.info.AccountID, } var response api.Bucket err = f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return errors.Wrap(err, "failed to delete bucket") } f.bucketOK = false f.clearBucketID() f.clearUploadURL() return nil } // Precision of the remote func (f *Fs) Precision() time.Duration { return time.Millisecond } // hide hides a file on the remote func (f *Fs) hide(Name string) error { bucketID, err := f.getBucketID() if err != nil { return err } opts := rest.Opts{ Method: "POST", Path: "/b2_hide_file", } var request = api.HideFileRequest{ BucketID: bucketID, Name: Name, } var response api.File err = f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return errors.Wrapf(err, "failed to hide %q", Name) } return nil } // deleteByID deletes a file version given Name and ID func (f *Fs) deleteByID(ID, Name string) error { opts := rest.Opts{ Method: "POST", Path: "/b2_delete_file_version", } var request = api.DeleteFileRequest{ ID: ID, Name: Name, } var response api.File err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return errors.Wrapf(err, "failed to delete %q", Name) } return nil } // purge deletes all the files and directories // // if oldOnly is true then it deletes only non current files. // // Implemented here so we can make sure we delete old versions. func (f *Fs) purge(oldOnly bool) error { var errReturn error var checkErrMutex sync.Mutex var checkErr = func(err error) { if err == nil { return } checkErrMutex.Lock() defer checkErrMutex.Unlock() if errReturn == nil { errReturn = err } } var isUnfinishedUploadStale = func(timestamp api.Timestamp) bool { if time.Since(time.Time(timestamp)).Hours() > 24 { return true } return false } // Delete Config.Transfers in parallel toBeDeleted := make(chan *api.File, fs.Config.Transfers) var wg sync.WaitGroup wg.Add(fs.Config.Transfers) for i := 0; i < fs.Config.Transfers; i++ { go func() { defer wg.Done() for object := range toBeDeleted { accounting.Stats.Checking(object.Name) checkErr(f.deleteByID(object.ID, object.Name)) accounting.Stats.DoneChecking(object.Name) } }() } last := "" checkErr(f.list("", true, "", 0, true, func(remote string, object *api.File, isDirectory bool) error { if !isDirectory { accounting.Stats.Checking(remote) if oldOnly && last != remote { if object.Action == "hide" { fs.Debugf(remote, "Deleting current version (id %q) as it is a hide marker", object.ID) toBeDeleted <- object } else if object.Action == "start" && isUnfinishedUploadStale(object.UploadTimestamp) { fs.Debugf(remote, "Deleting current version (id %q) as it is a start marker (upload started at %s)", object.ID, time.Time(object.UploadTimestamp).Local()) toBeDeleted <- object } else { fs.Debugf(remote, "Not deleting current version (id %q) %q", object.ID, object.Action) } } else { fs.Debugf(remote, "Deleting (id %q)", object.ID) toBeDeleted <- object } last = remote accounting.Stats.DoneChecking(remote) } return nil })) close(toBeDeleted) wg.Wait() if !oldOnly { checkErr(f.Rmdir("")) } return errReturn } // Purge deletes all the files and directories including the old versions. func (f *Fs) Purge() error { return f.purge(false) } // CleanUp deletes all the hidden files. func (f *Fs) CleanUp() error { return f.purge(true) } // Hashes returns the supported hash sets. func (f *Fs) Hashes() hash.Set { return hash.Set(hash.SHA1) } // ------------------------------------------------------------ // Fs returns the parent Fs func (o *Object) Fs() fs.Info { return o.fs } // Return a string version func (o *Object) String() string { if o == nil { return "<nil>" } return o.remote } // Remote returns the remote path func (o *Object) Remote() string { return o.remote } // Hash returns the Sha-1 of an object returning a lowercase hex string func (o *Object) Hash(t hash.Type) (string, error) { if t != hash.SHA1 { return "", hash.ErrUnsupported } if o.sha1 == "" { // Error is logged in readMetaData err := o.readMetaData() if err != nil { return "", err } } return o.sha1, nil } // Size returns the size of an object in bytes func (o *Object) Size() int64 { return o.size } // decodeMetaDataRaw sets the metadata from the data passed in // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaDataRaw(ID, SHA1 string, Size int64, UploadTimestamp api.Timestamp, Info map[string]string, mimeType string) (err error) { o.id = ID o.sha1 = SHA1 o.mimeType = mimeType // Read SHA1 from metadata if it exists and isn't set if o.sha1 == "" || o.sha1 == "none" { o.sha1 = Info[sha1Key] } o.size = Size // Use the UploadTimestamp if can't get file info o.modTime = time.Time(UploadTimestamp) return o.parseTimeString(Info[timeKey]) } // decodeMetaData sets the metadata in the object from an api.File // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaData(info *api.File) (err error) { return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType) } // decodeMetaDataFileInfo sets the metadata in the object from an api.FileInfo // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaDataFileInfo(info *api.FileInfo) (err error) { return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType) } // readMetaData gets the metadata if it hasn't already been fetched // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) readMetaData() (err error) { if o.id != "" { return nil } maxSearched := 1 var timestamp api.Timestamp baseRemote := o.remote if o.fs.opt.Versions { timestamp, baseRemote = api.RemoveVersion(baseRemote) maxSearched = maxVersions } var info *api.File err = o.fs.list("", true, baseRemote, maxSearched, o.fs.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { if isDirectory { return nil } if remote == baseRemote { if !timestamp.IsZero() && !timestamp.Equal(object.UploadTimestamp) { return nil } info = object } return errEndList // read only 1 item }) if err != nil { if err == fs.ErrorDirNotFound { return fs.ErrorObjectNotFound } return err } if info == nil { return fs.ErrorObjectNotFound } return o.decodeMetaData(info) } // timeString returns modTime as the number of milliseconds // elapsed since January 1, 1970 UTC as a decimal string. func timeString(modTime time.Time) string { return strconv.FormatInt(modTime.UnixNano()/1E6, 10) } // parseTimeString converts a decimal string number of milliseconds // elapsed since January 1, 1970 UTC into a time.Time and stores it in // the modTime variable. func (o *Object) parseTimeString(timeString string) (err error) { if timeString == "" { return nil } unixMilliseconds, err := strconv.ParseInt(timeString, 10, 64) if err != nil { fs.Debugf(o, "Failed to parse mod time string %q: %v", timeString, err) return err } o.modTime = time.Unix(unixMilliseconds/1E3, (unixMilliseconds%1E3)*1E6).UTC() return nil } // ModTime returns the modification time of the object // // It attempts to read the objects mtime and if that isn't present the // LastModified returned in the http headers // // SHA-1 will also be updated once the request has completed. func (o *Object) ModTime() (result time.Time) { // The error is logged in readMetaData _ = o.readMetaData() return o.modTime } // SetModTime sets the modification time of the local fs object func (o *Object) SetModTime(modTime time.Time) error { // Not possible with B2 return fs.ErrorCantSetModTime } // Storable returns if this object is storable func (o *Object) Storable() bool { return true } // openFile represents an Object open for reading type openFile struct { o *Object // Object we are reading for resp *http.Response // response of the GET body io.Reader // reading from here hash gohash.Hash // currently accumulating SHA1 bytes int64 // number of bytes read on this connection eof bool // whether we have read end of file } // newOpenFile wraps an io.ReadCloser and checks the sha1sum func newOpenFile(o *Object, resp *http.Response) *openFile { file := &openFile{ o: o, resp: resp, hash: sha1.New(), } file.body = io.TeeReader(resp.Body, file.hash) return file } // Read bytes from the object - see io.Reader func (file *openFile) Read(p []byte) (n int, err error) { n, err = file.body.Read(p) file.bytes += int64(n) if err == io.EOF { file.eof = true } return } // Close the object and checks the length and SHA1 if all the object // was read func (file *openFile) Close() (err error) { // Close the body at the end defer fs.CheckClose(file.resp.Body, &err) // If not end of file then can't check SHA1 if !file.eof { return nil } // Check to see we read the correct number of bytes if file.o.Size() != file.bytes { return errors.Errorf("object corrupted on transfer - length mismatch (want %d got %d)", file.o.Size(), file.bytes) } // Check the SHA1 receivedSHA1 := file.o.sha1 calculatedSHA1 := fmt.Sprintf("%x", file.hash.Sum(nil)) if receivedSHA1 != "" && receivedSHA1 != calculatedSHA1 { return errors.Errorf("object corrupted on transfer - SHA1 mismatch (want %q got %q)", receivedSHA1, calculatedSHA1) } return nil } // Check it satisfies the interfaces var _ io.ReadCloser = &openFile{} // Open an object for read func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) { opts := rest.Opts{ Method: "GET", Options: options, } // Use downloadUrl from backblaze if downloadUrl is not set // otherwise use the custom downloadUrl if o.fs.opt.DownloadURL == "" { opts.RootURL = o.fs.info.DownloadURL } else { opts.RootURL = o.fs.opt.DownloadURL } // Download by id if set otherwise by name if o.id != "" { opts.Path += "/b2api/v1/b2_download_file_by_id?fileId=" + urlEncode(o.id) } else { opts.Path += "/file/" + urlEncode(o.fs.bucket) + "/" + urlEncode(o.fs.root+o.remote) } var resp *http.Response err = o.fs.pacer.Call(func() (bool, error) { resp, err = o.fs.srv.Call(&opts) return o.fs.shouldRetry(resp, err) }) if err != nil { return nil, errors.Wrap(err, "failed to open for download") } // Parse the time out of the headers if possible err = o.parseTimeString(resp.Header.Get(timeHeader)) if err != nil { _ = resp.Body.Close() return nil, err } // Read sha1 from header if it isn't set if o.sha1 == "" { o.sha1 = resp.Header.Get(sha1Header) fs.Debugf(o, "Reading sha1 from header - %q", o.sha1) // if sha1 header is "none" (in big files), then need // to read it from the metadata if o.sha1 == "none" { o.sha1 = resp.Header.Get(sha1InfoHeader) fs.Debugf(o, "Reading sha1 from info - %q", o.sha1) } } // Don't check length or hash on partial content if resp.StatusCode == http.StatusPartialContent { return resp.Body, nil } return newOpenFile(o, resp), nil } // dontEncode is the characters that do not need percent-encoding // // The characters that do not need percent-encoding are a subset of // the printable ASCII characters: upper-case letters, lower-case // letters, digits, ".", "_", "-", "/", "~", "!", "$", "'", "(", ")", // "*", ";", "=", ":", and "@". All other byte values in a UTF-8 must // be replaced with "%" and the two-digit hex value of the byte. const dontEncode = (`abcdefghijklmnopqrstuvwxyz` + `ABCDEFGHIJKLMNOPQRSTUVWXYZ` + `0123456789` + `._-/~!$'()*;=:@`) // noNeedToEncode is a bitmap of characters which don't need % encoding var noNeedToEncode [256]bool func init() { for _, c := range dontEncode { noNeedToEncode[c] = true } } // urlEncode encodes in with % encoding func urlEncode(in string) string { var out bytes.Buffer for i := 0; i < len(in); i++ { c := in[i] if noNeedToEncode[c] { _ = out.WriteByte(c) } else { _, _ = out.WriteString(fmt.Sprintf("%%%2X", c)) } } return out.String() } // Update the object with the contents of the io.Reader, modTime and size // // The new object may have been created if an error is returned func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) { if o.fs.opt.Versions { return errNotWithVersions } err = o.fs.Mkdir("") if err != nil { return err } size := src.Size() if size == -1 { // Check if the file is large enough for a chunked upload (needs to be at least two chunks) buf := o.fs.getUploadBlock() n, err := io.ReadFull(in, buf) if err == nil { bufReader := bufio.NewReader(in) in = bufReader _, err = bufReader.Peek(1) } if err == nil { fs.Debugf(o, "File is big enough for chunked streaming") up, err := o.fs.newLargeUpload(o, in, src) if err != nil { o.fs.putUploadBlock(buf) return err } return up.Stream(buf) } else if err == io.EOF || err == io.ErrUnexpectedEOF { fs.Debugf(o, "File has %d bytes, which makes only one chunk. Using direct upload.", n) defer o.fs.putUploadBlock(buf) size = int64(n) in = bytes.NewReader(buf[:n]) } else { return err } } else if size > int64(o.fs.opt.UploadCutoff) { up, err := o.fs.newLargeUpload(o, in, src) if err != nil { return err } return up.Upload() } modTime := src.ModTime() calculatedSha1, _ := src.Hash(hash.SHA1) if calculatedSha1 == "" { calculatedSha1 = "hex_digits_at_end" har := newHashAppendingReader(in, sha1.New()) size += int64(har.AdditionalLength()) in = har } // Get upload URL upload, err := o.fs.getUploadURL() if err != nil { return err } defer func() { // return it like this because we might nil it out o.fs.returnUploadURL(upload) }() // Headers for upload file // // Authorization // required // An upload authorization token, from b2_get_upload_url. // // X-Bz-File-Name // required // // The name of the file, in percent-encoded UTF-8. See Files for requirements on file names. See String Encoding. // // Content-Type // required // // The MIME type of the content of the file, which will be returned in // the Content-Type header when downloading the file. Use the // Content-Type b2/x-auto to automatically set the stored Content-Type // post upload. In the case where a file extension is absent or the // lookup fails, the Content-Type is set to application/octet-stream. The // Content-Type mappings can be pursued here. // // X-Bz-Content-Sha1 // required // // The SHA1 checksum of the content of the file. B2 will check this when // the file is uploaded, to make sure that the file arrived correctly. It // will be returned in the X-Bz-Content-Sha1 header when the file is // downloaded. // // X-Bz-Info-src_last_modified_millis // optional // // If the original source of the file being uploaded has a last modified // time concept, Backblaze recommends using this spelling of one of your // ten X-Bz-Info-* headers (see below). Using a standard spelling allows // different B2 clients and the B2 web user interface to interoperate // correctly. The value should be a base 10 number which represents a UTC // time when the original source file was last modified. It is a base 10 // number of milliseconds since midnight, January 1, 1970 UTC. This fits // in a 64 bit integer such as the type "long" in the programming // language Java. It is intended to be compatible with Java's time // long. For example, it can be passed directly into the Java call // Date.setTime(long time). // // X-Bz-Info-* // optional // // Up to 10 of these headers may be present. The * part of the header // name is replace with the name of a custom field in the file // information stored with the file, and the value is an arbitrary UTF-8 // string, percent-encoded. The same info headers sent with the upload // will be returned with the download. opts := rest.Opts{ Method: "POST", RootURL: upload.UploadURL, Body: in, ExtraHeaders: map[string]string{ "Authorization": upload.AuthorizationToken, "X-Bz-File-Name": urlEncode(o.fs.root + o.remote), "Content-Type": fs.MimeType(src), sha1Header: calculatedSha1, timeHeader: timeString(modTime), }, ContentLength: &size, } var response api.FileInfo // Don't retry, return a retry error instead err = o.fs.pacer.CallNoRetry(func() (bool, error) { resp, err := o.fs.srv.CallJSON(&opts, nil, &response) retry, err := o.fs.shouldRetry(resp, err) // On retryable error clear UploadURL if retry { fs.Debugf(o, "Clearing upload URL because of error: %v", err) upload = nil } return retry, err }) if err != nil { return err } return o.decodeMetaDataFileInfo(&response) } // Remove an object func (o *Object) Remove() error { if o.fs.opt.Versions { return errNotWithVersions } if o.fs.opt.HardDelete { return o.fs.deleteByID(o.id, o.fs.root+o.remote) } return o.fs.hide(o.fs.root + o.remote) } // MimeType of an Object if known, "" otherwise func (o *Object) MimeType() string { return o.mimeType } // ID returns the ID of the Object if known, or "" if not func (o *Object) ID() string { return o.id } // Check the interfaces are satisfied var ( _ fs.Fs = &Fs{} _ fs.Purger = &Fs{} _ fs.PutStreamer = &Fs{} _ fs.CleanUpper = &Fs{} _ fs.ListRer = &Fs{} _ fs.Object = &Object{} _ fs.MimeTyper = &Object{} _ fs.IDer = &Object{} ) b2: ignore already_hidden error on remove Sometimes (possibly through eventual consistency) b2 returns an already_hidden error on a delete. Ignore this since it is harmless. // Package b2 provides an interface to the Backblaze B2 object storage system package b2 // FIXME should we remove sha1 checks from here as rclone now supports // checking SHA1s? import ( "bufio" "bytes" "crypto/sha1" "fmt" gohash "hash" "io" "net/http" "path" "regexp" "strconv" "strings" "sync" "time" "github.com/ncw/rclone/backend/b2/api" "github.com/ncw/rclone/fs" "github.com/ncw/rclone/fs/accounting" "github.com/ncw/rclone/fs/config/configmap" "github.com/ncw/rclone/fs/config/configstruct" "github.com/ncw/rclone/fs/fserrors" "github.com/ncw/rclone/fs/fshttp" "github.com/ncw/rclone/fs/hash" "github.com/ncw/rclone/fs/walk" "github.com/ncw/rclone/lib/pacer" "github.com/ncw/rclone/lib/rest" "github.com/pkg/errors" ) const ( defaultEndpoint = "https://api.backblazeb2.com" headerPrefix = "x-bz-info-" // lower case as that is what the server returns timeKey = "src_last_modified_millis" timeHeader = headerPrefix + timeKey sha1Key = "large_file_sha1" sha1Header = "X-Bz-Content-Sha1" sha1InfoHeader = headerPrefix + sha1Key testModeHeader = "X-Bz-Test-Mode" retryAfterHeader = "Retry-After" minSleep = 10 * time.Millisecond maxSleep = 5 * time.Minute decayConstant = 1 // bigger for slower decay, exponential maxParts = 10000 maxVersions = 100 // maximum number of versions we search in --b2-versions mode minChunkSize = 5 * fs.MebiByte defaultChunkSize = 96 * fs.MebiByte defaultUploadCutoff = 200 * fs.MebiByte ) // Globals var ( errNotWithVersions = errors.New("can't modify or delete files in --b2-versions mode") ) // Register with Fs func init() { fs.Register(&fs.RegInfo{ Name: "b2", Description: "Backblaze B2", NewFs: NewFs, Options: []fs.Option{{ Name: "account", Help: "Account ID or Application Key ID", Required: true, }, { Name: "key", Help: "Application Key", Required: true, }, { Name: "endpoint", Help: "Endpoint for the service.\nLeave blank normally.", Advanced: true, }, { Name: "test_mode", Help: `A flag string for X-Bz-Test-Mode header for debugging. This is for debugging purposes only. Setting it to one of the strings below will cause b2 to return specific errors: * "fail_some_uploads" * "expire_some_account_authorization_tokens" * "force_cap_exceeded" These will be set in the "X-Bz-Test-Mode" header which is documented in the [b2 integrations checklist](https://www.backblaze.com/b2/docs/integration_checklist.html).`, Default: "", Hide: fs.OptionHideConfigurator, Advanced: true, }, { Name: "versions", Help: "Include old versions in directory listings.\nNote that when using this no file write operations are permitted,\nso you can't upload files or delete them.", Default: false, Advanced: true, }, { Name: "hard_delete", Help: "Permanently delete files on remote removal, otherwise hide files.", Default: false, }, { Name: "upload_cutoff", Help: `Cutoff for switching to chunked upload. Files above this size will be uploaded in chunks of "--b2-chunk-size". This value should be set no larger than 4.657GiB (== 5GB).`, Default: defaultUploadCutoff, Advanced: true, }, { Name: "chunk_size", Help: `Upload chunk size. Must fit in memory. When uploading large files, chunk the file into this size. Note that these chunks are buffered in memory and there might a maximum of "--transfers" chunks in progress at once. 5,000,000 Bytes is the minimum size.`, Default: defaultChunkSize, Advanced: true, }, { Name: "disable_checksum", Help: `Disable checksums for large (> upload cutoff) files`, Default: false, Advanced: true, }, { Name: "download_url", Help: `Custom endpoint for downloads. This is usually set to a Cloudflare CDN URL as Backblaze offers free egress for data downloaded through the Cloudflare network. Leave blank if you want to use the endpoint provided by Backblaze.`, Advanced: true, }}, }) } // Options defines the configuration for this backend type Options struct { Account string `config:"account"` Key string `config:"key"` Endpoint string `config:"endpoint"` TestMode string `config:"test_mode"` Versions bool `config:"versions"` HardDelete bool `config:"hard_delete"` UploadCutoff fs.SizeSuffix `config:"upload_cutoff"` ChunkSize fs.SizeSuffix `config:"chunk_size"` DisableCheckSum bool `config:"disable_checksum"` DownloadURL string `config:"download_url"` } // Fs represents a remote b2 server type Fs struct { name string // name of this remote root string // the path we are working on if any opt Options // parsed config options features *fs.Features // optional features srv *rest.Client // the connection to the b2 server bucket string // the bucket we are working on bucketOKMu sync.Mutex // mutex to protect bucket OK bucketOK bool // true if we have created the bucket bucketIDMutex sync.Mutex // mutex to protect _bucketID _bucketID string // the ID of the bucket we are working on info api.AuthorizeAccountResponse // result of authorize call uploadMu sync.Mutex // lock for upload variable uploads []*api.GetUploadURLResponse // result of get upload URL calls authMu sync.Mutex // lock for authorizing the account pacer *fs.Pacer // To pace and retry the API calls bufferTokens chan []byte // control concurrency of multipart uploads } // Object describes a b2 object type Object struct { fs *Fs // what this object is part of remote string // The remote path id string // b2 id of the file modTime time.Time // The modified time of the object if known sha1 string // SHA-1 hash if known size int64 // Size of the object mimeType string // Content-Type of the object } // ------------------------------------------------------------ // Name of the remote (as passed into NewFs) func (f *Fs) Name() string { return f.name } // Root of the remote (as passed into NewFs) func (f *Fs) Root() string { if f.root == "" { return f.bucket } return f.bucket + "/" + f.root } // String converts this Fs to a string func (f *Fs) String() string { if f.root == "" { return fmt.Sprintf("B2 bucket %s", f.bucket) } return fmt.Sprintf("B2 bucket %s path %s", f.bucket, f.root) } // Features returns the optional features of this Fs func (f *Fs) Features() *fs.Features { return f.features } // Pattern to match a b2 path var matcher = regexp.MustCompile(`^/*([^/]*)(.*)$`) // parseParse parses a b2 'url' func parsePath(path string) (bucket, directory string, err error) { parts := matcher.FindStringSubmatch(path) if parts == nil { err = errors.Errorf("couldn't find bucket in b2 path %q", path) } else { bucket, directory = parts[1], parts[2] directory = strings.Trim(directory, "/") } return } // retryErrorCodes is a slice of error codes that we will retry var retryErrorCodes = []int{ 401, // Unauthorized (eg "Token has expired") 408, // Request Timeout 429, // Rate exceeded. 500, // Get occasional 500 Internal Server Error 503, // Service Unavailable 504, // Gateway Time-out } // shouldRetryNoAuth returns a boolean as to whether this resp and err // deserve to be retried. It returns the err as a convenience func (f *Fs) shouldRetryNoReauth(resp *http.Response, err error) (bool, error) { // For 429 or 503 errors look at the Retry-After: header and // set the retry appropriately, starting with a minimum of 1 // second if it isn't set. if resp != nil && (resp.StatusCode == 429 || resp.StatusCode == 503) { var retryAfter = 1 retryAfterString := resp.Header.Get(retryAfterHeader) if retryAfterString != "" { var err error retryAfter, err = strconv.Atoi(retryAfterString) if err != nil { fs.Errorf(f, "Malformed %s header %q: %v", retryAfterHeader, retryAfterString, err) } } return true, pacer.RetryAfterError(err, time.Duration(retryAfter)*time.Second) } return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err } // shouldRetry returns a boolean as to whether this resp and err // deserve to be retried. It returns the err as a convenience func (f *Fs) shouldRetry(resp *http.Response, err error) (bool, error) { if resp != nil && resp.StatusCode == 401 { fs.Debugf(f, "Unauthorized: %v", err) // Reauth authErr := f.authorizeAccount() if authErr != nil { err = authErr } return true, err } return f.shouldRetryNoReauth(resp, err) } // errorHandler parses a non 2xx error response into an error func errorHandler(resp *http.Response) error { // Decode error response errResponse := new(api.Error) err := rest.DecodeJSON(resp, &errResponse) if err != nil { fs.Debugf(nil, "Couldn't decode error response: %v", err) } if errResponse.Code == "" { errResponse.Code = "unknown" } if errResponse.Status == 0 { errResponse.Status = resp.StatusCode } if errResponse.Message == "" { errResponse.Message = "Unknown " + resp.Status } return errResponse } func checkUploadChunkSize(cs fs.SizeSuffix) error { if cs < minChunkSize { return errors.Errorf("%s is less than %s", cs, minChunkSize) } return nil } func (f *Fs) setUploadChunkSize(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) { err = checkUploadChunkSize(cs) if err == nil { old, f.opt.ChunkSize = f.opt.ChunkSize, cs f.fillBufferTokens() // reset the buffer tokens } return } func checkUploadCutoff(opt *Options, cs fs.SizeSuffix) error { if cs < opt.ChunkSize { return errors.Errorf("%v is less than chunk size %v", cs, opt.ChunkSize) } return nil } func (f *Fs) setUploadCutoff(cs fs.SizeSuffix) (old fs.SizeSuffix, err error) { err = checkUploadCutoff(&f.opt, cs) if err == nil { old, f.opt.UploadCutoff = f.opt.UploadCutoff, cs } return } // NewFs constructs an Fs from the path, bucket:path func NewFs(name, root string, m configmap.Mapper) (fs.Fs, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } err = checkUploadCutoff(opt, opt.UploadCutoff) if err != nil { return nil, errors.Wrap(err, "b2: upload cutoff") } err = checkUploadChunkSize(opt.ChunkSize) if err != nil { return nil, errors.Wrap(err, "b2: chunk size") } bucket, directory, err := parsePath(root) if err != nil { return nil, err } if opt.Account == "" { return nil, errors.New("account not found") } if opt.Key == "" { return nil, errors.New("key not found") } if opt.Endpoint == "" { opt.Endpoint = defaultEndpoint } f := &Fs{ name: name, opt: *opt, bucket: bucket, root: directory, srv: rest.NewClient(fshttp.NewClient(fs.Config)).SetErrorHandler(errorHandler), pacer: fs.NewPacer(pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))), } f.features = (&fs.Features{ ReadMimeType: true, WriteMimeType: true, BucketBased: true, }).Fill(f) // Set the test flag if required if opt.TestMode != "" { testMode := strings.TrimSpace(opt.TestMode) f.srv.SetHeader(testModeHeader, testMode) fs.Debugf(f, "Setting test header \"%s: %s\"", testModeHeader, testMode) } f.fillBufferTokens() err = f.authorizeAccount() if err != nil { return nil, errors.Wrap(err, "failed to authorize account") } // If this is a key limited to a single bucket, it must exist already if f.bucket != "" && f.info.Allowed.BucketID != "" { allowedBucket := f.info.Allowed.BucketName if allowedBucket == "" { return nil, errors.New("bucket that application key is restricted to no longer exists") } if allowedBucket != f.bucket { return nil, errors.Errorf("you must use bucket %q with this application key", allowedBucket) } f.markBucketOK() f.setBucketID(f.info.Allowed.BucketID) } if f.root != "" { f.root += "/" // Check to see if the (bucket,directory) is actually an existing file oldRoot := f.root remote := path.Base(directory) f.root = path.Dir(directory) if f.root == "." { f.root = "" } else { f.root += "/" } _, err := f.NewObject(remote) if err != nil { if err == fs.ErrorObjectNotFound { // File doesn't exist so return old f f.root = oldRoot return f, nil } return nil, err } // return an error with an fs which points to the parent return f, fs.ErrorIsFile } return f, nil } // authorizeAccount gets the API endpoint and auth token. Can be used // for reauthentication too. func (f *Fs) authorizeAccount() error { f.authMu.Lock() defer f.authMu.Unlock() opts := rest.Opts{ Method: "GET", Path: "/b2api/v1/b2_authorize_account", RootURL: f.opt.Endpoint, UserName: f.opt.Account, Password: f.opt.Key, ExtraHeaders: map[string]string{"Authorization": ""}, // unset the Authorization for this request } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, nil, &f.info) return f.shouldRetryNoReauth(resp, err) }) if err != nil { return errors.Wrap(err, "failed to authenticate") } f.srv.SetRoot(f.info.APIURL+"/b2api/v1").SetHeader("Authorization", f.info.AuthorizationToken) return nil } // getUploadURL returns the upload info with the UploadURL and the AuthorizationToken // // This should be returned with returnUploadURL when finished func (f *Fs) getUploadURL() (upload *api.GetUploadURLResponse, err error) { f.uploadMu.Lock() defer f.uploadMu.Unlock() bucketID, err := f.getBucketID() if err != nil { return nil, err } if len(f.uploads) == 0 { opts := rest.Opts{ Method: "POST", Path: "/b2_get_upload_url", } var request = api.GetUploadURLRequest{ BucketID: bucketID, } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &upload) return f.shouldRetry(resp, err) }) if err != nil { return nil, errors.Wrap(err, "failed to get upload URL") } } else { upload, f.uploads = f.uploads[0], f.uploads[1:] } return upload, nil } // returnUploadURL returns the UploadURL to the cache func (f *Fs) returnUploadURL(upload *api.GetUploadURLResponse) { if upload == nil { return } f.uploadMu.Lock() f.uploads = append(f.uploads, upload) f.uploadMu.Unlock() } // clearUploadURL clears the current UploadURL and the AuthorizationToken func (f *Fs) clearUploadURL() { f.uploadMu.Lock() f.uploads = nil f.uploadMu.Unlock() } // Fill up (or reset) the buffer tokens func (f *Fs) fillBufferTokens() { f.bufferTokens = make(chan []byte, fs.Config.Transfers) for i := 0; i < fs.Config.Transfers; i++ { f.bufferTokens <- nil } } // getUploadBlock gets a block from the pool of size chunkSize func (f *Fs) getUploadBlock() []byte { buf := <-f.bufferTokens if buf == nil { buf = make([]byte, f.opt.ChunkSize) } // fs.Debugf(f, "Getting upload block %p", buf) return buf } // putUploadBlock returns a block to the pool of size chunkSize func (f *Fs) putUploadBlock(buf []byte) { buf = buf[:cap(buf)] if len(buf) != int(f.opt.ChunkSize) { panic("bad blocksize returned to pool") } // fs.Debugf(f, "Returning upload block %p", buf) f.bufferTokens <- buf } // Return an Object from a path // // If it can't be found it returns the error fs.ErrorObjectNotFound. func (f *Fs) newObjectWithInfo(remote string, info *api.File) (fs.Object, error) { o := &Object{ fs: f, remote: remote, } if info != nil { err := o.decodeMetaData(info) if err != nil { return nil, err } } else { err := o.readMetaData() // reads info and headers, returning an error if err != nil { return nil, err } } return o, nil } // NewObject finds the Object at remote. If it can't be found // it returns the error fs.ErrorObjectNotFound. func (f *Fs) NewObject(remote string) (fs.Object, error) { return f.newObjectWithInfo(remote, nil) } // listFn is called from list to handle an object type listFn func(remote string, object *api.File, isDirectory bool) error // errEndList is a sentinel used to end the list iteration now. // listFn should return it to end the iteration with no errors. var errEndList = errors.New("end list") // list lists the objects into the function supplied from // the bucket and root supplied // // dir is the starting directory, "" for root // // level is the depth to search to // // If prefix is set then startFileName is used as a prefix which all // files must have // // If limit is > 0 then it limits to that many files (must be less // than 1000) // // If hidden is set then it will list the hidden (deleted) files too. func (f *Fs) list(dir string, recurse bool, prefix string, limit int, hidden bool, fn listFn) error { root := f.root if dir != "" { root += dir + "/" } delimiter := "" if !recurse { delimiter = "/" } bucketID, err := f.getBucketID() if err != nil { return err } chunkSize := 1000 if limit > 0 { chunkSize = limit } var request = api.ListFileNamesRequest{ BucketID: bucketID, MaxFileCount: chunkSize, Prefix: root, Delimiter: delimiter, } prefix = root + prefix if prefix != "" { request.StartFileName = prefix } opts := rest.Opts{ Method: "POST", Path: "/b2_list_file_names", } if hidden { opts.Path = "/b2_list_file_versions" } for { var response api.ListFileNamesResponse err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return err } for i := range response.Files { file := &response.Files[i] // Finish if file name no longer has prefix if prefix != "" && !strings.HasPrefix(file.Name, prefix) { return nil } if !strings.HasPrefix(file.Name, f.root) { fs.Debugf(f, "Odd name received %q", file.Name) continue } remote := file.Name[len(f.root):] // Check for directory isDirectory := strings.HasSuffix(remote, "/") if isDirectory { remote = remote[:len(remote)-1] } // Send object err = fn(remote, file, isDirectory) if err != nil { if err == errEndList { return nil } return err } } // end if no NextFileName if response.NextFileName == nil { break } request.StartFileName = *response.NextFileName if response.NextFileID != nil { request.StartFileID = *response.NextFileID } } return nil } // Convert a list item into a DirEntry func (f *Fs) itemToDirEntry(remote string, object *api.File, isDirectory bool, last *string) (fs.DirEntry, error) { if isDirectory { d := fs.NewDir(remote, time.Time{}) return d, nil } if remote == *last { remote = object.UploadTimestamp.AddVersion(remote) } else { *last = remote } // hide objects represent deleted files which we don't list if object.Action == "hide" { return nil, nil } o, err := f.newObjectWithInfo(remote, object) if err != nil { return nil, err } return o, nil } // mark the bucket as being OK func (f *Fs) markBucketOK() { if f.bucket != "" { f.bucketOKMu.Lock() f.bucketOK = true f.bucketOKMu.Unlock() } } // listDir lists a single directory func (f *Fs) listDir(dir string) (entries fs.DirEntries, err error) { last := "" err = f.list(dir, false, "", 0, f.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { entry, err := f.itemToDirEntry(remote, object, isDirectory, &last) if err != nil { return err } if entry != nil { entries = append(entries, entry) } return nil }) if err != nil { return nil, err } // bucket must be present if listing succeeded f.markBucketOK() return entries, nil } // listBuckets returns all the buckets to out func (f *Fs) listBuckets(dir string) (entries fs.DirEntries, err error) { if dir != "" { return nil, fs.ErrorListBucketRequired } err = f.listBucketsToFn(func(bucket *api.Bucket) error { d := fs.NewDir(bucket.Name, time.Time{}) entries = append(entries, d) return nil }) if err != nil { return nil, err } return entries, nil } // List the objects and directories in dir into entries. The // entries can be returned in any order but should be for a // complete directory. // // dir should be "" to list the root, and should not have // trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. func (f *Fs) List(dir string) (entries fs.DirEntries, err error) { if f.bucket == "" { return f.listBuckets(dir) } return f.listDir(dir) } // ListR lists the objects and directories of the Fs starting // from dir recursively into out. // // dir should be "" to start from the root, and should not // have trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. // // It should call callback for each tranche of entries read. // These need not be returned in any particular order. If // callback returns an error then the listing will stop // immediately. // // Don't implement this unless you have a more efficient way // of listing recursively that doing a directory traversal. func (f *Fs) ListR(dir string, callback fs.ListRCallback) (err error) { if f.bucket == "" { return fs.ErrorListBucketRequired } list := walk.NewListRHelper(callback) last := "" err = f.list(dir, true, "", 0, f.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { entry, err := f.itemToDirEntry(remote, object, isDirectory, &last) if err != nil { return err } return list.Add(entry) }) if err != nil { return err } // bucket must be present if listing succeeded f.markBucketOK() return list.Flush() } // listBucketFn is called from listBucketsToFn to handle a bucket type listBucketFn func(*api.Bucket) error // listBucketsToFn lists the buckets to the function supplied func (f *Fs) listBucketsToFn(fn listBucketFn) error { var account = api.ListBucketsRequest{ AccountID: f.info.AccountID, BucketID: f.info.Allowed.BucketID, } var response api.ListBucketsResponse opts := rest.Opts{ Method: "POST", Path: "/b2_list_buckets", } err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &account, &response) return f.shouldRetry(resp, err) }) if err != nil { return err } for i := range response.Buckets { err = fn(&response.Buckets[i]) if err != nil { return err } } return nil } // getBucketID finds the ID for the current bucket name func (f *Fs) getBucketID() (bucketID string, err error) { f.bucketIDMutex.Lock() defer f.bucketIDMutex.Unlock() if f._bucketID != "" { return f._bucketID, nil } err = f.listBucketsToFn(func(bucket *api.Bucket) error { if bucket.Name == f.bucket { bucketID = bucket.ID } return nil }) if bucketID == "" { err = fs.ErrorDirNotFound } f._bucketID = bucketID return bucketID, err } // setBucketID sets the ID for the current bucket name func (f *Fs) setBucketID(ID string) { f.bucketIDMutex.Lock() f._bucketID = ID f.bucketIDMutex.Unlock() } // clearBucketID clears the ID for the current bucket name func (f *Fs) clearBucketID() { f.bucketIDMutex.Lock() f._bucketID = "" f.bucketIDMutex.Unlock() } // Put the object into the bucket // // Copy the reader in to the new object which is returned // // The new object may have been created if an error is returned func (f *Fs) Put(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { // Temporary Object under construction fs := &Object{ fs: f, remote: src.Remote(), } return fs, fs.Update(in, src, options...) } // PutStream uploads to the remote path with the modTime given of indeterminate size func (f *Fs) PutStream(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.Put(in, src, options...) } // Mkdir creates the bucket if it doesn't exist func (f *Fs) Mkdir(dir string) error { f.bucketOKMu.Lock() defer f.bucketOKMu.Unlock() if f.bucketOK { return nil } opts := rest.Opts{ Method: "POST", Path: "/b2_create_bucket", } var request = api.CreateBucketRequest{ AccountID: f.info.AccountID, Name: f.bucket, Type: "allPrivate", } var response api.Bucket err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { if apiErr, ok := err.(*api.Error); ok { if apiErr.Code == "duplicate_bucket_name" { // Check this is our bucket - buckets are globally unique and this // might be someone elses. _, getBucketErr := f.getBucketID() if getBucketErr == nil { // found so it is our bucket f.bucketOK = true return nil } if getBucketErr != fs.ErrorDirNotFound { fs.Debugf(f, "Error checking bucket exists: %v", getBucketErr) } } } return errors.Wrap(err, "failed to create bucket") } f.setBucketID(response.ID) f.bucketOK = true return nil } // Rmdir deletes the bucket if the fs is at the root // // Returns an error if it isn't empty func (f *Fs) Rmdir(dir string) error { f.bucketOKMu.Lock() defer f.bucketOKMu.Unlock() if f.root != "" || dir != "" { return nil } opts := rest.Opts{ Method: "POST", Path: "/b2_delete_bucket", } bucketID, err := f.getBucketID() if err != nil { return err } var request = api.DeleteBucketRequest{ ID: bucketID, AccountID: f.info.AccountID, } var response api.Bucket err = f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return errors.Wrap(err, "failed to delete bucket") } f.bucketOK = false f.clearBucketID() f.clearUploadURL() return nil } // Precision of the remote func (f *Fs) Precision() time.Duration { return time.Millisecond } // hide hides a file on the remote func (f *Fs) hide(Name string) error { bucketID, err := f.getBucketID() if err != nil { return err } opts := rest.Opts{ Method: "POST", Path: "/b2_hide_file", } var request = api.HideFileRequest{ BucketID: bucketID, Name: Name, } var response api.File err = f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { if apiErr, ok := err.(*api.Error); ok { if apiErr.Code == "already_hidden" { // sometimes eventual consistency causes this, so // ignore this error since it is harmless return nil } } return errors.Wrapf(err, "failed to hide %q", Name) } return nil } // deleteByID deletes a file version given Name and ID func (f *Fs) deleteByID(ID, Name string) error { opts := rest.Opts{ Method: "POST", Path: "/b2_delete_file_version", } var request = api.DeleteFileRequest{ ID: ID, Name: Name, } var response api.File err := f.pacer.Call(func() (bool, error) { resp, err := f.srv.CallJSON(&opts, &request, &response) return f.shouldRetry(resp, err) }) if err != nil { return errors.Wrapf(err, "failed to delete %q", Name) } return nil } // purge deletes all the files and directories // // if oldOnly is true then it deletes only non current files. // // Implemented here so we can make sure we delete old versions. func (f *Fs) purge(oldOnly bool) error { var errReturn error var checkErrMutex sync.Mutex var checkErr = func(err error) { if err == nil { return } checkErrMutex.Lock() defer checkErrMutex.Unlock() if errReturn == nil { errReturn = err } } var isUnfinishedUploadStale = func(timestamp api.Timestamp) bool { if time.Since(time.Time(timestamp)).Hours() > 24 { return true } return false } // Delete Config.Transfers in parallel toBeDeleted := make(chan *api.File, fs.Config.Transfers) var wg sync.WaitGroup wg.Add(fs.Config.Transfers) for i := 0; i < fs.Config.Transfers; i++ { go func() { defer wg.Done() for object := range toBeDeleted { accounting.Stats.Checking(object.Name) checkErr(f.deleteByID(object.ID, object.Name)) accounting.Stats.DoneChecking(object.Name) } }() } last := "" checkErr(f.list("", true, "", 0, true, func(remote string, object *api.File, isDirectory bool) error { if !isDirectory { accounting.Stats.Checking(remote) if oldOnly && last != remote { if object.Action == "hide" { fs.Debugf(remote, "Deleting current version (id %q) as it is a hide marker", object.ID) toBeDeleted <- object } else if object.Action == "start" && isUnfinishedUploadStale(object.UploadTimestamp) { fs.Debugf(remote, "Deleting current version (id %q) as it is a start marker (upload started at %s)", object.ID, time.Time(object.UploadTimestamp).Local()) toBeDeleted <- object } else { fs.Debugf(remote, "Not deleting current version (id %q) %q", object.ID, object.Action) } } else { fs.Debugf(remote, "Deleting (id %q)", object.ID) toBeDeleted <- object } last = remote accounting.Stats.DoneChecking(remote) } return nil })) close(toBeDeleted) wg.Wait() if !oldOnly { checkErr(f.Rmdir("")) } return errReturn } // Purge deletes all the files and directories including the old versions. func (f *Fs) Purge() error { return f.purge(false) } // CleanUp deletes all the hidden files. func (f *Fs) CleanUp() error { return f.purge(true) } // Hashes returns the supported hash sets. func (f *Fs) Hashes() hash.Set { return hash.Set(hash.SHA1) } // ------------------------------------------------------------ // Fs returns the parent Fs func (o *Object) Fs() fs.Info { return o.fs } // Return a string version func (o *Object) String() string { if o == nil { return "<nil>" } return o.remote } // Remote returns the remote path func (o *Object) Remote() string { return o.remote } // Hash returns the Sha-1 of an object returning a lowercase hex string func (o *Object) Hash(t hash.Type) (string, error) { if t != hash.SHA1 { return "", hash.ErrUnsupported } if o.sha1 == "" { // Error is logged in readMetaData err := o.readMetaData() if err != nil { return "", err } } return o.sha1, nil } // Size returns the size of an object in bytes func (o *Object) Size() int64 { return o.size } // decodeMetaDataRaw sets the metadata from the data passed in // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaDataRaw(ID, SHA1 string, Size int64, UploadTimestamp api.Timestamp, Info map[string]string, mimeType string) (err error) { o.id = ID o.sha1 = SHA1 o.mimeType = mimeType // Read SHA1 from metadata if it exists and isn't set if o.sha1 == "" || o.sha1 == "none" { o.sha1 = Info[sha1Key] } o.size = Size // Use the UploadTimestamp if can't get file info o.modTime = time.Time(UploadTimestamp) return o.parseTimeString(Info[timeKey]) } // decodeMetaData sets the metadata in the object from an api.File // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaData(info *api.File) (err error) { return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType) } // decodeMetaDataFileInfo sets the metadata in the object from an api.FileInfo // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) decodeMetaDataFileInfo(info *api.FileInfo) (err error) { return o.decodeMetaDataRaw(info.ID, info.SHA1, info.Size, info.UploadTimestamp, info.Info, info.ContentType) } // readMetaData gets the metadata if it hasn't already been fetched // // Sets // o.id // o.modTime // o.size // o.sha1 func (o *Object) readMetaData() (err error) { if o.id != "" { return nil } maxSearched := 1 var timestamp api.Timestamp baseRemote := o.remote if o.fs.opt.Versions { timestamp, baseRemote = api.RemoveVersion(baseRemote) maxSearched = maxVersions } var info *api.File err = o.fs.list("", true, baseRemote, maxSearched, o.fs.opt.Versions, func(remote string, object *api.File, isDirectory bool) error { if isDirectory { return nil } if remote == baseRemote { if !timestamp.IsZero() && !timestamp.Equal(object.UploadTimestamp) { return nil } info = object } return errEndList // read only 1 item }) if err != nil { if err == fs.ErrorDirNotFound { return fs.ErrorObjectNotFound } return err } if info == nil { return fs.ErrorObjectNotFound } return o.decodeMetaData(info) } // timeString returns modTime as the number of milliseconds // elapsed since January 1, 1970 UTC as a decimal string. func timeString(modTime time.Time) string { return strconv.FormatInt(modTime.UnixNano()/1E6, 10) } // parseTimeString converts a decimal string number of milliseconds // elapsed since January 1, 1970 UTC into a time.Time and stores it in // the modTime variable. func (o *Object) parseTimeString(timeString string) (err error) { if timeString == "" { return nil } unixMilliseconds, err := strconv.ParseInt(timeString, 10, 64) if err != nil { fs.Debugf(o, "Failed to parse mod time string %q: %v", timeString, err) return err } o.modTime = time.Unix(unixMilliseconds/1E3, (unixMilliseconds%1E3)*1E6).UTC() return nil } // ModTime returns the modification time of the object // // It attempts to read the objects mtime and if that isn't present the // LastModified returned in the http headers // // SHA-1 will also be updated once the request has completed. func (o *Object) ModTime() (result time.Time) { // The error is logged in readMetaData _ = o.readMetaData() return o.modTime } // SetModTime sets the modification time of the local fs object func (o *Object) SetModTime(modTime time.Time) error { // Not possible with B2 return fs.ErrorCantSetModTime } // Storable returns if this object is storable func (o *Object) Storable() bool { return true } // openFile represents an Object open for reading type openFile struct { o *Object // Object we are reading for resp *http.Response // response of the GET body io.Reader // reading from here hash gohash.Hash // currently accumulating SHA1 bytes int64 // number of bytes read on this connection eof bool // whether we have read end of file } // newOpenFile wraps an io.ReadCloser and checks the sha1sum func newOpenFile(o *Object, resp *http.Response) *openFile { file := &openFile{ o: o, resp: resp, hash: sha1.New(), } file.body = io.TeeReader(resp.Body, file.hash) return file } // Read bytes from the object - see io.Reader func (file *openFile) Read(p []byte) (n int, err error) { n, err = file.body.Read(p) file.bytes += int64(n) if err == io.EOF { file.eof = true } return } // Close the object and checks the length and SHA1 if all the object // was read func (file *openFile) Close() (err error) { // Close the body at the end defer fs.CheckClose(file.resp.Body, &err) // If not end of file then can't check SHA1 if !file.eof { return nil } // Check to see we read the correct number of bytes if file.o.Size() != file.bytes { return errors.Errorf("object corrupted on transfer - length mismatch (want %d got %d)", file.o.Size(), file.bytes) } // Check the SHA1 receivedSHA1 := file.o.sha1 calculatedSHA1 := fmt.Sprintf("%x", file.hash.Sum(nil)) if receivedSHA1 != "" && receivedSHA1 != calculatedSHA1 { return errors.Errorf("object corrupted on transfer - SHA1 mismatch (want %q got %q)", receivedSHA1, calculatedSHA1) } return nil } // Check it satisfies the interfaces var _ io.ReadCloser = &openFile{} // Open an object for read func (o *Object) Open(options ...fs.OpenOption) (in io.ReadCloser, err error) { opts := rest.Opts{ Method: "GET", Options: options, } // Use downloadUrl from backblaze if downloadUrl is not set // otherwise use the custom downloadUrl if o.fs.opt.DownloadURL == "" { opts.RootURL = o.fs.info.DownloadURL } else { opts.RootURL = o.fs.opt.DownloadURL } // Download by id if set otherwise by name if o.id != "" { opts.Path += "/b2api/v1/b2_download_file_by_id?fileId=" + urlEncode(o.id) } else { opts.Path += "/file/" + urlEncode(o.fs.bucket) + "/" + urlEncode(o.fs.root+o.remote) } var resp *http.Response err = o.fs.pacer.Call(func() (bool, error) { resp, err = o.fs.srv.Call(&opts) return o.fs.shouldRetry(resp, err) }) if err != nil { return nil, errors.Wrap(err, "failed to open for download") } // Parse the time out of the headers if possible err = o.parseTimeString(resp.Header.Get(timeHeader)) if err != nil { _ = resp.Body.Close() return nil, err } // Read sha1 from header if it isn't set if o.sha1 == "" { o.sha1 = resp.Header.Get(sha1Header) fs.Debugf(o, "Reading sha1 from header - %q", o.sha1) // if sha1 header is "none" (in big files), then need // to read it from the metadata if o.sha1 == "none" { o.sha1 = resp.Header.Get(sha1InfoHeader) fs.Debugf(o, "Reading sha1 from info - %q", o.sha1) } } // Don't check length or hash on partial content if resp.StatusCode == http.StatusPartialContent { return resp.Body, nil } return newOpenFile(o, resp), nil } // dontEncode is the characters that do not need percent-encoding // // The characters that do not need percent-encoding are a subset of // the printable ASCII characters: upper-case letters, lower-case // letters, digits, ".", "_", "-", "/", "~", "!", "$", "'", "(", ")", // "*", ";", "=", ":", and "@". All other byte values in a UTF-8 must // be replaced with "%" and the two-digit hex value of the byte. const dontEncode = (`abcdefghijklmnopqrstuvwxyz` + `ABCDEFGHIJKLMNOPQRSTUVWXYZ` + `0123456789` + `._-/~!$'()*;=:@`) // noNeedToEncode is a bitmap of characters which don't need % encoding var noNeedToEncode [256]bool func init() { for _, c := range dontEncode { noNeedToEncode[c] = true } } // urlEncode encodes in with % encoding func urlEncode(in string) string { var out bytes.Buffer for i := 0; i < len(in); i++ { c := in[i] if noNeedToEncode[c] { _ = out.WriteByte(c) } else { _, _ = out.WriteString(fmt.Sprintf("%%%2X", c)) } } return out.String() } // Update the object with the contents of the io.Reader, modTime and size // // The new object may have been created if an error is returned func (o *Object) Update(in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) { if o.fs.opt.Versions { return errNotWithVersions } err = o.fs.Mkdir("") if err != nil { return err } size := src.Size() if size == -1 { // Check if the file is large enough for a chunked upload (needs to be at least two chunks) buf := o.fs.getUploadBlock() n, err := io.ReadFull(in, buf) if err == nil { bufReader := bufio.NewReader(in) in = bufReader _, err = bufReader.Peek(1) } if err == nil { fs.Debugf(o, "File is big enough for chunked streaming") up, err := o.fs.newLargeUpload(o, in, src) if err != nil { o.fs.putUploadBlock(buf) return err } return up.Stream(buf) } else if err == io.EOF || err == io.ErrUnexpectedEOF { fs.Debugf(o, "File has %d bytes, which makes only one chunk. Using direct upload.", n) defer o.fs.putUploadBlock(buf) size = int64(n) in = bytes.NewReader(buf[:n]) } else { return err } } else if size > int64(o.fs.opt.UploadCutoff) { up, err := o.fs.newLargeUpload(o, in, src) if err != nil { return err } return up.Upload() } modTime := src.ModTime() calculatedSha1, _ := src.Hash(hash.SHA1) if calculatedSha1 == "" { calculatedSha1 = "hex_digits_at_end" har := newHashAppendingReader(in, sha1.New()) size += int64(har.AdditionalLength()) in = har } // Get upload URL upload, err := o.fs.getUploadURL() if err != nil { return err } defer func() { // return it like this because we might nil it out o.fs.returnUploadURL(upload) }() // Headers for upload file // // Authorization // required // An upload authorization token, from b2_get_upload_url. // // X-Bz-File-Name // required // // The name of the file, in percent-encoded UTF-8. See Files for requirements on file names. See String Encoding. // // Content-Type // required // // The MIME type of the content of the file, which will be returned in // the Content-Type header when downloading the file. Use the // Content-Type b2/x-auto to automatically set the stored Content-Type // post upload. In the case where a file extension is absent or the // lookup fails, the Content-Type is set to application/octet-stream. The // Content-Type mappings can be pursued here. // // X-Bz-Content-Sha1 // required // // The SHA1 checksum of the content of the file. B2 will check this when // the file is uploaded, to make sure that the file arrived correctly. It // will be returned in the X-Bz-Content-Sha1 header when the file is // downloaded. // // X-Bz-Info-src_last_modified_millis // optional // // If the original source of the file being uploaded has a last modified // time concept, Backblaze recommends using this spelling of one of your // ten X-Bz-Info-* headers (see below). Using a standard spelling allows // different B2 clients and the B2 web user interface to interoperate // correctly. The value should be a base 10 number which represents a UTC // time when the original source file was last modified. It is a base 10 // number of milliseconds since midnight, January 1, 1970 UTC. This fits // in a 64 bit integer such as the type "long" in the programming // language Java. It is intended to be compatible with Java's time // long. For example, it can be passed directly into the Java call // Date.setTime(long time). // // X-Bz-Info-* // optional // // Up to 10 of these headers may be present. The * part of the header // name is replace with the name of a custom field in the file // information stored with the file, and the value is an arbitrary UTF-8 // string, percent-encoded. The same info headers sent with the upload // will be returned with the download. opts := rest.Opts{ Method: "POST", RootURL: upload.UploadURL, Body: in, ExtraHeaders: map[string]string{ "Authorization": upload.AuthorizationToken, "X-Bz-File-Name": urlEncode(o.fs.root + o.remote), "Content-Type": fs.MimeType(src), sha1Header: calculatedSha1, timeHeader: timeString(modTime), }, ContentLength: &size, } var response api.FileInfo // Don't retry, return a retry error instead err = o.fs.pacer.CallNoRetry(func() (bool, error) { resp, err := o.fs.srv.CallJSON(&opts, nil, &response) retry, err := o.fs.shouldRetry(resp, err) // On retryable error clear UploadURL if retry { fs.Debugf(o, "Clearing upload URL because of error: %v", err) upload = nil } return retry, err }) if err != nil { return err } return o.decodeMetaDataFileInfo(&response) } // Remove an object func (o *Object) Remove() error { if o.fs.opt.Versions { return errNotWithVersions } if o.fs.opt.HardDelete { return o.fs.deleteByID(o.id, o.fs.root+o.remote) } return o.fs.hide(o.fs.root + o.remote) } // MimeType of an Object if known, "" otherwise func (o *Object) MimeType() string { return o.mimeType } // ID returns the ID of the Object if known, or "" if not func (o *Object) ID() string { return o.id } // Check the interfaces are satisfied var ( _ fs.Fs = &Fs{} _ fs.Purger = &Fs{} _ fs.PutStreamer = &Fs{} _ fs.CleanUpper = &Fs{} _ fs.ListRer = &Fs{} _ fs.Object = &Object{} _ fs.MimeTyper = &Object{} _ fs.IDer = &Object{} )
package backend import ( "fmt" "github.com/Monnoroch/golfstream/errors" "github.com/Monnoroch/golfstream/stream" "github.com/siddontang/ledisdb/config" "github.com/siddontang/ledisdb/ledis" "log" "os" "sync" ) type ledisListStream struct { db *ledis.DB key []byte num int32 s int32 l int32 delLock *sync.RWMutex } func (self *ledisListStream) Next() (stream.Event, error) { if self.num >= self.l { return nil, stream.EOI } res, err := self.db.LIndex(self.key, self.num) if err != nil { self.delLock.RUnlock() return nil, err } self.num += 1 if self.num >= self.l { self.delLock.RUnlock() } return stream.Event(res), nil } func (self *ledisListStream) Len() int { return int(self.s - self.num) } func (self *ledisListStream) Drain() { self.num = self.l self.delLock.RUnlock() } type ledisStreamObj struct { db *ledis.DB back *ledisBackend name string key []byte delLock sync.RWMutex refcnt int } func (self *ledisStreamObj) Add(evt stream.Event) error { bs, ok := evt.([]byte) if !ok { return errors.New(fmt.Sprintf("ledisStreamObj.Add: Expected []byte, got %v", evt)) } self.delLock.RLock() defer self.delLock.RUnlock() _, err := self.db.RPush(self.key, bs) return err } func (self *ledisStreamObj) Read(from uint, to uint) (stream.Stream, error) { if from == to { return stream.Empty(), nil } self.delLock.RLock() l, err := self.db.LLen(self.key) if err != nil { return nil, err } if _, _, err := convRange(int(from), int(to), int(l), "ledisStreamObj.Read"); err != nil { return nil, err } return &ledisListStream{self.db, self.key, int32(from), int32(from), int32(to), &self.delLock}, nil } func (self *ledisStreamObj) Interval(from int, to int) (uint, uint, error) { if from == to { return 0, 0, nil } self.delLock.RLock() defer self.delLock.RUnlock() l, err := self.db.LLen(self.key) if err != nil { return 0, 0, err } f, t, err := convRange(from, to, int(l), "ledisStreamObj.Interval") if err != nil { return 0, 0, err } if f == t { return 0, 0, nil } return f, t, nil } func (self *ledisStreamObj) Del(afrom uint, ato uint) (bool, error) { from := int64(afrom) to := int64(ato) if from == to { return true, nil } self.delLock.Lock() defer self.delLock.Unlock() l, err := self.db.LLen(self.key) if err != nil { return false, err } if _, _, err := convRange(int(from), int(to), int(l), "ledisStreamObj.Del"); err != nil { return false, err } if from == 0 && to == l { cnt, err := self.db.LClear(self.key) if err != nil { return false, err } return cnt != 0, nil } if from == 0 { err := self.db.LTrim(self.key, int64(to-1), l) return err == nil, err } if to == l { err := self.db.LTrim(self.key, 0, from-1) return err == nil, err } // TODO: optimize: read smaller part to the memory rest, err := self.db.LRange(self.key, int32(to), int32(l)) if err != nil { return false, err } if err := self.db.LTrim(self.key, 0, from-1); err != nil { return false, err } // TODO: if this fails, we should roll back the trim... but whatever. For now. _, err = self.db.RPush(self.key, rest...) if err != nil { log.Println(fmt.Sprintf("ledisStreamObj.Del: WARNING: RPush failed, but Trim wasn't rolled back. Lost the data.")) } return err == nil, err } func (self *ledisStreamObj) Len() (uint, error) { l, err := self.db.LLen(self.key) if err != nil { return 0, err } return uint(l), nil } func (self *ledisStreamObj) Close() error { return nil } type ledisBackend struct { dirname string ledis *ledis.Ledis db *ledis.DB lock sync.Mutex data map[string]*ledisStreamObj } func (self *ledisBackend) Config() (interface{}, error) { return map[string]interface{}{ "type": "ledis", "arg": self.dirname, }, nil } func (self *ledisBackend) Streams() ([]string, error) { r := make([][]byte, 0, 10) lastKey := []byte{} for { keys, err := self.db.Scan(ledis.LIST, lastKey, 10, false, "") if err != nil { return nil, err } if len(keys) == 0 { break } r = append(r, keys...) lastKey = r[len(r)-1] } res := make([]string, len(r)) for i, v := range r { res[i] = string(v) r[i] = nil // help GC } return res, nil } func (self *ledisBackend) GetStream(name string) (BackendStream, error) { self.lock.Lock() defer self.lock.Unlock() v, ok := self.data[name] if !ok { v = &ledisStreamObj{self.db, self, name, []byte(name), sync.RWMutex{}, 0} self.data[name] = v } v.refcnt += 1 return v, nil } func (self *ledisBackend) Drop() error { return errors.List(). Add(self.ledis.FlushAll()). Add(os.RemoveAll(self.dirname)). Err() } func (self *ledisBackend) Close() error { self.data = nil self.ledis.Close() return nil } func (self *ledisBackend) release(s *ledisStreamObj) { self.lock.Lock() defer self.lock.Unlock() s.refcnt -= 1 if s.refcnt == 0 { delete(self.data, s.name) } } /* Create a backend that stores pushed events in ledisdb. */ func NewLedis(dirname string) (Backend, error) { lcfg := config.NewConfigDefault() lcfg.DataDir = dirname lcfg.Addr = "" lcfg.Databases = 1 ledis, err := ledis.Open(lcfg) if err != nil { return nil, err } db, err := ledis.Select(0) if err != nil { return nil, err } return &ledisBackend{dirname, ledis, db, sync.Mutex{}, map[string]*ledisStreamObj{}}, nil } fix Close method in Ledis package backend import ( "fmt" "github.com/Monnoroch/golfstream/errors" "github.com/Monnoroch/golfstream/stream" "github.com/siddontang/ledisdb/config" "github.com/siddontang/ledisdb/ledis" "log" "os" "sync" ) type ledisListStream struct { db *ledis.DB key []byte num int32 s int32 l int32 delLock *sync.RWMutex } func (self *ledisListStream) Next() (stream.Event, error) { if self.num >= self.l { return nil, stream.EOI } res, err := self.db.LIndex(self.key, self.num) if err != nil { self.delLock.RUnlock() return nil, err } self.num += 1 if self.num >= self.l { self.delLock.RUnlock() } return stream.Event(res), nil } func (self *ledisListStream) Len() int { return int(self.s - self.num) } func (self *ledisListStream) Drain() { self.num = self.l self.delLock.RUnlock() } type ledisStreamObj struct { db *ledis.DB back *ledisBackend name string key []byte delLock sync.RWMutex refcnt int } func (self *ledisStreamObj) Add(evt stream.Event) error { bs, ok := evt.([]byte) if !ok { return errors.New(fmt.Sprintf("ledisStreamObj.Add: Expected []byte, got %v", evt)) } self.delLock.RLock() defer self.delLock.RUnlock() _, err := self.db.RPush(self.key, bs) return err } func (self *ledisStreamObj) Read(from uint, to uint) (stream.Stream, error) { if from == to { return stream.Empty(), nil } self.delLock.RLock() l, err := self.db.LLen(self.key) if err != nil { return nil, err } if _, _, err := convRange(int(from), int(to), int(l), "ledisStreamObj.Read"); err != nil { return nil, err } return &ledisListStream{self.db, self.key, int32(from), int32(from), int32(to), &self.delLock}, nil } func (self *ledisStreamObj) Interval(from int, to int) (uint, uint, error) { if from == to { return 0, 0, nil } self.delLock.RLock() defer self.delLock.RUnlock() l, err := self.db.LLen(self.key) if err != nil { return 0, 0, err } f, t, err := convRange(from, to, int(l), "ledisStreamObj.Interval") if err != nil { return 0, 0, err } if f == t { return 0, 0, nil } return f, t, nil } func (self *ledisStreamObj) Del(afrom uint, ato uint) (bool, error) { from := int64(afrom) to := int64(ato) if from == to { return true, nil } self.delLock.Lock() defer self.delLock.Unlock() l, err := self.db.LLen(self.key) if err != nil { return false, err } if _, _, err := convRange(int(from), int(to), int(l), "ledisStreamObj.Del"); err != nil { return false, err } if from == 0 && to == l { cnt, err := self.db.LClear(self.key) if err != nil { return false, err } return cnt != 0, nil } if from == 0 { err := self.db.LTrim(self.key, int64(to-1), l) return err == nil, err } if to == l { err := self.db.LTrim(self.key, 0, from-1) return err == nil, err } // TODO: optimize: read smaller part to the memory rest, err := self.db.LRange(self.key, int32(to), int32(l)) if err != nil { return false, err } if err := self.db.LTrim(self.key, 0, from-1); err != nil { return false, err } // TODO: if this fails, we should roll back the trim... but whatever. For now. _, err = self.db.RPush(self.key, rest...) if err != nil { log.Println(fmt.Sprintf("ledisStreamObj.Del: WARNING: RPush failed, but Trim wasn't rolled back. Lost the data.")) } return err == nil, err } func (self *ledisStreamObj) Len() (uint, error) { l, err := self.db.LLen(self.key) if err != nil { return 0, err } return uint(l), nil } func (self *ledisStreamObj) Close() error { self.back.release(self) return nil } type ledisBackend struct { dirname string ledis *ledis.Ledis db *ledis.DB lock sync.Mutex data map[string]*ledisStreamObj } func (self *ledisBackend) Config() (interface{}, error) { return map[string]interface{}{ "type": "ledis", "arg": self.dirname, }, nil } func (self *ledisBackend) Streams() ([]string, error) { r := make([][]byte, 0, 10) lastKey := []byte{} for { keys, err := self.db.Scan(ledis.LIST, lastKey, 10, false, "") if err != nil { return nil, err } if len(keys) == 0 { break } r = append(r, keys...) lastKey = r[len(r)-1] } res := make([]string, len(r)) for i, v := range r { res[i] = string(v) r[i] = nil // help GC } return res, nil } func (self *ledisBackend) GetStream(name string) (BackendStream, error) { self.lock.Lock() defer self.lock.Unlock() v, ok := self.data[name] if !ok { v = &ledisStreamObj{self.db, self, name, []byte(name), sync.RWMutex{}, 0} self.data[name] = v } v.refcnt += 1 return v, nil } func (self *ledisBackend) Drop() error { return errors.List(). Add(self.ledis.FlushAll()). Add(os.RemoveAll(self.dirname)). Err() } func (self *ledisBackend) Close() error { self.data = nil self.ledis.Close() return nil } func (self *ledisBackend) release(s *ledisStreamObj) { self.lock.Lock() defer self.lock.Unlock() s.refcnt -= 1 if s.refcnt == 0 { delete(self.data, s.name) } } /* Create a backend that stores pushed events in ledisdb. */ func NewLedis(dirname string) (Backend, error) { lcfg := config.NewConfigDefault() lcfg.DataDir = dirname lcfg.Addr = "" lcfg.Databases = 1 ledis, err := ledis.Open(lcfg) if err != nil { return nil, err } db, err := ledis.Select(0) if err != nil { return nil, err } return &ledisBackend{dirname, ledis, db, sync.Mutex{}, map[string]*ledisStreamObj{}}, nil }
// Copyright Istio Authors // // 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 xds import ( "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "istio.io/istio/pilot/pkg/model" v3 "istio.io/istio/pilot/pkg/xds/v3" "istio.io/pkg/monitoring" ) var ( errTag = monitoring.MustCreateLabel("err") nodeTag = monitoring.MustCreateLabel("node") typeTag = monitoring.MustCreateLabel("type") versionTag = monitoring.MustCreateLabel("version") // pilot_total_xds_rejects should be used instead. This is for backwards compatibility cdsReject = monitoring.NewGauge( "pilot_xds_cds_reject", "Pilot rejected CDS configs.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility edsReject = monitoring.NewGauge( "pilot_xds_eds_reject", "Pilot rejected EDS.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility ldsReject = monitoring.NewGauge( "pilot_xds_lds_reject", "Pilot rejected LDS.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility rdsReject = monitoring.NewGauge( "pilot_xds_rds_reject", "Pilot rejected RDS.", monitoring.WithLabels(nodeTag, errTag), ) totalXDSRejects = monitoring.NewSum( "pilot_total_xds_rejects", "Total number of XDS responses from pilot rejected by proxy.", monitoring.WithLabels(typeTag), ) // Number of delayed pushes. Currently this happens only when the last push has not been ACKed totalDelayedPushes = monitoring.NewSum( "pilot_xds_delayed_pushes_total", "Total number of XDS pushes that are delayed.", monitoring.WithLabels(typeTag), ) // Number of delayed pushes that we pushed prematurely as a failsafe. // This indicates that either the failsafe timeout is too aggressive or there is a deadlock totalDelayedPushTimeouts = monitoring.NewSum( "pilot_xds_delayed_push_timeouts_total", "Total number of XDS pushes that are delayed and timed out", monitoring.WithLabels(typeTag), ) xdsExpiredNonce = monitoring.NewSum( "pilot_xds_expired_nonce", "Total number of XDS requests with an expired nonce.", monitoring.WithLabels(typeTag), ) monServices = monitoring.NewGauge( "pilot_services", "Total services known to pilot.", ) // TODO: Update all the resource stats in separate routine // virtual services, destination rules, gateways, etc. xdsClients = monitoring.NewGauge( "pilot_xds", "Number of endpoints connected to this pilot using XDS.", monitoring.WithLabels(versionTag), ) xdsClientTrackerMutex = &sync.Mutex{} xdsClientTracker = make(map[string]float64) xdsResponseWriteTimeouts = monitoring.NewSum( "pilot_xds_write_timeout", "Pilot XDS response write timeouts.", ) // Covers xds_builderr and xds_senderr for xds in {lds, rds, cds, eds}. pushes = monitoring.NewSum( "pilot_xds_pushes", "Pilot build and send errors for lds, rds, cds and eds.", monitoring.WithLabels(typeTag), ) cdsSendErrPushes = pushes.With(typeTag.Value("cds_senderr")) edsSendErrPushes = pushes.With(typeTag.Value("eds_senderr")) ldsSendErrPushes = pushes.With(typeTag.Value("lds_senderr")) rdsSendErrPushes = pushes.With(typeTag.Value("rds_senderr")) debounceTime = monitoring.NewDistribution( "pilot_debounce_time", "Delay in seconds between the first config enters debouncing and the merged push request is pushed into the push queue.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, ) pushContextInitTime = monitoring.NewDistribution( "pilot_pushcontext_init_seconds", "Total time in seconds Pilot takes to init pushContext.", []float64{.01, .1, 0.5, 1, 3, 5}, ) pushTime = monitoring.NewDistribution( "pilot_xds_push_time", "Total time in seconds Pilot takes to push lds, rds, cds and eds.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, monitoring.WithLabels(typeTag), ) sendTime = monitoring.NewDistribution( "pilot_xds_send_time", "Total time in seconds Pilot takes to send generated configuration.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, ) // only supported dimension is millis, unfortunately. default to unitdimensionless. proxiesQueueTime = monitoring.NewDistribution( "pilot_proxy_queue_time", "Time in seconds, a proxy is in the push queue before being dequeued.", []float64{.1, .5, 1, 3, 5, 10, 20, 30}, ) pushTriggers = monitoring.NewSum( "pilot_push_triggers", "Total number of times a push was triggered, labeled by reason for the push.", monitoring.WithLabels(typeTag), ) // only supported dimension is millis, unfortunately. default to unitdimensionless. proxiesConvergeDelay = monitoring.NewDistribution( "pilot_proxy_convergence_time", "Delay in seconds between config change and a proxy receiving all required configuration.", []float64{.1, .5, 1, 3, 5, 10, 20, 30}, ) pushContextErrors = monitoring.NewSum( "pilot_xds_push_context_errors", "Number of errors (timeouts) initiating push context.", ) totalXDSInternalErrors = monitoring.NewSum( "pilot_total_xds_internal_errors", "Total number of internal XDS errors in pilot.", ) inboundUpdates = monitoring.NewSum( "pilot_inbound_updates", "Total number of updates received by pilot.", monitoring.WithLabels(typeTag), ) pilotSDSCertificateErrors = monitoring.NewSum( "pilot_sds_certificate_errors_total", "Total number of failures to fetch SDS key and certificate.", ) inboundConfigUpdates = inboundUpdates.With(typeTag.Value("config")) inboundEDSUpdates = inboundUpdates.With(typeTag.Value("eds")) inboundServiceUpdates = inboundUpdates.With(typeTag.Value("svc")) inboundServiceDeletes = inboundUpdates.With(typeTag.Value("svcdelete")) configSizeBytes = monitoring.NewDistribution( "pilot_xds_config_size_bytes", "Distribution of configuration sizes pushed to clients", // Important boundaries: 10K, 1M, 4M, 10M, 40M // 4M default limit for gRPC, 10M config will start to strain system, // 40M is likely upper-bound on config sizes supported. []float64{1, 10000, 1000000, 4000000, 10000000, 40000000}, monitoring.WithLabels(typeTag), monitoring.WithUnit(monitoring.Bytes), ) ) func recordXDSClients(version string, delta float64) { xdsClientTrackerMutex.Lock() defer xdsClientTrackerMutex.Unlock() xdsClientTracker[version] += delta xdsClients.With(versionTag.Value(version)).Record(xdsClientTracker[version]) } // triggerMetric is a precomputed monitoring.Metric for each trigger type. This saves on a lot of allocations var triggerMetric = map[model.TriggerReason]monitoring.Metric{ model.EndpointUpdate: pushTriggers.With(typeTag.Value(string(model.EndpointUpdate))), model.ConfigUpdate: pushTriggers.With(typeTag.Value(string(model.ConfigUpdate))), model.ServiceUpdate: pushTriggers.With(typeTag.Value(string(model.ServiceUpdate))), model.ProxyUpdate: pushTriggers.With(typeTag.Value(string(model.ProxyUpdate))), model.GlobalUpdate: pushTriggers.With(typeTag.Value(string(model.GlobalUpdate))), model.UnknownTrigger: pushTriggers.With(typeTag.Value(string(model.UnknownTrigger))), model.DebugTrigger: pushTriggers.With(typeTag.Value(string(model.DebugTrigger))), model.SecretTrigger: pushTriggers.With(typeTag.Value(string(model.SecretTrigger))), model.NetworksTrigger: pushTriggers.With(typeTag.Value(string(model.NetworksTrigger))), model.ProxyRequest: pushTriggers.With(typeTag.Value(string(model.ProxyRequest))), model.NamespaceUpdate: pushTriggers.With(typeTag.Value(string(model.NamespaceUpdate))), model.ClusterUpdate: pushTriggers.With(typeTag.Value(string(model.ClusterUpdate))), } func recordPushTriggers(reasons ...model.TriggerReason) { for _, r := range reasons { t, f := triggerMetric[r] if f { t.Increment() } else { pushTriggers.With(typeTag.Value(string(r))).Increment() } } } func isUnexpectedError(err error) bool { s, ok := status.FromError(err) // Unavailable or canceled code will be sent when a connection is closing down. This is very normal, // due to the XDS connection being dropped every 30 minutes, or a pod shutting down. isError := s.Code() != codes.Unavailable && s.Code() != codes.Canceled return !ok || isError } // recordSendError records a metric indicating that a push failed. It returns true if this was an unexpected // error func recordSendError(xdsType string, err error) bool { if isUnexpectedError(err) { // TODO use a single metric with a type tag switch xdsType { case v3.ListenerType: ldsSendErrPushes.Increment() case v3.ClusterType: cdsSendErrPushes.Increment() case v3.EndpointType: edsSendErrPushes.Increment() case v3.RouteType: rdsSendErrPushes.Increment() } return true } return false } func incrementXDSRejects(xdsType string, node, errCode string) { totalXDSRejects.With(typeTag.Value(v3.GetMetricType(xdsType))).Increment() switch xdsType { case v3.ListenerType: ldsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.ClusterType: cdsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.EndpointType: edsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.RouteType: rdsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() } } func recordSendTime(duration time.Duration) { sendTime.Record(duration.Seconds()) } func recordPushTime(xdsType string, duration time.Duration) { pushTime.With(typeTag.Value(v3.GetMetricType(xdsType))).Record(duration.Seconds()) pushes.With(typeTag.Value(v3.GetMetricType(xdsType))).Increment() } func init() { monitoring.MustRegister( cdsReject, edsReject, ldsReject, rdsReject, xdsExpiredNonce, totalXDSRejects, monServices, xdsClients, xdsResponseWriteTimeouts, pushes, debounceTime, pushContextInitTime, pushTime, proxiesConvergeDelay, proxiesQueueTime, pushContextErrors, totalXDSInternalErrors, inboundUpdates, pushTriggers, sendTime, totalDelayedPushes, totalDelayedPushTimeouts, pilotSDSCertificateErrors, configSizeBytes, ) } Fix stale comments (#40641) Fixes https://github.com/istio/istio/issues/39147 // Copyright Istio Authors // // 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 xds import ( "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "istio.io/istio/pilot/pkg/model" v3 "istio.io/istio/pilot/pkg/xds/v3" "istio.io/pkg/monitoring" ) var ( errTag = monitoring.MustCreateLabel("err") nodeTag = monitoring.MustCreateLabel("node") typeTag = monitoring.MustCreateLabel("type") versionTag = monitoring.MustCreateLabel("version") // pilot_total_xds_rejects should be used instead. This is for backwards compatibility cdsReject = monitoring.NewGauge( "pilot_xds_cds_reject", "Pilot rejected CDS configs.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility edsReject = monitoring.NewGauge( "pilot_xds_eds_reject", "Pilot rejected EDS.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility ldsReject = monitoring.NewGauge( "pilot_xds_lds_reject", "Pilot rejected LDS.", monitoring.WithLabels(nodeTag, errTag), ) // pilot_total_xds_rejects should be used instead. This is for backwards compatibility rdsReject = monitoring.NewGauge( "pilot_xds_rds_reject", "Pilot rejected RDS.", monitoring.WithLabels(nodeTag, errTag), ) totalXDSRejects = monitoring.NewSum( "pilot_total_xds_rejects", "Total number of XDS responses from pilot rejected by proxy.", monitoring.WithLabels(typeTag), ) // Number of delayed pushes. Currently this happens only when the last push has not been ACKed totalDelayedPushes = monitoring.NewSum( "pilot_xds_delayed_pushes_total", "Total number of XDS pushes that are delayed.", monitoring.WithLabels(typeTag), ) // Number of delayed pushes that we pushed prematurely as a failsafe. // This indicates that either the failsafe timeout is too aggressive or there is a deadlock totalDelayedPushTimeouts = monitoring.NewSum( "pilot_xds_delayed_push_timeouts_total", "Total number of XDS pushes that are delayed and timed out", monitoring.WithLabels(typeTag), ) xdsExpiredNonce = monitoring.NewSum( "pilot_xds_expired_nonce", "Total number of XDS requests with an expired nonce.", monitoring.WithLabels(typeTag), ) monServices = monitoring.NewGauge( "pilot_services", "Total services known to pilot.", ) // TODO: Update all the resource stats in separate routine // virtual services, destination rules, gateways, etc. xdsClients = monitoring.NewGauge( "pilot_xds", "Number of endpoints connected to this pilot using XDS.", monitoring.WithLabels(versionTag), ) xdsClientTrackerMutex = &sync.Mutex{} xdsClientTracker = make(map[string]float64) xdsResponseWriteTimeouts = monitoring.NewSum( "pilot_xds_write_timeout", "Pilot XDS response write timeouts.", ) // Covers xds_builderr and xds_senderr for xds in {lds, rds, cds, eds}. pushes = monitoring.NewSum( "pilot_xds_pushes", "Pilot build and send errors for lds, rds, cds and eds.", monitoring.WithLabels(typeTag), ) cdsSendErrPushes = pushes.With(typeTag.Value("cds_senderr")) edsSendErrPushes = pushes.With(typeTag.Value("eds_senderr")) ldsSendErrPushes = pushes.With(typeTag.Value("lds_senderr")) rdsSendErrPushes = pushes.With(typeTag.Value("rds_senderr")) debounceTime = monitoring.NewDistribution( "pilot_debounce_time", "Delay in seconds between the first config enters debouncing and the merged push request is pushed into the push queue.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, ) pushContextInitTime = monitoring.NewDistribution( "pilot_pushcontext_init_seconds", "Total time in seconds Pilot takes to init pushContext.", []float64{.01, .1, 0.5, 1, 3, 5}, ) pushTime = monitoring.NewDistribution( "pilot_xds_push_time", "Total time in seconds Pilot takes to push lds, rds, cds and eds.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, monitoring.WithLabels(typeTag), ) sendTime = monitoring.NewDistribution( "pilot_xds_send_time", "Total time in seconds Pilot takes to send generated configuration.", []float64{.01, .1, 1, 3, 5, 10, 20, 30}, ) proxiesQueueTime = monitoring.NewDistribution( "pilot_proxy_queue_time", "Time in seconds, a proxy is in the push queue before being dequeued.", []float64{.1, .5, 1, 3, 5, 10, 20, 30}, ) pushTriggers = monitoring.NewSum( "pilot_push_triggers", "Total number of times a push was triggered, labeled by reason for the push.", monitoring.WithLabels(typeTag), ) proxiesConvergeDelay = monitoring.NewDistribution( "pilot_proxy_convergence_time", "Delay in seconds between config change and a proxy receiving all required configuration.", []float64{.1, .5, 1, 3, 5, 10, 20, 30}, ) pushContextErrors = monitoring.NewSum( "pilot_xds_push_context_errors", "Number of errors (timeouts) initiating push context.", ) totalXDSInternalErrors = monitoring.NewSum( "pilot_total_xds_internal_errors", "Total number of internal XDS errors in pilot.", ) inboundUpdates = monitoring.NewSum( "pilot_inbound_updates", "Total number of updates received by pilot.", monitoring.WithLabels(typeTag), ) pilotSDSCertificateErrors = monitoring.NewSum( "pilot_sds_certificate_errors_total", "Total number of failures to fetch SDS key and certificate.", ) inboundConfigUpdates = inboundUpdates.With(typeTag.Value("config")) inboundEDSUpdates = inboundUpdates.With(typeTag.Value("eds")) inboundServiceUpdates = inboundUpdates.With(typeTag.Value("svc")) inboundServiceDeletes = inboundUpdates.With(typeTag.Value("svcdelete")) configSizeBytes = monitoring.NewDistribution( "pilot_xds_config_size_bytes", "Distribution of configuration sizes pushed to clients", // Important boundaries: 10K, 1M, 4M, 10M, 40M // 4M default limit for gRPC, 10M config will start to strain system, // 40M is likely upper-bound on config sizes supported. []float64{1, 10000, 1000000, 4000000, 10000000, 40000000}, monitoring.WithLabels(typeTag), monitoring.WithUnit(monitoring.Bytes), ) ) func recordXDSClients(version string, delta float64) { xdsClientTrackerMutex.Lock() defer xdsClientTrackerMutex.Unlock() xdsClientTracker[version] += delta xdsClients.With(versionTag.Value(version)).Record(xdsClientTracker[version]) } // triggerMetric is a precomputed monitoring.Metric for each trigger type. This saves on a lot of allocations var triggerMetric = map[model.TriggerReason]monitoring.Metric{ model.EndpointUpdate: pushTriggers.With(typeTag.Value(string(model.EndpointUpdate))), model.ConfigUpdate: pushTriggers.With(typeTag.Value(string(model.ConfigUpdate))), model.ServiceUpdate: pushTriggers.With(typeTag.Value(string(model.ServiceUpdate))), model.ProxyUpdate: pushTriggers.With(typeTag.Value(string(model.ProxyUpdate))), model.GlobalUpdate: pushTriggers.With(typeTag.Value(string(model.GlobalUpdate))), model.UnknownTrigger: pushTriggers.With(typeTag.Value(string(model.UnknownTrigger))), model.DebugTrigger: pushTriggers.With(typeTag.Value(string(model.DebugTrigger))), model.SecretTrigger: pushTriggers.With(typeTag.Value(string(model.SecretTrigger))), model.NetworksTrigger: pushTriggers.With(typeTag.Value(string(model.NetworksTrigger))), model.ProxyRequest: pushTriggers.With(typeTag.Value(string(model.ProxyRequest))), model.NamespaceUpdate: pushTriggers.With(typeTag.Value(string(model.NamespaceUpdate))), model.ClusterUpdate: pushTriggers.With(typeTag.Value(string(model.ClusterUpdate))), } func recordPushTriggers(reasons ...model.TriggerReason) { for _, r := range reasons { t, f := triggerMetric[r] if f { t.Increment() } else { pushTriggers.With(typeTag.Value(string(r))).Increment() } } } func isUnexpectedError(err error) bool { s, ok := status.FromError(err) // Unavailable or canceled code will be sent when a connection is closing down. This is very normal, // due to the XDS connection being dropped every 30 minutes, or a pod shutting down. isError := s.Code() != codes.Unavailable && s.Code() != codes.Canceled return !ok || isError } // recordSendError records a metric indicating that a push failed. It returns true if this was an unexpected // error func recordSendError(xdsType string, err error) bool { if isUnexpectedError(err) { // TODO use a single metric with a type tag switch xdsType { case v3.ListenerType: ldsSendErrPushes.Increment() case v3.ClusterType: cdsSendErrPushes.Increment() case v3.EndpointType: edsSendErrPushes.Increment() case v3.RouteType: rdsSendErrPushes.Increment() } return true } return false } func incrementXDSRejects(xdsType string, node, errCode string) { totalXDSRejects.With(typeTag.Value(v3.GetMetricType(xdsType))).Increment() switch xdsType { case v3.ListenerType: ldsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.ClusterType: cdsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.EndpointType: edsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() case v3.RouteType: rdsReject.With(nodeTag.Value(node), errTag.Value(errCode)).Increment() } } func recordSendTime(duration time.Duration) { sendTime.Record(duration.Seconds()) } func recordPushTime(xdsType string, duration time.Duration) { pushTime.With(typeTag.Value(v3.GetMetricType(xdsType))).Record(duration.Seconds()) pushes.With(typeTag.Value(v3.GetMetricType(xdsType))).Increment() } func init() { monitoring.MustRegister( cdsReject, edsReject, ldsReject, rdsReject, xdsExpiredNonce, totalXDSRejects, monServices, xdsClients, xdsResponseWriteTimeouts, pushes, debounceTime, pushContextInitTime, pushTime, proxiesConvergeDelay, proxiesQueueTime, pushContextErrors, totalXDSInternalErrors, inboundUpdates, pushTriggers, sendTime, totalDelayedPushes, totalDelayedPushTimeouts, pilotSDSCertificateErrors, configSizeBytes, ) }
/* Copyright 2014 Huawei Technologies Co., Ltd. All rights reserved. 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 module import ( "encoding/json" "errors" "strconv" "strings" "time" "github.com/Huawei/containerops/pilotage/models" "github.com/Huawei/containerops/pilotage/utils" log "github.com/Sirupsen/logrus" "github.com/containerops/configure" ) const ( PipelineStopReasonTimeout = "TIME_OUT" PipelineStopReasonRunSuccess = "RunSuccess" PipelineStopReasonRunFailed = "RunFailed" ) var ( startPipelineChan chan bool createPipelineChan chan bool pipelinelogAuthChan chan bool pipelinelogListenChan chan bool pipelinelogSequenceGenerateChan chan bool ) func init() { startPipelineChan = make(chan bool, 1) createPipelineChan = make(chan bool, 1) pipelinelogAuthChan = make(chan bool, 1) pipelinelogListenChan = make(chan bool, 1) pipelinelogSequenceGenerateChan = make(chan bool, 1) } type Pipeline struct { *models.Pipeline } type PipelineLog struct { *models.PipelineLog } // CreateNewPipeline is create a new pipeline with given data func CreateNewPipeline(namespace, repository, pipelineName, pipelineVersion string) (string, error) { createPipelineChan <- true defer func() { <-createPipelineChan }() var count int64 err := new(models.Pipeline).GetPipeline().Where("namespace = ?", namespace).Where("pipeline = ?", pipelineName).Order("-id").Count(&count).Error if err != nil { return "", errors.New("error when query pipeline data in database:" + err.Error()) } if count > 0 { return "", errors.New("pipelien name is exist!") } pipelineInfo := new(models.Pipeline) pipelineInfo.Namespace = namespace pipelineInfo.Repository = repository pipelineInfo.Pipeline = pipelineName pipelineInfo.Version = pipelineVersion pipelineInfo.VersionCode = 1 err = pipelineInfo.GetPipeline().Save(pipelineInfo).Error if err != nil { return "", errors.New("error when save pipeline info:" + err.Error()) } return "create new pipeline success", nil } func GetPipelineListByNamespaceAndRepository(namespace, repository string) ([]map[string]interface{}, error) { resultMap := make([]map[string]interface{}, 0) pipelineList := make([]models.Pipeline, 0) pipelinesMap := make(map[string]interface{}, 0) err := new(models.Pipeline).GetPipeline().Where("namespace = ?", namespace).Where("repository = ?", repository).Order("-updated_at").Find(&pipelineList).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipeline's GetPipelineListByNamespaceAndRepository]error when get pipeline list from db:" + err.Error()) return nil, errors.New("error when get pipeline list by namespace and repository from db:" + err.Error()) } for _, pipelineInfo := range pipelineList { if _, ok := pipelinesMap[pipelineInfo.Pipeline]; !ok { tempMap := make(map[string]interface{}) tempMap["version"] = make(map[int64]interface{}) pipelinesMap[pipelineInfo.Pipeline] = tempMap } pipelineMap := pipelinesMap[pipelineInfo.Pipeline].(map[string]interface{}) versionMap := pipelineMap["version"].(map[int64]interface{}) versionMap[pipelineInfo.VersionCode] = pipelineInfo pipelineMap["id"] = pipelineInfo.ID pipelineMap["name"] = pipelineInfo.Pipeline pipelineMap["version"] = versionMap } for _, pipeline := range pipelineList { pipelineInfo := pipelinesMap[pipeline.Pipeline].(map[string]interface{}) if isSign, ok := pipelineInfo["isSign"].(bool); ok && isSign { continue } pipelineInfo["isSign"] = true pipelinesMap[pipeline.Pipeline] = pipelineInfo versionList := make([]map[string]interface{}, 0) for _, pipelineVersion := range pipelineList { if pipelineVersion.Pipeline == pipelineInfo["name"].(string) { versionMap := make(map[string]interface{}) versionMap["id"] = pipelineVersion.ID versionMap["version"] = pipelineVersion.Version versionMap["versionCode"] = pipelineVersion.VersionCode // get current version latest run result outcome := new(models.Outcome) err := outcome.GetOutcome().Where("real_pipeline = ?", pipelineVersion.ID).Where("real_action = ?", 0).Order("-id").First(outcome).Error if err != nil && strings.Contains(err.Error(), "record not found") { log.Info("can't get pipeline(" + pipelineVersion.Pipeline + "} version(" + pipelineVersion.Version + ")'s input info:" + err.Error()) } if outcome.ID != 0 { statusMap := make(map[string]interface{}) statusMap["status"] = false statusMap["time"] = outcome.CreatedAt.Format("2006-01-02 15:04:05") finalResult := new(models.Outcome) err := finalResult.GetOutcome().Where("pipeline = ?", outcome.Pipeline).Where("sequence = ?", outcome.Sequence).Where("action = ?", -1).First(finalResult).Error if err != nil && strings.Contains(err.Error(), "record not found") { log.Info("can't get pipeline(" + pipelineVersion.Pipeline + "} version(" + pipelineVersion.Version + ")'s output info:" + err.Error()) } if finalResult.ID != 0 && finalResult.Status { statusMap["status"] = finalResult.Status } versionMap["status"] = statusMap } versionList = append(versionList, versionMap) } } tempResult := make(map[string]interface{}) tempResult["id"] = pipelineInfo["id"] tempResult["name"] = pipelineInfo["name"] tempResult["version"] = versionList resultMap = append(resultMap, tempResult) } return resultMap, nil } func GetPipelineInfo(namespace, repository, pipelineName string, pipelineId int64) (map[string]interface{}, error) { resultMap := make(map[string]interface{}) pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(&pipelineInfo).Error if err != nil { return nil, errors.New("error when get pipeline info from db:" + err.Error()) } if pipelineInfo.Namespace != namespace || pipelineInfo.Repository != repository || pipelineInfo.Pipeline != pipelineName { return nil, errors.New("pipeline is not equal to target pipeline") } // get pipeline define json first, if has a define json,return it if pipelineInfo.Manifest != "" { defineMap := make(map[string]interface{}) json.Unmarshal([]byte(pipelineInfo.Manifest), &defineMap) if defineInfo, ok := defineMap["define"]; ok { if defineInfoMap, ok := defineInfo.(map[string]interface{}); ok { defineInfoMap["status"] = pipelineInfo.State == models.PipelineStateAble return defineInfoMap, nil } } } // get all stage info of current pipeline // if a pipeline done have a define of itself // then the pipeline is a new pipeline ,so only get it's stage list is ok stageList, err := getDefaultStageListByPipeline(*pipelineInfo) if err != nil { return nil, err } resultMap["stageList"] = stageList // resultMap["stageList"] = make([]map[string]interface{}, 0) resultMap["lineList"] = make([]map[string]interface{}, 0) resultMap["status"] = false return resultMap, nil } func getDefaultStageListByPipeline(pipelineInfo models.Pipeline) ([]map[string]interface{}, error) { stageListMap := make([]map[string]interface{}, 0) startStage := make(map[string]interface{}) startStage["id"] = "start-stage" startStage["type"] = "pipeline-start" startStage["setupData"] = make(map[string]interface{}) stageListMap = append(stageListMap, startStage) addStage := make(map[string]interface{}) addStage["id"] = "add-stage" addStage["type"] = "pipeline-add-stage" stageListMap = append(stageListMap, addStage) endStage := make(map[string]interface{}) endStage["id"] = "end-stage" endStage["type"] = "pipeline-end" endStage["setupData"] = make(map[string]interface{}) stageListMap = append(stageListMap, endStage) return stageListMap, nil } func GetStageHistoryInfo(stageLogId int64) (map[string]interface{}, error) { result := make(map[string]interface{}) // get all actions that belong to current stage , // return stage info and action{id:actionId, name:actionName, status:true/false} actionList := make([]models.ActionLog, 0) actionListMap := make([]map[string]interface{}, 0) stageInfo := new(models.StageLog) stageStatus := true stageInfo.GetStageLog().Where("id = ?", stageLogId).First(stageInfo) new(models.ActionLog).GetActionLog().Where("stage = ?", stageLogId).Find(&actionList) for _, action := range actionList { actionOutcome := new(models.Outcome) new(models.Outcome).GetOutcome().Where("action = ?", action.ID).First(actionOutcome) actionMap := make(map[string]interface{}) actionMap["id"] = "a-" + strconv.FormatInt(action.ID, 10) actionMap["name"] = action.Action if actionOutcome.Status { actionMap["status"] = true } else { actionMap["status"] = false stageStatus = false } actionListMap = append(actionListMap, actionMap) } firstActionStartEvent := new(models.Event) leastActionStopEvent := new(models.Event) firstActionStartEvent.GetEvent().Where("stage = ?", stageInfo.ID).Where("title = ?", "COMPONENT_START").Order("created_at").First(firstActionStartEvent) leastActionStopEvent.GetEvent().Where("stage = ?", stageInfo.ID).Where("title = ?", "COMPONENT_STOP").Order("-created_at").First(leastActionStopEvent) stageRunTime := "" if firstActionStartEvent.ID != 0 { stageRunTime = firstActionStartEvent.CreatedAt.Format("2006-01-02 15:04:05") stageRunTime += " - " if leastActionStopEvent.ID != 0 { stageRunTime += leastActionStopEvent.CreatedAt.Format("2006-01-02 15:04:05") } } result["name"] = stageInfo.Stage result["status"] = stageStatus result["actions"] = actionListMap result["runTime"] = stageRunTime return result, nil } func Run(pipelineId int64, authMap map[string]interface{}, startData string) error { pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(pipelineInfo).Error if err != nil { log.Error("[pipeline's Run]:error when get pipeline's info from db:", err.Error()) return errors.New("error when get target pipeline info:" + err.Error()) } pipeline := new(Pipeline) pipeline.Pipeline = pipelineInfo // first generate a pipeline log to record all current pipeline's info which will be used in feature pipelineLog, err := pipeline.GenerateNewLog() if err != nil { return err } // let pipeline log listen all auth, if all auth is ok, start run this pipeline log err = pipelineLog.Listen(startData) if err != nil { return err } // auth this pipeline log by given auth info err = pipelineLog.Auth(authMap) if err != nil { return err } return nil } func GetPipeline(pipelineId int64) (*Pipeline, error) { if pipelineId == int64(0) { return nil, errors.New("pipeline's id is empty") } pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(pipelineInfo).Error if err != nil { log.Error("[pipeline's GetPipeline]:error when get pipeline info from db:", err.Error()) return nil, err } pipeline := new(Pipeline) pipeline.Pipeline = pipelineInfo return pipeline, nil } func GetPipelineLog(namespace, repository, versionName string, sequence int64) (*PipelineLog, error) { var err error pipelineLogInfo := new(models.PipelineLog) query := pipelineLogInfo.GetPipelineLog().Where("namespace =? ", namespace).Where("repository = ?", repository).Where("version = ?", versionName) if sequence == int64(0) { query = query.Order("-id") } else { query = query.Where("sequence = ?", sequence) } err = query.First(pipelineLogInfo).Error if err != nil { log.Error("[pipelineLog's GetPipelineLog]:error when get pipelineLog(version=", versionName, ", sequence=", sequence, ") info from db:", err.Error()) return nil, err } pipelineLog := new(PipelineLog) pipelineLog.PipelineLog = pipelineLogInfo return pipelineLog, nil } func getPipelineEnvList(pipelineLogId int64) ([]map[string]interface{}, error) { resultList := make([]map[string]interface{}, 0) pipelineLog := new(models.PipelineLog) err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLogId).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's getPipelineEnvList]:error when get pipelinelog info from db:", err.Error()) return nil, errors.New("error when get pipeline info from db:" + err.Error()) } envMap := make(map[string]string) if pipelineLog.Env != "" { err = json.Unmarshal([]byte(pipelineLog.Env), &envMap) if err != nil { log.Error("[pipelineLog's getPipelineEnvList]:error when unmarshal pipeline's env setting:", pipelineLog.Env, " ===>error is:", err.Error()) return nil, errors.New("error when unmarshal pipeline env info" + err.Error()) } } for key, value := range envMap { tempEnvMap := make(map[string]interface{}) tempEnvMap["name"] = key tempEnvMap["value"] = value resultList = append(resultList, tempEnvMap) } return resultList, nil } func GetPipelineRunHistoryList(namespace, repository string) ([]map[string]interface{}, error) { resultList := make([]map[string]interface{}, 0) pipelineLogIndexMap := make(map[string]int) pipelineLogVersionIndexMap := make(map[string]interface{}) pipelineLogList := make([]models.PipelineLog, 0) err := new(models.PipelineLog).GetPipelineLog().Where("namespace = ?", namespace).Where("repository = ?", repository).Order("-id").Find(&pipelineLogList).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipeline's GetPipelineRunHistoryList]:error when get pipelineLog list from db:", err.Error()) return nil, err } for _, pipelinelog := range pipelineLogList { if _, ok := pipelineLogIndexMap[pipelinelog.Pipeline]; !ok { pipelineInfoMap := make(map[string]interface{}) pipelineVersionListInfoMap := make([]map[string]interface{}, 0) pipelineInfoMap["id"] = pipelinelog.FromPipeline pipelineInfoMap["name"] = pipelinelog.Pipeline pipelineInfoMap["versionList"] = pipelineVersionListInfoMap resultList = append(resultList, pipelineInfoMap) pipelineLogIndexMap[pipelinelog.Pipeline] = len(resultList) - 1 versionIndexMap := make(map[string]int64) pipelineLogVersionIndexMap[pipelinelog.Pipeline] = versionIndexMap } pipelineInfoMap := resultList[pipelineLogIndexMap[pipelinelog.Pipeline]] if _, ok := pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string]int64)[pipelinelog.Version]; !ok { pipelineVersionInfoMap := make(map[string]interface{}) pipelineVersionSequenceListInfoMap := make([]map[string]interface{}, 0) pipelineVersionInfoMap["id"] = pipelinelog.ID pipelineVersionInfoMap["name"] = pipelinelog.Version pipelineVersionInfoMap["info"] = "" pipelineVersionInfoMap["total"] = int64(0) pipelineVersionInfoMap["success"] = int64(0) pipelineVersionInfoMap["sequenceList"] = pipelineVersionSequenceListInfoMap pipelineInfoMap["versionList"] = append(pipelineInfoMap["versionList"].([]map[string]interface{}), pipelineVersionInfoMap) pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string]int64)[pipelinelog.Version] = int64(len(pipelineInfoMap["versionList"].([]map[string]interface{})) - 1) } pipelineVersionInfoMap := pipelineInfoMap["versionList"].([]map[string]interface{})[pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string](int64))[pipelinelog.Version]] sequenceList := pipelineVersionInfoMap["sequenceList"].([]map[string]interface{}) sequenceInfoMap := make(map[string]interface{}) sequenceInfoMap["pipelineSequenceID"] = pipelinelog.ID sequenceInfoMap["sequence"] = pipelinelog.Sequence sequenceInfoMap["status"] = pipelinelog.RunState sequenceInfoMap["time"] = pipelinelog.CreatedAt sequenceList = append(sequenceList, sequenceInfoMap) pipelineVersionInfoMap["sequenceList"] = sequenceList pipelineVersionInfoMap["total"] = pipelineVersionInfoMap["total"].(int64) + 1 if pipelinelog.RunState == models.PipelineLogStateRunSuccess { pipelineVersionInfoMap["success"] = pipelineVersionInfoMap["success"].(int64) + 1 } } for _, pipelineInfoMap := range resultList { for _, versionInfoMap := range pipelineInfoMap["versionList"].([]map[string]interface{}) { success := versionInfoMap["success"].(int64) total := versionInfoMap["total"].(int64) versionInfoMap["info"] = "Success: " + strconv.FormatInt(success, 10) + " Total: " + strconv.FormatInt(total, 10) } } return resultList, nil } func (pipelineInfo *Pipeline) CreateNewVersion(define map[string]interface{}, versionName string) error { var count int64 err := new(models.Pipeline).GetPipeline().Where("namespace = ?", pipelineInfo.Namespace).Where("repository = ?", pipelineInfo.Repository).Where("pipeline = ?", pipelineInfo.Pipeline.Pipeline).Where("version = ?", versionName).Count(&count).Error if count > 0 { return errors.New("version code already exist!") } // get current least pipeline's version leastPipeline := new(models.Pipeline) err = leastPipeline.GetPipeline().Where("namespace = ? ", pipelineInfo.Namespace).Where("pipeline = ?", pipelineInfo.Pipeline.Pipeline).Order("-id").First(&leastPipeline).Error if err != nil { return errors.New("error when get least pipeline info :" + err.Error()) } newPipelineInfo := new(models.Pipeline) newPipelineInfo.Namespace = pipelineInfo.Namespace newPipelineInfo.Repository = pipelineInfo.Repository newPipelineInfo.Pipeline = pipelineInfo.Pipeline.Pipeline newPipelineInfo.Event = pipelineInfo.Event newPipelineInfo.Version = versionName newPipelineInfo.VersionCode = leastPipeline.VersionCode + 1 newPipelineInfo.State = models.PipelineStateDisable newPipelineInfo.Manifest = pipelineInfo.Manifest newPipelineInfo.Description = pipelineInfo.Description newPipelineInfo.SourceInfo = pipelineInfo.SourceInfo newPipelineInfo.Env = pipelineInfo.Env newPipelineInfo.Requires = pipelineInfo.Requires err = newPipelineInfo.GetPipeline().Save(newPipelineInfo).Error if err != nil { return err } return pipelineInfo.UpdatePipelineInfo(define) } func (pipelineInfo *Pipeline) GetPipelineToken() (map[string]interface{}, error) { result := make(map[string]interface{}) if pipelineInfo.ID == 0 { log.Error("[pipeline's GetPipelineToken]:got an empty pipelin:", pipelineInfo) return nil, errors.New("pipeline's info is empty") } token := "" tokenMap := make(map[string]interface{}) if pipelineInfo.SourceInfo == "" { // if sourceInfo is empty generate a token token = utils.MD5(pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline) } else { json.Unmarshal([]byte(pipelineInfo.SourceInfo), &tokenMap) if _, ok := tokenMap["token"].(string); !ok { token = utils.MD5(pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline) } else { token = tokenMap["token"].(string) } } tokenMap["token"] = token sourceInfo, _ := json.Marshal(tokenMap) pipelineInfo.SourceInfo = string(sourceInfo) err := pipelineInfo.GetPipeline().Save(pipelineInfo).Error if err != nil { log.Error("[pipeline's GetPipelineToken]:error when save pipeline's info to db:", err.Error()) return nil, errors.New("error when get pipeline info from db:" + err.Error()) } result["token"] = token url := "" projectAddr := "" if configure.GetString("projectaddr") == "" { projectAddr = "current-pipeline's-ip:port" } else { projectAddr = configure.GetString("projectaddr") } url += projectAddr url = strings.TrimSuffix(url, "/") url += "/pipeline/v1" + "/" + pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline result["url"] = url return result, nil } func (pipelineInfo *Pipeline) UpdatePipelineInfo(define map[string]interface{}) error { db := models.GetDB() err := db.Begin().Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when db.Begin():", err.Error()) return err } pipelineOriginalManifestMap := make(map[string]interface{}) if pipelineInfo.Manifest != "" { err := json.Unmarshal([]byte(pipelineInfo.Manifest), pipelineOriginalManifestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error unmarshal pipeline's manifest info:", err.Error(), " set it to empty") pipelineInfo.Manifest = "" } } pipelineOriginalManifestMap["define"] = define pipelineNewManifestBytes, err := json.Marshal(pipelineOriginalManifestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when marshal pipeline's manifest info:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in save pipeline's info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when save pipeline's define info:" + err.Error()) } requestMap := make([]interface{}, 0) if request, ok := define["request"]; ok { if requestMap, ok = request.([]interface{}); !ok { log.Error("[pipeline's UpdatePipelineInfo]:error when get pipeline's request info:want a json array,got:", request) return errors.New("error when get pipeline's request info,want a json array") } } else { defaultRequestMap := make(map[string]interface{}) defaultRequestMap["type"] = AuthTypePipelineDefault defaultRequestMap["token"] = AuthTokenDefault requestMap = append(requestMap, defaultRequestMap) } requestInfo, err := json.Marshal(requestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when marshal pipeline's request info:", requestMap, " ===>error is:", err.Error()) return errors.New("error when save pipeline's request info") } pipelineInfo.State = models.PipelineStateDisable pipelineInfo.Manifest = string(pipelineNewManifestBytes) pipelineInfo.Requires = string(requestInfo) err = db.Save(pipelineInfo).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when save pipeline's info:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in save pipeline's info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } relationMap, stageDefineList, err := pipelineInfo.getPipelineDefineInfo(pipelineInfo.Pipeline) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when get pipeline's define info:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback after get pipeline define info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } // first delete old pipeline define err = db.Model(&models.Action{}).Where("pipeline = ?", pipelineInfo.ID).Delete(&models.Action{}).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when delete action's that belong pipeline:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in delete action info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when remove old action info:" + err.Error()) } err = db.Model(&models.Stage{}).Where("pipeline = ?", pipelineInfo.ID).Delete(&models.Stage{}).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when delete stage's that belong pipeline:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in delete stage info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when update stage info:" + err.Error()) } // then create new pipeline by define stageInfoMap := make(map[string]map[string]interface{}) preStageId := int64(-1) allActionIdMap := make(map[string]int64) for _, stageDefine := range stageDefineList { stageId, stageTagId, actionMap, err := CreateNewStage(db, preStageId, pipelineInfo.Pipeline, stageDefine, relationMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when create new stage that pipeline define:", stageDefine, " preStage is :", preStageId, " pipeline is:", pipelineInfo, " relation is:", relationMap) return err } if stageId != 0 { preStageId = stageId } stageDefine["stageId"] = stageId stageInfoMap[stageTagId] = stageDefine for key, value := range actionMap { allActionIdMap[key] = value } } for actionOriginId, actionID := range allActionIdMap { if relations, ok := relationMap[actionOriginId].(map[string]interface{}); ok { actionRealtionList := make([]map[string]interface{}, 0) for fromActionOriginId, realRelations := range relations { fromActionId, ok := allActionIdMap[fromActionOriginId] if !ok { log.Error("[pipeline's UpdatePipelineInfo]:error when get action's relation info in map:", allActionIdMap, " want :", fromActionOriginId) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in get action relation info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("action's relation is illegal") } tempRelation := make(map[string]interface{}) tempRelation["toAction"] = actionID tempRelation["fromAction"] = fromActionId tempRelation["relation"] = realRelations actionRealtionList = append(actionRealtionList, tempRelation) } actionInfo := new(models.Action) err = db.Model(&models.Action{}).Where("id = ?", actionID).First(&actionInfo).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when get action info from db:", actionID, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in get action info from db:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } manifestMap := make(map[string]interface{}) if actionInfo.Manifest != "" { json.Unmarshal([]byte(actionInfo.Manifest), &manifestMap) } manifestMap["relation"] = actionRealtionList relationBytes, _ := json.Marshal(manifestMap) actionInfo.Manifest = string(relationBytes) err = actionInfo.GetAction().Where("id = ?", actionID).UpdateColumn("manifest", actionInfo.Manifest).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when update action's column manifest:", actionInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in update action's column info from db:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } } } return nil } func (pipeline *Pipeline) getPipelineDefineInfo(pipelineInfo *models.Pipeline) (map[string]interface{}, []map[string]interface{}, error) { lineList := make([]map[string]interface{}, 0) stageList := make([]map[string]interface{}, 0) manifestMap := make(map[string]interface{}) err := json.Unmarshal([]byte(pipelineInfo.Manifest), &manifestMap) if err != nil { log.Error("[pipeline's getPipelineDefineInfo]:error when unmarshal pipeline's manifes info:", pipeline.Manifest, " ===>error is:", err.Error()) return nil, nil, errors.New("error when unmarshal pipeline manifes info:" + err.Error()) } defineMap, ok := manifestMap["define"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:pipeline's define is not a json obj:", manifestMap["define"]) return nil, nil, errors.New("pipeline's define is not a json:" + err.Error()) } realtionMap := make(map[string]interface{}) if linesList, ok := defineMap["lineList"].([]interface{}); ok { if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's lineList define,want a array,got:", defineMap["lineList"]) return nil, nil, errors.New("pipeline's lineList define is not an array") } for _, lineInfo := range linesList { lineInfoMap, ok := lineInfo.(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define: want a json obj,got:", lineInfo) return nil, nil, errors.New("pipeline's line info is not a json") } lineList = append(lineList, lineInfoMap) } for _, lineInfo := range lineList { endData, ok := lineInfo["endData"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:line doesn't define any end point info:", lineInfo) return nil, nil, errors.New("pipeline's line define is illegal,don't have a end point info") } endPointId, ok := endData["id"].(string) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:end point's id is not a string:", endData) return nil, nil, errors.New("pipeline's line define is illegal,endPoint id is not a string") } if _, ok := realtionMap[endPointId]; !ok { realtionMap[endPointId] = make(map[string]interface{}) } endPointMap := realtionMap[endPointId].(map[string]interface{}) startData, ok := lineInfo["startData"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:line doesn't define any start point info:", lineInfo) return nil, nil, errors.New("pipeline's line define is illegal,don;t have a start point info") } startDataId, ok := startData["id"].(string) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:start point's id is not a string:", endData) return nil, nil, errors.New("pipeline's line define is illegal,startPoint id is not a string") } if _, ok := endPointMap[startDataId]; !ok { endPointMap[startDataId] = make([]interface{}, 0) } lineList, ok := lineInfo["relation"].([]interface{}) if !ok { continue } endPointMap[startDataId] = append(endPointMap[startDataId].([]interface{}), lineList...) } } stageListInfo, ok := defineMap["stageList"] if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's define:pipeline doesn't define any stage info", defineMap) return nil, nil, errors.New("pipeline don't have a stage define") } stagesList, ok := stageListInfo.([]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in stageList's define:want array,got:", stageListInfo) return nil, nil, errors.New("pipeline's stageList define is not an array") } for _, stageInfo := range stagesList { stageInfoMap, ok := stageInfo.(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in stage's define,want a json obj,got:", stageInfo) return nil, nil, errors.New("pipeline's stage info is not a json") } stageList = append(stageList, stageInfoMap) } return realtionMap, stageList, nil } func (pipelineInfo *Pipeline) GenerateNewLog() (*PipelineLog, error) { pipelinelogSequenceGenerateChan <- true result := new(PipelineLog) stageList := make([]models.Stage, 0) err := new(models.Stage).GetStage().Where("pipeline = ?", pipelineInfo.ID).Find(&stageList).Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:error when get stage list by pipeline info", pipelineInfo, "===>error is :", err.Error()) return nil, err } latestPipelineLog := new(models.PipelineLog) err = new(models.PipelineLog).GetPipelineLog().Where("from_pipeline = ?", pipelineInfo.ID).Order("-sequence").First(&latestPipelineLog).Error if err != nil && !strings.Contains(err.Error(), "record not found") { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:error when get pipeline's latest sequence from db:", err.Error()) return nil, err } db := models.GetDB() db = db.Begin() // record pipeline's info pipelineLog := new(models.PipelineLog) pipelineLog.Namespace = pipelineInfo.Namespace pipelineLog.Repository = pipelineInfo.Repository pipelineLog.Pipeline = pipelineInfo.Pipeline.Pipeline pipelineLog.FromPipeline = pipelineInfo.ID pipelineLog.Version = pipelineInfo.Version pipelineLog.VersionCode = pipelineInfo.VersionCode pipelineLog.Sequence = latestPipelineLog.Sequence + 1 pipelineLog.RunState = models.PipelineLogStateCanListen pipelineLog.Event = pipelineInfo.Event pipelineLog.Manifest = pipelineInfo.Manifest pipelineLog.Description = pipelineInfo.Description pipelineLog.SourceInfo = pipelineInfo.SourceInfo pipelineLog.Env = pipelineInfo.Env pipelineLog.Requires = pipelineInfo.Requires pipelineLog.AuthList = "" err = db.Save(pipelineLog).Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when save pipeline log to db:", pipelineLog, "===>error is :", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's GenerateNewLog]:when rollback in save pipeline log:", rollbackErr.Error()) return nil, errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return nil, err } preStageLogId := int64(-1) for _, stageInfo := range stageList { stage := new(Stage) stage.Stage = &stageInfo preStageLogId, err = stage.GenerateNewLog(db, pipelineLog, preStageLogId) if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when generate stage log:", err.Error()) return nil, err } } err = db.Commit().Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when commit to db:", err.Error()) return nil, errors.New("error when save pipeline info to db:" + err.Error()) } result.PipelineLog = pipelineLog <-pipelinelogSequenceGenerateChan return result, nil } func (pipelineLog *PipelineLog) GetDefineInfo() (map[string]interface{}, error) { defineMap := make(map[string]interface{}) stageListMap := make([]map[string]interface{}, 0) lineList := make([]map[string]interface{}, 0) stageList := make([]*models.StageLog, 0) err := new(models.StageLog).GetStageLog().Where("pipeline = ?", pipelineLog.ID).Find(&stageList).Error if err != nil { log.Error("[StageLog's GetStageLogDefineListByPipelineLogID]:error when get stage list from db:", err.Error()) return nil, err } for _, stageInfo := range stageList { stage := new(StageLog) stage.StageLog = stageInfo stageDefineMap, err := stage.GetStageLogDefine() if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get stagelog define:", stage, " ===>error is:", err.Error()) return nil, err } stageListMap = append(stageListMap, stageDefineMap) } for _, stageInfo := range stageList { if stageInfo.Type == models.StageTypeStart || stageInfo.Type == models.StageTypeEnd { continue } actionList := make([]*models.ActionLog, 0) err = new(models.ActionLog).GetActionLog().Where("stage = ?", stageInfo.ID).Find(&actionList).Error if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get actionlog list from db:", err.Error()) continue } for _, actionInfo := range actionList { action := new(ActionLog) action.ActionLog = actionInfo actionLineInfo, err := action.GetActionLineInfo() if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get actionlog line info:", err.Error()) continue } lineList = append(lineList, actionLineInfo...) } } defineMap["pipeline"] = pipelineLog.Pipeline defineMap["version"] = pipelineLog.Version defineMap["sequence"] = pipelineLog.Sequence defineMap["lineList"] = lineList defineMap["stageList"] = stageListMap return defineMap, nil } func (pipelineLog *PipelineLog) GetStartStageData() (map[string]interface{}, error) { dataMap := make(map[string]interface{}) outCome := new(models.Outcome) err := outCome.GetOutcome().Where("pipeline = ?", pipelineLog.ID).Where("sequence = ?", pipelineLog.Sequence).Where("action = ?", models.OutcomeTypeStageStartActionID).First(outCome).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipelineLog's GetStartStageData]:error when get start stage data from db:", err.Error()) return nil, err } err = json.Unmarshal([]byte(outCome.Output), &dataMap) if err != nil { log.Error("[pipelineLog's GetStartStageData]:error when unmarshal start stage's data:", outCome.Output, " ===>error is:", err.Error()) } return dataMap, nil } func (pipelineLog *PipelineLog) Listen(startData string) error { pipelinelogListenChan <- true defer func() { <-pipelinelogListenChan }() err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when get pipelineLog info from db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipelinelog's info from db:" + err.Error()) } if pipelineLog.RunState != models.PipelineLogStateCanListen { log.Error("[pipelineLog's Listen]:error pipelinelog state:", pipelineLog) return errors.New("can't listen curren pipelinelog,current state is:" + strconv.FormatInt(pipelineLog.RunState, 10)) } pipelineLog.RunState = models.PipelineLogStateWaitToStart err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when change pipelinelog's run state to wait to start:", pipelineLog, " ===>error is:", err.Error()) return errors.New("can't listen target pipeline,change pipeline's state failed") } canStartChan := make(chan bool, 1) go func() { for true { time.Sleep(1 * time.Second) err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when get pipelineLog's info:", pipelineLog, " ===>error is:", err.Error()) canStartChan <- false break } if pipelineLog.Requires == "" || pipelineLog.Requires == "[]" { log.Info("[pipelineLog's Listen]:pipelineLog", pipelineLog, "is ready and will start") canStartChan <- true break } } }() go func() { canStart := <-canStartChan if !canStart { log.Error("[pipelineLog's Listen]:pipelineLog can't start", pipelineLog) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) } else { go pipelineLog.Start(startData) } }() return nil } func (pipelineLog *PipelineLog) Auth(authMap map[string]interface{}) error { pipelinelogAuthChan <- true defer func() { <-pipelinelogAuthChan }() authType, ok := authMap["type"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get authType from given authMap:", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("authType is illegal") } token, ok := authMap["token"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get token from given authMap:", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("token is illegal") } err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when get pipelineLog info from db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipelinelog's info from db:" + err.Error()) } if pipelineLog.Requires == "" || pipelineLog.Requires == "[]" { log.Error("[pipelineLog's Auth]:error when set auth info,pipelinelog's requires is empty", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("pipeline don't need any more auth") } requireList := make([]interface{}, 0) remainRequireList := make([]interface{}, 0) err = json.Unmarshal([]byte(pipelineLog.Requires), &requireList) if err != nil { log.Error("[pipelineLog's Auth]:error when unmarshal pipelinelog's require list:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipeline require auth info:" + err.Error()) } hasAuthed := false for _, require := range requireList { requireMap, ok := require.(map[string]interface{}) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require info:", pipelineLog, " ===> require is:", require) return errors.New("error when get pipeline require auth info,require is not a json object") } requireType, ok := requireMap["type"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require type:", pipelineLog, " ===> require map is:", requireMap) return errors.New("error when get pipeline require auth info,require don't have a type") } requireToken, ok := requireMap["token"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require token:", pipelineLog, " ===> require map is:", requireMap) return errors.New("error when get pipeline require auth info,require don't have a token") } if requireType == authType && requireToken == token { hasAuthed = true // record auth info to pipelinelog's auth info list pipelineLogAuthList := make([]interface{}, 0) if pipelineLog.AuthList != "" { err = json.Unmarshal([]byte(pipelineLog.AuthList), &pipelineLogAuthList) if err != nil { log.Error("[pipelineLog's Auth]:error when unmarshal pipelinelog's auth list:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when set auth info to pipeline") } } pipelineLogAuthList = append(pipelineLogAuthList, authMap) authListInfo, err := json.Marshal(pipelineLogAuthList) if err != nil { log.Error("[pipelineLog's Auth]:error when marshal pipelinelog's auth list:", pipelineLogAuthList, " ===>error is:", err.Error()) return errors.New("error when save pipeline auth info") } pipelineLog.AuthList = string(authListInfo) err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when save pipelinelog's info to db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when save pipeline auth info") } } else { remainRequireList = append(remainRequireList, requireMap) } } if !hasAuthed { log.Error("[pipelineLog's Auth]:error when auth a pipelinelog to start, given auth:", authMap, " is not equal to any request one:", pipelineLog.Requires) return errors.New("illegal auth info, auth failed") } remainRequireAuthInfo, err := json.Marshal(remainRequireList) if err != nil { log.Error("[pipelineLog's Auth]:error when marshal pipelinelog's remainRequireAuth list:", remainRequireList, " ===>error is:", err.Error()) return errors.New("error when sync remain require auth info") } pipelineLog.Requires = string(remainRequireAuthInfo) err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when save pipelinelog's remain require auth info:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when sync remain require auth info") } return nil } func (pipelineLog *PipelineLog) Start(startData string) { // get current pipelinelog's start stage startStageLog := new(models.StageLog) err := startStageLog.GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("pre_stage = ?", -1).Where("type = ?", models.StageTypeStart).First(startStageLog).Error if err != nil { log.Error("[pipelineLog's Start]:error when get pipelinelog's start stage info from db:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } stage := new(StageLog) stage.StageLog = startStageLog err = stage.Listen() if err != nil { log.Error("[pipelineLog's Start]:error when set pipeline", pipelineLog, " start stage:", startStageLog, "to listen:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } authMap := make(map[string]interface{}) authMap["type"] = AuthTypePipelineStartDone authMap["token"] = AuthTokenDefault authMap["authorizer"] = "system - " + pipelineLog.Namespace + " - " + pipelineLog.Repository + " - " + pipelineLog.Pipeline + "(" + strconv.FormatInt(pipelineLog.FromPipeline, 10) + ")" authMap["time"] = time.Now().Format("2006-01-02 15:04:05") err = stage.Auth(authMap) if err != nil { log.Error("[pipelineLog's Start]:error when auth to start stage:", pipelineLog, " start stage is ", startStageLog, " ===>error is:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } err = pipelineLog.recordPipelineStartData(startData) if err != nil { log.Error("[pipelineLog's Start]:error when record pipeline's start data:", startData, " ===>error is:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } } func (pipelineLog *PipelineLog) Stop(reason string, runState int64) { err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Stop]:error when get pipelinelog info from db:", err.Error()) return } notEndStageLogList := make([]models.StageLog, 0) new(models.StageLog).GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("run_state != ?", models.StageLogStateRunSuccess).Where("run_state != ?", models.StageLogStateRunFailed).Find(&notEndStageLogList) for _, stageLogInfo := range notEndStageLogList { stage := new(StageLog) stage.StageLog = &stageLogInfo stage.Stop(StageStopScopeAll, StageStopReasonRunFailed, models.StageLogStateRunFailed) } pipelineLog.RunState = runState err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Stop]:error when change pipelinelog's run state:", pipelineLog, " ===>error is:", err.Error()) } } func (pipelineLog *PipelineLog) recordPipelineStartData(startData string) error { startStage := new(models.StageLog) err := startStage.GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("type = ?", models.StageTypeStart).First(startStage).Error if err != nil { log.Error("[pipelineLog's recordPipelineStartData]:error when get pipeline startStage info:", startData, " ===>error is:", err.Error()) return err } err = RecordOutcom(pipelineLog.ID, pipelineLog.FromPipeline, startStage.ID, startStage.FromStage, models.OutcomeTypeStageStartActionID, models.OutcomeTypeStageStartActionID, pipelineLog.Sequence, models.OutcomeTypeStageStartEventID, true, startData, startData) if err != nil { log.Error("[pipelineLog's recordPipelineStartData]:error when record pipeline startData info:", " ===>error is:", err.Error()) return err } return nil } modify log return info /* Copyright 2014 Huawei Technologies Co., Ltd. All rights reserved. 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 module import ( "encoding/json" "errors" "strconv" "strings" "time" "github.com/Huawei/containerops/pilotage/models" "github.com/Huawei/containerops/pilotage/utils" log "github.com/Sirupsen/logrus" "github.com/containerops/configure" ) const ( PipelineStopReasonTimeout = "TIME_OUT" PipelineStopReasonRunSuccess = "RunSuccess" PipelineStopReasonRunFailed = "RunFailed" ) var ( startPipelineChan chan bool createPipelineChan chan bool pipelinelogAuthChan chan bool pipelinelogListenChan chan bool pipelinelogSequenceGenerateChan chan bool ) func init() { startPipelineChan = make(chan bool, 1) createPipelineChan = make(chan bool, 1) pipelinelogAuthChan = make(chan bool, 1) pipelinelogListenChan = make(chan bool, 1) pipelinelogSequenceGenerateChan = make(chan bool, 1) } type Pipeline struct { *models.Pipeline } type PipelineLog struct { *models.PipelineLog } // CreateNewPipeline is create a new pipeline with given data func CreateNewPipeline(namespace, repository, pipelineName, pipelineVersion string) (string, error) { createPipelineChan <- true defer func() { <-createPipelineChan }() var count int64 err := new(models.Pipeline).GetPipeline().Where("namespace = ?", namespace).Where("pipeline = ?", pipelineName).Order("-id").Count(&count).Error if err != nil { return "", errors.New("error when query pipeline data in database:" + err.Error()) } if count > 0 { return "", errors.New("pipelien name is exist!") } pipelineInfo := new(models.Pipeline) pipelineInfo.Namespace = namespace pipelineInfo.Repository = repository pipelineInfo.Pipeline = pipelineName pipelineInfo.Version = pipelineVersion pipelineInfo.VersionCode = 1 err = pipelineInfo.GetPipeline().Save(pipelineInfo).Error if err != nil { return "", errors.New("error when save pipeline info:" + err.Error()) } return "create new pipeline success", nil } func GetPipelineListByNamespaceAndRepository(namespace, repository string) ([]map[string]interface{}, error) { resultMap := make([]map[string]interface{}, 0) pipelineList := make([]models.Pipeline, 0) pipelinesMap := make(map[string]interface{}, 0) err := new(models.Pipeline).GetPipeline().Where("namespace = ?", namespace).Where("repository = ?", repository).Order("-updated_at").Find(&pipelineList).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipeline's GetPipelineListByNamespaceAndRepository]error when get pipeline list from db:" + err.Error()) return nil, errors.New("error when get pipeline list by namespace and repository from db:" + err.Error()) } for _, pipelineInfo := range pipelineList { if _, ok := pipelinesMap[pipelineInfo.Pipeline]; !ok { tempMap := make(map[string]interface{}) tempMap["version"] = make(map[int64]interface{}) pipelinesMap[pipelineInfo.Pipeline] = tempMap } pipelineMap := pipelinesMap[pipelineInfo.Pipeline].(map[string]interface{}) versionMap := pipelineMap["version"].(map[int64]interface{}) versionMap[pipelineInfo.VersionCode] = pipelineInfo pipelineMap["id"] = pipelineInfo.ID pipelineMap["name"] = pipelineInfo.Pipeline pipelineMap["version"] = versionMap } for _, pipeline := range pipelineList { pipelineInfo := pipelinesMap[pipeline.Pipeline].(map[string]interface{}) if isSign, ok := pipelineInfo["isSign"].(bool); ok && isSign { continue } pipelineInfo["isSign"] = true pipelinesMap[pipeline.Pipeline] = pipelineInfo versionList := make([]map[string]interface{}, 0) for _, pipelineVersion := range pipelineList { if pipelineVersion.Pipeline == pipelineInfo["name"].(string) { versionMap := make(map[string]interface{}) versionMap["id"] = pipelineVersion.ID versionMap["version"] = pipelineVersion.Version versionMap["versionCode"] = pipelineVersion.VersionCode // get current version latest run result outcome := new(models.Outcome) err := outcome.GetOutcome().Where("real_pipeline = ?", pipelineVersion.ID).Where("real_action = ?", 0).Order("-id").First(outcome).Error if err != nil && strings.Contains(err.Error(), "record not found") { log.Info("can't get pipeline(" + pipelineVersion.Pipeline + "} version(" + pipelineVersion.Version + ")'s input info:" + err.Error()) } if outcome.ID != 0 { statusMap := make(map[string]interface{}) statusMap["status"] = false statusMap["time"] = outcome.CreatedAt.Format("2006-01-02 15:04:05") finalResult := new(models.Outcome) err := finalResult.GetOutcome().Where("pipeline = ?", outcome.Pipeline).Where("sequence = ?", outcome.Sequence).Where("action = ?", -1).First(finalResult).Error if err != nil && strings.Contains(err.Error(), "record not found") { log.Info("can't get pipeline(" + pipelineVersion.Pipeline + "} version(" + pipelineVersion.Version + ")'s output info:" + err.Error()) } if finalResult.ID != 0 && finalResult.Status { statusMap["status"] = finalResult.Status } versionMap["status"] = statusMap } versionList = append(versionList, versionMap) } } tempResult := make(map[string]interface{}) tempResult["id"] = pipelineInfo["id"] tempResult["name"] = pipelineInfo["name"] tempResult["version"] = versionList resultMap = append(resultMap, tempResult) } return resultMap, nil } func GetPipelineInfo(namespace, repository, pipelineName string, pipelineId int64) (map[string]interface{}, error) { resultMap := make(map[string]interface{}) pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(&pipelineInfo).Error if err != nil { return nil, errors.New("error when get pipeline info from db:" + err.Error()) } if pipelineInfo.Namespace != namespace || pipelineInfo.Repository != repository || pipelineInfo.Pipeline != pipelineName { return nil, errors.New("pipeline is not equal to target pipeline") } // get pipeline define json first, if has a define json,return it if pipelineInfo.Manifest != "" { defineMap := make(map[string]interface{}) json.Unmarshal([]byte(pipelineInfo.Manifest), &defineMap) if defineInfo, ok := defineMap["define"]; ok { if defineInfoMap, ok := defineInfo.(map[string]interface{}); ok { defineInfoMap["status"] = pipelineInfo.State == models.PipelineStateAble return defineInfoMap, nil } } } // get all stage info of current pipeline // if a pipeline done have a define of itself // then the pipeline is a new pipeline ,so only get it's stage list is ok stageList, err := getDefaultStageListByPipeline(*pipelineInfo) if err != nil { return nil, err } resultMap["stageList"] = stageList // resultMap["stageList"] = make([]map[string]interface{}, 0) resultMap["lineList"] = make([]map[string]interface{}, 0) resultMap["status"] = false return resultMap, nil } func getDefaultStageListByPipeline(pipelineInfo models.Pipeline) ([]map[string]interface{}, error) { stageListMap := make([]map[string]interface{}, 0) startStage := make(map[string]interface{}) startStage["id"] = "start-stage" startStage["type"] = "pipeline-start" startStage["setupData"] = make(map[string]interface{}) stageListMap = append(stageListMap, startStage) addStage := make(map[string]interface{}) addStage["id"] = "add-stage" addStage["type"] = "pipeline-add-stage" stageListMap = append(stageListMap, addStage) endStage := make(map[string]interface{}) endStage["id"] = "end-stage" endStage["type"] = "pipeline-end" endStage["setupData"] = make(map[string]interface{}) stageListMap = append(stageListMap, endStage) return stageListMap, nil } func GetStageHistoryInfo(stageLogId int64) (map[string]interface{}, error) { result := make(map[string]interface{}) // get all actions that belong to current stage , // return stage info and action{id:actionId, name:actionName, status:true/false} actionList := make([]models.ActionLog, 0) actionListMap := make([]map[string]interface{}, 0) stageInfo := new(models.StageLog) stageStatus := true stageInfo.GetStageLog().Where("id = ?", stageLogId).First(stageInfo) new(models.ActionLog).GetActionLog().Where("stage = ?", stageLogId).Find(&actionList) for _, action := range actionList { actionOutcome := new(models.Outcome) new(models.Outcome).GetOutcome().Where("action = ?", action.ID).First(actionOutcome) actionMap := make(map[string]interface{}) actionMap["id"] = "a-" + strconv.FormatInt(action.ID, 10) actionMap["name"] = action.Action if actionOutcome.Status { actionMap["status"] = true } else { actionMap["status"] = false stageStatus = false } actionListMap = append(actionListMap, actionMap) } firstActionStartEvent := new(models.Event) leastActionStopEvent := new(models.Event) firstActionStartEvent.GetEvent().Where("stage = ?", stageInfo.ID).Where("title = ?", "COMPONENT_START").Order("created_at").First(firstActionStartEvent) leastActionStopEvent.GetEvent().Where("stage = ?", stageInfo.ID).Where("title = ?", "COMPONENT_STOP").Order("-created_at").First(leastActionStopEvent) stageRunTime := "" if firstActionStartEvent.ID != 0 { stageRunTime = firstActionStartEvent.CreatedAt.Format("2006-01-02 15:04:05") stageRunTime += " - " if leastActionStopEvent.ID != 0 { stageRunTime += leastActionStopEvent.CreatedAt.Format("2006-01-02 15:04:05") } } result["name"] = stageInfo.Stage result["status"] = stageStatus result["actions"] = actionListMap result["runTime"] = stageRunTime return result, nil } func Run(pipelineId int64, authMap map[string]interface{}, startData string) error { pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(pipelineInfo).Error if err != nil { log.Error("[pipeline's Run]:error when get pipeline's info from db:", err.Error()) return errors.New("error when get target pipeline info:" + err.Error()) } pipeline := new(Pipeline) pipeline.Pipeline = pipelineInfo // first generate a pipeline log to record all current pipeline's info which will be used in feature pipelineLog, err := pipeline.GenerateNewLog() if err != nil { return err } // let pipeline log listen all auth, if all auth is ok, start run this pipeline log err = pipelineLog.Listen(startData) if err != nil { return err } // auth this pipeline log by given auth info err = pipelineLog.Auth(authMap) if err != nil { return err } return nil } func GetPipeline(pipelineId int64) (*Pipeline, error) { if pipelineId == int64(0) { return nil, errors.New("pipeline's id is empty") } pipelineInfo := new(models.Pipeline) err := pipelineInfo.GetPipeline().Where("id = ?", pipelineId).First(pipelineInfo).Error if err != nil { log.Error("[pipeline's GetPipeline]:error when get pipeline info from db:", err.Error()) return nil, err } pipeline := new(Pipeline) pipeline.Pipeline = pipelineInfo return pipeline, nil } func GetPipelineLog(namespace, repository, versionName string, sequence int64) (*PipelineLog, error) { var err error pipelineLogInfo := new(models.PipelineLog) query := pipelineLogInfo.GetPipelineLog().Where("namespace =? ", namespace).Where("repository = ?", repository).Where("version = ?", versionName) if sequence == int64(0) { query = query.Order("-id") } else { query = query.Where("sequence = ?", sequence) } err = query.First(pipelineLogInfo).Error if err != nil { log.Error("[pipelineLog's GetPipelineLog]:error when get pipelineLog(version=", versionName, ", sequence=", sequence, ") info from db:", err.Error()) return nil, err } pipelineLog := new(PipelineLog) pipelineLog.PipelineLog = pipelineLogInfo return pipelineLog, nil } func getPipelineEnvList(pipelineLogId int64) ([]map[string]interface{}, error) { resultList := make([]map[string]interface{}, 0) pipelineLog := new(models.PipelineLog) err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLogId).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's getPipelineEnvList]:error when get pipelinelog info from db:", err.Error()) return nil, errors.New("error when get pipeline info from db:" + err.Error()) } envMap := make(map[string]string) if pipelineLog.Env != "" { err = json.Unmarshal([]byte(pipelineLog.Env), &envMap) if err != nil { log.Error("[pipelineLog's getPipelineEnvList]:error when unmarshal pipeline's env setting:", pipelineLog.Env, " ===>error is:", err.Error()) return nil, errors.New("error when unmarshal pipeline env info" + err.Error()) } } for key, value := range envMap { tempEnvMap := make(map[string]interface{}) tempEnvMap["name"] = key tempEnvMap["value"] = value resultList = append(resultList, tempEnvMap) } return resultList, nil } func GetPipelineRunHistoryList(namespace, repository string) ([]map[string]interface{}, error) { resultList := make([]map[string]interface{}, 0) pipelineLogIndexMap := make(map[string]int) pipelineLogVersionIndexMap := make(map[string]interface{}) pipelineLogList := make([]models.PipelineLog, 0) err := new(models.PipelineLog).GetPipelineLog().Where("namespace = ?", namespace).Where("repository = ?", repository).Order("-id").Find(&pipelineLogList).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipeline's GetPipelineRunHistoryList]:error when get pipelineLog list from db:", err.Error()) return nil, err } for _, pipelinelog := range pipelineLogList { if _, ok := pipelineLogIndexMap[pipelinelog.Pipeline]; !ok { pipelineInfoMap := make(map[string]interface{}) pipelineVersionListInfoMap := make([]map[string]interface{}, 0) pipelineInfoMap["id"] = pipelinelog.FromPipeline pipelineInfoMap["name"] = pipelinelog.Pipeline pipelineInfoMap["versionList"] = pipelineVersionListInfoMap resultList = append(resultList, pipelineInfoMap) pipelineLogIndexMap[pipelinelog.Pipeline] = len(resultList) - 1 versionIndexMap := make(map[string]int64) pipelineLogVersionIndexMap[pipelinelog.Pipeline] = versionIndexMap } pipelineInfoMap := resultList[pipelineLogIndexMap[pipelinelog.Pipeline]] if _, ok := pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string]int64)[pipelinelog.Version]; !ok { pipelineVersionInfoMap := make(map[string]interface{}) pipelineVersionSequenceListInfoMap := make([]map[string]interface{}, 0) pipelineVersionInfoMap["id"] = pipelinelog.ID pipelineVersionInfoMap["name"] = pipelinelog.Version pipelineVersionInfoMap["info"] = "" pipelineVersionInfoMap["total"] = int64(0) pipelineVersionInfoMap["success"] = int64(0) pipelineVersionInfoMap["sequenceList"] = pipelineVersionSequenceListInfoMap pipelineInfoMap["versionList"] = append(pipelineInfoMap["versionList"].([]map[string]interface{}), pipelineVersionInfoMap) pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string]int64)[pipelinelog.Version] = int64(len(pipelineInfoMap["versionList"].([]map[string]interface{})) - 1) } pipelineVersionInfoMap := pipelineInfoMap["versionList"].([]map[string]interface{})[pipelineLogVersionIndexMap[pipelinelog.Pipeline].(map[string](int64))[pipelinelog.Version]] sequenceList := pipelineVersionInfoMap["sequenceList"].([]map[string]interface{}) sequenceInfoMap := make(map[string]interface{}) sequenceInfoMap["pipelineSequenceID"] = pipelinelog.ID sequenceInfoMap["sequence"] = pipelinelog.Sequence sequenceInfoMap["status"] = pipelinelog.RunState sequenceInfoMap["time"] = pipelinelog.CreatedAt sequenceList = append(sequenceList, sequenceInfoMap) pipelineVersionInfoMap["sequenceList"] = sequenceList pipelineVersionInfoMap["total"] = pipelineVersionInfoMap["total"].(int64) + 1 if pipelinelog.RunState == models.PipelineLogStateRunSuccess { pipelineVersionInfoMap["success"] = pipelineVersionInfoMap["success"].(int64) + 1 } } for _, pipelineInfoMap := range resultList { for _, versionInfoMap := range pipelineInfoMap["versionList"].([]map[string]interface{}) { success := versionInfoMap["success"].(int64) total := versionInfoMap["total"].(int64) versionInfoMap["info"] = "Success: " + strconv.FormatInt(success, 10) + " Total: " + strconv.FormatInt(total, 10) } } return resultList, nil } func (pipelineInfo *Pipeline) CreateNewVersion(define map[string]interface{}, versionName string) error { var count int64 err := new(models.Pipeline).GetPipeline().Where("namespace = ?", pipelineInfo.Namespace).Where("repository = ?", pipelineInfo.Repository).Where("pipeline = ?", pipelineInfo.Pipeline.Pipeline).Where("version = ?", versionName).Count(&count).Error if count > 0 { return errors.New("version code already exist!") } // get current least pipeline's version leastPipeline := new(models.Pipeline) err = leastPipeline.GetPipeline().Where("namespace = ? ", pipelineInfo.Namespace).Where("pipeline = ?", pipelineInfo.Pipeline.Pipeline).Order("-id").First(&leastPipeline).Error if err != nil { return errors.New("error when get least pipeline info :" + err.Error()) } newPipelineInfo := new(models.Pipeline) newPipelineInfo.Namespace = pipelineInfo.Namespace newPipelineInfo.Repository = pipelineInfo.Repository newPipelineInfo.Pipeline = pipelineInfo.Pipeline.Pipeline newPipelineInfo.Event = pipelineInfo.Event newPipelineInfo.Version = versionName newPipelineInfo.VersionCode = leastPipeline.VersionCode + 1 newPipelineInfo.State = models.PipelineStateDisable newPipelineInfo.Manifest = pipelineInfo.Manifest newPipelineInfo.Description = pipelineInfo.Description newPipelineInfo.SourceInfo = pipelineInfo.SourceInfo newPipelineInfo.Env = pipelineInfo.Env newPipelineInfo.Requires = pipelineInfo.Requires err = newPipelineInfo.GetPipeline().Save(newPipelineInfo).Error if err != nil { return err } return pipelineInfo.UpdatePipelineInfo(define) } func (pipelineInfo *Pipeline) GetPipelineToken() (map[string]interface{}, error) { result := make(map[string]interface{}) if pipelineInfo.ID == 0 { log.Error("[pipeline's GetPipelineToken]:got an empty pipelin:", pipelineInfo) return nil, errors.New("pipeline's info is empty") } token := "" tokenMap := make(map[string]interface{}) if pipelineInfo.SourceInfo == "" { // if sourceInfo is empty generate a token token = utils.MD5(pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline) } else { json.Unmarshal([]byte(pipelineInfo.SourceInfo), &tokenMap) if _, ok := tokenMap["token"].(string); !ok { token = utils.MD5(pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline) } else { token = tokenMap["token"].(string) } } tokenMap["token"] = token sourceInfo, _ := json.Marshal(tokenMap) pipelineInfo.SourceInfo = string(sourceInfo) err := pipelineInfo.GetPipeline().Save(pipelineInfo).Error if err != nil { log.Error("[pipeline's GetPipelineToken]:error when save pipeline's info to db:", err.Error()) return nil, errors.New("error when get pipeline info from db:" + err.Error()) } result["token"] = token url := "" projectAddr := "" if configure.GetString("projectaddr") == "" { projectAddr = "current-pipeline's-ip:port" } else { projectAddr = configure.GetString("projectaddr") } url += projectAddr url = strings.TrimSuffix(url, "/") url += "/pipeline/v1" + "/" + pipelineInfo.Namespace + "/" + pipelineInfo.Repository + "/" + pipelineInfo.Pipeline.Pipeline result["url"] = url return result, nil } func (pipelineInfo *Pipeline) UpdatePipelineInfo(define map[string]interface{}) error { db := models.GetDB() err := db.Begin().Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when db.Begin():", err.Error()) return err } pipelineOriginalManifestMap := make(map[string]interface{}) if pipelineInfo.Manifest != "" { err := json.Unmarshal([]byte(pipelineInfo.Manifest), pipelineOriginalManifestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error unmarshal pipeline's manifest info:", err.Error(), " set it to empty") pipelineInfo.Manifest = "" } } pipelineOriginalManifestMap["define"] = define pipelineNewManifestBytes, err := json.Marshal(pipelineOriginalManifestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when marshal pipeline's manifest info:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in save pipeline's info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when save pipeline's define info:" + err.Error()) } requestMap := make([]interface{}, 0) if request, ok := define["request"]; ok { if requestMap, ok = request.([]interface{}); !ok { log.Error("[pipeline's UpdatePipelineInfo]:error when get pipeline's request info:want a json array,got:", request) return errors.New("error when get pipeline's request info,want a json array") } } else { defaultRequestMap := make(map[string]interface{}) defaultRequestMap["type"] = AuthTypePipelineDefault defaultRequestMap["token"] = AuthTokenDefault requestMap = append(requestMap, defaultRequestMap) } requestInfo, err := json.Marshal(requestMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when marshal pipeline's request info:", requestMap, " ===>error is:", err.Error()) return errors.New("error when save pipeline's request info") } pipelineInfo.State = models.PipelineStateDisable pipelineInfo.Manifest = string(pipelineNewManifestBytes) pipelineInfo.Requires = string(requestInfo) err = db.Save(pipelineInfo).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when save pipeline's info:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in save pipeline's info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } relationMap, stageDefineList, err := pipelineInfo.getPipelineDefineInfo(pipelineInfo.Pipeline) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when get pipeline's define info:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback after get pipeline define info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } // first delete old pipeline define err = db.Model(&models.Action{}).Where("pipeline = ?", pipelineInfo.ID).Delete(&models.Action{}).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when delete action's that belong pipeline:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in delete action info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when remove old action info:" + err.Error()) } err = db.Model(&models.Stage{}).Where("pipeline = ?", pipelineInfo.ID).Delete(&models.Stage{}).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:when delete stage's that belong pipeline:", pipelineInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in delete stage info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("error when update stage info:" + err.Error()) } // then create new pipeline by define stageInfoMap := make(map[string]map[string]interface{}) preStageId := int64(-1) allActionIdMap := make(map[string]int64) for _, stageDefine := range stageDefineList { stageId, stageTagId, actionMap, err := CreateNewStage(db, preStageId, pipelineInfo.Pipeline, stageDefine, relationMap) if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when create new stage that pipeline define:", stageDefine, " preStage is :", preStageId, " pipeline is:", pipelineInfo, " relation is:", relationMap) return err } if stageId != 0 { preStageId = stageId } stageDefine["stageId"] = stageId stageInfoMap[stageTagId] = stageDefine for key, value := range actionMap { allActionIdMap[key] = value } } for actionOriginId, actionID := range allActionIdMap { if relations, ok := relationMap[actionOriginId].(map[string]interface{}); ok { actionRealtionList := make([]map[string]interface{}, 0) for fromActionOriginId, realRelations := range relations { fromActionId, ok := allActionIdMap[fromActionOriginId] if !ok { log.Error("[pipeline's UpdatePipelineInfo]:error when get action's relation info in map:", allActionIdMap, " want :", fromActionOriginId) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in get action relation info:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return errors.New("action's relation is illegal") } tempRelation := make(map[string]interface{}) tempRelation["toAction"] = actionID tempRelation["fromAction"] = fromActionId tempRelation["relation"] = realRelations actionRealtionList = append(actionRealtionList, tempRelation) } actionInfo := new(models.Action) err = db.Model(&models.Action{}).Where("id = ?", actionID).First(&actionInfo).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when get action info from db:", actionID, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in get action info from db:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } manifestMap := make(map[string]interface{}) if actionInfo.Manifest != "" { json.Unmarshal([]byte(actionInfo.Manifest), &manifestMap) } manifestMap["relation"] = actionRealtionList relationBytes, _ := json.Marshal(manifestMap) actionInfo.Manifest = string(relationBytes) err = actionInfo.GetAction().Where("id = ?", actionID).UpdateColumn("manifest", actionInfo.Manifest).Error if err != nil { log.Error("[pipeline's UpdatePipelineInfo]:error when update action's column manifest:", actionInfo, " ===>error is:", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's UpdatePipelineInfo]:when rollback in update action's column info from db:", rollbackErr.Error()) return errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return err } } } return nil } func (pipeline *Pipeline) getPipelineDefineInfo(pipelineInfo *models.Pipeline) (map[string]interface{}, []map[string]interface{}, error) { lineList := make([]map[string]interface{}, 0) stageList := make([]map[string]interface{}, 0) manifestMap := make(map[string]interface{}) err := json.Unmarshal([]byte(pipelineInfo.Manifest), &manifestMap) if err != nil { log.Error("[pipeline's getPipelineDefineInfo]:error when unmarshal pipeline's manifes info:", pipeline.Manifest, " ===>error is:", err.Error()) return nil, nil, errors.New("error when unmarshal pipeline manifes info:" + err.Error()) } defineMap, ok := manifestMap["define"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:pipeline's define is not a json obj:", manifestMap["define"]) return nil, nil, errors.New("pipeline's define is not a json:" + err.Error()) } realtionMap := make(map[string]interface{}) if linesList, ok := defineMap["lineList"].([]interface{}); ok { if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's lineList define,want a array,got:", defineMap["lineList"]) return nil, nil, errors.New("pipeline's lineList define is not an array") } for _, lineInfo := range linesList { lineInfoMap, ok := lineInfo.(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define: want a json obj,got:", lineInfo) return nil, nil, errors.New("pipeline's line info is not a json") } lineList = append(lineList, lineInfoMap) } for _, lineInfo := range lineList { endData, ok := lineInfo["endData"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:line doesn't define any end point info:", lineInfo) return nil, nil, errors.New("pipeline's line define is illegal,don't have a end point info") } endPointId, ok := endData["id"].(string) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:end point's id is not a string:", endData) return nil, nil, errors.New("pipeline's line define is illegal,endPoint id is not a string") } if _, ok := realtionMap[endPointId]; !ok { realtionMap[endPointId] = make(map[string]interface{}) } endPointMap := realtionMap[endPointId].(map[string]interface{}) startData, ok := lineInfo["startData"].(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:line doesn't define any start point info:", lineInfo) return nil, nil, errors.New("pipeline's line define is illegal,don;t have a start point info") } startDataId, ok := startData["id"].(string) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's line define:start point's id is not a string:", endData) return nil, nil, errors.New("pipeline's line define is illegal,startPoint id is not a string") } if _, ok := endPointMap[startDataId]; !ok { endPointMap[startDataId] = make([]interface{}, 0) } lineList, ok := lineInfo["relation"].([]interface{}) if !ok { continue } endPointMap[startDataId] = append(endPointMap[startDataId].([]interface{}), lineList...) } } stageListInfo, ok := defineMap["stageList"] if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in pipeline's define:pipeline doesn't define any stage info", defineMap) return nil, nil, errors.New("pipeline don't have a stage define") } stagesList, ok := stageListInfo.([]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in stageList's define:want array,got:", stageListInfo) return nil, nil, errors.New("pipeline's stageList define is not an array") } for _, stageInfo := range stagesList { stageInfoMap, ok := stageInfo.(map[string]interface{}) if !ok { log.Error("[pipeline's getPipelineDefineInfo]:error in stage's define,want a json obj,got:", stageInfo) return nil, nil, errors.New("pipeline's stage info is not a json") } stageList = append(stageList, stageInfoMap) } return realtionMap, stageList, nil } func (pipelineInfo *Pipeline) GenerateNewLog() (*PipelineLog, error) { pipelinelogSequenceGenerateChan <- true result := new(PipelineLog) stageList := make([]models.Stage, 0) err := new(models.Stage).GetStage().Where("pipeline = ?", pipelineInfo.ID).Find(&stageList).Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:error when get stage list by pipeline info", pipelineInfo, "===>error is :", err.Error()) return nil, err } latestPipelineLog := new(models.PipelineLog) err = new(models.PipelineLog).GetPipelineLog().Where("from_pipeline = ?", pipelineInfo.ID).Order("-sequence").First(&latestPipelineLog).Error if err != nil && !strings.Contains(err.Error(), "record not found") { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:error when get pipeline's latest sequence from db:", err.Error()) return nil, err } db := models.GetDB() db = db.Begin() // record pipeline's info pipelineLog := new(models.PipelineLog) pipelineLog.Namespace = pipelineInfo.Namespace pipelineLog.Repository = pipelineInfo.Repository pipelineLog.Pipeline = pipelineInfo.Pipeline.Pipeline pipelineLog.FromPipeline = pipelineInfo.ID pipelineLog.Version = pipelineInfo.Version pipelineLog.VersionCode = pipelineInfo.VersionCode pipelineLog.Sequence = latestPipelineLog.Sequence + 1 pipelineLog.RunState = models.PipelineLogStateCanListen pipelineLog.Event = pipelineInfo.Event pipelineLog.Manifest = pipelineInfo.Manifest pipelineLog.Description = pipelineInfo.Description pipelineLog.SourceInfo = pipelineInfo.SourceInfo pipelineLog.Env = pipelineInfo.Env pipelineLog.Requires = pipelineInfo.Requires pipelineLog.AuthList = "" err = db.Save(pipelineLog).Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when save pipeline log to db:", pipelineLog, "===>error is :", err.Error()) rollbackErr := db.Rollback().Error if rollbackErr != nil { log.Error("[pipeline's GenerateNewLog]:when rollback in save pipeline log:", rollbackErr.Error()) return nil, errors.New("errors occur:\nerror1:" + err.Error() + "\nerror2:" + rollbackErr.Error()) } return nil, err } preStageLogId := int64(-1) for _, stageInfo := range stageList { stage := new(Stage) stage.Stage = &stageInfo preStageLogId, err = stage.GenerateNewLog(db, pipelineLog, preStageLogId) if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when generate stage log:", err.Error()) return nil, err } } err = db.Commit().Error if err != nil { <-pipelinelogSequenceGenerateChan log.Error("[pipeline's GenerateNewLog]:when commit to db:", err.Error()) return nil, errors.New("error when save pipeline info to db:" + err.Error()) } result.PipelineLog = pipelineLog <-pipelinelogSequenceGenerateChan return result, nil } func (pipelineLog *PipelineLog) GetDefineInfo() (map[string]interface{}, error) { defineMap := make(map[string]interface{}) stageListMap := make([]map[string]interface{}, 0) lineList := make([]map[string]interface{}, 0) stageList := make([]*models.StageLog, 0) err := new(models.StageLog).GetStageLog().Where("pipeline = ?", pipelineLog.ID).Find(&stageList).Error if err != nil { log.Error("[StageLog's GetStageLogDefineListByPipelineLogID]:error when get stage list from db:", err.Error()) return nil, err } for _, stageInfo := range stageList { stage := new(StageLog) stage.StageLog = stageInfo stageDefineMap, err := stage.GetStageLogDefine() if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get stagelog define:", stage, " ===>error is:", err.Error()) return nil, err } stageListMap = append(stageListMap, stageDefineMap) } for _, stageInfo := range stageList { if stageInfo.Type == models.StageTypeStart || stageInfo.Type == models.StageTypeEnd { continue } actionList := make([]*models.ActionLog, 0) err = new(models.ActionLog).GetActionLog().Where("stage = ?", stageInfo.ID).Find(&actionList).Error if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get actionlog list from db:", err.Error()) continue } for _, actionInfo := range actionList { action := new(ActionLog) action.ActionLog = actionInfo actionLineInfo, err := action.GetActionLineInfo() if err != nil { log.Error("[pipelineLog's GetDefineInfo]:error when get actionlog line info:", err.Error()) continue } lineList = append(lineList, actionLineInfo...) } } defineMap["pipeline"] = pipelineLog.Pipeline defineMap["version"] = pipelineLog.Version defineMap["sequence"] = pipelineLog.Sequence defineMap["status"] = pipelineLog.RunState defineMap["lineList"] = lineList defineMap["stageList"] = stageListMap return defineMap, nil } func (pipelineLog *PipelineLog) GetStartStageData() (map[string]interface{}, error) { dataMap := make(map[string]interface{}) outCome := new(models.Outcome) err := outCome.GetOutcome().Where("pipeline = ?", pipelineLog.ID).Where("sequence = ?", pipelineLog.Sequence).Where("action = ?", models.OutcomeTypeStageStartActionID).First(outCome).Error if err != nil && !strings.Contains(err.Error(), "record not found") { log.Error("[pipelineLog's GetStartStageData]:error when get start stage data from db:", err.Error()) return nil, err } err = json.Unmarshal([]byte(outCome.Output), &dataMap) if err != nil { log.Error("[pipelineLog's GetStartStageData]:error when unmarshal start stage's data:", outCome.Output, " ===>error is:", err.Error()) } return dataMap, nil } func (pipelineLog *PipelineLog) Listen(startData string) error { pipelinelogListenChan <- true defer func() { <-pipelinelogListenChan }() err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when get pipelineLog info from db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipelinelog's info from db:" + err.Error()) } if pipelineLog.RunState != models.PipelineLogStateCanListen { log.Error("[pipelineLog's Listen]:error pipelinelog state:", pipelineLog) return errors.New("can't listen curren pipelinelog,current state is:" + strconv.FormatInt(pipelineLog.RunState, 10)) } pipelineLog.RunState = models.PipelineLogStateWaitToStart err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when change pipelinelog's run state to wait to start:", pipelineLog, " ===>error is:", err.Error()) return errors.New("can't listen target pipeline,change pipeline's state failed") } canStartChan := make(chan bool, 1) go func() { for true { time.Sleep(1 * time.Second) err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Listen]:error when get pipelineLog's info:", pipelineLog, " ===>error is:", err.Error()) canStartChan <- false break } if pipelineLog.Requires == "" || pipelineLog.Requires == "[]" { log.Info("[pipelineLog's Listen]:pipelineLog", pipelineLog, "is ready and will start") canStartChan <- true break } } }() go func() { canStart := <-canStartChan if !canStart { log.Error("[pipelineLog's Listen]:pipelineLog can't start", pipelineLog) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) } else { go pipelineLog.Start(startData) } }() return nil } func (pipelineLog *PipelineLog) Auth(authMap map[string]interface{}) error { pipelinelogAuthChan <- true defer func() { <-pipelinelogAuthChan }() authType, ok := authMap["type"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get authType from given authMap:", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("authType is illegal") } token, ok := authMap["token"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get token from given authMap:", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("token is illegal") } err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when get pipelineLog info from db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipelinelog's info from db:" + err.Error()) } if pipelineLog.Requires == "" || pipelineLog.Requires == "[]" { log.Error("[pipelineLog's Auth]:error when set auth info,pipelinelog's requires is empty", authMap, " ===>to pipelinelog:", pipelineLog) return errors.New("pipeline don't need any more auth") } requireList := make([]interface{}, 0) remainRequireList := make([]interface{}, 0) err = json.Unmarshal([]byte(pipelineLog.Requires), &requireList) if err != nil { log.Error("[pipelineLog's Auth]:error when unmarshal pipelinelog's require list:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when get pipeline require auth info:" + err.Error()) } hasAuthed := false for _, require := range requireList { requireMap, ok := require.(map[string]interface{}) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require info:", pipelineLog, " ===> require is:", require) return errors.New("error when get pipeline require auth info,require is not a json object") } requireType, ok := requireMap["type"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require type:", pipelineLog, " ===> require map is:", requireMap) return errors.New("error when get pipeline require auth info,require don't have a type") } requireToken, ok := requireMap["token"].(string) if !ok { log.Error("[pipelineLog's Auth]:error when get pipelinelog's require token:", pipelineLog, " ===> require map is:", requireMap) return errors.New("error when get pipeline require auth info,require don't have a token") } if requireType == authType && requireToken == token { hasAuthed = true // record auth info to pipelinelog's auth info list pipelineLogAuthList := make([]interface{}, 0) if pipelineLog.AuthList != "" { err = json.Unmarshal([]byte(pipelineLog.AuthList), &pipelineLogAuthList) if err != nil { log.Error("[pipelineLog's Auth]:error when unmarshal pipelinelog's auth list:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when set auth info to pipeline") } } pipelineLogAuthList = append(pipelineLogAuthList, authMap) authListInfo, err := json.Marshal(pipelineLogAuthList) if err != nil { log.Error("[pipelineLog's Auth]:error when marshal pipelinelog's auth list:", pipelineLogAuthList, " ===>error is:", err.Error()) return errors.New("error when save pipeline auth info") } pipelineLog.AuthList = string(authListInfo) err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when save pipelinelog's info to db:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when save pipeline auth info") } } else { remainRequireList = append(remainRequireList, requireMap) } } if !hasAuthed { log.Error("[pipelineLog's Auth]:error when auth a pipelinelog to start, given auth:", authMap, " is not equal to any request one:", pipelineLog.Requires) return errors.New("illegal auth info, auth failed") } remainRequireAuthInfo, err := json.Marshal(remainRequireList) if err != nil { log.Error("[pipelineLog's Auth]:error when marshal pipelinelog's remainRequireAuth list:", remainRequireList, " ===>error is:", err.Error()) return errors.New("error when sync remain require auth info") } pipelineLog.Requires = string(remainRequireAuthInfo) err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Auth]:error when save pipelinelog's remain require auth info:", pipelineLog, " ===>error is:", err.Error()) return errors.New("error when sync remain require auth info") } return nil } func (pipelineLog *PipelineLog) Start(startData string) { // get current pipelinelog's start stage startStageLog := new(models.StageLog) err := startStageLog.GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("pre_stage = ?", -1).Where("type = ?", models.StageTypeStart).First(startStageLog).Error if err != nil { log.Error("[pipelineLog's Start]:error when get pipelinelog's start stage info from db:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } stage := new(StageLog) stage.StageLog = startStageLog err = stage.Listen() if err != nil { log.Error("[pipelineLog's Start]:error when set pipeline", pipelineLog, " start stage:", startStageLog, "to listen:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } authMap := make(map[string]interface{}) authMap["type"] = AuthTypePipelineStartDone authMap["token"] = AuthTokenDefault authMap["authorizer"] = "system - " + pipelineLog.Namespace + " - " + pipelineLog.Repository + " - " + pipelineLog.Pipeline + "(" + strconv.FormatInt(pipelineLog.FromPipeline, 10) + ")" authMap["time"] = time.Now().Format("2006-01-02 15:04:05") err = stage.Auth(authMap) if err != nil { log.Error("[pipelineLog's Start]:error when auth to start stage:", pipelineLog, " start stage is ", startStageLog, " ===>error is:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } err = pipelineLog.recordPipelineStartData(startData) if err != nil { log.Error("[pipelineLog's Start]:error when record pipeline's start data:", startData, " ===>error is:", err.Error()) pipelineLog.Stop(PipelineStopReasonRunFailed, models.PipelineLogStateRunFailed) return } } func (pipelineLog *PipelineLog) Stop(reason string, runState int64) { err := pipelineLog.GetPipelineLog().Where("id = ?", pipelineLog.ID).First(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Stop]:error when get pipelinelog info from db:", err.Error()) return } notEndStageLogList := make([]models.StageLog, 0) new(models.StageLog).GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("run_state != ?", models.StageLogStateRunSuccess).Where("run_state != ?", models.StageLogStateRunFailed).Find(&notEndStageLogList) for _, stageLogInfo := range notEndStageLogList { stage := new(StageLog) stage.StageLog = &stageLogInfo stage.Stop(StageStopScopeAll, StageStopReasonRunFailed, models.StageLogStateRunFailed) } pipelineLog.RunState = runState err = pipelineLog.GetPipelineLog().Save(pipelineLog).Error if err != nil { log.Error("[pipelineLog's Stop]:error when change pipelinelog's run state:", pipelineLog, " ===>error is:", err.Error()) } } func (pipelineLog *PipelineLog) recordPipelineStartData(startData string) error { startStage := new(models.StageLog) err := startStage.GetStageLog().Where("pipeline = ?", pipelineLog.ID).Where("type = ?", models.StageTypeStart).First(startStage).Error if err != nil { log.Error("[pipelineLog's recordPipelineStartData]:error when get pipeline startStage info:", startData, " ===>error is:", err.Error()) return err } err = RecordOutcom(pipelineLog.ID, pipelineLog.FromPipeline, startStage.ID, startStage.FromStage, models.OutcomeTypeStageStartActionID, models.OutcomeTypeStageStartActionID, pipelineLog.Sequence, models.OutcomeTypeStageStartEventID, true, startData, startData) if err != nil { log.Error("[pipelineLog's recordPipelineStartData]:error when record pipeline startData info:", " ===>error is:", err.Error()) return err } return nil }
package sobjects // Base struct that contains fields that all objects, standard and custom, include. type BaseSObject struct { Attributes SObjectAttributes `json:"-" force:"attributes,omitempty"` Id string `force:",omitempty"` IsDeleted bool `force:",omitempty"` Name string `force:",omitempty"` CreatedDate string `force:",omitempty"` CreatedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` LastModifiedById string `force:",omitempty"` SystemModstamp string `force:",omitempty"` } type SObjectAttributes struct { Type string `force:"type,omitempty"` Url string `force:"url,omitempty"` } // Implementing this here because most objects don't have an external id and as such this is not needed. // Feel free to override this function when embedding the BaseSObject in other structs. func (b BaseSObject) ExternalIdApiName() string { return "" } // Fields that are returned in every query response. Use this to build custom structs. // type MyCustomQueryResponse struct { // BaseQuery // Records []sobjects.Account `json:"records" force:"records"` // } type BaseQuery struct { Done bool `json:"Done" force:"done"` TotalSize float64 `json:"TotalSize" force:"totalSize"` NextRecordsUri string `json:"NextRecordsUrl" force:"nextRecordsUrl"` } Added ConvertFieldNames func. Which converts json field names to their corresponding force api names. Great when you want to dynamically set the elements after SELECT package sobjects import ( "reflect" "strings" ) var baseFieldNameMap map[string]string func init() { baseFieldNameMap = map[string]string{ "Id": "Id", "IsDeleted": "IsDeleted", "Name": "Name", "CreatedDate": "CreatedDate", "CreatedById": "CreatedById", "LastModifiedDate": "LastModifiedDate", "LastModifiedById": "LastModifiedById", "SystemModstamp": "SystemModstamp", } } // Base struct that contains fields that all objects, standard and custom, include. type BaseSObject struct { Attributes SObjectAttributes `json:"-" force:"attributes,omitempty"` Id string `force:",omitempty"` IsDeleted bool `force:",omitempty"` Name string `force:",omitempty"` CreatedDate string `force:",omitempty"` CreatedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` LastModifiedById string `force:",omitempty"` SystemModstamp string `force:",omitempty"` } type SObjectAttributes struct { Type string `force:"type,omitempty"` Url string `force:"url,omitempty"` } // Implementing this here because most objects don't have an external id and as such this is not needed. // Feel free to override this function when embedding the BaseSObject in other structs. func (b BaseSObject) ExternalIdApiName() string { return "" } // Fields that are returned in every query response. Use this to build custom structs. // type MyCustomQueryResponse struct { // BaseQuery // Records []sobjects.Account `json:"records" force:"records"` // } type BaseQuery struct { Done bool `json:"Done" force:"done"` TotalSize float64 `json:"TotalSize" force:"totalSize"` NextRecordsUri string `json:"NextRecordsUrl" force:"nextRecordsUrl"` } // ConvertFieldNames takes in any interface that inplements SObject and a comma seperated list of json field names. // It converts the json field names to the force struct tag stated equivalent. func ConvertFieldNames(obj interface{}, jsonFields string) string { if jsonFields != "" { fields := strings.Split(jsonFields, ",") length := len(fields) if length > 0 { mapping := fieldNameMapping(obj) var forceFields []string for _, field := range fields { if forceField, ok := mapping[field]; ok { forceFields = append(forceFields, forceField) } } return strings.Join(forceFields, ",") } } return "" } // Helper function used in ConvertFieldNames func fieldNameMapping(obj interface{}) map[string]string { st := reflect.TypeOf(obj) fl := st.NumField() jsonToForce := make(map[string]string, fl) for i := 0; i < fl; i++ { sf := st.Field(i) jName := strings.SplitN(sf.Tag.Get("json"), ",", 2)[0] fName := strings.SplitN(sf.Tag.Get("force"), ",", 2)[0] if jName == "-" { continue } if fName == "-" { continue } if jName == "" { jName = sf.Name } if fName == "" { fName = sf.Name } jsonToForce[jName] = fName } for k, v := range baseFieldNameMap { jsonToForce[k] = v } return jsonToForce }
// Copyright 2017 HenryLee. All Rights Reserved. // // 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 socket import ( "bytes" "context" "encoding/json" "errors" "fmt" "math" "net/url" "sync" "github.com/henrylee2cn/goutil" "github.com/henrylee2cn/teleport/codec" "github.com/henrylee2cn/teleport/utils" "github.com/henrylee2cn/teleport/xfer" ) type ( // Packet a socket data packet. Packet struct { // packet sequence seq uint64 // packet type, such as PULL, PUSH, REPLY ptype byte // URI string uri string // URI object uriObject *url.URL // metadata meta *utils.Args // body codec type bodyCodec byte // body object body interface{} // newBodyFunc creates a new body by packet type and URI. // Note: // only for writing packet; // should be nil when reading packet. newBodyFunc NewBodyFunc // XferPipe transfer filter pipe, handlers from outer-most to inner-most. // Note: the length can not be bigger than 255! xferPipe *xfer.XferPipe // packet size size uint32 // ctx is the packet handling context, // carries a deadline, a cancelation signal, // and other values across API boundaries. ctx context.Context // stack next *Packet } // Header packet header interface Header interface { // Ptype returns the packet sequence Seq() uint64 // SetSeq sets the packet sequence SetSeq(uint64) // Ptype returns the packet type, such as PULL, PUSH, REPLY Ptype() byte // Ptype sets the packet type SetPtype(byte) // Uri returns the URI string Uri() string // UriObject returns the URI object UriObject() *url.URL // SetUri sets the packet URI SetUri(string) // SetUriObject sets the packet URI SetUriObject(uriObject *url.URL) // Meta returns the metadata Meta() *utils.Args } // Body packet body interface Body interface { // BodyCodec returns the body codec type id BodyCodec() byte // SetBodyCodec sets the body codec type id SetBodyCodec(bodyCodec byte) // Body returns the body object Body() interface{} // SetBody sets the body object SetBody(body interface{}) // SetNewBody resets the function of geting body. SetNewBody(newBodyFunc NewBodyFunc) // MarshalBody returns the encoding of body. // Note: when the body is a stream of bytes, no marshalling is done. MarshalBody() ([]byte, error) // UnmarshalBody unmarshals the encoded data to the existed body. // Note: // seq, ptype, uri must be setted already; // when the body is a stream of bytes, no unmarshalling is done. UnmarshalBody(bodyBytes []byte) error } // NewBodyFunc creates a new body by header. NewBodyFunc func(Header) interface{} ) var ( _ Header = new(Packet) _ Body = new(Packet) ) var packetStack = new(struct { freePacket *Packet mu sync.Mutex }) // GetPacket gets a *Packet form packet stack. // Note: // newBodyFunc is only for reading form connection; // settings are only for writing to connection. func GetPacket(settings ...PacketSetting) *Packet { packetStack.mu.Lock() p := packetStack.freePacket if p == nil { p = NewPacket(settings...) } else { packetStack.freePacket = p.next p.doSetting(settings...) } packetStack.mu.Unlock() return p } // PutPacket puts a *Packet to packet stack. func PutPacket(p *Packet) { packetStack.mu.Lock() p.Reset() p.next = packetStack.freePacket packetStack.freePacket = p packetStack.mu.Unlock() } // NewPacket creates a new *Packet. // Note: // NewBody is only for reading form connection; // settings are only for writing to connection. func NewPacket(settings ...PacketSetting) *Packet { var p = &Packet{ meta: new(utils.Args), xferPipe: new(xfer.XferPipe), } p.doSetting(settings...) return p } // Reset resets itself. // Note: // newBodyFunc is only for reading form connection; // settings are only for writing to connection. func (p *Packet) Reset(settings ...PacketSetting) { p.next = nil p.body = nil p.meta.Reset() p.xferPipe.Reset() p.newBodyFunc = nil p.seq = 0 p.ptype = 0 p.uri = "" p.uriObject = nil p.size = 0 p.ctx = nil p.bodyCodec = codec.NilCodecId p.doSetting(settings...) } func (p *Packet) doSetting(settings ...PacketSetting) { for _, fn := range settings { if fn != nil { fn(p) } } } // Context returns the packet handling context. func (p *Packet) Context() context.Context { if p.ctx == nil { return context.Background() } return p.ctx } // Seq returns the packet sequence func (p *Packet) Seq() uint64 { return p.seq } // SetSeq sets the packet sequence func (p *Packet) SetSeq(seq uint64) { p.seq = seq } // Ptype returns the packet type, such as PULL, PUSH, REPLY func (p *Packet) Ptype() byte { return p.ptype } // SetPtype sets the packet type func (p *Packet) SetPtype(ptype byte) { p.ptype = ptype } // Uri returns the URI string func (p *Packet) Uri() string { if p.uriObject != nil { return p.uriObject.String() } return p.uri } // UriObject returns the URI object func (p *Packet) UriObject() *url.URL { if p.uriObject == nil { p.uriObject, _ = url.Parse(p.uri) if p.uriObject == nil { p.uriObject = new(url.URL) } p.uri = "" } return p.uriObject } // SetUri sets the packet URI func (p *Packet) SetUri(uri string) { p.uri = uri p.uriObject = nil } // SetUriObject sets the packet URI func (p *Packet) SetUriObject(uriObject *url.URL) { p.uriObject = uriObject p.uri = "" } // Meta returns the metadata. // When the package is reset, it will be reset. func (p *Packet) Meta() *utils.Args { return p.meta } // BodyCodec returns the body codec type id func (p *Packet) BodyCodec() byte { return p.bodyCodec } // SetBodyCodec sets the body codec type id func (p *Packet) SetBodyCodec(bodyCodec byte) { p.bodyCodec = bodyCodec } // Body returns the body object func (p *Packet) Body() interface{} { return p.body } // SetBody sets the body object func (p *Packet) SetBody(body interface{}) { p.body = body } // SetNewBody resets the function of geting body. func (p *Packet) SetNewBody(newBodyFunc NewBodyFunc) { p.newBodyFunc = newBodyFunc } // MarshalBody returns the encoding of body. // Note: when the body is a stream of bytes, no marshalling is done. func (p *Packet) MarshalBody() ([]byte, error) { switch body := p.body.(type) { default: c, err := codec.Get(p.bodyCodec) if err != nil { return []byte{}, err } return c.Marshal(body) case nil: return []byte{}, nil case *[]byte: if body == nil { return []byte{}, nil } return *body, nil case []byte: return body, nil } } // UnmarshalBody unmarshals the encoded data to the existed body. // Note: // seq, ptype, uri must be setted already; // when the body is a stream of bytes, no unmarshalling is done. func (p *Packet) UnmarshalBody(bodyBytes []byte) error { if p.body == nil && p.newBodyFunc != nil { p.body = p.newBodyFunc(p) } if len(bodyBytes) == 0 { return nil } switch body := p.body.(type) { default: c, err := codec.Get(p.bodyCodec) if err != nil { return err } return c.Unmarshal(bodyBytes, p.body) case nil: return nil case *[]byte: if body != nil { *body = make([]byte, len(bodyBytes)) copy(*body, bodyBytes) } return nil } } // XferPipe returns transfer filter pipe, handlers from outer-most to inner-most. // Note: the length can not be bigger than 255! func (p *Packet) XferPipe() *xfer.XferPipe { return p.xferPipe } // Size returns the size of packet. func (p *Packet) Size() uint32 { return p.size } // SetSize sets the size of packet. // If the size is too big, returns error. func (p *Packet) SetSize(size uint32) error { err := checkPacketSize(size) if err != nil { return err } p.size = size return nil } const packetFormat = ` { "seq": %d, "ptype": %d, "uri": %q, "meta": %q, "body_codec": %d, "body": %s, "xfer_pipe": %s, "size": %d }` // String returns printing text. func (p *Packet) String() string { var xferPipeIds = make([]int, p.xferPipe.Len()) for i, id := range p.xferPipe.Ids() { xferPipeIds[i] = int(id) } idsBytes, _ := json.Marshal(xferPipeIds) b, _ := json.Marshal(p.body) dst := bytes.NewBuffer(make([]byte, 0, len(b)*2)) json.Indent(dst, goutil.StringToBytes( fmt.Sprintf(packetFormat, p.seq, p.ptype, p.uri, p.meta.QueryString(), p.bodyCodec, b, idsBytes, p.size, ), ), "", " ") return goutil.BytesToString(dst.Bytes()) } // PacketSetting sets Header field. type PacketSetting func(*Packet) // WithContext sets the packet handling context. func WithContext(ctx context.Context) PacketSetting { return func(p *Packet) { p.ctx = ctx } } // WithSeq sets the packet sequence. func WithSeq(seq uint64) PacketSetting { return func(p *Packet) { p.seq = seq } } // WithPtype sets the packet type. func WithPtype(ptype byte) PacketSetting { return func(p *Packet) { p.ptype = ptype } } // WithUri sets the packet URI string. func WithUri(uri string) PacketSetting { return func(p *Packet) { p.SetUri(uri) } } // WithUriObject sets the packet URI object. func WithUriObject(uriObject *url.URL) PacketSetting { return func(p *Packet) { p.SetUriObject(uriObject) } } // WithQuery sets the packet URI query parameter. func WithQuery(key, value string) PacketSetting { return func(p *Packet) { u := p.UriObject() v := u.Query() v.Add(key, value) u.RawQuery = v.Encode() } } // WithAddMeta adds 'key=value' metadata argument. // Multiple values for the same key may be added. func WithAddMeta(key, value string) PacketSetting { return func(p *Packet) { p.meta.Add(key, value) } } // WithSetMeta sets 'key=value' metadata argument. func WithSetMeta(key, value string) PacketSetting { return func(p *Packet) { p.meta.Set(key, value) } } // WithBodyCodec sets the body codec. func WithBodyCodec(bodyCodec byte) PacketSetting { return func(p *Packet) { p.bodyCodec = bodyCodec } } // WithBody sets the body object. func WithBody(body interface{}) PacketSetting { return func(p *Packet) { p.body = body } } // WithNewBody resets the function of geting body. func WithNewBody(newBodyFunc NewBodyFunc) PacketSetting { return func(p *Packet) { p.newBodyFunc = newBodyFunc } } // WithXferPipe sets transfer filter pipe. func WithXferPipe(filterId ...byte) PacketSetting { return func(p *Packet) { p.xferPipe.Append(filterId...) } } var ( packetSizeLimit uint32 = math.MaxUint32 // ErrExceedPacketSizeLimit error ErrExceedPacketSizeLimit = errors.New("Size of package exceeds limit.") ) // PacketSizeLimit gets the packet size upper limit of reading. func PacketSizeLimit() uint32 { return packetSizeLimit } // SetPacketSizeLimit sets max packet size. // If maxSize<=0, set it to max uint32. func SetPacketSizeLimit(maxPacketSize uint32) { if maxPacketSize <= 0 { packetSizeLimit = math.MaxUint32 } else { packetSizeLimit = maxPacketSize } } func checkPacketSize(packetSize uint32) error { if packetSize > packetSizeLimit { return ErrExceedPacketSizeLimit } return nil } socket.Packet: update UnmarshalBody comment // Copyright 2017 HenryLee. All Rights Reserved. // // 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 socket import ( "bytes" "context" "encoding/json" "errors" "fmt" "math" "net/url" "sync" "github.com/henrylee2cn/goutil" "github.com/henrylee2cn/teleport/codec" "github.com/henrylee2cn/teleport/utils" "github.com/henrylee2cn/teleport/xfer" ) type ( // Packet a socket data packet. Packet struct { // packet sequence seq uint64 // packet type, such as PULL, PUSH, REPLY ptype byte // URI string uri string // URI object uriObject *url.URL // metadata meta *utils.Args // body codec type bodyCodec byte // body object body interface{} // newBodyFunc creates a new body by packet type and URI. // Note: // only for writing packet; // should be nil when reading packet. newBodyFunc NewBodyFunc // XferPipe transfer filter pipe, handlers from outer-most to inner-most. // Note: the length can not be bigger than 255! xferPipe *xfer.XferPipe // packet size size uint32 // ctx is the packet handling context, // carries a deadline, a cancelation signal, // and other values across API boundaries. ctx context.Context // stack next *Packet } // Header packet header interface Header interface { // Ptype returns the packet sequence Seq() uint64 // SetSeq sets the packet sequence SetSeq(uint64) // Ptype returns the packet type, such as PULL, PUSH, REPLY Ptype() byte // Ptype sets the packet type SetPtype(byte) // Uri returns the URI string Uri() string // UriObject returns the URI object UriObject() *url.URL // SetUri sets the packet URI SetUri(string) // SetUriObject sets the packet URI SetUriObject(uriObject *url.URL) // Meta returns the metadata Meta() *utils.Args } // Body packet body interface Body interface { // BodyCodec returns the body codec type id BodyCodec() byte // SetBodyCodec sets the body codec type id SetBodyCodec(bodyCodec byte) // Body returns the body object Body() interface{} // SetBody sets the body object SetBody(body interface{}) // SetNewBody resets the function of geting body. SetNewBody(newBodyFunc NewBodyFunc) // MarshalBody returns the encoding of body. // Note: when the body is a stream of bytes, no marshalling is done. MarshalBody() ([]byte, error) // UnmarshalBody unmarshals the encoded data to the body. // Note: // seq, ptype, uri must be setted already; // if body=nil, try to use newBodyFunc to create a new one; // when the body is a stream of bytes, no unmarshalling is done. UnmarshalBody(bodyBytes []byte) error } // NewBodyFunc creates a new body by header. NewBodyFunc func(Header) interface{} ) var ( _ Header = new(Packet) _ Body = new(Packet) ) var packetStack = new(struct { freePacket *Packet mu sync.Mutex }) // GetPacket gets a *Packet form packet stack. // Note: // newBodyFunc is only for reading form connection; // settings are only for writing to connection. func GetPacket(settings ...PacketSetting) *Packet { packetStack.mu.Lock() p := packetStack.freePacket if p == nil { p = NewPacket(settings...) } else { packetStack.freePacket = p.next p.doSetting(settings...) } packetStack.mu.Unlock() return p } // PutPacket puts a *Packet to packet stack. func PutPacket(p *Packet) { packetStack.mu.Lock() p.Reset() p.next = packetStack.freePacket packetStack.freePacket = p packetStack.mu.Unlock() } // NewPacket creates a new *Packet. // Note: // NewBody is only for reading form connection; // settings are only for writing to connection. func NewPacket(settings ...PacketSetting) *Packet { var p = &Packet{ meta: new(utils.Args), xferPipe: new(xfer.XferPipe), } p.doSetting(settings...) return p } // Reset resets itself. // Note: // newBodyFunc is only for reading form connection; // settings are only for writing to connection. func (p *Packet) Reset(settings ...PacketSetting) { p.next = nil p.body = nil p.meta.Reset() p.xferPipe.Reset() p.newBodyFunc = nil p.seq = 0 p.ptype = 0 p.uri = "" p.uriObject = nil p.size = 0 p.ctx = nil p.bodyCodec = codec.NilCodecId p.doSetting(settings...) } func (p *Packet) doSetting(settings ...PacketSetting) { for _, fn := range settings { if fn != nil { fn(p) } } } // Context returns the packet handling context. func (p *Packet) Context() context.Context { if p.ctx == nil { return context.Background() } return p.ctx } // Seq returns the packet sequence func (p *Packet) Seq() uint64 { return p.seq } // SetSeq sets the packet sequence func (p *Packet) SetSeq(seq uint64) { p.seq = seq } // Ptype returns the packet type, such as PULL, PUSH, REPLY func (p *Packet) Ptype() byte { return p.ptype } // SetPtype sets the packet type func (p *Packet) SetPtype(ptype byte) { p.ptype = ptype } // Uri returns the URI string func (p *Packet) Uri() string { if p.uriObject != nil { return p.uriObject.String() } return p.uri } // UriObject returns the URI object func (p *Packet) UriObject() *url.URL { if p.uriObject == nil { p.uriObject, _ = url.Parse(p.uri) if p.uriObject == nil { p.uriObject = new(url.URL) } p.uri = "" } return p.uriObject } // SetUri sets the packet URI func (p *Packet) SetUri(uri string) { p.uri = uri p.uriObject = nil } // SetUriObject sets the packet URI func (p *Packet) SetUriObject(uriObject *url.URL) { p.uriObject = uriObject p.uri = "" } // Meta returns the metadata. // When the package is reset, it will be reset. func (p *Packet) Meta() *utils.Args { return p.meta } // BodyCodec returns the body codec type id func (p *Packet) BodyCodec() byte { return p.bodyCodec } // SetBodyCodec sets the body codec type id func (p *Packet) SetBodyCodec(bodyCodec byte) { p.bodyCodec = bodyCodec } // Body returns the body object func (p *Packet) Body() interface{} { return p.body } // SetBody sets the body object func (p *Packet) SetBody(body interface{}) { p.body = body } // SetNewBody resets the function of geting body. func (p *Packet) SetNewBody(newBodyFunc NewBodyFunc) { p.newBodyFunc = newBodyFunc } // MarshalBody returns the encoding of body. // Note: when the body is a stream of bytes, no marshalling is done. func (p *Packet) MarshalBody() ([]byte, error) { switch body := p.body.(type) { default: c, err := codec.Get(p.bodyCodec) if err != nil { return []byte{}, err } return c.Marshal(body) case nil: return []byte{}, nil case *[]byte: if body == nil { return []byte{}, nil } return *body, nil case []byte: return body, nil } } // UnmarshalBody unmarshals the encoded data to the body. // Note: // seq, ptype, uri must be setted already; // if body=nil, try to use newBodyFunc to create a new one; // when the body is a stream of bytes, no unmarshalling is done. func (p *Packet) UnmarshalBody(bodyBytes []byte) error { if p.body == nil && p.newBodyFunc != nil { p.body = p.newBodyFunc(p) } if len(bodyBytes) == 0 { return nil } switch body := p.body.(type) { default: c, err := codec.Get(p.bodyCodec) if err != nil { return err } return c.Unmarshal(bodyBytes, p.body) case nil: return nil case *[]byte: if body != nil { *body = make([]byte, len(bodyBytes)) copy(*body, bodyBytes) } return nil } } // XferPipe returns transfer filter pipe, handlers from outer-most to inner-most. // Note: the length can not be bigger than 255! func (p *Packet) XferPipe() *xfer.XferPipe { return p.xferPipe } // Size returns the size of packet. func (p *Packet) Size() uint32 { return p.size } // SetSize sets the size of packet. // If the size is too big, returns error. func (p *Packet) SetSize(size uint32) error { err := checkPacketSize(size) if err != nil { return err } p.size = size return nil } const packetFormat = ` { "seq": %d, "ptype": %d, "uri": %q, "meta": %q, "body_codec": %d, "body": %s, "xfer_pipe": %s, "size": %d }` // String returns printing text. func (p *Packet) String() string { var xferPipeIds = make([]int, p.xferPipe.Len()) for i, id := range p.xferPipe.Ids() { xferPipeIds[i] = int(id) } idsBytes, _ := json.Marshal(xferPipeIds) b, _ := json.Marshal(p.body) dst := bytes.NewBuffer(make([]byte, 0, len(b)*2)) json.Indent(dst, goutil.StringToBytes( fmt.Sprintf(packetFormat, p.seq, p.ptype, p.uri, p.meta.QueryString(), p.bodyCodec, b, idsBytes, p.size, ), ), "", " ") return goutil.BytesToString(dst.Bytes()) } // PacketSetting sets Header field. type PacketSetting func(*Packet) // WithContext sets the packet handling context. func WithContext(ctx context.Context) PacketSetting { return func(p *Packet) { p.ctx = ctx } } // WithSeq sets the packet sequence. func WithSeq(seq uint64) PacketSetting { return func(p *Packet) { p.seq = seq } } // WithPtype sets the packet type. func WithPtype(ptype byte) PacketSetting { return func(p *Packet) { p.ptype = ptype } } // WithUri sets the packet URI string. func WithUri(uri string) PacketSetting { return func(p *Packet) { p.SetUri(uri) } } // WithUriObject sets the packet URI object. func WithUriObject(uriObject *url.URL) PacketSetting { return func(p *Packet) { p.SetUriObject(uriObject) } } // WithQuery sets the packet URI query parameter. func WithQuery(key, value string) PacketSetting { return func(p *Packet) { u := p.UriObject() v := u.Query() v.Add(key, value) u.RawQuery = v.Encode() } } // WithAddMeta adds 'key=value' metadata argument. // Multiple values for the same key may be added. func WithAddMeta(key, value string) PacketSetting { return func(p *Packet) { p.meta.Add(key, value) } } // WithSetMeta sets 'key=value' metadata argument. func WithSetMeta(key, value string) PacketSetting { return func(p *Packet) { p.meta.Set(key, value) } } // WithBodyCodec sets the body codec. func WithBodyCodec(bodyCodec byte) PacketSetting { return func(p *Packet) { p.bodyCodec = bodyCodec } } // WithBody sets the body object. func WithBody(body interface{}) PacketSetting { return func(p *Packet) { p.body = body } } // WithNewBody resets the function of geting body. func WithNewBody(newBodyFunc NewBodyFunc) PacketSetting { return func(p *Packet) { p.newBodyFunc = newBodyFunc } } // WithXferPipe sets transfer filter pipe. func WithXferPipe(filterId ...byte) PacketSetting { return func(p *Packet) { p.xferPipe.Append(filterId...) } } var ( packetSizeLimit uint32 = math.MaxUint32 // ErrExceedPacketSizeLimit error ErrExceedPacketSizeLimit = errors.New("Size of package exceeds limit.") ) // PacketSizeLimit gets the packet size upper limit of reading. func PacketSizeLimit() uint32 { return packetSizeLimit } // SetPacketSizeLimit sets max packet size. // If maxSize<=0, set it to max uint32. func SetPacketSizeLimit(maxPacketSize uint32) { if maxPacketSize <= 0 { packetSizeLimit = math.MaxUint32 } else { packetSizeLimit = maxPacketSize } } func checkPacketSize(packetSize uint32) error { if packetSize > packetSizeLimit { return ErrExceedPacketSizeLimit } return nil }
package ydls import ( "context" "fmt" "io" "io/ioutil" "log" "net/http" "os" "sort" "strings" "sync" "github.com/wader/ydls/ffmpeg" "github.com/wader/ydls/id3v2" "github.com/wader/ydls/rereader" "github.com/wader/ydls/stringprioset" "github.com/wader/ydls/timerange" "github.com/wader/ydls/writelogger" "github.com/wader/ydls/youtubedl" ) const maxProbeBytes = 10 * 1024 * 1024 type MediaType uint const ( MediaAudio MediaType = iota MediaVideo MediaUnknown ) func (m MediaType) String() string { switch m { case MediaAudio: return "audio" case MediaVideo: return "video" default: return "unknown" } } func firstNonEmpty(sl ...string) string { for _, s := range sl { if s != "" { return s } } return "" } func logOrDiscard(l *log.Logger) *log.Logger { if l != nil { return l } return log.New(ioutil.Discard, "", 0) } func metadataFromYoutubeDLInfo(yi youtubedl.Info) ffmpeg.Metadata { return ffmpeg.Metadata{ Artist: firstNonEmpty(yi.Artist, yi.Creator, yi.Uploader), Title: yi.Title, Comment: yi.Description, } } func id3v2FramesFromMetadata(m ffmpeg.Metadata, yi youtubedl.Info) []id3v2.Frame { frames := []id3v2.Frame{ &id3v2.TextFrame{ID: "TPE1", Text: m.Artist}, &id3v2.TextFrame{ID: "TIT2", Text: m.Title}, &id3v2.COMMFrame{Language: "XXX", Description: "", Text: m.Comment}, } if yi.Duration > 0 { frames = append(frames, &id3v2.TextFrame{ ID: "TLEN", Text: fmt.Sprintf("%d", uint32(yi.Duration*1000)), }) } if len(yi.ThumbnailBytes) > 0 { frames = append(frames, &id3v2.APICFrame{ MIMEType: http.DetectContentType(yi.ThumbnailBytes), PictureType: id3v2.PictureTypeOther, Description: "", Data: yi.ThumbnailBytes, }) } return frames } func safeFilename(filename string) string { r := strings.NewReplacer("/", "_", "\\", "_") return r.Replace(filename) } func findYDLFormat(formats []youtubedl.Format, media MediaType, codecs stringprioset.Set) (youtubedl.Format, bool) { var sorted []youtubedl.Format // filter out only audio or video formats for _, f := range formats { if media == MediaAudio && f.NormACodec == "" || media == MediaVideo && f.NormVCodec == "" { continue } sorted = append(sorted, f) } // sort by has-codec, media bitrate, total bitrate, format id sort.Slice(sorted, func(i int, j int) bool { type order struct { codec string br float64 tbr float64 id string } fi := sorted[i] fj := sorted[j] var oi order var oj order switch media { case MediaAudio: oi = order{ codec: fi.NormACodec, br: fi.ABR, tbr: fi.NormBR, id: fi.FormatID, } oj = order{ codec: fj.NormACodec, br: fj.ABR, tbr: fj.NormBR, id: fj.FormatID, } case MediaVideo: oi = order{ codec: fi.NormVCodec, br: fi.VBR, tbr: fi.NormBR, id: fi.FormatID, } oj = order{ codec: fj.NormVCodec, br: fj.VBR, tbr: fj.NormBR, id: fj.FormatID, } } // codecs argument will always be only audio or only video codecs switch a, b := codecs.Member(oi.codec), codecs.Member(oj.codec); { case a && !b: return true case !a && b: return false } switch a, b := oi.br, oj.br; { case a > b: return true case a < b: return false } switch a, b := oi.tbr, oj.tbr; { case a > b: return true case a < b: return false } if strings.Compare(oi.id, oj.id) > 0 { return false } return true }) if len(sorted) > 0 { return sorted[0], true } return youtubedl.Format{}, false } type downloadProbeReadCloser struct { downloadResult *youtubedl.DownloadResult probeInfo ffmpeg.ProbeInfo reader io.ReadCloser } func (d *downloadProbeReadCloser) Read(p []byte) (n int, err error) { return d.reader.Read(p) } func (d *downloadProbeReadCloser) Close() error { d.reader.Close() d.downloadResult.Wait() return nil } func downloadAndProbeFormat( ctx context.Context, ydl youtubedl.Info, filter string, debugLog *log.Logger, ) (*downloadProbeReadCloser, error) { log := logOrDiscard(debugLog) ydlStderr := writelogger.New(log, fmt.Sprintf("ydl-dl %s stderr> ", filter)) dr, err := ydl.Download(ctx, filter, ydlStderr) if err != nil { return nil, err } rr := rereader.NewReReadCloser(dr.Reader) dprc := &downloadProbeReadCloser{ downloadResult: dr, reader: rr, } ffprobeStderr := writelogger.New(log, fmt.Sprintf("ffprobe %s stderr> ", filter)) dprc.probeInfo, err = ffmpeg.Probe( ctx, ffmpeg.Reader{Reader: io.LimitReader(rr, maxProbeBytes)}, log, ffprobeStderr, ) if err != nil { dr.Reader.Close() dr.Wait() return nil, err } // restart and replay buffer data used when probing rr.Restarted = true return dprc, nil } // YDLS youtubedl downloader with some extras type YDLS struct { Config Config } // NewFromFile new YDLs using config file func NewFromFile(configPath string) (YDLS, error) { configFile, err := os.Open(configPath) if err != nil { return YDLS{}, err } defer configFile.Close() config, err := parseConfig(configFile) if err != nil { return YDLS{}, err } return YDLS{Config: config}, nil } // DownloadOptions download options type DownloadOptions struct { URL string Format string Codecs []string // force codecs Retranscode bool // force retranscode even if same input codec TimeRange timerange.TimeRange // time range limit } // DownloadResult download result type DownloadResult struct { Media io.ReadCloser Filename string MIMEType string waitCh chan struct{} } // Wait for download resources to cleanup func (dr DownloadResult) Wait() { <-dr.waitCh } func chooseCodec(formatCodecs []Codec, optionCodecs []string, probedCodecs []string) Codec { findCodec := func(codecs []string) (Codec, bool) { for _, c := range codecs { for _, fc := range formatCodecs { if fc.Name == c { return fc, true } } } return Codec{}, false } // prefer option codec, probed codec then first format codec if codec, ok := findCodec(optionCodecs); ok { return codec } if codec, ok := findCodec(probedCodecs); ok { return codec } // TODO: could return false if there is no formats but only happens with very weird config // default use first codec return formatCodecs[0] } // ParseDownloadOptions parse options based on curret config func (ydls *YDLS) ParseDownloadOptions(url string, formatName string, optStrings []string) (DownloadOptions, error) { if formatName == "" { return DownloadOptions{ URL: url, Format: "", }, nil } format, formatFound := ydls.Config.Formats.FindByName(formatName) if !formatFound { return DownloadOptions{}, fmt.Errorf("unknown format %s", formatName) } opts := DownloadOptions{ URL: url, Format: formatName, } codecNames := map[string]bool{} for _, s := range format.Streams { for _, c := range s.Codecs { codecNames[c.Name] = true } } for _, opt := range optStrings { if opt == "retranscode" { opts.Retranscode = true } else if _, ok := codecNames[opt]; ok { opts.Codecs = append(opts.Codecs, opt) } else if tr, trErr := timerange.NewFromString(opt); trErr == nil { opts.TimeRange = tr } else { return DownloadOptions{}, fmt.Errorf("unknown opt %s", opt) } } return opts, nil } func codecsFromProbeInfo(pi ffmpeg.ProbeInfo) []string { var codecs []string if c := pi.AudioCodec(); c != "" { codecs = append(codecs, c) } if c := pi.VideoCodec(); c != "" { codecs = append(codecs, c) } return codecs } // Download downloads media from URL using context and makes sure output is in specified format func (ydls *YDLS) Download(ctx context.Context, options DownloadOptions, debugLog *log.Logger) (DownloadResult, error) { log := logOrDiscard(debugLog) log.Printf("URL: %s", options.URL) log.Printf("Output format: %s", options.Format) var ydlStdout io.Writer ydlStdout = writelogger.New(log, "ydl-new stdout> ") ydl, err := youtubedl.NewFromURL(ctx, options.URL, ydlStdout) if err != nil { log.Printf("Failed to download: %s", err) return DownloadResult{}, err } log.Printf("Title: %s", ydl.Title) log.Printf("Available youtubedl formats:") for _, f := range ydl.Formats { log.Printf(" %s", f) } if options.Format == "" { return ydls.downloadRaw(ctx, log, ydl) } return ydls.downloadFormat(ctx, log, options, ydl) } func (ydls *YDLS) downloadRaw(ctx context.Context, log *log.Logger, ydl youtubedl.Info) (DownloadResult, error) { dprc, err := downloadAndProbeFormat(ctx, ydl, "best", log) if err != nil { return DownloadResult{}, err } log.Printf("Probed format %s", dprc.probeInfo) dr := DownloadResult{ waitCh: make(chan struct{}), } // see if we know about the probed format, otherwise fallback to "raw" outFormat, outFormatName := ydls.Config.Formats.FindByFormatCodecs( dprc.probeInfo.FormatName(), codecsFromProbeInfo(dprc.probeInfo), ) if outFormatName != "" { dr.MIMEType = outFormat.MIMEType dr.Filename = safeFilename(ydl.Title + "." + outFormat.Ext) } else { dr.MIMEType = "application/octet-stream" dr.Filename = safeFilename(ydl.Title + ".raw") } var w io.WriteCloser dr.Media, w = io.Pipe() go func() { n, err := io.Copy(w, dprc) dprc.Close() w.Close() log.Printf("Copy done (n=%v err=%v)", n, err) close(dr.waitCh) }() return dr, nil } // TODO: messy, needs refactor func (ydls *YDLS) downloadFormat(ctx context.Context, log *log.Logger, options DownloadOptions, ydl youtubedl.Info) (DownloadResult, error) { type streamDownloadMap struct { stream Stream ydlFormat youtubedl.Format download *downloadProbeReadCloser } dr := DownloadResult{ waitCh: make(chan struct{}), } outFormat, outFormatFound := ydls.Config.Formats.FindByName(options.Format) if !outFormatFound { return DownloadResult{}, fmt.Errorf("could not find format %s", options.Format) } var closeOnDone []io.Closer closeOnDoneFn := func() { for _, c := range closeOnDone { c.Close() } } deferCloseFn := closeOnDoneFn defer func() { // will be nil if cmd starts and goroutine takes care of closing instead if deferCloseFn != nil { deferCloseFn() } }() dr.MIMEType = outFormat.MIMEType dr.Filename = safeFilename(ydl.Title + "." + outFormat.Ext) log.Printf("Best format for streams:") streamDownloads := []streamDownloadMap{} for _, s := range outFormat.Streams { preferredCodecs := s.CodecNames optionsCodecCommon := stringprioset.New(options.Codecs).Intersect(s.CodecNames) if !optionsCodecCommon.Empty() { preferredCodecs = optionsCodecCommon } if ydlFormat, ydlsFormatFound := findYDLFormat( ydl.Formats, s.Media, preferredCodecs, ); ydlsFormatFound { streamDownloads = append(streamDownloads, streamDownloadMap{ stream: s, ydlFormat: ydlFormat, }) log.Printf(" %s -> %s", s.CodecNames, ydlFormat) } else { return DownloadResult{}, fmt.Errorf("no %s stream found", s.Media) } } uniqueFormatIDs := map[string]bool{} for _, sdm := range streamDownloads { uniqueFormatIDs[sdm.ydlFormat.FormatID] = true } type downloadProbeResult struct { err error download *downloadProbeReadCloser } downloads := map[string]downloadProbeResult{} var downloadsMutex sync.Mutex var downloadsWG sync.WaitGroup downloadsWG.Add(len(uniqueFormatIDs)) for formatID := range uniqueFormatIDs { go func(formatID string) { dprc, err := downloadAndProbeFormat(ctx, ydl, formatID, log) downloadsMutex.Lock() downloads[formatID] = downloadProbeResult{err: err, download: dprc} downloadsMutex.Unlock() downloadsWG.Done() }(formatID) } downloadsWG.Wait() for _, d := range downloads { closeOnDone = append(closeOnDone, d.download) } for formatID, d := range downloads { // TODO: more than one error? if d.err != nil { return DownloadResult{}, fmt.Errorf("failed to probe: %s: %s", formatID, d.err) } if d.download == nil { return DownloadResult{}, fmt.Errorf("failed to download: %s", formatID) } } for i, sdm := range streamDownloads { streamDownloads[i].download = downloads[sdm.ydlFormat.FormatID].download } log.Printf("Stream mapping:") var ffmpegMaps []ffmpeg.Map ffmpegFormatFlags := make([]string, len(outFormat.FormatFlags)) copy(ffmpegFormatFlags, outFormat.FormatFlags) for _, sdm := range streamDownloads { var ffmpegCodec ffmpeg.Codec var codec Codec codec = chooseCodec( sdm.stream.Codecs, options.Codecs, codecsFromProbeInfo(sdm.download.probeInfo), ) if sdm.stream.Media == MediaAudio { if !options.Retranscode && codec.Name == sdm.download.probeInfo.AudioCodec() { ffmpegCodec = ffmpeg.AudioCodec("copy") } else { ffmpegCodec = ffmpeg.AudioCodec(firstNonEmpty(ydls.Config.CodecMap[codec.Name], codec.Name)) } } else if sdm.stream.Media == MediaVideo { if !options.Retranscode && codec.Name == sdm.download.probeInfo.VideoCodec() { ffmpegCodec = ffmpeg.VideoCodec("copy") } else { ffmpegCodec = ffmpeg.VideoCodec(firstNonEmpty(ydls.Config.CodecMap[codec.Name], codec.Name)) } } else { return DownloadResult{}, fmt.Errorf("unknown media type %v", sdm.stream.Media) } ffmpegMaps = append(ffmpegMaps, ffmpeg.Map{ Input: ffmpeg.Reader{Reader: sdm.download}, Specifier: sdm.stream.Specifier, Codec: ffmpegCodec, CodecFlags: codec.Flags, }) ffmpegFormatFlags = append(ffmpegFormatFlags, codec.FormatFlags...) log.Printf(" %s ydl:%s probed:%s -> %s (%s)", sdm.stream.Specifier, sdm.ydlFormat, sdm.download.probeInfo, codec.Name, ydls.Config.CodecMap[codec.Name], ) } var ffmpegStderr io.Writer ffmpegStderr = writelogger.New(log, "ffmpeg stderr> ") ffmpegR, ffmpegW := io.Pipe() closeOnDone = append(closeOnDone, ffmpegR) var inputFlags []string var outputFlags []string inputFlags = append(inputFlags, ydls.Config.InputFlags...) if !options.TimeRange.IsZero() { if options.TimeRange.Start != 0 { inputFlags = append(inputFlags, "-ss", ffmpeg.DurationToPosition(options.TimeRange.Start)) } outputFlags = []string{"-to", ffmpeg.DurationToPosition(options.TimeRange.Duration())} } metadata := metadataFromYoutubeDLInfo(ydl) for _, sdm := range streamDownloads { metadata = metadata.Merge(sdm.download.probeInfo.Format.Tags) } firstOutFormat, _ := outFormat.Formats.First() ffmpegP := &ffmpeg.FFmpeg{ Streams: []ffmpeg.Stream{ ffmpeg.Stream{ InputFlags: inputFlags, OutputFlags: outputFlags, Maps: ffmpegMaps, Format: ffmpeg.Format{ Name: firstOutFormat, Flags: ffmpegFormatFlags, }, Metadata: metadata, Output: ffmpeg.Writer{Writer: ffmpegW}, }, }, DebugLog: log, Stderr: ffmpegStderr, } if err := ffmpegP.Start(ctx); err != nil { return DownloadResult{}, err } // goroutine will take care of closing deferCloseFn = nil var w io.WriteCloser dr.Media, w = io.Pipe() closeOnDone = append(closeOnDone, w) go func() { // TODO: ffmpeg mp3enc id3 writer does not work with streamed output // (id3v2 header length update requires seek) if outFormat.Prepend == "id3v2" { id3v2.Write(w, id3v2FramesFromMetadata(metadata, ydl)) } log.Printf("Starting to copy") n, err := io.Copy(w, ffmpegR) log.Printf("Copy ffmpeg done (n=%v err=%v)", n, err) closeOnDoneFn() ffmpegP.Wait() log.Printf("Done") close(dr.waitCh) }() return dr, nil } Make choosen format debug log more clear package ydls import ( "context" "fmt" "io" "io/ioutil" "log" "net/http" "os" "sort" "strings" "sync" "github.com/wader/ydls/ffmpeg" "github.com/wader/ydls/id3v2" "github.com/wader/ydls/rereader" "github.com/wader/ydls/stringprioset" "github.com/wader/ydls/timerange" "github.com/wader/ydls/writelogger" "github.com/wader/ydls/youtubedl" ) const maxProbeBytes = 10 * 1024 * 1024 type MediaType uint const ( MediaAudio MediaType = iota MediaVideo MediaUnknown ) func (m MediaType) String() string { switch m { case MediaAudio: return "audio" case MediaVideo: return "video" default: return "unknown" } } func firstNonEmpty(sl ...string) string { for _, s := range sl { if s != "" { return s } } return "" } func logOrDiscard(l *log.Logger) *log.Logger { if l != nil { return l } return log.New(ioutil.Discard, "", 0) } func metadataFromYoutubeDLInfo(yi youtubedl.Info) ffmpeg.Metadata { return ffmpeg.Metadata{ Artist: firstNonEmpty(yi.Artist, yi.Creator, yi.Uploader), Title: yi.Title, Comment: yi.Description, } } func id3v2FramesFromMetadata(m ffmpeg.Metadata, yi youtubedl.Info) []id3v2.Frame { frames := []id3v2.Frame{ &id3v2.TextFrame{ID: "TPE1", Text: m.Artist}, &id3v2.TextFrame{ID: "TIT2", Text: m.Title}, &id3v2.COMMFrame{Language: "XXX", Description: "", Text: m.Comment}, } if yi.Duration > 0 { frames = append(frames, &id3v2.TextFrame{ ID: "TLEN", Text: fmt.Sprintf("%d", uint32(yi.Duration*1000)), }) } if len(yi.ThumbnailBytes) > 0 { frames = append(frames, &id3v2.APICFrame{ MIMEType: http.DetectContentType(yi.ThumbnailBytes), PictureType: id3v2.PictureTypeOther, Description: "", Data: yi.ThumbnailBytes, }) } return frames } func safeFilename(filename string) string { r := strings.NewReplacer("/", "_", "\\", "_") return r.Replace(filename) } func findYDLFormat(formats []youtubedl.Format, media MediaType, codecs stringprioset.Set) (youtubedl.Format, bool) { var sorted []youtubedl.Format // filter out only audio or video formats for _, f := range formats { if media == MediaAudio && f.NormACodec == "" || media == MediaVideo && f.NormVCodec == "" { continue } sorted = append(sorted, f) } // sort by has-codec, media bitrate, total bitrate, format id sort.Slice(sorted, func(i int, j int) bool { type order struct { codec string br float64 tbr float64 id string } fi := sorted[i] fj := sorted[j] var oi order var oj order switch media { case MediaAudio: oi = order{ codec: fi.NormACodec, br: fi.ABR, tbr: fi.NormBR, id: fi.FormatID, } oj = order{ codec: fj.NormACodec, br: fj.ABR, tbr: fj.NormBR, id: fj.FormatID, } case MediaVideo: oi = order{ codec: fi.NormVCodec, br: fi.VBR, tbr: fi.NormBR, id: fi.FormatID, } oj = order{ codec: fj.NormVCodec, br: fj.VBR, tbr: fj.NormBR, id: fj.FormatID, } } // codecs argument will always be only audio or only video codecs switch a, b := codecs.Member(oi.codec), codecs.Member(oj.codec); { case a && !b: return true case !a && b: return false } switch a, b := oi.br, oj.br; { case a > b: return true case a < b: return false } switch a, b := oi.tbr, oj.tbr; { case a > b: return true case a < b: return false } if strings.Compare(oi.id, oj.id) > 0 { return false } return true }) if len(sorted) > 0 { return sorted[0], true } return youtubedl.Format{}, false } type downloadProbeReadCloser struct { downloadResult *youtubedl.DownloadResult probeInfo ffmpeg.ProbeInfo reader io.ReadCloser } func (d *downloadProbeReadCloser) Read(p []byte) (n int, err error) { return d.reader.Read(p) } func (d *downloadProbeReadCloser) Close() error { d.reader.Close() d.downloadResult.Wait() return nil } func downloadAndProbeFormat( ctx context.Context, ydl youtubedl.Info, filter string, debugLog *log.Logger, ) (*downloadProbeReadCloser, error) { log := logOrDiscard(debugLog) ydlStderr := writelogger.New(log, fmt.Sprintf("ydl-dl %s stderr> ", filter)) dr, err := ydl.Download(ctx, filter, ydlStderr) if err != nil { return nil, err } rr := rereader.NewReReadCloser(dr.Reader) dprc := &downloadProbeReadCloser{ downloadResult: dr, reader: rr, } ffprobeStderr := writelogger.New(log, fmt.Sprintf("ffprobe %s stderr> ", filter)) dprc.probeInfo, err = ffmpeg.Probe( ctx, ffmpeg.Reader{Reader: io.LimitReader(rr, maxProbeBytes)}, log, ffprobeStderr, ) if err != nil { dr.Reader.Close() dr.Wait() return nil, err } // restart and replay buffer data used when probing rr.Restarted = true return dprc, nil } // YDLS youtubedl downloader with some extras type YDLS struct { Config Config } // NewFromFile new YDLs using config file func NewFromFile(configPath string) (YDLS, error) { configFile, err := os.Open(configPath) if err != nil { return YDLS{}, err } defer configFile.Close() config, err := parseConfig(configFile) if err != nil { return YDLS{}, err } return YDLS{Config: config}, nil } // DownloadOptions download options type DownloadOptions struct { URL string Format string Codecs []string // force codecs Retranscode bool // force retranscode even if same input codec TimeRange timerange.TimeRange // time range limit } // DownloadResult download result type DownloadResult struct { Media io.ReadCloser Filename string MIMEType string waitCh chan struct{} } // Wait for download resources to cleanup func (dr DownloadResult) Wait() { <-dr.waitCh } func chooseCodec(formatCodecs []Codec, optionCodecs []string, probedCodecs []string) Codec { findCodec := func(codecs []string) (Codec, bool) { for _, c := range codecs { for _, fc := range formatCodecs { if fc.Name == c { return fc, true } } } return Codec{}, false } // prefer option codec, probed codec then first format codec if codec, ok := findCodec(optionCodecs); ok { return codec } if codec, ok := findCodec(probedCodecs); ok { return codec } // TODO: could return false if there is no formats but only happens with very weird config // default use first codec return formatCodecs[0] } // ParseDownloadOptions parse options based on curret config func (ydls *YDLS) ParseDownloadOptions(url string, formatName string, optStrings []string) (DownloadOptions, error) { if formatName == "" { return DownloadOptions{ URL: url, Format: "", }, nil } format, formatFound := ydls.Config.Formats.FindByName(formatName) if !formatFound { return DownloadOptions{}, fmt.Errorf("unknown format %s", formatName) } opts := DownloadOptions{ URL: url, Format: formatName, } codecNames := map[string]bool{} for _, s := range format.Streams { for _, c := range s.Codecs { codecNames[c.Name] = true } } for _, opt := range optStrings { if opt == "retranscode" { opts.Retranscode = true } else if _, ok := codecNames[opt]; ok { opts.Codecs = append(opts.Codecs, opt) } else if tr, trErr := timerange.NewFromString(opt); trErr == nil { opts.TimeRange = tr } else { return DownloadOptions{}, fmt.Errorf("unknown opt %s", opt) } } return opts, nil } func codecsFromProbeInfo(pi ffmpeg.ProbeInfo) []string { var codecs []string if c := pi.AudioCodec(); c != "" { codecs = append(codecs, c) } if c := pi.VideoCodec(); c != "" { codecs = append(codecs, c) } return codecs } // Download downloads media from URL using context and makes sure output is in specified format func (ydls *YDLS) Download(ctx context.Context, options DownloadOptions, debugLog *log.Logger) (DownloadResult, error) { log := logOrDiscard(debugLog) log.Printf("URL: %s", options.URL) log.Printf("Output format: %s", options.Format) var ydlStdout io.Writer ydlStdout = writelogger.New(log, "ydl-new stdout> ") ydl, err := youtubedl.NewFromURL(ctx, options.URL, ydlStdout) if err != nil { log.Printf("Failed to download: %s", err) return DownloadResult{}, err } log.Printf("Title: %s", ydl.Title) log.Printf("Available youtubedl formats:") for _, f := range ydl.Formats { log.Printf(" %s", f) } if options.Format == "" { return ydls.downloadRaw(ctx, log, ydl) } return ydls.downloadFormat(ctx, log, options, ydl) } func (ydls *YDLS) downloadRaw(ctx context.Context, log *log.Logger, ydl youtubedl.Info) (DownloadResult, error) { dprc, err := downloadAndProbeFormat(ctx, ydl, "best", log) if err != nil { return DownloadResult{}, err } log.Printf("Probed format %s", dprc.probeInfo) dr := DownloadResult{ waitCh: make(chan struct{}), } // see if we know about the probed format, otherwise fallback to "raw" outFormat, outFormatName := ydls.Config.Formats.FindByFormatCodecs( dprc.probeInfo.FormatName(), codecsFromProbeInfo(dprc.probeInfo), ) if outFormatName != "" { dr.MIMEType = outFormat.MIMEType dr.Filename = safeFilename(ydl.Title + "." + outFormat.Ext) } else { dr.MIMEType = "application/octet-stream" dr.Filename = safeFilename(ydl.Title + ".raw") } var w io.WriteCloser dr.Media, w = io.Pipe() go func() { n, err := io.Copy(w, dprc) dprc.Close() w.Close() log.Printf("Copy done (n=%v err=%v)", n, err) close(dr.waitCh) }() return dr, nil } // TODO: messy, needs refactor func (ydls *YDLS) downloadFormat(ctx context.Context, log *log.Logger, options DownloadOptions, ydl youtubedl.Info) (DownloadResult, error) { type streamDownloadMap struct { stream Stream ydlFormat youtubedl.Format download *downloadProbeReadCloser } dr := DownloadResult{ waitCh: make(chan struct{}), } outFormat, outFormatFound := ydls.Config.Formats.FindByName(options.Format) if !outFormatFound { return DownloadResult{}, fmt.Errorf("could not find format %s", options.Format) } var closeOnDone []io.Closer closeOnDoneFn := func() { for _, c := range closeOnDone { c.Close() } } deferCloseFn := closeOnDoneFn defer func() { // will be nil if cmd starts and goroutine takes care of closing instead if deferCloseFn != nil { deferCloseFn() } }() dr.MIMEType = outFormat.MIMEType dr.Filename = safeFilename(ydl.Title + "." + outFormat.Ext) log.Printf("Best format for streams:") streamDownloads := []streamDownloadMap{} for _, s := range outFormat.Streams { preferredCodecs := s.CodecNames optionsCodecCommon := stringprioset.New(options.Codecs).Intersect(s.CodecNames) if !optionsCodecCommon.Empty() { preferredCodecs = optionsCodecCommon } if ydlFormat, ydlsFormatFound := findYDLFormat( ydl.Formats, s.Media, preferredCodecs, ); ydlsFormatFound { streamDownloads = append(streamDownloads, streamDownloadMap{ stream: s, ydlFormat: ydlFormat, }) log.Printf(" %s: %s", preferredCodecs, ydlFormat) } else { return DownloadResult{}, fmt.Errorf("no %s stream found", s.Media) } } uniqueFormatIDs := map[string]bool{} for _, sdm := range streamDownloads { uniqueFormatIDs[sdm.ydlFormat.FormatID] = true } type downloadProbeResult struct { err error download *downloadProbeReadCloser } downloads := map[string]downloadProbeResult{} var downloadsMutex sync.Mutex var downloadsWG sync.WaitGroup downloadsWG.Add(len(uniqueFormatIDs)) for formatID := range uniqueFormatIDs { go func(formatID string) { dprc, err := downloadAndProbeFormat(ctx, ydl, formatID, log) downloadsMutex.Lock() downloads[formatID] = downloadProbeResult{err: err, download: dprc} downloadsMutex.Unlock() downloadsWG.Done() }(formatID) } downloadsWG.Wait() for _, d := range downloads { closeOnDone = append(closeOnDone, d.download) } for formatID, d := range downloads { // TODO: more than one error? if d.err != nil { return DownloadResult{}, fmt.Errorf("failed to probe: %s: %s", formatID, d.err) } if d.download == nil { return DownloadResult{}, fmt.Errorf("failed to download: %s", formatID) } } for i, sdm := range streamDownloads { streamDownloads[i].download = downloads[sdm.ydlFormat.FormatID].download } log.Printf("Stream mapping:") var ffmpegMaps []ffmpeg.Map ffmpegFormatFlags := make([]string, len(outFormat.FormatFlags)) copy(ffmpegFormatFlags, outFormat.FormatFlags) for _, sdm := range streamDownloads { var ffmpegCodec ffmpeg.Codec var codec Codec codec = chooseCodec( sdm.stream.Codecs, options.Codecs, codecsFromProbeInfo(sdm.download.probeInfo), ) if sdm.stream.Media == MediaAudio { if !options.Retranscode && codec.Name == sdm.download.probeInfo.AudioCodec() { ffmpegCodec = ffmpeg.AudioCodec("copy") } else { ffmpegCodec = ffmpeg.AudioCodec(firstNonEmpty(ydls.Config.CodecMap[codec.Name], codec.Name)) } } else if sdm.stream.Media == MediaVideo { if !options.Retranscode && codec.Name == sdm.download.probeInfo.VideoCodec() { ffmpegCodec = ffmpeg.VideoCodec("copy") } else { ffmpegCodec = ffmpeg.VideoCodec(firstNonEmpty(ydls.Config.CodecMap[codec.Name], codec.Name)) } } else { return DownloadResult{}, fmt.Errorf("unknown media type %v", sdm.stream.Media) } ffmpegMaps = append(ffmpegMaps, ffmpeg.Map{ Input: ffmpeg.Reader{Reader: sdm.download}, Specifier: sdm.stream.Specifier, Codec: ffmpegCodec, CodecFlags: codec.Flags, }) ffmpegFormatFlags = append(ffmpegFormatFlags, codec.FormatFlags...) log.Printf(" %s ydl:%s probed:%s -> %s (%s)", sdm.stream.Specifier, sdm.ydlFormat, sdm.download.probeInfo, codec.Name, ydls.Config.CodecMap[codec.Name], ) } var ffmpegStderr io.Writer ffmpegStderr = writelogger.New(log, "ffmpeg stderr> ") ffmpegR, ffmpegW := io.Pipe() closeOnDone = append(closeOnDone, ffmpegR) var inputFlags []string var outputFlags []string inputFlags = append(inputFlags, ydls.Config.InputFlags...) if !options.TimeRange.IsZero() { if options.TimeRange.Start != 0 { inputFlags = append(inputFlags, "-ss", ffmpeg.DurationToPosition(options.TimeRange.Start)) } outputFlags = []string{"-to", ffmpeg.DurationToPosition(options.TimeRange.Duration())} } metadata := metadataFromYoutubeDLInfo(ydl) for _, sdm := range streamDownloads { metadata = metadata.Merge(sdm.download.probeInfo.Format.Tags) } firstOutFormat, _ := outFormat.Formats.First() ffmpegP := &ffmpeg.FFmpeg{ Streams: []ffmpeg.Stream{ ffmpeg.Stream{ InputFlags: inputFlags, OutputFlags: outputFlags, Maps: ffmpegMaps, Format: ffmpeg.Format{ Name: firstOutFormat, Flags: ffmpegFormatFlags, }, Metadata: metadata, Output: ffmpeg.Writer{Writer: ffmpegW}, }, }, DebugLog: log, Stderr: ffmpegStderr, } if err := ffmpegP.Start(ctx); err != nil { return DownloadResult{}, err } // goroutine will take care of closing deferCloseFn = nil var w io.WriteCloser dr.Media, w = io.Pipe() closeOnDone = append(closeOnDone, w) go func() { // TODO: ffmpeg mp3enc id3 writer does not work with streamed output // (id3v2 header length update requires seek) if outFormat.Prepend == "id3v2" { id3v2.Write(w, id3v2FramesFromMetadata(metadata, ydl)) } log.Printf("Starting to copy") n, err := io.Copy(w, ffmpegR) log.Printf("Copy ffmpeg done (n=%v err=%v)", n, err) closeOnDoneFn() ffmpegP.Wait() log.Printf("Done") close(dr.waitCh) }() return dr, nil }
package sdl // #include <SDL2/SDL_events.h> import "C" import "unsafe" import "reflect" import "fmt" const ( FIRSTEVENT = 0 QUIT = 0x100 APP_TERMINATING = 0x101 APP_LOWMEMORY = 0x102 APP_WILLENTERBACKGROUND = 0x103 APP_DIDENTERBACKGROUND = 0x104 APP_WILLENTERFOREGROUND = 0x105 APP_DIDENTERFOREGROUND = 0x106 /* Window events */ WINDOWEVENT = 0x200 SYSWMEVENT = 0x201 /* Keyboard events */ KEYDOWN = 0x300 KEYUP = 0x301 TEXTEDITING = 0x302 TEXTINPUT = 0x303 /* Mouse events */ MOUSEMOTION = 0x400 MOUSEBUTTONDOWN = 0x401 MOUSEBUTTONUP = 0x402 MOUSEWHEEL = 0x403 /* Joystick events */ JOYAXISMOTION = 0x600 JOYBALLMOTION = 0x601 JOYHATMOTION = 0x602 JOYBUTTONDOWN = 0x603 JOYBUTTONUP = 0x604 JOYDEVICEADDED = 0x605 JOYDEVICEREMOVED = 0x606 /* Game controller events */ CONTROLLERAXISMOTION = 0x650 CONTROLLERBUTTONDOWN = 0x651 CONTROLLERBUTTONUP = 0x652 CONTROLLERDEVICEADDED = 0x653 CONTROLLERDEVICEREMOVED = 0x654 CONTROLLERDEVICEREMAPPED = 0x655 /* Touch events */ FINGERDOWN = 0x700 FINGERUP = 0x701 FINGERMOTION = 0x702 /* Gesture events */ DOLLARGESTURE = 0x800 DOLLARRECORD = 0x801 MULTIGESTURE = 0x802 /* Clipboard events */ CLIPBOARDUPDATE = 0x900 /* Drag and drop events */ DROPFILE = 0x1000 USEREVENT = 0x8000 LASTEVENT = 0xFFFF ) const ( ADDEVENT = iota PEEKEVENT GETEVENT ) const ( QUERY = -1 IGNORE = 0 DISABLE = 0 ENABLE = 1 ) type Event interface {} type CEvent struct { Type uint32 padding1 [52]byte } type Scancode uint32 type CommonEvent struct { Type uint32 Timestamp uint32 } type WindowEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Event uint8 padding1 uint8 padding2 uint8 padding3 uint8 Data1 int32 Data2 int32 } type KeyDownEvent struct { Type uint32 Timestamp uint32 WindowID uint32 State uint8 Repeat uint8 padding1 uint8 padding2 uint8 Keysym Keysym } type KeyUpEvent struct { Type uint32 Timestamp uint32 WindowID uint32 State uint8 Repeat uint8 padding1 uint8 padding2 uint8 Keysym Keysym } type TextEditingEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte; Start int32 Length int32 } type TextInputEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte; } type MouseMotionEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 State uint32 X int32 Y int32 XRel int32 YRel int32 } type MouseButtonEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 Button uint8 State uint8 padding1 uint8 padding2 uint8 X int32 Y int32 } type MouseWheelEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 X int32 Y int32 } type JoyAxisEvent struct { Type uint32 Timestamp uint32 Which JoystickID Axis uint8 padding1 uint8 padding2 uint8 padding3 uint8 Value int16 padding4 uint16 } type JoyBallEvent struct { Type uint32 Timestamp uint32 Which JoystickID Ball uint8 padding1 uint8 padding2 uint8 padding3 uint8 XRel int16 YRel int16 } type JoyHatEvent struct { Type uint32 Timestamp uint32 Which JoystickID Hat uint8 Value uint8 padding1 uint8 padding2 uint8 } type JoyButtonEvent struct { Type uint32 Timestamp uint32 Which JoystickID Button uint8 State uint8 padding1 uint8 padding2 uint8 } type JoyDeviceEvent struct { Type uint32 Timestamp uint32 Which JoystickID } type ControllerAxisEvent struct { Type uint32 Timestamp uint32 Which JoystickID Axis uint8 padding1 uint8 padding2 uint8 padding3 uint8 Value int16 padding4 uint16 } type ControllerButtonEvent struct { Type uint32 Timestamp uint32 Which JoystickID Button uint8 State uint8 padding1 uint8 padding2 uint8 } type ControllerDeviceEvent struct { Type uint32 Timestamp uint32 Which JoystickID } type TouchFingerEvent struct { Type uint32 Timestamp uint32 TouchID TouchID FingerID FingerID X float32 Y float32 DX float32 DY float32 Pressure float32 } type MultiGestureEvent struct { Type uint32 Timestamp uint32 TouchId TouchID DTheta float32 DDist float32 X float32 Y float32 NumFingers uint16 padding uint16 } type DollarGestureEvent struct { Type uint32 Timestamp uint32 TouchID TouchID GestureID GestureID NumFingers uint32 Error float32 X float32 Y float32 } type DropEvent struct { Type uint32 Timestamp uint32 file unsafe.Pointer } type QuitEvent struct { Type uint32 Timestamp uint32 } type OSEvent struct { Type uint32 Timestamp uint32 } type ClipboardEvent struct { Type uint32 Timestamp uint32 } type UserEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Code int32 Data1 unsafe.Pointer Data2 unsafe.Pointer } type SysWMEvent struct { Type uint32 Timestamp uint32 msg unsafe.Pointer } type EventFilter C.SDL_EventFilter func PumpEvents() { C.SDL_PumpEvents() } func PeepEvents(events []Event, numevents int, action, minType, maxType uint32) int { _events := (*C.SDL_Event) (unsafe.Pointer(cEvent(&events[0]))) _numevents := (C.int) (numevents) _action := (C.SDL_eventaction) (action) _mintype := (C.Uint32) (minType) _maxtype := (C.Uint32) (maxType) return (int) (C.SDL_PeepEvents(_events, _numevents, _action, _mintype, _maxtype)) } func HasEvent(type_ uint32) bool { _type := (C.Uint32) (type_) return C.SDL_HasEvent(_type) != 0 } func HasEvents(minType, maxType uint32) bool { _minType := (C.Uint32) (minType) _maxType := (C.Uint32) (maxType) return C.SDL_HasEvents(_minType, _maxType) != 0 } func FlushEvent(type_ uint32) { _type := (C.Uint32) (type_) C.SDL_FlushEvent(_type) } func FlushEvents(minType, maxType uint32) { _minType := (C.Uint32) (minType) _maxType := (C.Uint32) (maxType) C.SDL_FlushEvents(_minType, _maxType) } func PollEvent() Event { var cevent C.SDL_Event ret := C.SDL_PollEvent(&cevent) if ret == 0 { return nil } return goEvent((*CEvent)(unsafe.Pointer(&cevent))) } func goEvent(cevent *CEvent) Event { switch cevent.Type { case WINDOWEVENT: return (*WindowEvent) (unsafe.Pointer(cevent)) case SYSWMEVENT: return (*SysWMEvent) (unsafe.Pointer(cevent)) case KEYDOWN: return (*KeyDownEvent) (unsafe.Pointer(cevent)) case KEYUP: return (*KeyUpEvent) (unsafe.Pointer(cevent)) case TEXTEDITING: return (*TextEditingEvent) (unsafe.Pointer(cevent)) case TEXTINPUT: return (*TextInputEvent) (unsafe.Pointer(cevent)) case MOUSEMOTION: return (*MouseMotionEvent) (unsafe.Pointer(cevent)) case MOUSEBUTTONDOWN, MOUSEBUTTONUP: return (*MouseButtonEvent) (unsafe.Pointer(cevent)) case MOUSEWHEEL: return (*MouseWheelEvent) (unsafe.Pointer(cevent)) case JOYAXISMOTION: return (*JoyAxisEvent) (unsafe.Pointer(cevent)) case JOYBALLMOTION: return (*JoyBallEvent) (unsafe.Pointer(cevent)) case JOYHATMOTION: return (*JoyHatEvent) (unsafe.Pointer(cevent)) case JOYBUTTONDOWN, JOYBUTTONUP: return (*JoyButtonEvent) (unsafe.Pointer(cevent)) case JOYDEVICEADDED, JOYDEVICEREMOVED: return (*JoyDeviceEvent) (unsafe.Pointer(cevent)) case CONTROLLERAXISMOTION: return (*ControllerAxisEvent) (unsafe.Pointer(cevent)) case CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP: return (*ControllerButtonEvent) (unsafe.Pointer(cevent)) case CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, CONTROLLERDEVICEREMAPPED: return (*ControllerDeviceEvent) (unsafe.Pointer(cevent)) case FINGERDOWN, FINGERUP, FINGERMOTION: return (*TouchFingerEvent) (unsafe.Pointer(cevent)) case DOLLARGESTURE, DOLLARRECORD: return (*DollarGestureEvent) (unsafe.Pointer(cevent)) case MULTIGESTURE: return (*MultiGestureEvent) (unsafe.Pointer(cevent)) case DROPFILE: return (*DropEvent) (unsafe.Pointer(cevent)) case QUIT: return (*QuitEvent) (unsafe.Pointer(cevent)) case USEREVENT: return (*UserEvent) (unsafe.Pointer(cevent)) case CLIPBOARDUPDATE: return (*ClipboardEvent) (unsafe.Pointer(cevent)) } panic(fmt.Errorf("Unknown event type: %v", cevent.Type)) } func cEvent(event Event) *CEvent { evv := reflect.ValueOf(event) return (*CEvent) (unsafe.Pointer(evv.UnsafeAddr())) } func WaitEventTimeout(event *Event, timeout int) bool { var cevent CEvent _event := (*C.SDL_Event) (unsafe.Pointer(&cevent)) _timeout := (C.int) (timeout) ok := (int) (C.SDL_WaitEventTimeout(_event, _timeout)) if ok == 0 { return false } *event = goEvent(&cevent) return true } func WaitEvent(event *Event) bool { var cevent CEvent _event := (*C.SDL_Event) (unsafe.Pointer(&cevent)) ok := (int) (C.SDL_WaitEvent(_event)) if ok == 0 { return false } *event = goEvent(&cevent) return true } func PushEvent(event *Event) int { _event := (*C.SDL_Event) (unsafe.Pointer(cEvent(event))) return (int) (C.SDL_PushEvent(_event)) } /* TODO: implement SDL_EventFilter functions */ func EventState(type_ uint32, state int) uint8 { _type := (C.Uint32) (type_) _state := (C.int) (state) return (uint8) (C.SDL_EventState(_type, _state)) } func GetEventState(type_ uint32) uint8 { _type := (C.Uint32) (type_) return (uint8) (C.SDL_EventState(_type, QUERY)) } func RegisterEvents(numevents int) uint32 { _numevents := (C.int) (numevents) return (uint32) (C.SDL_RegisterEvents(_numevents)) } Changed *Event to Event for PushEvent() Signed-off-by: Jacky Boen <d2266ffb9ea7feef4bb8def6871fc3b7343ab3ab@gmail.com> package sdl // #include <SDL2/SDL_events.h> import "C" import "unsafe" import "reflect" import "fmt" const ( FIRSTEVENT = 0 QUIT = 0x100 APP_TERMINATING = 0x101 APP_LOWMEMORY = 0x102 APP_WILLENTERBACKGROUND = 0x103 APP_DIDENTERBACKGROUND = 0x104 APP_WILLENTERFOREGROUND = 0x105 APP_DIDENTERFOREGROUND = 0x106 /* Window events */ WINDOWEVENT = 0x200 SYSWMEVENT = 0x201 /* Keyboard events */ KEYDOWN = 0x300 KEYUP = 0x301 TEXTEDITING = 0x302 TEXTINPUT = 0x303 /* Mouse events */ MOUSEMOTION = 0x400 MOUSEBUTTONDOWN = 0x401 MOUSEBUTTONUP = 0x402 MOUSEWHEEL = 0x403 /* Joystick events */ JOYAXISMOTION = 0x600 JOYBALLMOTION = 0x601 JOYHATMOTION = 0x602 JOYBUTTONDOWN = 0x603 JOYBUTTONUP = 0x604 JOYDEVICEADDED = 0x605 JOYDEVICEREMOVED = 0x606 /* Game controller events */ CONTROLLERAXISMOTION = 0x650 CONTROLLERBUTTONDOWN = 0x651 CONTROLLERBUTTONUP = 0x652 CONTROLLERDEVICEADDED = 0x653 CONTROLLERDEVICEREMOVED = 0x654 CONTROLLERDEVICEREMAPPED = 0x655 /* Touch events */ FINGERDOWN = 0x700 FINGERUP = 0x701 FINGERMOTION = 0x702 /* Gesture events */ DOLLARGESTURE = 0x800 DOLLARRECORD = 0x801 MULTIGESTURE = 0x802 /* Clipboard events */ CLIPBOARDUPDATE = 0x900 /* Drag and drop events */ DROPFILE = 0x1000 USEREVENT = 0x8000 LASTEVENT = 0xFFFF ) const ( ADDEVENT = iota PEEKEVENT GETEVENT ) const ( QUERY = -1 IGNORE = 0 DISABLE = 0 ENABLE = 1 ) type Event interface {} type CEvent struct { Type uint32 padding1 [52]byte } type Scancode uint32 type CommonEvent struct { Type uint32 Timestamp uint32 } type WindowEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Event uint8 padding1 uint8 padding2 uint8 padding3 uint8 Data1 int32 Data2 int32 } type KeyDownEvent struct { Type uint32 Timestamp uint32 WindowID uint32 State uint8 Repeat uint8 padding1 uint8 padding2 uint8 Keysym Keysym } type KeyUpEvent struct { Type uint32 Timestamp uint32 WindowID uint32 State uint8 Repeat uint8 padding1 uint8 padding2 uint8 Keysym Keysym } type TextEditingEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte; Start int32 Length int32 } type TextInputEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Text [C.SDL_TEXTINPUTEVENT_TEXT_SIZE]byte; } type MouseMotionEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 State uint32 X int32 Y int32 XRel int32 YRel int32 } type MouseButtonEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 Button uint8 State uint8 padding1 uint8 padding2 uint8 X int32 Y int32 } type MouseWheelEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Which uint32 X int32 Y int32 } type JoyAxisEvent struct { Type uint32 Timestamp uint32 Which JoystickID Axis uint8 padding1 uint8 padding2 uint8 padding3 uint8 Value int16 padding4 uint16 } type JoyBallEvent struct { Type uint32 Timestamp uint32 Which JoystickID Ball uint8 padding1 uint8 padding2 uint8 padding3 uint8 XRel int16 YRel int16 } type JoyHatEvent struct { Type uint32 Timestamp uint32 Which JoystickID Hat uint8 Value uint8 padding1 uint8 padding2 uint8 } type JoyButtonEvent struct { Type uint32 Timestamp uint32 Which JoystickID Button uint8 State uint8 padding1 uint8 padding2 uint8 } type JoyDeviceEvent struct { Type uint32 Timestamp uint32 Which JoystickID } type ControllerAxisEvent struct { Type uint32 Timestamp uint32 Which JoystickID Axis uint8 padding1 uint8 padding2 uint8 padding3 uint8 Value int16 padding4 uint16 } type ControllerButtonEvent struct { Type uint32 Timestamp uint32 Which JoystickID Button uint8 State uint8 padding1 uint8 padding2 uint8 } type ControllerDeviceEvent struct { Type uint32 Timestamp uint32 Which JoystickID } type TouchFingerEvent struct { Type uint32 Timestamp uint32 TouchID TouchID FingerID FingerID X float32 Y float32 DX float32 DY float32 Pressure float32 } type MultiGestureEvent struct { Type uint32 Timestamp uint32 TouchId TouchID DTheta float32 DDist float32 X float32 Y float32 NumFingers uint16 padding uint16 } type DollarGestureEvent struct { Type uint32 Timestamp uint32 TouchID TouchID GestureID GestureID NumFingers uint32 Error float32 X float32 Y float32 } type DropEvent struct { Type uint32 Timestamp uint32 file unsafe.Pointer } type QuitEvent struct { Type uint32 Timestamp uint32 } type OSEvent struct { Type uint32 Timestamp uint32 } type ClipboardEvent struct { Type uint32 Timestamp uint32 } type UserEvent struct { Type uint32 Timestamp uint32 WindowID uint32 Code int32 Data1 unsafe.Pointer Data2 unsafe.Pointer } type SysWMEvent struct { Type uint32 Timestamp uint32 msg unsafe.Pointer } type EventFilter C.SDL_EventFilter func PumpEvents() { C.SDL_PumpEvents() } func PeepEvents(events []Event, numevents int, action, minType, maxType uint32) int { _events := (*C.SDL_Event) (unsafe.Pointer(cEvent(&events[0]))) _numevents := (C.int) (numevents) _action := (C.SDL_eventaction) (action) _mintype := (C.Uint32) (minType) _maxtype := (C.Uint32) (maxType) return (int) (C.SDL_PeepEvents(_events, _numevents, _action, _mintype, _maxtype)) } func HasEvent(type_ uint32) bool { _type := (C.Uint32) (type_) return C.SDL_HasEvent(_type) != 0 } func HasEvents(minType, maxType uint32) bool { _minType := (C.Uint32) (minType) _maxType := (C.Uint32) (maxType) return C.SDL_HasEvents(_minType, _maxType) != 0 } func FlushEvent(type_ uint32) { _type := (C.Uint32) (type_) C.SDL_FlushEvent(_type) } func FlushEvents(minType, maxType uint32) { _minType := (C.Uint32) (minType) _maxType := (C.Uint32) (maxType) C.SDL_FlushEvents(_minType, _maxType) } func PollEvent() Event { var cevent C.SDL_Event ret := C.SDL_PollEvent(&cevent) if ret == 0 { return nil } return goEvent((*CEvent)(unsafe.Pointer(&cevent))) } func goEvent(cevent *CEvent) Event { switch cevent.Type { case WINDOWEVENT: return (*WindowEvent) (unsafe.Pointer(cevent)) case SYSWMEVENT: return (*SysWMEvent) (unsafe.Pointer(cevent)) case KEYDOWN: return (*KeyDownEvent) (unsafe.Pointer(cevent)) case KEYUP: return (*KeyUpEvent) (unsafe.Pointer(cevent)) case TEXTEDITING: return (*TextEditingEvent) (unsafe.Pointer(cevent)) case TEXTINPUT: return (*TextInputEvent) (unsafe.Pointer(cevent)) case MOUSEMOTION: return (*MouseMotionEvent) (unsafe.Pointer(cevent)) case MOUSEBUTTONDOWN, MOUSEBUTTONUP: return (*MouseButtonEvent) (unsafe.Pointer(cevent)) case MOUSEWHEEL: return (*MouseWheelEvent) (unsafe.Pointer(cevent)) case JOYAXISMOTION: return (*JoyAxisEvent) (unsafe.Pointer(cevent)) case JOYBALLMOTION: return (*JoyBallEvent) (unsafe.Pointer(cevent)) case JOYHATMOTION: return (*JoyHatEvent) (unsafe.Pointer(cevent)) case JOYBUTTONDOWN, JOYBUTTONUP: return (*JoyButtonEvent) (unsafe.Pointer(cevent)) case JOYDEVICEADDED, JOYDEVICEREMOVED: return (*JoyDeviceEvent) (unsafe.Pointer(cevent)) case CONTROLLERAXISMOTION: return (*ControllerAxisEvent) (unsafe.Pointer(cevent)) case CONTROLLERBUTTONDOWN, CONTROLLERBUTTONUP: return (*ControllerButtonEvent) (unsafe.Pointer(cevent)) case CONTROLLERDEVICEADDED, CONTROLLERDEVICEREMOVED, CONTROLLERDEVICEREMAPPED: return (*ControllerDeviceEvent) (unsafe.Pointer(cevent)) case FINGERDOWN, FINGERUP, FINGERMOTION: return (*TouchFingerEvent) (unsafe.Pointer(cevent)) case DOLLARGESTURE, DOLLARRECORD: return (*DollarGestureEvent) (unsafe.Pointer(cevent)) case MULTIGESTURE: return (*MultiGestureEvent) (unsafe.Pointer(cevent)) case DROPFILE: return (*DropEvent) (unsafe.Pointer(cevent)) case QUIT: return (*QuitEvent) (unsafe.Pointer(cevent)) case USEREVENT: return (*UserEvent) (unsafe.Pointer(cevent)) case CLIPBOARDUPDATE: return (*ClipboardEvent) (unsafe.Pointer(cevent)) } panic(fmt.Errorf("Unknown event type: %v", cevent.Type)) } func cEvent(event Event) *CEvent { evv := reflect.ValueOf(event) return (*CEvent) (unsafe.Pointer(evv.UnsafeAddr())) } func WaitEventTimeout(event *Event, timeout int) bool { var cevent CEvent _event := (*C.SDL_Event) (unsafe.Pointer(&cevent)) _timeout := (C.int) (timeout) ok := (int) (C.SDL_WaitEventTimeout(_event, _timeout)) if ok == 0 { return false } *event = goEvent(&cevent) return true } func WaitEvent(event *Event) bool { var cevent CEvent _event := (*C.SDL_Event) (unsafe.Pointer(&cevent)) ok := (int) (C.SDL_WaitEvent(_event)) if ok == 0 { return false } *event = goEvent(&cevent) return true } func PushEvent(event Event) int { _event := (*C.SDL_Event) (unsafe.Pointer(cEvent(&event))) return (int) (C.SDL_PushEvent(_event)) } /* TODO: implement SDL_EventFilter functions */ func EventState(type_ uint32, state int) uint8 { _type := (C.Uint32) (type_) _state := (C.int) (state) return (uint8) (C.SDL_EventState(_type, _state)) } func GetEventState(type_ uint32) uint8 { _type := (C.Uint32) (type_) return (uint8) (C.SDL_EventState(_type, QUERY)) } func RegisterEvents(numevents int) uint32 { _numevents := (C.int) (numevents) return (uint32) (C.SDL_RegisterEvents(_numevents)) }
/* cli is a simple package to allow a game to render to the screen and be interacted with. It's intended primarily as a tool to diagnose and play around with a game while its moves and logic are being defined. */ package cli import ( "github.com/jkomoros/boardgame" "github.com/nsf/termbox-go" "strings" ) //Controller is the primary type of the package. type Controller struct { game *boardgame.Game mode inputMode renderer RendererFunc //Whether or not we should render JSON (false) or the RendererFunc (true) render bool } //RenderrerFunc takes a state and outputs a list of strings that should be //printed to screen to depict it. type RendererFunc func(boardgame.StatePayload) []string func NewController(game *boardgame.Game, renderer RendererFunc) *Controller { return &Controller{ game: game, mode: modeDefault, renderer: renderer, } } //Once the controller is set up, call Start. It will block until it is time //to exit. func (c *Controller) Start() { termbox.Init() defer termbox.Close() c.draw() for { evt := termbox.PollEvent() if c.mode.handleInput(c, evt) { return } c.draw() } } //draw draws the entire app to the screen func (c *Controller) draw() { clearScreen() if c.render { c.drawRender() } else { c.drawJSON() } c.drawStatusLine() termbox.Flush() } func (c *Controller) ToggleRender() { c.render = !c.render } func (c *Controller) statusLine() string { return c.mode.statusLine() } func clearScreen() { width, height := termbox.Size() for x := 0; x < width; x++ { for y := 0; y < height; y++ { termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault) } } } //TODO: these should be global funcs that take a cont func (c *Controller) drawStatusLine() { line := c.statusLine() width, height := termbox.Size() //Render white background y := height - 1 for x := 0; x < width; x++ { termbox.SetCell(x, y, ' ', termbox.ColorBlack, termbox.ColorWhite) } x := 0 underlined := false var fg termbox.Attribute for _, ch := range ">>> " + line { if ch == '{' { underlined = true continue } else if ch == '}' { underlined = false continue } fg = termbox.ColorBlack if underlined { fg = fg | termbox.AttrUnderline | termbox.AttrBold } termbox.SetCell(x, y, ch, fg, termbox.ColorWhite) x++ } } func (c *Controller) drawRender() { x := 0 y := 0 for _, line := range c.renderer(c.game.State.Payload) { x = 0 for _, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorWhite, termbox.ColorBlack) x++ } y++ } } //Draws the JSON output of the current state to the screen func (c *Controller) drawJSON() { x := 0 y := 0 json := string(boardgame.Serialize(c.game.State.JSON())) for _, line := range strings.Split(json, "\n") { x = 0 for _, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorWhite, termbox.ColorBlack) x++ } y++ } } A very basic version hacked up to use gocui. Can't figure out why, but key bindings don't appear to be running, so you have to force quit it. /* cli is a simple package to allow a game to render to the screen and be interacted with. It's intended primarily as a tool to diagnose and play around with a game while its moves and logic are being defined. */ package cli import ( "fmt" "github.com/jkomoros/boardgame" "github.com/jroimartin/gocui" ) //Controller is the primary type of the package. type Controller struct { game *boardgame.Game gui *gocui.Gui mode inputMode renderer RendererFunc //Whether or not we should render JSON (false) or the RendererFunc (true) render bool } //RenderrerFunc takes a state and outputs a list of strings that should be //printed to screen to depict it. type RendererFunc func(boardgame.StatePayload) []string func NewController(game *boardgame.Game, renderer RendererFunc) *Controller { return &Controller{ game: game, mode: modeDefault, renderer: renderer, } } func layout(g *gocui.Gui) error { maxX, maxY := g.Size() if v, err := g.SetView("main", 0, 0, maxX/2-1, maxY/2-1); err != nil { if err != gocui.ErrUnknownView { return err } v.Title = "Hey!" v.Frame = true fmt.Fprintln(v, "Hello, world!") } return nil } func quit(g *gocui.Gui, v *gocui.View) error { panic("quit called") return gocui.ErrQuit } //Once the controller is set up, call Start. It will block until it is time //to exit. func (c *Controller) Start() { g, err := gocui.NewGui(gocui.OutputNormal) if err != nil { panic("Couldn't create gui:" + err.Error()) } defer g.Close() c.gui = g //TODO: key bindings don't appear to be running... if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil { panic(err) } g.SetManagerFunc(layout) if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { panic(err) } } func (c *Controller) ToggleRender() { c.render = !c.render } /* //draw draws the entire app to the screen func (c *Controller) draw() { clearScreen() if c.render { c.drawRender() } else { c.drawJSON() } c.drawStatusLine() termbox.Flush() } func (c *Controller) statusLine() string { return c.mode.statusLine() } func clearScreen() { width, height := termbox.Size() for x := 0; x < width; x++ { for y := 0; y < height; y++ { termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault) } } } //TODO: these should be global funcs that take a cont func (c *Controller) drawStatusLine() { line := c.statusLine() width, height := termbox.Size() //Render white background y := height - 1 for x := 0; x < width; x++ { termbox.SetCell(x, y, ' ', termbox.ColorBlack, termbox.ColorWhite) } x := 0 underlined := false var fg termbox.Attribute for _, ch := range ">>> " + line { if ch == '{' { underlined = true continue } else if ch == '}' { underlined = false continue } fg = termbox.ColorBlack if underlined { fg = fg | termbox.AttrUnderline | termbox.AttrBold } termbox.SetCell(x, y, ch, fg, termbox.ColorWhite) x++ } } func (c *Controller) drawRender() { x := 0 y := 0 for _, line := range c.renderer(c.game.State.Payload) { x = 0 for _, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorWhite, termbox.ColorBlack) x++ } y++ } } //Draws the JSON output of the current state to the screen func (c *Controller) drawJSON() { x := 0 y := 0 json := string(boardgame.Serialize(c.game.State.JSON())) for _, line := range strings.Split(json, "\n") { x = 0 for _, ch := range line { termbox.SetCell(x, y, ch, termbox.ColorWhite, termbox.ColorBlack) x++ } y++ } } */
// Copyright (c) 2017 Qian Qiao // // 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 cli import ( "bytes" "context" "fmt" "os" "strings" "testing" ) const usageLine = `test [-i] input` func TestName(t *testing.T) { c := Component{ UsageLine: "test [-i] input", } if "test" != c.Name() { t.Errorf("Expected '%s', got '%s'", "test", c.Name()) } } func TestSetUsageOutput(t *testing.T) { c := Component{} if os.Stderr != c.out() { t.Error("Expected os.Stderr to be the output") } var output bytes.Buffer c.SetUsageOutput(&output) if &output != c.out() { t.Error("SetUsageOutput failed") } } func TestRunnable(t *testing.T) { r := Component{ Run: func(context.Context, *Component, []string) {}, } if !r.Runnable() { t.Errorf("Expected '%t', got '%t'", true, r.Runnable()) } nr := Component{} if nr.Runnable() { t.Errorf("Expected '%t', got '%t'", false, nr.Runnable()) } } func TestUsageFlags(t *testing.T) { var buf bytes.Buffer c := Component{} c.SetUsageOutput(&buf) c.Flag.String("i", "", "input of the test component") } func TestUsageRunnable(t *testing.T) { expectedUsageLine := fmt.Sprintf("Usage: %s", usageLine) var buf bytes.Buffer c := Component{ UsageLine: usageLine, Long: "This is the long description of the test component.", } c.SetUsageOutput(&buf) c.Usage() usage := buf.String() if strings.HasPrefix(usage, expectedUsageLine) { t.Error("Non-runnable component shouldn't have a usage line") } buf.Reset() c.Run = func(context.Context, *Component, []string) {} c.Usage() usage = buf.String() if !strings.HasPrefix(usage, expectedUsageLine) { t.Error("Usage line missing") } } func TestUsageSubComponent(t *testing.T) { // TODO: implement sub component handling test } Completed the TestUsageFlag function. // Copyright (c) 2017 Qian Qiao // // 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 cli import ( "bytes" "context" "fmt" "os" "strings" "testing" ) const usageLine = `test [-i input]` func TestName(t *testing.T) { c := Component{ UsageLine: usageLine, } if "test" != c.Name() { t.Errorf("Expected '%s', got '%s'", "test", c.Name()) } } func TestSetUsageOutput(t *testing.T) { c := Component{} if os.Stderr != c.out() { t.Error("Expected os.Stderr to be the output") } var output bytes.Buffer c.SetUsageOutput(&output) if &output != c.out() { t.Error("SetUsageOutput failed") } } func TestRunnable(t *testing.T) { r := Component{ Run: func(context.Context, *Component, []string) {}, } if !r.Runnable() { t.Errorf("Expected '%t', got '%t'", true, r.Runnable()) } nr := Component{} if nr.Runnable() { t.Errorf("Expected '%t', got '%t'", false, nr.Runnable()) } } func TestUsageFlags(t *testing.T) { var buf bytes.Buffer c := Component{ UsageLine: usageLine, Run: func(context.Context, *Component, []string) {}, } c.SetUsageOutput(&buf) c.Flag.String("i", "", "input of the test component") c.Usage() expected := `Usage: test [-i input] -i string input of the test component ` if buf.String() != expected { t.Errorf("Expected '%s'. got '%s'", expected, buf.String()) } } func TestUsageRunnable(t *testing.T) { expectedUsageLine := fmt.Sprintf("Usage: %s", usageLine) var buf bytes.Buffer c := Component{ UsageLine: usageLine, Long: "This is the long description of the test component.", } c.SetUsageOutput(&buf) c.Usage() usage := buf.String() if strings.HasPrefix(usage, expectedUsageLine) { t.Error("Non-runnable component shouldn't have a usage line") } buf.Reset() c.Run = func(context.Context, *Component, []string) {} c.Usage() usage = buf.String() if !strings.HasPrefix(usage, expectedUsageLine) { t.Error("Usage line missing") } } func TestUsageSubComponent(t *testing.T) { // TODO: implement sub component handling test }
/* * Clifford.go, part of gochem. * * * Copyright 2012 Janne Pesonen <janne.pesonen{at}helsinkiDOTfi> * and Raul Mera <rmera{at}chemDOThelsinkiDOTfi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * * * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, * University of Helsinki, Finland. * * */ /***RM: Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ package chem import "math" //import "fmt" type paravector struct { Real float64 Imag float64 Vreal *VecMatrix Vimag *VecMatrix } //creates a new paravector func makeParavector() *paravector { R := new(paravector) R.Real = 0 //I shouldnt need this R.Imag = 0 R.Vreal = ZeroVecs(1) R.Vimag = ZeroVecs(1) return R } //Takes a vector and creates a paravector. Uses copy so the vector is not affected //By future changes to the paravector. func paravectorFromVector(A,B *VecMatrix) *paravector { R := new(paravector) R.Real = 0 //I shouldnt need this R.Imag = 0 R.Vreal = A R.Vimag = B return R } //Puts a copy fo the paravector P in the receiver func (R *paravector) Copy(P *paravector) { R.Real = P.Real R.Imag = P.Imag R.Vreal.Copy(P.Vreal) R.Vimag.Copy(P.Vimag) } //Puts the reverse of paravector P in the received func (R *paravector) reverse(P *paravector) { if P!=R{ R.Copy(P) } R.Vimag.Scale(-1, R.Vimag) } //Puts the normalized version of P in the receiver. If R and P are the same, func (R *paravector) unit (P *paravector) { norm := 0.0 norm += math.Pow(P.Real, 2) + math.Pow(P.Imag, 2) for i := 0; i < 3; i++ { norm += math.Pow(P.Vreal.At(0, i), 2) + math.Pow(P.Vimag.At(0, i), 2) } //fmt.Println("norm", norm) R.Real = P.Real / math.Sqrt(norm) R.Imag = P.Imag / math.Sqrt(norm) for i := 0; i < 3; i++ { R.Vreal.Set(0, i, P.Vreal.At(0, i)/math.Sqrt(norm)) R.Vimag.Set(0, i, P.Vimag.At(0, i)/math.Sqrt(norm)) } //fmt.Println("normalized", R) } //Clifford product of 2 paravectors, the imaginary parts are simply set to zero, since this is the case //when rotating 3D real vectors. The proper Cliffor product is in fullCliProduct func (R *paravector) cliProduct(A, B *paravector) { R.Real = A.Real*B.Real - A.Imag*B.Imag for i := 0; i < 3; i++ { R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) } R.Imag = A.Real*B.Imag + A.Imag*B.Real for i := 0; i < 3; i++ { R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) } //Now the vector part //First real R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) //Second real R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) //Third real R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) /* //First imag R.Vimag.Set(0,0,A.Real*B.Vimag.At(0,0) + B.Real*A.Vimag.At(0,0) + A.Imag*B.Vreal.At(0,0) - B.Imag*A.Vreal.At(0,0) + A.Vreal.At(0,1)*B.Vreal.At(0,2) - A.Vreal.At(0,2)*B.Vreal.At(0,1) + A.Vimag.At(0,2)*B.Vimag.At(0,1) - A.Vimag.At(0,1)*B.Vimag.At(0,2)) //Second imag R.Vimag.Set(0,1,A.Real*B.Vimag.At(0,1) + B.Real*A.Vimag.At(0,1) + A.Imag*B.Vreal.At(0,1) - B.Imag*A.Vreal.At(0,1) + A.Vreal.At(0,2)*B.Vreal.At(0,0) - A.Vreal.At(0,0)*B.Vreal.At(0,2) + A.Vimag.At(0,0)*B.Vimag.At(0,2) - A.Vimag.At(0,2)*B.Vimag.At(0,0)) //Third imag R.Vimag.Set(0,2,A.Real*B.Vimag.At(0,2) + B.Real*A.Vimag.At(0,2) + A.Imag*B.Vreal.At(0,2) - B.Imag*A.Vreal.At(0,2) + A.Vreal.At(0,0)*B.Vreal.At(0,1) - A.Vreal.At(0,1)*B.Vreal.At(0,0) + A.Vimag.At(0,1)*B.Vimag.At(0,0) - A.Vimag.At(0,0)*B.Vimag.At(0,1)) */ //fmt.Println("R slido del horno", R) // A.Real, B.Vimag.At(0,0), "g2", B.Real,A.Vimag.At(0,0),"g3", A.Imag, B.Vreal.At(0,0),"g4" ,B.Imag,A.Vreal.At(0,0), //"g5", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* //A.Vimag.At(0,1)*B.Vimag.At(0,2)) // return R } //cliRotation uses Clifford algebra to rotate a paravector Aby angle radians around axis. Returns the rotated //paravector. axis must be normalized. func (R *paravector) cliRotation(A, axis, tmp, tmp2 *paravector, angle float64) { // R := makeParavector() R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*axis.Vreal.At(0, i)) } R.reverse(R) // tmp:=makeParavector() // tmp2:=makeParavector() tmp.cliProduct(R, A) tmp2.cliProduct(tmp, R) R.Copy(tmp2) } //RotateSer takes the matrix Target and uses Clifford algebra to rotate each of its rows //by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. //The Ser in the name is from "serial". ToRot will be overwritten and returned func RotateSer(Target,ToRot, axis *VecMatrix, angle float64) *VecMatrix { cake:=ZeroVecs(10) //Better ask for one chunk of memory than allocate 10 different times. R:=cake.VecView(0) Rrev:=cake.VecView(1) tmp:=cake.VecView(2) Rotated:=cake.VecView(3) itmp1:=cake.VecView(4) itmp2:=cake.VecView(5) itmp3:=cake.VecView(6) itmp4:=cake.VecView(7) itmp5:=cake.VecView(8) itmp6:=cake.VecView(9) RotateSerP(Target,ToRot,axis,tmp,R,Rrev,Rotated,itmp1,itmp2,itmp3,itmp4,itmp5,itmp6,angle) return ToRot } //RotateSerP takes the matrix Target and uses Clifford algebra to rotate each of its rows //by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. //The Ser in the name is from "serial". ToRot will be overwritten and returned. RotateSerP only allocates some floats but not //any VecMatrix. Instead, it takes the needed intermediates as arguments, hence the "P" for "performance" If performance is not an issue, //use RotateSer instead, it will perform the allocations for you and call this function. Notice that if you use this function directly //you may have to zero at least some of the intermediates before reusing them. func RotateSerP(Target,ToRot, axis,tmpv,Rv,Rvrev,Rotatedv, itmp1,itmp2,itmp3,itmp4,itmp5,itmp6 *VecMatrix, angle float64) { tarr, _ := Target.Dims() torotr := ToRot.NVecs() if tarr != torotr || Target.Dense == ToRot.Dense { panic("RotateSerP: Target and Res must have the same dimensions. Target and Res cannot reference the same matrix") } //Make the paravectors from the passed vectors: tmp:=paravectorFromVector(tmpv,itmp3) R:=paravectorFromVector(Rv,itmp4) Rrev:=paravectorFromVector(Rvrev,itmp5) Rotated:=paravectorFromVector(Rotatedv,itmp6) //That is with the building of temporary paravectors. paxis := paravectorFromVector(axis,itmp1) paxis.unit(paxis) R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) } Rrev.reverse(R) for i := 0; i < tarr; i++ { rowvec := Target.VecView(i) tmp.cliProduct(Rrev, paravectorFromVector(rowvec,itmp2)) Rotated.cliProduct(tmp, R) ToRot.SetMatrix(i, 0, Rotated.Vreal) } } //Rotate takes the matrix Target and uses Clifford algebra to _concurrently_ rotate each //of its rows by angle radians around axis. Axis must be a 3D row vector. //Target must be an N,3 matrix. func Rotate(Target, axis *VecMatrix, angle float64) *VecMatrix { return ZeroVecs(1) //temporary, of course } /* rows, _ := Target.Dims() paxis := paravectorFromVector(axis,ZeroVecs(1)) paxis.unit(paxis) R := makeParavector() //build the rotor (R) R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) } Rrev := R.reverse() // R-dagger Res := ZeroVecs(rows) ended := make(chan bool, rows) for i := 0; i < rows; i++ { go func(i int) { //Here we simply do R^dagger A R, and assign to the corresponding row. targetrow := Target.VecView(i) tmp := cliProduct(Rrev, paravectorFromVector(targetrow,ZeroVecs(1))) Rotated := cliProduct(tmp, R) //a,b:=Res.Dims() //debug //c,d:=Rotated.Vreal.Dims() //fmt.Println("rows",a,c,"cols",b,d,"i","rowss",) Res.SetMatrix(i, 0, Rotated.Vreal) ended <- true return }(i) } //Takes care of the concurrency for i := 0; i < rows; i++ { <-ended } return Res } */ //Clifford product of 2 paravectors. func fullCliProduct(A, B *paravector) *paravector { R := makeParavector() R.Real = A.Real*B.Real - A.Imag*B.Imag for i := 0; i < 3; i++ { R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) } R.Imag = A.Real*B.Imag + A.Imag*B.Real for i := 0; i < 3; i++ { R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) } //Now the vector part //First real R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) //Second real R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) //Third real R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) //First imag R.Vimag.Set(0, 0, A.Real*B.Vimag.At(0, 0)+B.Real*A.Vimag.At(0, 0)+A.Imag*B.Vreal.At(0, 0)-B.Imag*A.Vreal.At(0, 0)+ A.Vreal.At(0, 1)*B.Vreal.At(0, 2)-A.Vreal.At(0, 2)*B.Vreal.At(0, 1)+A.Vimag.At(0, 2)*B.Vimag.At(0, 1)- A.Vimag.At(0, 1)*B.Vimag.At(0, 2)) //Second imag R.Vimag.Set(0, 1, A.Real*B.Vimag.At(0, 1)+B.Real*A.Vimag.At(0, 1)+A.Imag*B.Vreal.At(0, 1)-B.Imag*A.Vreal.At(0, 1)+ A.Vreal.At(0, 2)*B.Vreal.At(0, 0)-A.Vreal.At(0, 0)*B.Vreal.At(0, 2)+A.Vimag.At(0, 0)*B.Vimag.At(0, 2)- A.Vimag.At(0, 2)*B.Vimag.At(0, 0)) //Third imag R.Vimag.Set(0, 2, A.Real*B.Vimag.At(0, 2)+B.Real*A.Vimag.At(0, 2)+A.Imag*B.Vreal.At(0, 2)-B.Imag*A.Vreal.At(0, 2)+ A.Vreal.At(0, 0)*B.Vreal.At(0, 1)-A.Vreal.At(0, 1)*B.Vreal.At(0, 0)+A.Vimag.At(0, 1)*B.Vimag.At(0, 0)- A.Vimag.At(0, 0)*B.Vimag.At(0, 1)) //fmt.Println("R slido del horno", R) // A.Real, B.Vimag.At(0,0), "g2", B.Real,A.Vimag.At(0,0),"g3", A.Imag, B.Vreal.At(0,0),"g4" ,B.Imag,A.Vreal.At(0,0), //"g5", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* //A.Vimag.At(0,1)*B.Vimag.At(0,2)) return R } Implemented the (concurrent) Rotate/RotateP functions, which pass the test. TODO: Minimize allocations, move allocations to RotateP, integrate the program I have been using as test to the test suite /* * Clifford.go, part of gochem. * * * Copyright 2012 Janne Pesonen <janne.pesonen{at}helsinkiDOTfi> * and Raul Mera <rmera{at}chemDOThelsinkiDOTfi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * * * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, * University of Helsinki, Finland. * * */ /***RM: Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ package chem import "math" import "runtime" //import "fmt" type paravector struct { Real float64 Imag float64 Vreal *VecMatrix Vimag *VecMatrix } //creates a new paravector func makeParavector() *paravector { R := new(paravector) R.Real = 0 //I shouldnt need this R.Imag = 0 R.Vreal = ZeroVecs(1) R.Vimag = ZeroVecs(1) return R } //Takes a vector and creates a paravector. Uses copy so the vector is not affected //By future changes to the paravector. func paravectorFromVector(A,B *VecMatrix) *paravector { R := new(paravector) R.Real = 0 //I shouldnt need this R.Imag = 0 R.Vreal = A R.Vimag = B return R } //Puts a copy fo the paravector P in the receiver func (R *paravector) Copy(P *paravector) { R.Real = P.Real R.Imag = P.Imag R.Vreal.Copy(P.Vreal) R.Vimag.Copy(P.Vimag) } //Puts the reverse of paravector P in the received func (R *paravector) reverse(P *paravector) { if P!=R{ R.Copy(P) } R.Vimag.Scale(-1, R.Vimag) } //Puts the normalized version of P in the receiver. If R and P are the same, func (R *paravector) unit (P *paravector) { norm := 0.0 norm += math.Pow(P.Real, 2) + math.Pow(P.Imag, 2) for i := 0; i < 3; i++ { norm += math.Pow(P.Vreal.At(0, i), 2) + math.Pow(P.Vimag.At(0, i), 2) } //fmt.Println("norm", norm) R.Real = P.Real / math.Sqrt(norm) R.Imag = P.Imag / math.Sqrt(norm) for i := 0; i < 3; i++ { R.Vreal.Set(0, i, P.Vreal.At(0, i)/math.Sqrt(norm)) R.Vimag.Set(0, i, P.Vimag.At(0, i)/math.Sqrt(norm)) } //fmt.Println("normalized", R) } //Clifford product of 2 paravectors, the imaginary parts are simply set to zero, since this is the case //when rotating 3D real vectors. The proper Cliffor product is in fullCliProduct func (R *paravector) cliProduct(A, B *paravector) { R.Real = A.Real*B.Real - A.Imag*B.Imag for i := 0; i < 3; i++ { R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) } R.Imag = A.Real*B.Imag + A.Imag*B.Real for i := 0; i < 3; i++ { R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) } //Now the vector part //First real R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) //Second real R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) //Third real R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) /* //First imag R.Vimag.Set(0,0,A.Real*B.Vimag.At(0,0) + B.Real*A.Vimag.At(0,0) + A.Imag*B.Vreal.At(0,0) - B.Imag*A.Vreal.At(0,0) + A.Vreal.At(0,1)*B.Vreal.At(0,2) - A.Vreal.At(0,2)*B.Vreal.At(0,1) + A.Vimag.At(0,2)*B.Vimag.At(0,1) - A.Vimag.At(0,1)*B.Vimag.At(0,2)) //Second imag R.Vimag.Set(0,1,A.Real*B.Vimag.At(0,1) + B.Real*A.Vimag.At(0,1) + A.Imag*B.Vreal.At(0,1) - B.Imag*A.Vreal.At(0,1) + A.Vreal.At(0,2)*B.Vreal.At(0,0) - A.Vreal.At(0,0)*B.Vreal.At(0,2) + A.Vimag.At(0,0)*B.Vimag.At(0,2) - A.Vimag.At(0,2)*B.Vimag.At(0,0)) //Third imag R.Vimag.Set(0,2,A.Real*B.Vimag.At(0,2) + B.Real*A.Vimag.At(0,2) + A.Imag*B.Vreal.At(0,2) - B.Imag*A.Vreal.At(0,2) + A.Vreal.At(0,0)*B.Vreal.At(0,1) - A.Vreal.At(0,1)*B.Vreal.At(0,0) + A.Vimag.At(0,1)*B.Vimag.At(0,0) - A.Vimag.At(0,0)*B.Vimag.At(0,1)) */ //fmt.Println("R slido del horno", R) // A.Real, B.Vimag.At(0,0), "g2", B.Real,A.Vimag.At(0,0),"g3", A.Imag, B.Vreal.At(0,0),"g4" ,B.Imag,A.Vreal.At(0,0), //"g5", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* //A.Vimag.At(0,1)*B.Vimag.At(0,2)) // return R } //cliRotation uses Clifford algebra to rotate a paravector Aby angle radians around axis. Returns the rotated //paravector. axis must be normalized. func (R *paravector) cliRotation(A, axis, tmp, tmp2 *paravector, angle float64) { // R := makeParavector() R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*axis.Vreal.At(0, i)) } R.reverse(R) // tmp:=makeParavector() // tmp2:=makeParavector() tmp.cliProduct(R, A) tmp2.cliProduct(tmp, R) R.Copy(tmp2) } //RotateSer takes the matrix Target and uses Clifford algebra to rotate each of its rows //by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. //The Ser in the name is from "serial". ToRot will be overwritten and returned func RotateSer(Target,ToRot, axis *VecMatrix, angle float64) *VecMatrix { cake:=ZeroVecs(10) //Better ask for one chunk of memory than allocate 10 different times. R:=cake.VecView(0) Rrev:=cake.VecView(1) tmp:=cake.VecView(2) Rotated:=cake.VecView(3) itmp1:=cake.VecView(4) itmp2:=cake.VecView(5) itmp3:=cake.VecView(6) itmp4:=cake.VecView(7) itmp5:=cake.VecView(8) itmp6:=cake.VecView(9) RotateSerP(Target,ToRot,axis,tmp,R,Rrev,Rotated,itmp1,itmp2,itmp3,itmp4,itmp5,itmp6,angle) return ToRot } //RotateSerP takes the matrix Target and uses Clifford algebra to rotate each of its rows //by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. //The Ser in the name is from "serial". ToRot will be overwritten and returned. RotateSerP only allocates some floats but not //any VecMatrix. Instead, it takes the needed intermediates as arguments, hence the "P" for "performance" If performance is not an issue, //use RotateSer instead, it will perform the allocations for you and call this function. Notice that if you use this function directly //you may have to zero at least some of the intermediates before reusing them. func RotateSerP(Target,ToRot, axis,tmpv,Rv,Rvrev,Rotatedv, itmp1,itmp2,itmp3,itmp4,itmp5,itmp6 *VecMatrix, angle float64) { tarr, _ := Target.Dims() torotr := ToRot.NVecs() if tarr != torotr || Target.Dense == ToRot.Dense { panic("RotateSerP: Target and Res must have the same dimensions. Target and Res cannot reference the same matrix") } //Make the paravectors from the passed vectors: tmp:=paravectorFromVector(tmpv,itmp3) R:=paravectorFromVector(Rv,itmp4) Rrev:=paravectorFromVector(Rvrev,itmp5) Rotated:=paravectorFromVector(Rotatedv,itmp6) //That is with the building of temporary paravectors. paxis := paravectorFromVector(axis,itmp1) paxis.unit(paxis) R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) } Rrev.reverse(R) for i := 0; i < tarr; i++ { rowvec := Target.VecView(i) tmp.cliProduct(Rrev, paravectorFromVector(rowvec,itmp2)) Rotated.cliProduct(tmp, R) ToRot.SetMatrix(i, 0, Rotated.Vreal) } } //Rotate takes the matrix Target and uses Clifford algebra to _concurrently_ rotate each //of its rows by angle radians around axis. Axis must be a 3D row vector. //Target must be an N,3 matrix. The result is returned. func Rotate(Target, axis *VecMatrix, angle float64) *VecMatrix { Res := ZeroVecs(Target.NVecs()) RotateP(Target, Res, axis, angle) return Res } //Rotate takes the matrix Target and uses Clifford algebra to _concurrently_ rotate each //of its rows by angle radians around axis. Axis must be a 3D row vector. //Target must be an N,3 matrix. func RotateP(Target, Res, axis *VecMatrix, angle float64) { gorut := runtime.GOMAXPROCS(-1) //Do not change anything, only query rows := Target.NVecs() rrows := Res.NVecs() if rrows != rows || Target.Dense == Res.Dense { panic("RotateP: Target and Res must have the same dimensions. Target and Res cannot reference the same matrix.") } paxis := paravectorFromVector(axis,ZeroVecs(1)) paxis.unit(paxis) R := makeParavector() //build the rotor (R) R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) } Rrev := makeParavector() //R-dagger Rrev.reverse(R) ended := make(chan bool, gorut) //Just temporal skit to be used by the gorutines tmp1 := ZeroVecs(gorut) tmp2 := ZeroVecs(gorut) tmp3 := ZeroVecs(gorut) tmp4 := ZeroVecs(gorut) fragmentlen := int(math.Ceil(float64(rows) / float64(gorut))) //len of the fragment of target that each gorutine will handle for i := 0; i < gorut; i++ { //These are the limits of the fragment of Target in which the gorutine will operate ini := i * fragmentlen end := i*fragmentlen + (fragmentlen - 1) if i == gorut-1 { end = rows - 1 //The last fragment may be smaller than fragmentlen } go func(ini, end, i int) { t1 := tmp1.VecView(i) t2 := tmp2.VecView(i) t4 := tmp4.VecView(i) pv := paravectorFromVector(t2, t4) t3 := tmp3.VecView(i) for j := ini; j <= end; j++ { //Here we simply do R^dagger A R, and assign to the corresponding row. Rotated := paravectorFromVector(Res.VecView(j), t3) targetparavec := paravectorFromVector(Target.VecView(j), t1) pv.cliProduct(Rrev, targetparavec) Rotated.cliProduct(pv, R) } ended <- true return }(ini, end, i) } //Takes care of the concurrency for i := 0; i < gorut; i++ { <-ended } return } /* rows, _ := Target.Dims() paxis := paravectorFromVector(axis,ZeroVecs(1)) paxis.unit(paxis) R := makeParavector() //build the rotor (R) R.Real = math.Cos(angle / 2.0) for i := 0; i < 3; i++ { R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) } Rrev := R.reverse() // R-dagger Res := ZeroVecs(rows) ended := make(chan bool, rows) for i := 0; i < rows; i++ { go func(i int) { //Here we simply do R^dagger A R, and assign to the corresponding row. targetrow := Target.VecView(i) tmp := cliProduct(Rrev, paravectorFromVector(targetrow,ZeroVecs(1))) Rotated := cliProduct(tmp, R) //a,b:=Res.Dims() //debug //c,d:=Rotated.Vreal.Dims() //fmt.Println("rows",a,c,"cols",b,d,"i","rowss",) Res.SetMatrix(i, 0, Rotated.Vreal) ended <- true return }(i) } //Takes care of the concurrency for i := 0; i < rows; i++ { <-ended } return Res } */ //Clifford product of 2 paravectors. func fullCliProduct(A, B *paravector) *paravector { R := makeParavector() R.Real = A.Real*B.Real - A.Imag*B.Imag for i := 0; i < 3; i++ { R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) } R.Imag = A.Real*B.Imag + A.Imag*B.Real for i := 0; i < 3; i++ { R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) } //Now the vector part //First real R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) //Second real R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) //Third real R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) //First imag R.Vimag.Set(0, 0, A.Real*B.Vimag.At(0, 0)+B.Real*A.Vimag.At(0, 0)+A.Imag*B.Vreal.At(0, 0)-B.Imag*A.Vreal.At(0, 0)+ A.Vreal.At(0, 1)*B.Vreal.At(0, 2)-A.Vreal.At(0, 2)*B.Vreal.At(0, 1)+A.Vimag.At(0, 2)*B.Vimag.At(0, 1)- A.Vimag.At(0, 1)*B.Vimag.At(0, 2)) //Second imag R.Vimag.Set(0, 1, A.Real*B.Vimag.At(0, 1)+B.Real*A.Vimag.At(0, 1)+A.Imag*B.Vreal.At(0, 1)-B.Imag*A.Vreal.At(0, 1)+ A.Vreal.At(0, 2)*B.Vreal.At(0, 0)-A.Vreal.At(0, 0)*B.Vreal.At(0, 2)+A.Vimag.At(0, 0)*B.Vimag.At(0, 2)- A.Vimag.At(0, 2)*B.Vimag.At(0, 0)) //Third imag R.Vimag.Set(0, 2, A.Real*B.Vimag.At(0, 2)+B.Real*A.Vimag.At(0, 2)+A.Imag*B.Vreal.At(0, 2)-B.Imag*A.Vreal.At(0, 2)+ A.Vreal.At(0, 0)*B.Vreal.At(0, 1)-A.Vreal.At(0, 1)*B.Vreal.At(0, 0)+A.Vimag.At(0, 1)*B.Vimag.At(0, 0)- A.Vimag.At(0, 0)*B.Vimag.At(0, 1)) //fmt.Println("R slido del horno", R) // A.Real, B.Vimag.At(0,0), "g2", B.Real,A.Vimag.At(0,0),"g3", A.Imag, B.Vreal.At(0,0),"g4" ,B.Imag,A.Vreal.At(0,0), //"g5", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* //A.Vimag.At(0,1)*B.Vimag.At(0,2)) return R }
package handler import ( "bytes" "encoding/json" "io" "io/ioutil" "log" "net/http" "runtime/debug" "time" "github.com/TimothyYe/godns" "golang.org/x/net/proxy" ) // CloudflareHandler struct definition type CloudflareHandler struct { Configuration *godns.Settings API string } // DNS api response type DNSRecordResponse struct { Records []DNSRecord `json:"result"` Success bool `json:"success"` } // DNS update api response type DNSRecordUpdateResponse struct { Record DNSRecord `json:"result"` Success bool `json:"success"` } type DNSRecord struct { Id string `json:"id"` Ip string `json:"content"` Name string `json:"name"` Proxied bool `json:"proxied"` Type string `json:"type"` ZoneId string `json:"zone_id"` } func (r *DNSRecord) SetIp(ip string) { r.Ip = ip } // response from zone api request type ZoneResponse struct { Zones []Zone `json:"result"` Success bool `json:"success"` } // nested results, only care about name and id type Zone struct { Id string `json:"id"` Name string `json:"name"` } // SetConfiguration pass dns settings and store it to handler instance func (handler *CloudflareHandler) SetConfiguration(conf *godns.Settings) { handler.Configuration = conf handler.API = "https://api.cloudflare.com/client/v4" } // DomainLoop the main logic loop func (handler *CloudflareHandler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.Domain) { defer func() { if err := recover(); err != nil { log.Printf("Recovered in %v: %v\n", err, debug.Stack()) panicChan <- *domain } }() for { currentIp, err := godns.GetCurrentIP(handler.Configuration) if err != nil { log.Println("Error in GetCurrentIP:", err) continue } log.Println("Current IP is:", currentIp) // TODO: check against locally cached IP, if no change, skip update log.Println("Checking IP for domain", domain.DomainName) zoneId := handler.getZone(domain.DomainName) if zoneId != "" { records := handler.getDNSRecords(zoneId) // update records for _, rec := range records { if recordTracked(domain, &rec) != true { log.Println("Skiping record:", rec.Name) continue } if rec.Ip != currentIp { log.Printf("IP mismatch: Current(%+v) vs Cloudflare(%+v)\r\n", currentIp, rec.Ip) handler.updateRecord(rec, currentIp) } else { log.Printf("Record OK: %+v - %+v\r\n", rec.Name, rec.Ip) } } } else { log.Println("Failed to find zone for domain:", domain.DomainName) } // Interval is 5 minutes log.Printf("Going to sleep, will start next checking in %d minutes...\r\n", godns.INTERVAL) time.Sleep(time.Minute * godns.INTERVAL) } } // Check if record is present in domain conf func recordTracked(domain *godns.Domain, record *DNSRecord) bool { if record.Name == domain.DomainName { return true } for _, subDomain := range domain.SubDomains { sd := subDomain + "." + domain.DomainName if record.Name == sd { return true } } return false } // Create a new request with auth in place and optional proxy func (handler *CloudflareHandler) newRequest(method, url string, body io.Reader) (*http.Request, *http.Client) { client := &http.Client{} if handler.Configuration.Socks5Proxy != "" { log.Println("use socks5 proxy:" + handler.Configuration.Socks5Proxy) dialer, err := proxy.SOCKS5("tcp", handler.Configuration.Socks5Proxy, nil, proxy.Direct) if err != nil { log.Println("can't connect to the proxy:", err) } else { httpTransport := &http.Transport{} client.Transport = httpTransport httpTransport.Dial = dialer.Dial } } req, _ := http.NewRequest(method, handler.API+url, body) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Auth-Email", handler.Configuration.Email) req.Header.Set("X-Auth-Key", handler.Configuration.Password) return req, client } // Find the correct zone via domain name func (handler *CloudflareHandler) getZone(domain string) string { var z ZoneResponse req, client := handler.newRequest("GET", "/zones", nil) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return "" } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &z) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return "" } if z.Success != true { log.Printf("Response failed: %+v\n", string(body)) return "" } for _, zone := range z.Zones { if zone.Name == domain { return zone.Id } } return "" } // Get all DNS A records for a zone func (handler *CloudflareHandler) getDNSRecords(zoneId string) []DNSRecord { var empty []DNSRecord var r DNSRecordResponse req, client := handler.newRequest("GET", "/zones/"+zoneId+"/dns_records?type=A", nil) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return empty } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return empty } if r.Success != true { body, _ := ioutil.ReadAll(resp.Body) log.Printf("Response failed: %+v\n", string(body)) return empty } return r.Records } // Update DNS A Record with new IP func (handler *CloudflareHandler) updateRecord(record DNSRecord, newIp string) { var r DNSRecordUpdateResponse record.SetIp(newIp) j, _ := json.Marshal(record) req, client := handler.newRequest("PUT", "/zones/"+record.ZoneId+"/dns_records/"+record.Id, bytes.NewBuffer(j), ) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return } if r.Success != true { body, _ := ioutil.ReadAll(resp.Body) log.Printf("Response failed: %+v\n", string(body)) } else { log.Printf("Record updated: %+v - %+v", record.Name, record.Ip) } } Linter fixes package handler import ( "bytes" "encoding/json" "io" "io/ioutil" "log" "net/http" "runtime/debug" "time" "github.com/TimothyYe/godns" "golang.org/x/net/proxy" ) // CloudflareHandler struct definition type CloudflareHandler struct { Configuration *godns.Settings API string } // DNS api response type DNSRecordResponse struct { Records []DNSRecord `json:"result"` Success bool `json:"success"` } // DNS update api response type DNSRecordUpdateResponse struct { Record DNSRecord `json:"result"` Success bool `json:"success"` } // DNSRecord for Cloudflare API type DNSRecord struct { ID string `json:"id"` IP string `json:"content"` Name string `json:"name"` Proxied bool `json:"proxied"` Type string `json:"type"` ZoneID string `json:"zone_id"` } // Update DNSRecord IP func (r *DNSRecord) SetIP(ip string) { r.IP = ip } // response from zone api request type ZoneResponse struct { Zones []Zone `json:"result"` Success bool `json:"success"` } // nested results, only care about name and id type Zone struct { ID string `json:"id"` Name string `json:"name"` } // SetConfiguration pass dns settings and store it to handler instance func (handler *CloudflareHandler) SetConfiguration(conf *godns.Settings) { handler.Configuration = conf handler.API = "https://api.cloudflare.com/client/v4" } // DomainLoop the main logic loop func (handler *CloudflareHandler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.Domain) { defer func() { if err := recover(); err != nil { log.Printf("Recovered in %v: %v\n", err, debug.Stack()) panicChan <- *domain } }() for { currentIP, err := godns.GetCurrentIP(handler.Configuration) if err != nil { log.Println("Error in GetCurrentIP:", err) continue } log.Println("Current IP is:", currentIP) // TODO: check against locally cached IP, if no change, skip update log.Println("Checking IP for domain", domain.DomainName) zoneID := handler.getZone(domain.DomainName) if zoneID != "" { records := handler.getDNSRecords(zoneID) // update records for _, rec := range records { if recordTracked(domain, &rec) != true { log.Println("Skiping record:", rec.Name) continue } if rec.IP != currentIP { log.Printf("IP mismatch: Current(%+v) vs Cloudflare(%+v)\r\n", currentIP, rec.IP) handler.updateRecord(rec, currentIP) } else { log.Printf("Record OK: %+v - %+v\r\n", rec.Name, rec.IP) } } } else { log.Println("Failed to find zone for domain:", domain.DomainName) } // Interval is 5 minutes log.Printf("Going to sleep, will start next checking in %d minutes...\r\n", godns.INTERVAL) time.Sleep(time.Minute * godns.INTERVAL) } } // Check if record is present in domain conf func recordTracked(domain *godns.Domain, record *DNSRecord) bool { if record.Name == domain.DomainName { return true } for _, subDomain := range domain.SubDomains { sd := subDomain + "." + domain.DomainName if record.Name == sd { return true } } return false } // Create a new request with auth in place and optional proxy func (handler *CloudflareHandler) newRequest(method, url string, body io.Reader) (*http.Request, *http.Client) { client := &http.Client{} if handler.Configuration.Socks5Proxy != "" { log.Println("use socks5 proxy:" + handler.Configuration.Socks5Proxy) dialer, err := proxy.SOCKS5("tcp", handler.Configuration.Socks5Proxy, nil, proxy.Direct) if err != nil { log.Println("can't connect to the proxy:", err) } else { httpTransport := &http.Transport{} client.Transport = httpTransport httpTransport.Dial = dialer.Dial } } req, _ := http.NewRequest(method, handler.API+url, body) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Auth-Email", handler.Configuration.Email) req.Header.Set("X-Auth-Key", handler.Configuration.Password) return req, client } // Find the correct zone via domain name func (handler *CloudflareHandler) getZone(domain string) string { var z ZoneResponse req, client := handler.newRequest("GET", "/zones", nil) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return "" } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &z) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return "" } if z.Success != true { log.Printf("Response failed: %+v\n", string(body)) return "" } for _, zone := range z.Zones { if zone.Name == domain { return zone.ID } } return "" } // Get all DNS A records for a zone func (handler *CloudflareHandler) getDNSRecords(zoneID string) []DNSRecord { var empty []DNSRecord var r DNSRecordResponse req, client := handler.newRequest("GET", "/zones/"+zoneID+"/dns_records?type=A", nil) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return empty } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return empty } if r.Success != true { body, _ := ioutil.ReadAll(resp.Body) log.Printf("Response failed: %+v\n", string(body)) return empty } return r.Records } // Update DNS A Record with new IP func (handler *CloudflareHandler) updateRecord(record DNSRecord, newIP string) { var r DNSRecordUpdateResponse record.SetIP(newIP) j, _ := json.Marshal(record) req, client := handler.newRequest("PUT", "/zones/"+record.ZoneID+"/dns_records/"+record.ID, bytes.NewBuffer(j), ) resp, err := client.Do(req) if err != nil { log.Println("Request error:", err.Error()) return } body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { log.Printf("Decoder error: %+v\n", err) log.Printf("Response body: %+v\n", string(body)) return } if r.Success != true { body, _ := ioutil.ReadAll(resp.Body) log.Printf("Response failed: %+v\n", string(body)) } else { log.Printf("Record updated: %+v - %+v", record.Name, record.IP) } }
// +build solaris package mlock import ( "syscall" "golang.org/x/sys/unix" ) func init() { supported = true } func lockMemory() error { // Mlockall prevents all current and future pages from being swapped out. return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) } `go fmt` was here, no functional change // +build solaris package mlock import ( "syscall" "golang.org/x/sys/unix" ) func init() { supported = true } func lockMemory() error { // Mlockall prevents all current and future pages from being swapped out. return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) }
package config_test import ( "encoding/json" "io/ioutil" "os" "time" cfg "github.com/cloudfoundry/cf-acceptance-tests/helpers/config" . "github.com/cloudfoundry/cf-acceptance-tests/helpers/validationerrors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type requiredConfig struct { // required ApiEndpoint string `json:"api"` AdminUser string `json:"admin_user"` AdminPassword string `json:"admin_password"` SkipSSLValidation bool `json:"skip_ssl_validation"` AppsDomain string `json:"apps_domain"` UseHttp bool `json:"use_http"` } type testConfig struct { // required ApiEndpoint string `json:"api"` AdminUser string `json:"admin_user"` AdminPassword string `json:"admin_password"` SkipSSLValidation bool `json:"skip_ssl_validation"` AppsDomain string `json:"apps_domain"` UseHttp bool `json:"use_http"` // timeouts DefaultTimeout int `json:"default_timeout"` CfPushTimeout int `json:"cf_push_timeout"` LongCurlTimeout int `json:"long_curl_timeout"` BrokerStartTimeout int `json:"broker_start_timeout"` AsyncServiceOperationTimeout int `json:"async_service_operation_timeout"` DetectTimeout int `json:"detect_timeout"` SleepTimeout int `json:"sleep_timeout"` // optional Backend string `json:"backend"` } var tmpFile *os.File var err error var errors Errors var requiredCfg requiredConfig var testCfg testConfig func writeConfigFile(updatedConfig interface{}) string { configFile, err := ioutil.TempFile("", "cf-test-helpers-config") Expect(err).NotTo(HaveOccurred()) encoder := json.NewEncoder(configFile) err = encoder.Encode(updatedConfig) Expect(err).NotTo(HaveOccurred()) err = configFile.Close() Expect(err).NotTo(HaveOccurred()) return configFile.Name() } func withConfig(initialConfig testConfig, setupConfig func(testConfig) testConfig, runTest func()) { previousConfig := os.Getenv("CONFIG") updatedConfig := setupConfig(initialConfig) newConfigFilePath := writeConfigFile(updatedConfig) os.Setenv("CONFIG", newConfigFilePath) runTest() os.Setenv("CONFIG", previousConfig) } var _ = Describe("Config", func() { BeforeEach(func() { testCfg = testConfig{ ApiEndpoint: "api.bosh-lite.com", AdminUser: "admin", AdminPassword: "admin", SkipSSLValidation: true, AppsDomain: "cf-app.bosh-lite.com", UseHttp: true, } requiredCfg = requiredConfig{ ApiEndpoint: "api.bosh-lite.com", AdminUser: "admin", AdminPassword: "admin", SkipSSLValidation: true, AppsDomain: "cf-app.bosh-lite.com", UseHttp: true, } tmpFile, err = ioutil.TempFile("", "cf-test-helpers-config") Expect(err).NotTo(HaveOccurred()) encoder := json.NewEncoder(tmpFile) err = encoder.Encode(requiredCfg) Expect(err).NotTo(HaveOccurred()) err = tmpFile.Close() Expect(err).NotTo(HaveOccurred()) os.Setenv("CONFIG", tmpFile.Name()) }) AfterEach(func() { err := os.Remove(tmpFile.Name()) Expect(err).NotTo(HaveOccurred()) }) It("should have the right defaults", func() { config, err := cfg.NewCatsConfig() Expect(err).ToNot(HaveOccurred()) Expect(config.GetIncludeApps()).To(BeTrue()) Expect(config.DefaultTimeoutDuration()).To(Equal(30 * time.Second)) Expect(config.CfPushTimeoutDuration()).To(Equal(2 * time.Minute)) Expect(config.LongCurlTimeoutDuration()).To(Equal(2 * time.Minute)) Expect(config.BrokerStartTimeoutDuration()).To(Equal(5 * time.Minute)) Expect(config.AsyncServiceOperationTimeoutDuration()).To(Equal(2 * time.Minute)) // undocumented Expect(config.DetectTimeoutDuration()).To(Equal(5 * time.Minute)) Expect(config.SleepTimeoutDuration()).To(Equal(30 * time.Second)) }) It("should have duration timeouts based on the configured values", func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.DefaultTimeout = 12 myConfig.CfPushTimeout = 34 myConfig.LongCurlTimeout = 56 myConfig.BrokerStartTimeout = 78 myConfig.AsyncServiceOperationTimeout = 90 myConfig.DetectTimeout = 100 myConfig.SleepTimeout = 101 return myConfig }, func() { config, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) Expect(config.DefaultTimeoutDuration()).To(Equal(12 * time.Second)) Expect(config.CfPushTimeoutDuration()).To(Equal(34 * time.Minute)) Expect(config.LongCurlTimeoutDuration()).To(Equal(56 * time.Minute)) Expect(config.BrokerStartTimeoutDuration()).To(Equal(78 * time.Minute)) Expect(config.AsyncServiceOperationTimeoutDuration()).To(Equal(90 * time.Minute)) Expect(config.DetectTimeoutDuration()).To(Equal(100 * time.Minute)) Expect(config.SleepTimeoutDuration()).To(Equal(101 * time.Second)) }, ) }) Context(`validations`, func() { It(`validates that the backend is "dea", "diego", or ""`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "lkjlkjlkjlkj" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("* Invalid configuration: 'backend' must be 'diego', 'dea', or empty but was set to 'lkjlkjlkjlkj'")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "dea" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "diego" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) }) It(`validates that ApiEndpoint is a valid URL`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingDomain := "api.bosh-lite.com" myConfig.ApiEndpoint = myAlwaysResolvingDomain return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingIP := "10.244.0.34" // api.bosh-lite.com myConfig.ApiEndpoint = myAlwaysResolvingIP return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.ApiEndpoint = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("* Invalid configuration: 'api' must be a valid Cloud Controller endpoint but was blank")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.ApiEndpoint = "_bogus%%%" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("* Invalid configuration: 'api' must be a valid URL but was set to '_bogus%%%'")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myNeverResolvingURI := "E437FE20-5F25-479E-8B79-A008A13E58F6.E437FE20-5F25-479E-8B79-A008A13E58F6.E437FE20-5F25-479E-8B79-A008A13E58F6" myConfig.ApiEndpoint = myNeverResolvingURI return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("no such host")) }, ) }) It(`validates that AppsDomain is a valid domain`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AppsDomain = "bosh-lite.com" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).ToNot(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingIP := "10.244.0.34" // api.bosh-lite.com myConfig.AppsDomain = myAlwaysResolvingIP return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("no such host")) }, ) }) It(`validates that AdminUser is present`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AdminUser = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("'admin_user' must be provided")) }, ) }) It(`validates that AdminPassword is present`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AdminPassword = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("'admin_password' must be provided")) }, ) }) }) }) Prevented test pollution [#132109325] Signed-off-by: Chunyi Lyu <0f8e751eae2b6087fa04691c2ff75f586389adcc@pivotal.io> package config_test import ( "encoding/json" "io/ioutil" "os" "time" cfg "github.com/cloudfoundry/cf-acceptance-tests/helpers/config" . "github.com/cloudfoundry/cf-acceptance-tests/helpers/validationerrors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type requiredConfig struct { // required ApiEndpoint string `json:"api"` AdminUser string `json:"admin_user"` AdminPassword string `json:"admin_password"` SkipSSLValidation bool `json:"skip_ssl_validation"` AppsDomain string `json:"apps_domain"` UseHttp bool `json:"use_http"` } type testConfig struct { // required ApiEndpoint string `json:"api"` AdminUser string `json:"admin_user"` AdminPassword string `json:"admin_password"` SkipSSLValidation bool `json:"skip_ssl_validation"` AppsDomain string `json:"apps_domain"` UseHttp bool `json:"use_http"` // timeouts DefaultTimeout int `json:"default_timeout"` CfPushTimeout int `json:"cf_push_timeout"` LongCurlTimeout int `json:"long_curl_timeout"` BrokerStartTimeout int `json:"broker_start_timeout"` AsyncServiceOperationTimeout int `json:"async_service_operation_timeout"` DetectTimeout int `json:"detect_timeout"` SleepTimeout int `json:"sleep_timeout"` // optional Backend string `json:"backend"` } var tmpFile *os.File var err error var errors Errors var requiredCfg requiredConfig var testCfg testConfig var originalConfig string func writeConfigFile(updatedConfig interface{}) string { configFile, err := ioutil.TempFile("", "cf-test-helpers-config") Expect(err).NotTo(HaveOccurred()) encoder := json.NewEncoder(configFile) err = encoder.Encode(updatedConfig) Expect(err).NotTo(HaveOccurred()) err = configFile.Close() Expect(err).NotTo(HaveOccurred()) return configFile.Name() } func withConfig(initialConfig testConfig, setupConfig func(testConfig) testConfig, runTest func()) { previousConfig := os.Getenv("CONFIG") updatedConfig := setupConfig(initialConfig) newConfigFilePath := writeConfigFile(updatedConfig) os.Setenv("CONFIG", newConfigFilePath) runTest() os.Setenv("CONFIG", previousConfig) } var _ = Describe("Config", func() { BeforeEach(func() { testCfg = testConfig{ ApiEndpoint: "api.bosh-lite.com", AdminUser: "admin", AdminPassword: "admin", SkipSSLValidation: true, AppsDomain: "cf-app.bosh-lite.com", UseHttp: true, } requiredCfg = requiredConfig{ ApiEndpoint: "api.bosh-lite.com", AdminUser: "admin", AdminPassword: "admin", SkipSSLValidation: true, AppsDomain: "cf-app.bosh-lite.com", UseHttp: true, } tmpFile, err = ioutil.TempFile("", "cf-test-helpers-config") Expect(err).NotTo(HaveOccurred()) encoder := json.NewEncoder(tmpFile) err = encoder.Encode(requiredCfg) Expect(err).NotTo(HaveOccurred()) err = tmpFile.Close() Expect(err).NotTo(HaveOccurred()) originalConfig = os.Getenv("CONFIG") os.Setenv("CONFIG", tmpFile.Name()) }) AfterEach(func() { err := os.Remove(tmpFile.Name()) Expect(err).NotTo(HaveOccurred()) os.Setenv("CONFIG", originalConfig) }) It("should have the right defaults", func() { config, err := cfg.NewCatsConfig() Expect(err).ToNot(HaveOccurred()) Expect(config.GetIncludeApps()).To(BeTrue()) Expect(config.DefaultTimeoutDuration()).To(Equal(30 * time.Second)) Expect(config.CfPushTimeoutDuration()).To(Equal(2 * time.Minute)) Expect(config.LongCurlTimeoutDuration()).To(Equal(2 * time.Minute)) Expect(config.BrokerStartTimeoutDuration()).To(Equal(5 * time.Minute)) Expect(config.AsyncServiceOperationTimeoutDuration()).To(Equal(2 * time.Minute)) // undocumented Expect(config.DetectTimeoutDuration()).To(Equal(5 * time.Minute)) Expect(config.SleepTimeoutDuration()).To(Equal(30 * time.Second)) }) It("should have duration timeouts based on the configured values", func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.DefaultTimeout = 12 myConfig.CfPushTimeout = 34 myConfig.LongCurlTimeout = 56 myConfig.BrokerStartTimeout = 78 myConfig.AsyncServiceOperationTimeout = 90 myConfig.DetectTimeout = 100 myConfig.SleepTimeout = 101 return myConfig }, func() { config, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) Expect(config.DefaultTimeoutDuration()).To(Equal(12 * time.Second)) Expect(config.CfPushTimeoutDuration()).To(Equal(34 * time.Minute)) Expect(config.LongCurlTimeoutDuration()).To(Equal(56 * time.Minute)) Expect(config.BrokerStartTimeoutDuration()).To(Equal(78 * time.Minute)) Expect(config.AsyncServiceOperationTimeoutDuration()).To(Equal(90 * time.Minute)) Expect(config.DetectTimeoutDuration()).To(Equal(100 * time.Minute)) Expect(config.SleepTimeoutDuration()).To(Equal(101 * time.Second)) }, ) }) Context(`validations`, func() { It(`validates that the backend is "dea", "diego", or ""`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "lkjlkjlkjlkj" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("* Invalid configuration: 'backend' must be 'diego', 'dea', or empty but was set to 'lkjlkjlkjlkj'")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "dea" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "diego" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.Backend = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) }) It(`validates that ApiEndpoint is a valid URL`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingDomain := "api.bosh-lite.com" myConfig.ApiEndpoint = myAlwaysResolvingDomain return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingIP := "10.244.0.34" // api.bosh-lite.com myConfig.ApiEndpoint = myAlwaysResolvingIP return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).NotTo(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.ApiEndpoint = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("* Invalid configuration: 'api' must be a valid Cloud Controller endpoint but was blank")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.ApiEndpoint = "_bogus%%%" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("* Invalid configuration: 'api' must be a valid URL but was set to '_bogus%%%'")) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myNeverResolvingURI := "E437FE20-5F25-479E-8B79-A008A13E58F6.E437FE20-5F25-479E-8B79-A008A13E58F6.E437FE20-5F25-479E-8B79-A008A13E58F6" myConfig.ApiEndpoint = myNeverResolvingURI return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("no such host")) }, ) }) It(`validates that AppsDomain is a valid domain`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AppsDomain = "bosh-lite.com" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).ToNot(HaveOccurred()) }, ) withConfig(testCfg, func(myConfig testConfig) testConfig { myAlwaysResolvingIP := "10.244.0.34" // api.bosh-lite.com myConfig.AppsDomain = myAlwaysResolvingIP return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("no such host")) }, ) }) It(`validates that AdminUser is present`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AdminUser = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("'admin_user' must be provided")) }, ) }) It(`validates that AdminPassword is present`, func() { withConfig(testCfg, func(myConfig testConfig) testConfig { myConfig.AdminPassword = "" return myConfig }, func() { _, err := cfg.NewCatsConfig() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("'admin_password' must be provided")) }, ) }) }) })
package main import ( "qmsk.net/clusterf/config" "qmsk.net/clusterf/clusterf" "flag" "log" "os" ) var ( filesConfig config.FilesConfig etcdConfig config.EtcdConfig ipvsConfig clusterf.IpvsConfig ipvsConfigPrint bool ) func init() { flag.StringVar(&filesConfig.Path, "config-path", "", "Local config tree") flag.StringVar(&etcdConfig.Machines, "etcd-machines", "http://127.0.0.1:2379", "Client endpoint for etcd") flag.StringVar(&etcdConfig.Prefix, "etcd-prefix", "/clusterf", "Etcd tree prefix") flag.BoolVar(&ipvsConfig.Debug, "ipvs-debug", false, "IPVS debugging") flag.BoolVar(&ipvsConfigPrint, "ipvs-print", false, "Dump initial IPVS config") flag.StringVar(&ipvsConfig.FwdMethod, "ipvs-fwd-method", "masq", "IPVS Forwarding method: masq tunnel droute") flag.StringVar(&ipvsConfig.SchedName, "ipvs-sched-name", "wlc", "IPVS Service Scheduler") } func main() { flag.Parse() if len(flag.Args()) > 0 { flag.Usage() os.Exit(1) } // setup services := clusterf.NewServices() // config var configFiles *config.Files var configEtcd *config.Etcd if filesConfig.Path != "" { if files, err := filesConfig.Open(); err != nil { log.Fatalf("config:Files.Open: %s\n", err) } else { configFiles = files log.Printf("config:Files.Open: %s\n", configFiles) } if configs, err := configFiles.Scan(); err != nil { log.Fatalf("config:Files.Scan: %s\n", err) } else { log.Printf("config:Files.Scan: %d configs\n", len(configs)) // iterate initial set of services for _, cfg := range configs { services.NewConfig(cfg) } } } if etcdConfig.Prefix != "" { if etcd, err := etcdConfig.Open(); err != nil { log.Fatalf("config:etcd.Open: %s\n", err) } else { configEtcd = etcd log.Printf("config:etcd.Open: %s\n", configEtcd) } if configs, err := configEtcd.Scan(); err != nil { log.Fatalf("config:Etcd.Scan: %s\n", err) } else { log.Printf("config:Etcd.Scan: %d configs\n", len(configs)) // iterate initial set of services for _, cfg := range configs { services.NewConfig(cfg) } } } // sync if ipvsDriver, err := services.SyncIPVS(ipvsConfig); err != nil { log.Fatalf("SyncIPVS: %s\n", err) } else { if ipvsConfigPrint { ipvsDriver.Print() } } if configEtcd != nil { // read channel for changes log.Printf("config:Etcd.Sync...\n") for event := range configEtcd.Sync() { log.Printf("config.Sync: %+v\n", event) services.ConfigEvent(event) } } log.Printf("Exit\n") } clusterf -advertise-route to publish a local route into etcd Lacking any mechanism to override etcd routes with local routes leaves this feature broken for now. package main import ( "qmsk.net/clusterf/config" "qmsk.net/clusterf/clusterf" "flag" "log" "os" ) var ( filesConfig config.FilesConfig etcdConfig config.EtcdConfig ipvsConfig clusterf.IpvsConfig ipvsConfigPrint bool advertiseConfig config.ConfigRoute ) func init() { flag.StringVar(&filesConfig.Path, "config-path", "", "Local config tree") flag.StringVar(&etcdConfig.Machines, "etcd-machines", "http://127.0.0.1:2379", "Client endpoint for etcd") flag.StringVar(&etcdConfig.Prefix, "etcd-prefix", "/clusterf", "Etcd tree prefix") flag.BoolVar(&ipvsConfig.Debug, "ipvs-debug", false, "IPVS debugging") flag.BoolVar(&ipvsConfigPrint, "ipvs-print", false, "Dump initial IPVS config") flag.StringVar(&ipvsConfig.FwdMethod, "ipvs-fwd-method", "masq", "IPVS Forwarding method: masq tunnel droute") flag.StringVar(&ipvsConfig.SchedName, "ipvs-sched-name", "wlc", "IPVS Service Scheduler") flag.StringVar(&advertiseConfig.RouteName, "advertise-route-name", "", "Advertise route by name") flag.StringVar(&advertiseConfig.Route.Prefix4, "advertise-route-prefix4", "", "Advertise route for prefix") flag.StringVar(&advertiseConfig.Route.Gateway4, "advertise-route-gateway4", "", "Advertise route via gateway") flag.StringVar(&advertiseConfig.Route.IpvsMethod, "advertise-route-ipvs-method", "", "Advertise route ipvs-fwd-method") } func main() { flag.Parse() if len(flag.Args()) > 0 { flag.Usage() os.Exit(1) } // setup services := clusterf.NewServices() // config var configFiles *config.Files var configEtcd *config.Etcd if filesConfig.Path != "" { if files, err := filesConfig.Open(); err != nil { log.Fatalf("config:Files.Open: %s\n", err) } else { configFiles = files log.Printf("config:Files.Open: %s\n", configFiles) } if configs, err := configFiles.Scan(); err != nil { log.Fatalf("config:Files.Scan: %s\n", err) } else { log.Printf("config:Files.Scan: %d configs\n", len(configs)) // iterate initial set of services for _, cfg := range configs { services.NewConfig(cfg) } } } if etcdConfig.Prefix != "" { if etcd, err := etcdConfig.Open(); err != nil { log.Fatalf("config:etcd.Open: %s\n", err) } else { configEtcd = etcd log.Printf("config:etcd.Open: %s\n", configEtcd) } if configs, err := configEtcd.Scan(); err != nil { log.Fatalf("config:Etcd.Scan: %s\n", err) } else { log.Printf("config:Etcd.Scan: %d configs\n", len(configs)) // iterate initial set of services for _, cfg := range configs { services.NewConfig(cfg) } } } // sync if ipvsDriver, err := services.SyncIPVS(ipvsConfig); err != nil { log.Fatalf("SyncIPVS: %s\n", err) } else { if ipvsConfigPrint { ipvsDriver.Print() } } // advertise if advertiseConfig.RouteName == "" || configEtcd == nil { } else if err := configEtcd.AdvertiseRoute(advertiseConfig); err != nil { log.Fatalf("config:Etcd.AdvertiseRoute: %v\n", err) } else { log.Printf("config:Etcd.AdvertiseRoute: %v\n", advertiseConfig) } if configEtcd != nil { // read channel for changes log.Printf("config:Etcd.Sync...\n") for event := range configEtcd.Sync() { log.Printf("config.Sync: %+v\n", event) services.ConfigEvent(event) } } log.Printf("Exit\n") }
package cmd // filesCmdGroup represents the instances command import ( "encoding/json" "errors" "fmt" "os" "text/tabwriter" "github.com/cozy/cozy-stack/client" "github.com/cozy/cozy-stack/pkg/config" "github.com/cozy/cozy-stack/pkg/consts" "github.com/spf13/cobra" ) var errAppsMissingDomain = errors.New("Missing --domain flag, or COZY_DOMAIN env variable") var flagAppsDomain string var flagAllDomains bool var flagAppsDeactivated bool var flagKonnectorAccountID string var flagKonnectorsParameters string var webappsCmdGroup = &cobra.Command{ Use: "apps [command]", Short: "Interact with the applications", Long: ` cozy-stack apps allows to interact with the cozy applications. It provides commands to install or update applications on a cozy. `, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Usage() }, } var installWebappCmd = &cobra.Command{ Use: "install [slug] [sourceurl]", Short: `Install an application with the specified slug name from the given source URL.`, Example: "$ cozy-stack apps install --domain cozy.tools:8080 drive 'git://github.com/cozy/cozy-drive.git#latest-drive'", Long: "[Some schemes](../../docs/apps.md#sources) are allowed as `[sourceurl]`.", RunE: func(cmd *cobra.Command, args []string) error { return installApp(cmd, args, consts.Apps) }, } var updateWebappCmd = &cobra.Command{ Use: "update [slug] [sourceurl]", Short: "Update the application with the specified slug name.", Aliases: []string{"upgrade"}, RunE: func(cmd *cobra.Command, args []string) error { return updateApp(cmd, args, consts.Apps) }, } var uninstallWebappCmd = &cobra.Command{ Use: "uninstall [slug]", Short: "Uninstall the application with the specified slug name.", Aliases: []string{"rm"}, RunE: func(cmd *cobra.Command, args []string) error { return uninstallApp(cmd, args, consts.Apps) }, } var lsWebappsCmd = &cobra.Command{ Use: "ls", Short: "List the installed applications.", RunE: func(cmd *cobra.Command, args []string) error { return lsApps(cmd, args, consts.Apps) }, } var showWebappCmd = &cobra.Command{ Use: "show [slug]", Short: "Show the application attributes", RunE: func(cmd *cobra.Command, args []string) error { return showApp(cmd, args, consts.Apps) }, } var showWebappTriggersCmd = &cobra.Command{ Use: "show-triggers [slug]", Short: "Show the application triggers", RunE: func(cmd *cobra.Command, args []string) error { return showWebAppTriggers(cmd, args, consts.Apps) }, } var showKonnectorCmd = &cobra.Command{ Use: "show [slug]", Short: "Show the application attributes", RunE: func(cmd *cobra.Command, args []string) error { return showApp(cmd, args, consts.Konnectors) }, } var konnectorsCmdGroup = &cobra.Command{ Use: "konnectors [command]", Short: "Interact with the konnectors", Long: ` cozy-stack konnectors allows to interact with the cozy konnectors. It provides commands to install or update applications on a cozy. `, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Usage() }, } var installKonnectorCmd = &cobra.Command{ Use: "install [slug] [sourceurl]", Short: `Install a konnector with the specified slug name from the given source URL.`, Example: "$ cozy-stack konnectors install --domain cozy.tools:8080 trainline 'git://github.com/cozy/cozy-konnector-trainline.git#build'", RunE: func(cmd *cobra.Command, args []string) error { return installApp(cmd, args, consts.Konnectors) }, } var updateKonnectorCmd = &cobra.Command{ Use: "update [slug] [sourceurl]", Short: "Update the konnector with the specified slug name.", Aliases: []string{"upgrade"}, RunE: func(cmd *cobra.Command, args []string) error { return updateApp(cmd, args, consts.Konnectors) }, } var uninstallKonnectorCmd = &cobra.Command{ Use: "uninstall [slug]", Short: "Uninstall the konnector with the specified slug name.", Aliases: []string{"rm"}, RunE: func(cmd *cobra.Command, args []string) error { return uninstallApp(cmd, args, consts.Konnectors) }, } var lsKonnectorsCmd = &cobra.Command{ Use: "ls", Short: "List the installed konnectors.", RunE: func(cmd *cobra.Command, args []string) error { return lsApps(cmd, args, consts.Konnectors) }, } var runKonnectorsCmd = &cobra.Command{ Use: "run [slug]", Short: "Run a konnector.", Long: "Run a konnector named with specified slug using the specified options.", RunE: func(cmd *cobra.Command, args []string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } slug := args[0] c := newClient(flagAppsDomain, consts.Jobs+":POST:konnector:worker", consts.Triggers, consts.Files, consts.Accounts, ) ts, err := c.GetTriggers("konnector") if err != nil { return err } type localTrigger struct { id string accountID string } var triggers []*localTrigger for _, t := range ts { var msg struct { Slug string `json:"konnector"` Account string `json:"account"` } if err = json.Unmarshal(t.Attrs.Message, &msg); err != nil { return err } if msg.Slug == slug { triggers = append(triggers, &localTrigger{t.ID, msg.Account}) } } if len(triggers) == 0 { return fmt.Errorf("Could not find a konnector %q: "+ "it may be installed but it is not activated (no related trigger)", slug) } var trigger *localTrigger if len(triggers) > 1 || flagKonnectorAccountID != "" { if flagKonnectorAccountID == "" { // TODO: better multi-account support return errors.New("Found multiple konnectors with different accounts:" + "use the --account-id flag (support for better multi-accounts support in the CLI is still a work in progress)") } for _, t := range triggers { if t.accountID == flagKonnectorAccountID { trigger = t break } } if trigger == nil { return fmt.Errorf("Could not find konnector linked to account with id %q", flagKonnectorAccountID) } } else { trigger = triggers[0] } j, err := c.TriggerLaunch(trigger.id) if err != nil { return err } json, err := json.MarshalIndent(j, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil }, } func installApp(cmd *cobra.Command, args []string, appType string) error { if len(args) < 1 { return cmd.Usage() } slug := args[0] var source string if len(args) == 1 { s, ok := consts.AppsRegistry[slug] if !ok { return cmd.Usage() } source = s } else { source = args[1] } if flagAllDomains { return foreachDomains(func(in *client.Instance) error { c := newClient(in.Attrs.Domain, appType) _, err := c.InstallApp(&client.AppOptions{ AppType: appType, Slug: slug, SourceURL: source, Deactivated: flagAppsDeactivated, }) if err != nil { if err.Error() == "Application with same slug already exists" { return nil } return err } fmt.Printf("Application installed successfully on %s\n", in.Attrs.Domain) return nil }) } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } var overridenParameters *json.RawMessage if flagKonnectorsParameters != "" { tmp := json.RawMessage(flagKonnectorsParameters) overridenParameters = &tmp } c := newClient(flagAppsDomain, appType) app, err := c.InstallApp(&client.AppOptions{ AppType: appType, Slug: slug, SourceURL: source, Deactivated: flagAppsDeactivated, OverridenParameters: overridenParameters, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func updateApp(cmd *cobra.Command, args []string, appType string) error { if len(args) == 0 || len(args) > 2 { return cmd.Usage() } var src string if len(args) > 1 { src = args[1] } if flagAllDomains { return foreachDomains(func(in *client.Instance) error { c := newClient(in.Attrs.Domain, appType) _, err := c.UpdateApp(&client.AppOptions{ AppType: appType, Slug: args[0], SourceURL: src, }) if err != nil { if err.Error() == "Application is not installed" { return nil } return err } fmt.Printf("Application updated successfully on %s\n", in.Attrs.Domain) return nil }) } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } var overridenParameters *json.RawMessage if flagKonnectorsParameters != "" { tmp := json.RawMessage(flagKonnectorsParameters) overridenParameters = &tmp } c := newClient(flagAppsDomain, appType) app, err := c.UpdateApp(&client.AppOptions{ AppType: appType, Slug: args[0], SourceURL: src, OverridenParameters: overridenParameters, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func uninstallApp(cmd *cobra.Command, args []string, appType string) error { if len(args) != 1 { return cmd.Usage() } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } c := newClient(flagAppsDomain, appType) app, err := c.UninstallApp(&client.AppOptions{ AppType: appType, Slug: args[0], }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func showApp(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } c := newClient(flagAppsDomain, appType) app, err := c.GetApp(&client.AppOptions{ Slug: args[0], AppType: appType, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func showWebAppTriggers(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } c := newClient(flagAppsDomain, appType, consts.Triggers) app, err := c.GetApp(&client.AppOptions{ Slug: args[0], AppType: appType, }) if err != nil { return err } var triggerIds []string for _, service := range *app.Attrs.Services { triggerIds = append(triggerIds, service.TriggerID) } var triggers []*client.Trigger for _, triggerId := range triggerIds { trigger, err := c.GetTrigger(triggerId) if err != nil { return err } triggers = append(triggers, trigger) } json, err := json.MarshalIndent(triggers, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func lsApps(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } c := newClient(flagAppsDomain, appType) // TODO(pagination) apps, err := c.ListApps(appType) if err != nil { return err } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) for _, app := range apps { fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", app.Attrs.Slug, app.Attrs.Source, app.Attrs.Version, app.Attrs.State, ) } return w.Flush() } func foreachDomains(predicate func(*client.Instance) error) error { c := newAdminClient() // TODO(pagination): Make this iteration more robust list, err := c.ListInstances() if err != nil { return nil } var hasErr bool for _, i := range list { if err = predicate(i); err != nil { errPrintfln("%s: %s", i.Attrs.Domain, err) hasErr = true } } if hasErr { return errors.New("At least one error occured while executing this command") } return nil } func init() { domain := os.Getenv("COZY_DOMAIN") if domain == "" && config.IsDevRelease() { domain = "cozy.tools:8080" } webappsCmdGroup.PersistentFlags().StringVar(&flagAppsDomain, "domain", domain, "specify the domain name of the instance") webappsCmdGroup.PersistentFlags().BoolVar(&flagAllDomains, "all-domains", false, "work on all domains iterativelly") installWebappCmd.PersistentFlags().BoolVar(&flagAppsDeactivated, "ask-permissions", false, "specify that the application should not be activated after installation") runKonnectorsCmd.PersistentFlags().StringVar(&flagKonnectorAccountID, "account-id", "", "specify the account ID to use for running the konnector") webappsCmdGroup.AddCommand(lsWebappsCmd) webappsCmdGroup.AddCommand(showWebappCmd) webappsCmdGroup.AddCommand(showWebappTriggersCmd) webappsCmdGroup.AddCommand(installWebappCmd) webappsCmdGroup.AddCommand(updateWebappCmd) webappsCmdGroup.AddCommand(uninstallWebappCmd) konnectorsCmdGroup.PersistentFlags().StringVar(&flagAppsDomain, "domain", domain, "specify the domain name of the instance") konnectorsCmdGroup.PersistentFlags().StringVar(&flagKonnectorsParameters, "parameters", "", "override the parameters of the installed konnector") konnectorsCmdGroup.PersistentFlags().BoolVar(&flagAllDomains, "all-domains", false, "work on all domains iterativelly") konnectorsCmdGroup.AddCommand(lsKonnectorsCmd) konnectorsCmdGroup.AddCommand(showKonnectorCmd) konnectorsCmdGroup.AddCommand(installKonnectorCmd) konnectorsCmdGroup.AddCommand(updateKonnectorCmd) konnectorsCmdGroup.AddCommand(uninstallKonnectorCmd) konnectorsCmdGroup.AddCommand(runKonnectorsCmd) RootCmd.AddCommand(webappsCmdGroup) RootCmd.AddCommand(konnectorsCmdGroup) } feat: launch trigger via CLI package cmd // filesCmdGroup represents the instances command import ( "encoding/json" "errors" "fmt" "os" "text/tabwriter" "github.com/cozy/cozy-stack/client" "github.com/cozy/cozy-stack/pkg/config" "github.com/cozy/cozy-stack/pkg/consts" "github.com/spf13/cobra" ) var errAppsMissingDomain = errors.New("Missing --domain flag, or COZY_DOMAIN env variable") var flagAppsDomain string var flagAllDomains bool var flagAppsDeactivated bool var flagKonnectorAccountID string var flagKonnectorsParameters string var webappsCmdGroup = &cobra.Command{ Use: "apps [command]", Short: "Interact with the applications", Long: ` cozy-stack apps allows to interact with the cozy applications. It provides commands to install or update applications on a cozy. `, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Usage() }, } var triggersCmdGroup = &cobra.Command{ Use: "triggers [command]", Short: "Interact with the triggers", Long: ` cozy-stack apps allows to interact with the cozy triggers. It provides command to run a specific trigger. `, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Usage() }, } var installWebappCmd = &cobra.Command{ Use: "install [slug] [sourceurl]", Short: `Install an application with the specified slug name from the given source URL.`, Example: "$ cozy-stack apps install --domain cozy.tools:8080 drive 'git://github.com/cozy/cozy-drive.git#latest-drive'", Long: "[Some schemes](../../docs/apps.md#sources) are allowed as `[sourceurl]`.", RunE: func(cmd *cobra.Command, args []string) error { return installApp(cmd, args, consts.Apps) }, } var updateWebappCmd = &cobra.Command{ Use: "update [slug] [sourceurl]", Short: "Update the application with the specified slug name.", Aliases: []string{"upgrade"}, RunE: func(cmd *cobra.Command, args []string) error { return updateApp(cmd, args, consts.Apps) }, } var uninstallWebappCmd = &cobra.Command{ Use: "uninstall [slug]", Short: "Uninstall the application with the specified slug name.", Aliases: []string{"rm"}, RunE: func(cmd *cobra.Command, args []string) error { return uninstallApp(cmd, args, consts.Apps) }, } var lsWebappsCmd = &cobra.Command{ Use: "ls", Short: "List the installed applications.", RunE: func(cmd *cobra.Command, args []string) error { return lsApps(cmd, args, consts.Apps) }, } var showWebappCmd = &cobra.Command{ Use: "show [slug]", Short: "Show the application attributes", RunE: func(cmd *cobra.Command, args []string) error { return showApp(cmd, args, consts.Apps) }, } var showWebappTriggersCmd = &cobra.Command{ Use: "show-triggers [slug]", Short: "Show the application triggers", RunE: func(cmd *cobra.Command, args []string) error { return showWebAppTriggers(cmd, args, consts.Apps) }, } var showKonnectorCmd = &cobra.Command{ Use: "show [slug]", Short: "Show the application attributes", RunE: func(cmd *cobra.Command, args []string) error { return showApp(cmd, args, consts.Konnectors) }, } var konnectorsCmdGroup = &cobra.Command{ Use: "konnectors [command]", Short: "Interact with the konnectors", Long: ` cozy-stack konnectors allows to interact with the cozy konnectors. It provides commands to install or update applications on a cozy. `, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Usage() }, } var installKonnectorCmd = &cobra.Command{ Use: "install [slug] [sourceurl]", Short: `Install a konnector with the specified slug name from the given source URL.`, Example: "$ cozy-stack konnectors install --domain cozy.tools:8080 trainline 'git://github.com/cozy/cozy-konnector-trainline.git#build'", RunE: func(cmd *cobra.Command, args []string) error { return installApp(cmd, args, consts.Konnectors) }, } var updateKonnectorCmd = &cobra.Command{ Use: "update [slug] [sourceurl]", Short: "Update the konnector with the specified slug name.", Aliases: []string{"upgrade"}, RunE: func(cmd *cobra.Command, args []string) error { return updateApp(cmd, args, consts.Konnectors) }, } var uninstallKonnectorCmd = &cobra.Command{ Use: "uninstall [slug]", Short: "Uninstall the konnector with the specified slug name.", Aliases: []string{"rm"}, RunE: func(cmd *cobra.Command, args []string) error { return uninstallApp(cmd, args, consts.Konnectors) }, } var lsKonnectorsCmd = &cobra.Command{ Use: "ls", Short: "List the installed konnectors.", RunE: func(cmd *cobra.Command, args []string) error { return lsApps(cmd, args, consts.Konnectors) }, } var runKonnectorsCmd = &cobra.Command{ Use: "run [slug]", Short: "Run a konnector.", Long: "Run a konnector named with specified slug using the specified options.", RunE: func(cmd *cobra.Command, args []string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } slug := args[0] c := newClient(flagAppsDomain, consts.Jobs+":POST:konnector:worker", consts.Triggers, consts.Files, consts.Accounts, ) ts, err := c.GetTriggers("konnector") if err != nil { return err } type localTrigger struct { id string accountID string } var triggers []*localTrigger for _, t := range ts { var msg struct { Slug string `json:"konnector"` Account string `json:"account"` } if err = json.Unmarshal(t.Attrs.Message, &msg); err != nil { return err } if msg.Slug == slug { triggers = append(triggers, &localTrigger{t.ID, msg.Account}) } } if len(triggers) == 0 { return fmt.Errorf("Could not find a konnector %q: "+ "it may be installed but it is not activated (no related trigger)", slug) } var trigger *localTrigger if len(triggers) > 1 || flagKonnectorAccountID != "" { if flagKonnectorAccountID == "" { // TODO: better multi-account support return errors.New("Found multiple konnectors with different accounts:" + "use the --account-id flag (support for better multi-accounts support in the CLI is still a work in progress)") } for _, t := range triggers { if t.accountID == flagKonnectorAccountID { trigger = t break } } if trigger == nil { return fmt.Errorf("Could not find konnector linked to account with id %q", flagKonnectorAccountID) } } else { trigger = triggers[0] } j, err := c.TriggerLaunch(trigger.id) if err != nil { return err } json, err := json.MarshalIndent(j, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil }, } func installApp(cmd *cobra.Command, args []string, appType string) error { if len(args) < 1 { return cmd.Usage() } slug := args[0] var source string if len(args) == 1 { s, ok := consts.AppsRegistry[slug] if !ok { return cmd.Usage() } source = s } else { source = args[1] } if flagAllDomains { return foreachDomains(func(in *client.Instance) error { c := newClient(in.Attrs.Domain, appType) _, err := c.InstallApp(&client.AppOptions{ AppType: appType, Slug: slug, SourceURL: source, Deactivated: flagAppsDeactivated, }) if err != nil { if err.Error() == "Application with same slug already exists" { return nil } return err } fmt.Printf("Application installed successfully on %s\n", in.Attrs.Domain) return nil }) } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } var overridenParameters *json.RawMessage if flagKonnectorsParameters != "" { tmp := json.RawMessage(flagKonnectorsParameters) overridenParameters = &tmp } c := newClient(flagAppsDomain, appType) app, err := c.InstallApp(&client.AppOptions{ AppType: appType, Slug: slug, SourceURL: source, Deactivated: flagAppsDeactivated, OverridenParameters: overridenParameters, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func updateApp(cmd *cobra.Command, args []string, appType string) error { if len(args) == 0 || len(args) > 2 { return cmd.Usage() } var src string if len(args) > 1 { src = args[1] } if flagAllDomains { return foreachDomains(func(in *client.Instance) error { c := newClient(in.Attrs.Domain, appType) _, err := c.UpdateApp(&client.AppOptions{ AppType: appType, Slug: args[0], SourceURL: src, }) if err != nil { if err.Error() == "Application is not installed" { return nil } return err } fmt.Printf("Application updated successfully on %s\n", in.Attrs.Domain) return nil }) } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } var overridenParameters *json.RawMessage if flagKonnectorsParameters != "" { tmp := json.RawMessage(flagKonnectorsParameters) overridenParameters = &tmp } c := newClient(flagAppsDomain, appType) app, err := c.UpdateApp(&client.AppOptions{ AppType: appType, Slug: args[0], SourceURL: src, OverridenParameters: overridenParameters, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func uninstallApp(cmd *cobra.Command, args []string, appType string) error { if len(args) != 1 { return cmd.Usage() } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } c := newClient(flagAppsDomain, appType) app, err := c.UninstallApp(&client.AppOptions{ AppType: appType, Slug: args[0], }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func showApp(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } c := newClient(flagAppsDomain, appType) app, err := c.GetApp(&client.AppOptions{ Slug: args[0], AppType: appType, }) if err != nil { return err } json, err := json.MarshalIndent(app.Attrs, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func showWebAppTriggers(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } if len(args) < 1 { return cmd.Usage() } c := newClient(flagAppsDomain, appType, consts.Triggers) app, err := c.GetApp(&client.AppOptions{ Slug: args[0], AppType: appType, }) if err != nil { return err } var triggerIds []string for _, service := range *app.Attrs.Services { triggerIds = append(triggerIds, service.TriggerID) } var triggers []*client.Trigger for _, triggerId := range triggerIds { trigger, err := c.GetTrigger(triggerId) if err != nil { return err } triggers = append(triggers, trigger) } json, err := json.MarshalIndent(triggers, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } var launchTriggerCmd = &cobra.Command{ Use: "launch [triggerId]", Short: `Creates a job from a specific trigger`, Example: "$ cozy-stack triggers launch --domain cozy.tools:8080 748f42b65aca8c99ec2492eb660d1891", RunE: func(cmd *cobra.Command, args []string) error { return launchTrigger(cmd, args) }, } func launchTrigger(cmd *cobra.Command, args []string) error { if len(args) < 1 { return cmd.Usage() } if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } // Creates client c := newClient(flagAppsDomain, consts.Triggers) // Creates job j, err := c.TriggerLaunch(args[0]) if err != nil { return err } // Print JSON json, err := json.MarshalIndent(j, "", " ") if err != nil { return err } fmt.Println(string(json)) return nil } func lsApps(cmd *cobra.Command, args []string, appType string) error { if flagAppsDomain == "" { errPrintfln("%s", errAppsMissingDomain) return cmd.Usage() } c := newClient(flagAppsDomain, appType) // TODO(pagination) apps, err := c.ListApps(appType) if err != nil { return err } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) for _, app := range apps { fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", app.Attrs.Slug, app.Attrs.Source, app.Attrs.Version, app.Attrs.State, ) } return w.Flush() } func foreachDomains(predicate func(*client.Instance) error) error { c := newAdminClient() // TODO(pagination): Make this iteration more robust list, err := c.ListInstances() if err != nil { return nil } var hasErr bool for _, i := range list { if err = predicate(i); err != nil { errPrintfln("%s: %s", i.Attrs.Domain, err) hasErr = true } } if hasErr { return errors.New("At least one error occured while executing this command") } return nil } func init() { domain := os.Getenv("COZY_DOMAIN") if domain == "" && config.IsDevRelease() { domain = "cozy.tools:8080" } webappsCmdGroup.PersistentFlags().StringVar(&flagAppsDomain, "domain", domain, "specify the domain name of the instance") webappsCmdGroup.PersistentFlags().BoolVar(&flagAllDomains, "all-domains", false, "work on all domains iterativelly") installWebappCmd.PersistentFlags().BoolVar(&flagAppsDeactivated, "ask-permissions", false, "specify that the application should not be activated after installation") runKonnectorsCmd.PersistentFlags().StringVar(&flagKonnectorAccountID, "account-id", "", "specify the account ID to use for running the konnector") triggersCmdGroup.AddCommand(launchTriggerCmd) webappsCmdGroup.AddCommand(lsWebappsCmd) webappsCmdGroup.AddCommand(showWebappCmd) webappsCmdGroup.AddCommand(showWebappTriggersCmd) webappsCmdGroup.AddCommand(installWebappCmd) webappsCmdGroup.AddCommand(updateWebappCmd) webappsCmdGroup.AddCommand(uninstallWebappCmd) konnectorsCmdGroup.PersistentFlags().StringVar(&flagAppsDomain, "domain", domain, "specify the domain name of the instance") konnectorsCmdGroup.PersistentFlags().StringVar(&flagKonnectorsParameters, "parameters", "", "override the parameters of the installed konnector") konnectorsCmdGroup.PersistentFlags().BoolVar(&flagAllDomains, "all-domains", false, "work on all domains iterativelly") konnectorsCmdGroup.AddCommand(lsKonnectorsCmd) konnectorsCmdGroup.AddCommand(showKonnectorCmd) konnectorsCmdGroup.AddCommand(installKonnectorCmd) konnectorsCmdGroup.AddCommand(updateKonnectorCmd) konnectorsCmdGroup.AddCommand(uninstallKonnectorCmd) konnectorsCmdGroup.AddCommand(runKonnectorsCmd) RootCmd.AddCommand(triggersCmdGroup) RootCmd.AddCommand(webappsCmdGroup) RootCmd.AddCommand(konnectorsCmdGroup) }
package cmd import ( "fmt" "strings" "github.com/dtan4/valec/aws" "github.com/dtan4/valec/util" "github.com/pkg/errors" "github.com/spf13/cobra" ) // dumpCmd represents the dump command var dumpCmd = &cobra.Command{ Use: "dump NAMESPACE", Short: "Dump secrets in dotenv format", RunE: doDump, } var dumpOpts = struct { dotenvTemplate string override bool output string quote bool }{} func doDump(cmd *cobra.Command, args []string) error { if len(args) != 1 { return errors.New("Please specify namespace.") } namespace := args[0] secrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace) if err != nil { return errors.Wrap(err, "Failed to retrieve secrets.") } if len(secrets) == 0 { return errors.Errorf("Namespace %s does not exist.", namespace) } var dotenv []string if dumpOpts.dotenvTemplate == "" { dotenv, err = dumpAll(secrets, dumpOpts.quote) if err != nil { return errors.Wrap(err, "Failed to dump all secrets.") } } else { dotenv, err = dumpWithTemplate(secrets, dumpOpts.quote, dumpOpts.dotenvTemplate, dumpOpts.override) if err != nil { return errors.Wrap(err, "Failed to dump secrets with dotenv template.") } } if dumpOpts.output == "" { for _, line := range dotenv { fmt.Println(line) } } else { body := []byte(strings.Join(dotenv, "\n") + "\n") if dumpOpts.override { if err := util.WriteFile(dumpOpts.output, body); err != nil { return errors.Wrapf(err, "Failed to write dotenv file. filename=%s", dumpOpts.output) } } else { if err := util.WriteFileWithoutSection(dumpOpts.output, body); err != nil { return errors.Wrapf(err, "Failed to write dotenv file. filename=%s", dumpOpts.output) } } } return nil } func init() { RootCmd.AddCommand(dumpCmd) dumpCmd.Flags().BoolVar(&dumpOpts.override, "override", false, "Override values in existing template") dumpCmd.Flags().StringVarP(&dumpOpts.output, "output", "o", "", "File to flush dotenv") dumpCmd.Flags().BoolVarP(&dumpOpts.quote, "quote", "q", false, "Quote values") dumpCmd.Flags().StringVarP(&dumpOpts.dotenvTemplate, "template", "t", "", "Dotenv template") } Craete output file if it does not exist package cmd import ( "fmt" "os" "strings" "github.com/dtan4/valec/aws" "github.com/dtan4/valec/util" "github.com/pkg/errors" "github.com/spf13/cobra" ) // dumpCmd represents the dump command var dumpCmd = &cobra.Command{ Use: "dump NAMESPACE", Short: "Dump secrets in dotenv format", RunE: doDump, } var dumpOpts = struct { dotenvTemplate string override bool output string quote bool }{} func doDump(cmd *cobra.Command, args []string) error { if len(args) != 1 { return errors.New("Please specify namespace.") } namespace := args[0] secrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace) if err != nil { return errors.Wrap(err, "Failed to retrieve secrets.") } if len(secrets) == 0 { return errors.Errorf("Namespace %s does not exist.", namespace) } var dotenv []string if dumpOpts.dotenvTemplate == "" { dotenv, err = dumpAll(secrets, dumpOpts.quote) if err != nil { return errors.Wrap(err, "Failed to dump all secrets.") } } else { dotenv, err = dumpWithTemplate(secrets, dumpOpts.quote, dumpOpts.dotenvTemplate, dumpOpts.override) if err != nil { return errors.Wrap(err, "Failed to dump secrets with dotenv template.") } } if dumpOpts.output == "" { for _, line := range dotenv { fmt.Println(line) } } else { body := []byte(strings.Join(dotenv, "\n") + "\n") if _, err := os.Stat(dumpOpts.output); err != nil { if os.IsNotExist(err) { if err2 := util.WriteFile(dumpOpts.output, body); err != nil { return errors.Wrapf(err2, "Failed to write dotenv file. filename=%s", dumpOpts.output) } } else { return errors.Wrapf(err, "Failed to open dotenv file. filename=%s", dumpOpts.output) } } else { if dumpOpts.override { if err := util.WriteFile(dumpOpts.output, body); err != nil { return errors.Wrapf(err, "Failed to write dotenv file. filename=%s", dumpOpts.output) } } else { if err := util.WriteFileWithoutSection(dumpOpts.output, body); err != nil { return errors.Wrapf(err, "Failed to write dotenv file. filename=%s", dumpOpts.output) } } } } return nil } func init() { RootCmd.AddCommand(dumpCmd) dumpCmd.Flags().BoolVar(&dumpOpts.override, "override", false, "Override values in existing template") dumpCmd.Flags().StringVarP(&dumpOpts.output, "output", "o", "", "File to flush dotenv") dumpCmd.Flags().BoolVarP(&dumpOpts.quote, "quote", "q", false, "Quote values") dumpCmd.Flags().StringVarP(&dumpOpts.dotenvTemplate, "template", "t", "", "Dotenv template") }
package cmd import ( "encoding/json" "fmt" "strings" "github.com/akerl/prospectus/checks" "github.com/spf13/cobra" ) var listCmd = &cobra.Command{ Use: "list", Short: "list checks", RunE: listRunner, } func init() { rootCmd.AddCommand(listCmd) f := listCmd.Flags() f.Bool("json", false, "Print output as JSON") } func listRunner(cmd *cobra.Command, args []string) error { flags := cmd.Flags() flagJSON, err := flags.GetBool("json") if err != nil { return err } params := []string{"."} if len(args) != 0 { params = args } cs, err := checks.NewSet(params) if err != nil { return err } var output strings.Builder if flagJSON { outputBytes, err := json.MarshalIndent(cs, "", " ") if err != nil { return err } output.Write(outputBytes) } else { for _, item := range cs { output.WriteString(item.String()) } } fmt.Println(output.String()) return nil } fix list printing package cmd import ( "encoding/json" "fmt" "strings" "github.com/akerl/prospectus/checks" "github.com/spf13/cobra" ) var listCmd = &cobra.Command{ Use: "list", Short: "list checks", RunE: listRunner, } func init() { rootCmd.AddCommand(listCmd) f := listCmd.Flags() f.Bool("json", false, "Print output as JSON") } func listRunner(cmd *cobra.Command, args []string) error { flags := cmd.Flags() flagJSON, err := flags.GetBool("json") if err != nil { return err } params := []string{"."} if len(args) != 0 { params = args } cs, err := checks.NewSet(params) if err != nil { return err } if cs == nil { cs = checks.CheckSet{} } var output strings.Builder if flagJSON { outputBytes, err := json.MarshalIndent(cs, "", " ") if err != nil { return err } output.Write(outputBytes) } else { for _, item := range cs { output.WriteString(item.String()) output.WriteString("\n") } } fmt.Println(output.String()) return nil }
package cmd import ( "io" "strings" "os" "github.com/containerum/chkit/cmd/util" "github.com/containerum/chkit/pkg/client" "gopkg.in/urfave/cli.v2" ) var logsCommandAliases = []string{"log"} var commandLogs = &cli.Command{ Name: "logs", Aliases: logsCommandAliases, Description: `View pod logs`, Usage: `view pod logs. Aliases: ` + strings.Join(logsCommandAliases, ", "), UsageText: `logs pod_label [container] [--follow] [--prev] [--tail n]`, Before: func(ctx *cli.Context) error { if ctx.Bool("help") { return cli.ShowSubcommandHelp(ctx) } return setupAll(ctx) }, Action: func(ctx *cli.Context) error { client := util.GetClient(ctx) defer util.StoreClient(ctx, client) var podName string var containerName string switch ctx.NArg() { case 2: containerName = ctx.Args().Tail()[0] fallthrough case 1: podName = ctx.Args().First() default: cli.ShowSubcommandHelp(ctx) return nil } params := chClient.GetPodLogsParams{ Namespace: util.GetNamespace(ctx), Pod: podName, Container: containerName, Follow: ctx.Bool("follow"), Previous: ctx.Bool("previous"), Tail: ctx.Int("tail"), } rc, err := client.GetPodLogs(params) if err != nil { return err } defer rc.Close() io.Copy(os.Stdout, rc) return nil }, Flags: []cli.Flag{ &cli.BoolFlag{ Name: "follow", Aliases: []string{"f"}, Usage: `follow pod logs`, }, &cli.BoolFlag{ Name: "prev", Aliases: []string{"p"}, Usage: `show logs from previous instance (useful for crashes debugging)`, }, &cli.IntFlag{ Name: "tail", Aliases: []string{"t"}, Value: 100, Usage: `print last <value> log lines`, }, util.NamespaceFlag, }, } add logs line scanning package cmd import ( "bufio" "fmt" "strings" "github.com/containerum/chkit/pkg/chkitErrors" "github.com/sirupsen/logrus" "github.com/containerum/chkit/cmd/util" "github.com/containerum/chkit/pkg/client" "gopkg.in/urfave/cli.v2" ) const ( ErrUnableToReadLogs chkitErrors.Err = "unable to read logs" ) var logsCommandAliases = []string{"log"} var commandLogs = &cli.Command{ Name: "logs", Aliases: logsCommandAliases, Description: `View pod logs`, Usage: `view pod logs. Aliases: ` + strings.Join(logsCommandAliases, ", "), UsageText: `logs pod_label [container] [--follow] [--prev] [--tail n] [--quiet]`, Before: func(ctx *cli.Context) error { if ctx.Bool("help") { return cli.ShowSubcommandHelp(ctx) } return setupAll(ctx) }, Action: func(ctx *cli.Context) error { client := util.GetClient(ctx) defer util.StoreClient(ctx, client) var podName string var containerName string switch ctx.NArg() { case 2: containerName = ctx.Args().Tail()[0] fallthrough case 1: podName = ctx.Args().First() default: cli.ShowSubcommandHelp(ctx) return nil } params := chClient.GetPodLogsParams{ Namespace: util.GetNamespace(ctx), Pod: podName, Container: containerName, Follow: ctx.Bool("follow"), Previous: ctx.Bool("previous"), Tail: ctx.Int("tail"), } rc, err := client.GetPodLogs(params) if err != nil { return err } defer rc.Close() scanner := bufio.NewScanner(rc) var nLines uint64 for scanner.Scan() { if err := scanner.Err(); err != nil { err = ErrUnableToReadLogs.Wrap(err) logrus.WithError(err).Errorf("unable to scan logs byte stream") return err } fmt.Println(scanner.Text()) nLines++ } fmt.Printf("%d lines of logs read\n", nLines) return nil }, Flags: []cli.Flag{ &cli.BoolFlag{ Name: "quiet", Aliases: []string{"q"}, Usage: "print only logs and errors", Value: false, }, &cli.BoolFlag{ Name: "follow", Aliases: []string{"f"}, Usage: `follow pod logs`, }, &cli.BoolFlag{ Name: "prev", Aliases: []string{"p"}, Usage: `show logs from previous instance (useful for crashes debugging)`, }, &cli.IntFlag{ Name: "tail", Aliases: []string{"t"}, Value: 100, Usage: `print last <value> log lines`, }, util.NamespaceFlag, }, }
package main import ( "fmt" "github.com/urfave/cli" "github.com/zrepl/zrepl/jobrun" "github.com/zrepl/zrepl/rpc" "github.com/zrepl/zrepl/sshbytestream" "github.com/zrepl/zrepl/zfs" "io" "log" "os" "runtime/debug" "sync" "time" ) type Logger interface { Printf(format string, v ...interface{}) } var conf Config var runner *jobrun.JobRunner var logFlags int = log.LUTC | log.Ldate | log.Ltime var defaultLog Logger func main() { defer func() { e := recover() defaultLog.Printf("panic:\n%s\n\n", debug.Stack()) defaultLog.Printf("error: %t %s", e, e) os.Exit(1) }() app := cli.NewApp() app.Name = "zrepl" app.Usage = "replicate zfs datasets" app.EnableBashCompletion = true app.Flags = []cli.Flag{ cli.StringFlag{Name: "config"}, } app.Before = func(c *cli.Context) (err error) { defaultLog = log.New(os.Stderr, "", logFlags) if !c.GlobalIsSet("config") { return cli.NewExitError("config flag not set", 2) } if conf, err = ParseConfig(c.GlobalString("config")); err != nil { return cli.NewExitError(err, 2) } jobrunLogger := log.New(os.Stderr, "jobrun ", logFlags) runner = jobrun.NewJobRunner(jobrunLogger) return } app.Commands = []cli.Command{ { Name: "sink", Aliases: []string{"s"}, Usage: "start in sink mode", Flags: []cli.Flag{ cli.StringFlag{Name: "identity"}, cli.StringFlag{Name: "logfile"}, }, Action: doSink, }, { Name: "run", Aliases: []string{"r"}, Usage: "do replication", Action: doRun, }, } app.Run(os.Args) } func doSink(c *cli.Context) (err error) { if !c.IsSet("identity") { return cli.NewExitError("identity flag not set", 2) } identity := c.String("identity") var logOut io.Writer if c.IsSet("logfile") { logOut, err = os.OpenFile(c.String("logfile"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) if err != nil { return } } else { logOut = os.Stderr } var sshByteStream io.ReadWriteCloser if sshByteStream, err = sshbytestream.Incoming(); err != nil { return } findMapping := func(cm []ClientMapping) zfs.DatasetMapping { for i := range cm { if cm[i].From == identity { return cm[i].Mapping } } return nil } sinkLogger := log.New(logOut, fmt.Sprintf("sink[%s] ", identity), logFlags) handler := Handler{ Logger: sinkLogger, PushMapping: findMapping(conf.Sinks), PullMapping: findMapping(conf.PullACLs), } if err = rpc.ListenByteStreamRPC(sshByteStream, handler, sinkLogger); err != nil { //os.Exit(1) err = cli.NewExitError(err, 1) defaultLog.Printf("listenbytestreamerror: %#v\n", err) } return } func doRun(c *cli.Context) error { // Do every pull, do every push // Scheduling var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() runner.Start() }() for i := range conf.Pulls { pull := conf.Pulls[i] j := jobrun.Job{ Name: fmt.Sprintf("pull%d", i), Interval: time.Duration(5 * time.Second), Repeats: true, RunFunc: func(log jobrun.Logger) error { log.Printf("doing pull: %v", pull) return doPull(pull, c, log) }, } runner.AddJob(j) } for i := range conf.Pushs { push := conf.Pushs[i] j := jobrun.Job{ Name: fmt.Sprintf("push%d", i), Interval: time.Duration(5 * time.Second), Repeats: true, RunFunc: func(log jobrun.Logger) error { log.Printf("%v: %#v\n", time.Now(), push) return nil }, } runner.AddJob(j) } for { select { case job := <-runner.NotificationChan(): log.Printf("notificaiton on job %s: error=%v\n", job.Name, job.LastError) } } wg.Wait() return nil } func doPull(pull Pull, c *cli.Context, log jobrun.Logger) (err error) { if lt, ok := pull.From.Transport.(LocalTransport); ok { lt.SetHandler(Handler{ Logger: log, PullMapping: pull.Mapping, }) pull.From.Transport = lt log.Printf("fixing up local transport: %#v", pull.From.Transport) } var remote rpc.RPCRequester if remote, err = pull.From.Transport.Connect(); err != nil { return } fsr := rpc.FilesystemRequest{ Direction: rpc.DirectionPull, } var remoteFilesystems []zfs.DatasetPath if remoteFilesystems, err = remote.FilesystemRequest(fsr); err != nil { return } type RemoteLocalMapping struct { Remote zfs.DatasetPath Local zfs.DatasetPath LocalExists bool } replMapping := make(map[string]RemoteLocalMapping, len(remoteFilesystems)) localTraversal := zfs.NewDatasetPathForest() localExists, err := zfs.ZFSListFilesystemExists() if err != nil { log.Printf("cannot get local filesystems map: %s", err) return err } { log.Printf("mapping using %#v\n", pull.Mapping) for fs := range remoteFilesystems { var err error var localFs zfs.DatasetPath localFs, err = pull.Mapping.Map(remoteFilesystems[fs]) if err != nil { if err != zfs.NoMatchError { log.Printf("error mapping %s: %#v\n", remoteFilesystems[fs], err) return err } continue } m := RemoteLocalMapping{remoteFilesystems[fs], localFs, localExists(localFs)} replMapping[m.Local.ToString()] = m localTraversal.Add(m.Local) } } log.Printf("remoteFilesystems: %#v\nreplMapping: %#v\n", remoteFilesystems, replMapping) // per fs sync, assume sorted in top-down order TODO localTraversal.WalkTopDown(func(v zfs.DatasetPathVisit) bool { if v.FilledIn { if localExists(v.Path) { return true } log.Printf("creating fill-in dataset %s", v.Path) return false } m, ok := replMapping[v.Path.ToString()] if !ok { panic("internal inconsistency: replMapping should contain mapping for any path that was not filled in by WalkTopDown()") } log := func(format string, args ...interface{}) { log.Printf("[%s => %s]: %s", m.Remote.ToString(), m.Local.ToString(), fmt.Sprintf(format, args...)) } log("mapping: %#v\n", m) var versions []zfs.FilesystemVersion if m.LocalExists { if versions, err = zfs.ZFSListFilesystemVersions(m.Local); err != nil { log("cannot get filesystem versions, stopping...: %v\n", m.Local.ToString(), m, err) return false } } var theirVersions []zfs.FilesystemVersion theirVersions, err = remote.FilesystemVersionsRequest(rpc.FilesystemVersionsRequest{ Filesystem: m.Remote, }) if err != nil { log("cannot fetch remote filesystem versions, stopping: %s", err) return false } diff := zfs.MakeFilesystemDiff(versions, theirVersions) log("diff: %#v\n", diff) if diff.IncrementalPath == nil { log("performing initial sync, following policy: %#v", pull.InitialReplPolicy) if pull.InitialReplPolicy != InitialReplPolicyMostRecent { panic(fmt.Sprintf("policy %#v not implemented", pull.InitialReplPolicy)) } snapsOnly := make([]zfs.FilesystemVersion, 0, len(diff.MRCAPathRight)) for s := range diff.MRCAPathRight { if diff.MRCAPathRight[s].Type == zfs.Snapshot { snapsOnly = append(snapsOnly, diff.MRCAPathRight[s]) } } if len(snapsOnly) < 1 { log("cannot perform initial sync: no remote snapshots. stopping...") return false } r := rpc.InitialTransferRequest{ Filesystem: m.Remote, FilesystemVersion: snapsOnly[len(snapsOnly)-1], } log("requesting initial transfer") var stream io.Reader if stream, err = remote.InitialTransferRequest(r); err != nil { log("error initial transfer request, stopping...: %s", err) return false } log("received initial transfer request response. zfs recv...") if err = zfs.ZFSRecv(m.Local, stream, "-u"); err != nil { log("error receiving stream, stopping...: %s", err) return false } log("configuring properties of received filesystem") if err = zfs.ZFSSet(m.Local, "readonly", "on"); err != nil { } log("finished initial transfer") } else if len(diff.IncrementalPath) < 2 { log("remote and local are in sync") } else { log("incremental transfers using path: %#v", diff.IncrementalPath) for i := 0; i < len(diff.IncrementalPath)-1; i++ { from, to := diff.IncrementalPath[i], diff.IncrementalPath[i+1] log := func(format string, args ...interface{}) { log("[%s => %s]: %s", from.Name, to.Name, fmt.Sprintf(format, args...)) } r := rpc.IncrementalTransferRequest{ Filesystem: m.Remote, From: from, To: to, } log("requesting incremental transfer: %#v", r) var stream io.Reader if stream, err = remote.IncrementalTransferRequest(r); err != nil { log("error requesting incremental transfer, stopping...: %s", err.Error()) return false } log("receving incremental transfer") if err = zfs.ZFSRecv(m.Local, stream); err != nil { log("error receiving stream, stopping...: %s", err) return false } log("finished incremental transfer") } log("finished incremental transfer path") } return true }) return nil } cmd: dup2(logfile, stderr) if logfile set package main import ( "fmt" "github.com/urfave/cli" "github.com/zrepl/zrepl/jobrun" "github.com/zrepl/zrepl/rpc" "github.com/zrepl/zrepl/sshbytestream" "github.com/zrepl/zrepl/zfs" "golang.org/x/sys/unix" "io" "log" "os" "runtime/debug" "sync" "time" ) type Logger interface { Printf(format string, v ...interface{}) } var conf Config var runner *jobrun.JobRunner var logFlags int = log.LUTC | log.Ldate | log.Ltime var defaultLog Logger func main() { defer func() { e := recover() defaultLog.Printf("panic:\n%s\n\n", debug.Stack()) defaultLog.Printf("error: %t %s", e, e) os.Exit(1) }() app := cli.NewApp() app.Name = "zrepl" app.Usage = "replicate zfs datasets" app.EnableBashCompletion = true app.Flags = []cli.Flag{ cli.StringFlag{Name: "config"}, } app.Before = func(c *cli.Context) (err error) { defaultLog = log.New(os.Stderr, "", logFlags) if !c.GlobalIsSet("config") { return cli.NewExitError("config flag not set", 2) } if conf, err = ParseConfig(c.GlobalString("config")); err != nil { return cli.NewExitError(err, 2) } jobrunLogger := log.New(os.Stderr, "jobrun ", logFlags) runner = jobrun.NewJobRunner(jobrunLogger) return } app.Commands = []cli.Command{ { Name: "sink", Aliases: []string{"s"}, Usage: "start in sink mode", Flags: []cli.Flag{ cli.StringFlag{Name: "identity"}, cli.StringFlag{Name: "logfile"}, }, Action: doSink, }, { Name: "run", Aliases: []string{"r"}, Usage: "do replication", Action: doRun, }, } app.Run(os.Args) } func doSink(c *cli.Context) (err error) { if !c.IsSet("identity") { return cli.NewExitError("identity flag not set", 2) } identity := c.String("identity") var logOut io.Writer if c.IsSet("logfile") { var logFile *os.File logFile, err = os.OpenFile(c.String("logfile"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) if err != nil { return } if err = unix.Dup2(int(logFile.Fd()), int(os.Stderr.Fd())); err != nil { logFile.WriteString(fmt.Sprintf("error duping logfile to stderr: %s\n", err)) return } logOut = logFile } else { logOut = os.Stderr } var sshByteStream io.ReadWriteCloser if sshByteStream, err = sshbytestream.Incoming(); err != nil { return } findMapping := func(cm []ClientMapping) zfs.DatasetMapping { for i := range cm { if cm[i].From == identity { return cm[i].Mapping } } return nil } sinkLogger := log.New(logOut, fmt.Sprintf("sink[%s] ", identity), logFlags) handler := Handler{ Logger: sinkLogger, PushMapping: findMapping(conf.Sinks), PullMapping: findMapping(conf.PullACLs), } if err = rpc.ListenByteStreamRPC(sshByteStream, handler, sinkLogger); err != nil { //os.Exit(1) err = cli.NewExitError(err, 1) defaultLog.Printf("listenbytestreamerror: %#v\n", err) } return } func doRun(c *cli.Context) error { // Do every pull, do every push // Scheduling var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() runner.Start() }() for i := range conf.Pulls { pull := conf.Pulls[i] j := jobrun.Job{ Name: fmt.Sprintf("pull%d", i), Interval: time.Duration(5 * time.Second), Repeats: true, RunFunc: func(log jobrun.Logger) error { log.Printf("doing pull: %v", pull) return doPull(pull, c, log) }, } runner.AddJob(j) } for i := range conf.Pushs { push := conf.Pushs[i] j := jobrun.Job{ Name: fmt.Sprintf("push%d", i), Interval: time.Duration(5 * time.Second), Repeats: true, RunFunc: func(log jobrun.Logger) error { log.Printf("%v: %#v\n", time.Now(), push) return nil }, } runner.AddJob(j) } for { select { case job := <-runner.NotificationChan(): log.Printf("notificaiton on job %s: error=%v\n", job.Name, job.LastError) } } wg.Wait() return nil } func doPull(pull Pull, c *cli.Context, log jobrun.Logger) (err error) { if lt, ok := pull.From.Transport.(LocalTransport); ok { lt.SetHandler(Handler{ Logger: log, PullMapping: pull.Mapping, }) pull.From.Transport = lt log.Printf("fixing up local transport: %#v", pull.From.Transport) } var remote rpc.RPCRequester if remote, err = pull.From.Transport.Connect(); err != nil { return } fsr := rpc.FilesystemRequest{ Direction: rpc.DirectionPull, } var remoteFilesystems []zfs.DatasetPath if remoteFilesystems, err = remote.FilesystemRequest(fsr); err != nil { return } type RemoteLocalMapping struct { Remote zfs.DatasetPath Local zfs.DatasetPath LocalExists bool } replMapping := make(map[string]RemoteLocalMapping, len(remoteFilesystems)) localTraversal := zfs.NewDatasetPathForest() localExists, err := zfs.ZFSListFilesystemExists() if err != nil { log.Printf("cannot get local filesystems map: %s", err) return err } { log.Printf("mapping using %#v\n", pull.Mapping) for fs := range remoteFilesystems { var err error var localFs zfs.DatasetPath localFs, err = pull.Mapping.Map(remoteFilesystems[fs]) if err != nil { if err != zfs.NoMatchError { log.Printf("error mapping %s: %#v\n", remoteFilesystems[fs], err) return err } continue } m := RemoteLocalMapping{remoteFilesystems[fs], localFs, localExists(localFs)} replMapping[m.Local.ToString()] = m localTraversal.Add(m.Local) } } log.Printf("remoteFilesystems: %#v\nreplMapping: %#v\n", remoteFilesystems, replMapping) // per fs sync, assume sorted in top-down order TODO localTraversal.WalkTopDown(func(v zfs.DatasetPathVisit) bool { if v.FilledIn { if localExists(v.Path) { return true } log.Printf("creating fill-in dataset %s", v.Path) return false } m, ok := replMapping[v.Path.ToString()] if !ok { panic("internal inconsistency: replMapping should contain mapping for any path that was not filled in by WalkTopDown()") } log := func(format string, args ...interface{}) { log.Printf("[%s => %s]: %s", m.Remote.ToString(), m.Local.ToString(), fmt.Sprintf(format, args...)) } log("mapping: %#v\n", m) var versions []zfs.FilesystemVersion if m.LocalExists { if versions, err = zfs.ZFSListFilesystemVersions(m.Local); err != nil { log("cannot get filesystem versions, stopping...: %v\n", m.Local.ToString(), m, err) return false } } var theirVersions []zfs.FilesystemVersion theirVersions, err = remote.FilesystemVersionsRequest(rpc.FilesystemVersionsRequest{ Filesystem: m.Remote, }) if err != nil { log("cannot fetch remote filesystem versions, stopping: %s", err) return false } diff := zfs.MakeFilesystemDiff(versions, theirVersions) log("diff: %#v\n", diff) if diff.IncrementalPath == nil { log("performing initial sync, following policy: %#v", pull.InitialReplPolicy) if pull.InitialReplPolicy != InitialReplPolicyMostRecent { panic(fmt.Sprintf("policy %#v not implemented", pull.InitialReplPolicy)) } snapsOnly := make([]zfs.FilesystemVersion, 0, len(diff.MRCAPathRight)) for s := range diff.MRCAPathRight { if diff.MRCAPathRight[s].Type == zfs.Snapshot { snapsOnly = append(snapsOnly, diff.MRCAPathRight[s]) } } if len(snapsOnly) < 1 { log("cannot perform initial sync: no remote snapshots. stopping...") return false } r := rpc.InitialTransferRequest{ Filesystem: m.Remote, FilesystemVersion: snapsOnly[len(snapsOnly)-1], } log("requesting initial transfer") var stream io.Reader if stream, err = remote.InitialTransferRequest(r); err != nil { log("error initial transfer request, stopping...: %s", err) return false } log("received initial transfer request response. zfs recv...") if err = zfs.ZFSRecv(m.Local, stream, "-u"); err != nil { log("error receiving stream, stopping...: %s", err) return false } log("configuring properties of received filesystem") if err = zfs.ZFSSet(m.Local, "readonly", "on"); err != nil { } log("finished initial transfer") } else if len(diff.IncrementalPath) < 2 { log("remote and local are in sync") } else { log("incremental transfers using path: %#v", diff.IncrementalPath) for i := 0; i < len(diff.IncrementalPath)-1; i++ { from, to := diff.IncrementalPath[i], diff.IncrementalPath[i+1] log := func(format string, args ...interface{}) { log("[%s => %s]: %s", from.Name, to.Name, fmt.Sprintf(format, args...)) } r := rpc.IncrementalTransferRequest{ Filesystem: m.Remote, From: from, To: to, } log("requesting incremental transfer: %#v", r) var stream io.Reader if stream, err = remote.IncrementalTransferRequest(r); err != nil { log("error requesting incremental transfer, stopping...: %s", err.Error()) return false } log("receving incremental transfer") if err = zfs.ZFSRecv(m.Local, stream); err != nil { log("error receiving stream, stopping...: %s", err) return false } log("finished incremental transfer") } log("finished incremental transfer path") } return true }) return nil }
//go:build ignore // +build ignore /* * Copyright (c) 2021 The GoPlus Authors (goplus.org). All rights reserved. * * 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 main import ( "bytes" "flag" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" ) func checkPathExist(path string, isDir bool) bool { stat, err := os.Stat(path) isExists := !os.IsNotExist(err) if isDir { return isExists && stat.IsDir() } return isExists && !stat.IsDir() } // Path returns single path to check type Path struct { path string isDir bool } func (p *Path) checkExists(rootDir string) bool { absPath := filepath.Join(rootDir, p.path) return checkPathExist(absPath, p.isDir) } func getGopRoot() string { pwd, _ := os.Getwd() pathsToCheck := []Path{ {path: "cmd/gop", isDir: true}, {path: "builtin", isDir: true}, {path: "go.mod", isDir: false}, {path: "go.sum", isDir: false}, } for _, path := range pathsToCheck { if !path.checkExists(pwd) { println("Error: This script should be run at the root directory of gop repository.") os.Exit(1) } } return pwd } var gopRoot = getGopRoot() var initCommandExecuteEnv = os.Environ() var commandExecuteEnv = initCommandExecuteEnv var gopBinFiles = []string{"gop", "gopfmt"} func execCommand(command string, arg ...string) (string, string, error) { var stdout, stderr bytes.Buffer cmd := exec.Command(command, arg...) cmd.Stdout = &stdout cmd.Stderr = &stderr cmd.Env = commandExecuteEnv err := cmd.Run() return stdout.String(), stderr.String(), err } func getRevCommit(tag string) string { commit, stderr, err := execCommand("git", "rev-parse", "--verify", tag) if err != nil || stderr != "" { return "" } return strings.TrimRight(commit, "\n") } func getGitInfo() (string, bool) { gitDir := filepath.Join(gopRoot, ".git") if checkPathExist(gitDir, true) { return getRevCommit("HEAD"), true } return "", false } func getBuildDateTime() string { now := time.Now() return now.Format("2006-01-02_15-04-05") } func getBuildVer() string { tagRet, tagErr, err := execCommand("git", "describe", "--tags") if err != nil || tagErr != "" { return "" } return strings.TrimRight(tagRet, "\n") } func getGopBuildFlags() string { defaultGopRoot := gopRoot if gopRootFinal := os.Getenv("GOPROOT_FINAL"); gopRootFinal != "" { defaultGopRoot = gopRootFinal } buildFlags := fmt.Sprintf("-X \"github.com/goplus/gop/env.defaultGopRoot=%s\"", defaultGopRoot) buildFlags += fmt.Sprintf(" -X \"github.com/goplus/gop/env.buildDate=%s\"", getBuildDateTime()) if commit, ok := getGitInfo(); ok { buildFlags += fmt.Sprintf(" -X github.com/goplus/gop/env.buildCommit=%s", commit) if buildVer := getBuildVer(); buildVer != "" { buildFlags += fmt.Sprintf(" -X github.com/goplus/gop/env.buildVersion=%s", buildVer) } } return buildFlags } func detectGopBinPath() string { return filepath.Join(gopRoot, "bin") } func detectGoBinPath() string { goBin, ok := os.LookupEnv("GOBIN") if ok { return goBin } goPath, ok := os.LookupEnv("GOPATH") if ok { list := filepath.SplitList(goPath) if len(list) > 0 { // Put in first directory of $GOPATH. return filepath.Join(list[0], "bin") } } homeDir, _ := os.UserHomeDir() return filepath.Join(homeDir, "go", "bin") } func linkGoplusToLocalBin() string { println("Start Linking.") gopBinPath := detectGopBinPath() goBinPath := detectGoBinPath() if !checkPathExist(gopBinPath, true) { log.Fatalf("Error: %s is not existed, you should build Go+ before linking.\n", gopBinPath) } if !checkPathExist(goBinPath, true) { if err := os.MkdirAll(goBinPath, 0755); err != nil { fmt.Printf("Error: target directory %s is not existed and we can't create one.\n", goBinPath) log.Fatalln(err) } } for _, file := range gopBinFiles { sourceFile := filepath.Join(gopBinPath, file) if !checkPathExist(sourceFile, false) { log.Fatalf("Error: %s is not existed, you should build Go+ before linking.\n", sourceFile) } targetLink := filepath.Join(goBinPath, file) if checkPathExist(targetLink, false) { // Delete existed one if err := os.Remove(targetLink); err != nil { log.Fatalln(err) } } if err := os.Symlink(sourceFile, targetLink); err != nil { log.Fatalln(err) } fmt.Printf("Link %s to %s successfully.\n", sourceFile, targetLink) } println("End linking.") return goBinPath } func buildGoplusTools(useGoProxy bool) { commandsDir := filepath.Join(gopRoot, "cmd") buildFlags := getGopBuildFlags() if useGoProxy { println("Info: we will use goproxy.cn as a Go proxy to accelerate installing process.") commandExecuteEnv = append(commandExecuteEnv, "GOPROXY=https://goproxy.cn,direct", ) } // Install Go+ binary files under current ./bin directory. gopBinPath := detectGopBinPath() if err := os.Mkdir(gopBinPath, 0755); err != nil { println("Error: Go+ can't create ./bin directory to put build assets.") log.Fatalln(err) } println("Installing Go+ tools...\n") os.Chdir(commandsDir) buildOutput, buildErr, err := execCommand("go", "build", "-o", gopBinPath, "-v", "-ldflags", buildFlags, "./...") print(buildErr) if err != nil { log.Fatalln(err) } print(buildOutput) installPath := linkGoplusToLocalBin() println("\nGo+ tools installed successfully!") if _, _, err := execCommand("gop", "version"); err != nil { showHelpPostInstall(installPath) } } func showHelpPostInstall(installPath string) { println("\nNEXT STEP:") println("\nWe just installed Go+ into the directory: ", installPath) message := ` To setup a better Go+ development environment, we recommend you add the above install directory into your PATH environment variable. ` println(message) } func runTestcases() { println("Start running testcases.") os.Chdir(gopRoot) coverage := "-coverprofile=coverage.txt" gopCommand := filepath.Join(detectGopBinPath(), "gop") if !checkPathExist(gopCommand, false) { println("Error: Go+ must be installed before running testcases.") os.Exit(1) } testOutput, testErr, err := execCommand(gopCommand, "test", coverage, "-covermode=atomic", "./...") println(testOutput) println(testErr) if err != nil { println(err.Error()) } println("End running testcases.") } func clean() { gopBinPath := detectGopBinPath() goBinPath := detectGoBinPath() // Clean links for _, file := range gopBinFiles { targetLink := filepath.Join(goBinPath, file) if checkPathExist(targetLink, false) { if err := os.Remove(targetLink); err != nil { log.Fatalln(err) } } } // Clean build binary files if checkPathExist(gopBinPath, true) { if err := os.RemoveAll(gopBinPath); err != nil { log.Fatalln(err) } } } func uninstall() { println("Uninstalling Go+ and related tools.") clean() println("Go+ and related tools uninstalled successfully.") } func isInChina() bool { const prefix = "LANG=\"" out, errMsg, err := execCommand("locale") if err != nil || errMsg != "" { return false } if strings.HasPrefix(out, prefix) { out = out[len(prefix):] return strings.HasPrefix(out, "zh_CN") || strings.HasPrefix(out, "zh_HK") } return false } func main() { isInstall := flag.Bool("install", false, "Install Go+") isTest := flag.Bool("test", false, "Run testcases") isUninstall := flag.Bool("uninstall", false, "Uninstall Go+") isGoProxy := flag.Bool("proxy", false, "Set GOPROXY for people in China") isAutoProxy := flag.Bool("autoproxy", false, "Check to set GOPROXY automatically") flag.Parse() useGoProxy := *isGoProxy if !useGoProxy && *isAutoProxy { useGoProxy = isInChina() } flagActionMap := map[*bool]func(){ isInstall: func() { buildGoplusTools(useGoProxy) }, isUninstall: uninstall, isTest: runTestcases, } // Sort flags, for example: install flag should be checked earlier than test flag. flags := []*bool{isInstall, isTest, isUninstall} hasActionDone := false for _, flag := range flags { if *flag { flagActionMap[flag]() hasActionDone = true } } if !hasActionDone { println("Usage:\n") flag.PrintDefaults() } } mkdir gopBinPath check exists //go:build ignore // +build ignore /* * Copyright (c) 2021 The GoPlus Authors (goplus.org). All rights reserved. * * 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 main import ( "bytes" "flag" "fmt" "log" "os" "os/exec" "path/filepath" "strings" "time" ) func checkPathExist(path string, isDir bool) bool { stat, err := os.Stat(path) isExists := !os.IsNotExist(err) if isDir { return isExists && stat.IsDir() } return isExists && !stat.IsDir() } // Path returns single path to check type Path struct { path string isDir bool } func (p *Path) checkExists(rootDir string) bool { absPath := filepath.Join(rootDir, p.path) return checkPathExist(absPath, p.isDir) } func getGopRoot() string { pwd, _ := os.Getwd() pathsToCheck := []Path{ {path: "cmd/gop", isDir: true}, {path: "builtin", isDir: true}, {path: "go.mod", isDir: false}, {path: "go.sum", isDir: false}, } for _, path := range pathsToCheck { if !path.checkExists(pwd) { println("Error: This script should be run at the root directory of gop repository.") os.Exit(1) } } return pwd } var gopRoot = getGopRoot() var initCommandExecuteEnv = os.Environ() var commandExecuteEnv = initCommandExecuteEnv var gopBinFiles = []string{"gop", "gopfmt"} func execCommand(command string, arg ...string) (string, string, error) { var stdout, stderr bytes.Buffer cmd := exec.Command(command, arg...) cmd.Stdout = &stdout cmd.Stderr = &stderr cmd.Env = commandExecuteEnv err := cmd.Run() return stdout.String(), stderr.String(), err } func getRevCommit(tag string) string { commit, stderr, err := execCommand("git", "rev-parse", "--verify", tag) if err != nil || stderr != "" { return "" } return strings.TrimRight(commit, "\n") } func getGitInfo() (string, bool) { gitDir := filepath.Join(gopRoot, ".git") if checkPathExist(gitDir, true) { return getRevCommit("HEAD"), true } return "", false } func getBuildDateTime() string { now := time.Now() return now.Format("2006-01-02_15-04-05") } func getBuildVer() string { tagRet, tagErr, err := execCommand("git", "describe", "--tags") if err != nil || tagErr != "" { return "" } return strings.TrimRight(tagRet, "\n") } func getGopBuildFlags() string { defaultGopRoot := gopRoot if gopRootFinal := os.Getenv("GOPROOT_FINAL"); gopRootFinal != "" { defaultGopRoot = gopRootFinal } buildFlags := fmt.Sprintf("-X \"github.com/goplus/gop/env.defaultGopRoot=%s\"", defaultGopRoot) buildFlags += fmt.Sprintf(" -X \"github.com/goplus/gop/env.buildDate=%s\"", getBuildDateTime()) if commit, ok := getGitInfo(); ok { buildFlags += fmt.Sprintf(" -X github.com/goplus/gop/env.buildCommit=%s", commit) if buildVer := getBuildVer(); buildVer != "" { buildFlags += fmt.Sprintf(" -X github.com/goplus/gop/env.buildVersion=%s", buildVer) } } return buildFlags } func detectGopBinPath() string { return filepath.Join(gopRoot, "bin") } func detectGoBinPath() string { goBin, ok := os.LookupEnv("GOBIN") if ok { return goBin } goPath, ok := os.LookupEnv("GOPATH") if ok { list := filepath.SplitList(goPath) if len(list) > 0 { // Put in first directory of $GOPATH. return filepath.Join(list[0], "bin") } } homeDir, _ := os.UserHomeDir() return filepath.Join(homeDir, "go", "bin") } func linkGoplusToLocalBin() string { println("Start Linking.") gopBinPath := detectGopBinPath() goBinPath := detectGoBinPath() if !checkPathExist(gopBinPath, true) { log.Fatalf("Error: %s is not existed, you should build Go+ before linking.\n", gopBinPath) } if !checkPathExist(goBinPath, true) { if err := os.MkdirAll(goBinPath, 0755); err != nil { fmt.Printf("Error: target directory %s is not existed and we can't create one.\n", goBinPath) log.Fatalln(err) } } for _, file := range gopBinFiles { sourceFile := filepath.Join(gopBinPath, file) if !checkPathExist(sourceFile, false) { log.Fatalf("Error: %s is not existed, you should build Go+ before linking.\n", sourceFile) } targetLink := filepath.Join(goBinPath, file) if checkPathExist(targetLink, false) { // Delete existed one if err := os.Remove(targetLink); err != nil { log.Fatalln(err) } } if err := os.Symlink(sourceFile, targetLink); err != nil { log.Fatalln(err) } fmt.Printf("Link %s to %s successfully.\n", sourceFile, targetLink) } println("End linking.") return goBinPath } func buildGoplusTools(useGoProxy bool) { commandsDir := filepath.Join(gopRoot, "cmd") buildFlags := getGopBuildFlags() if useGoProxy { println("Info: we will use goproxy.cn as a Go proxy to accelerate installing process.") commandExecuteEnv = append(commandExecuteEnv, "GOPROXY=https://goproxy.cn,direct", ) } // Install Go+ binary files under current ./bin directory. gopBinPath := detectGopBinPath() if err := os.Mkdir(gopBinPath, 0755); err != nil && !os.IsExist(err) { println("Error: Go+ can't create ./bin directory to put build assets.") log.Fatalln(err) } println("Installing Go+ tools...\n") os.Chdir(commandsDir) buildOutput, buildErr, err := execCommand("go", "build", "-o", gopBinPath, "-v", "-ldflags", buildFlags, "./...") print(buildErr) if err != nil { log.Fatalln(err) } print(buildOutput) installPath := linkGoplusToLocalBin() println("\nGo+ tools installed successfully!") if _, _, err := execCommand("gop", "version"); err != nil { showHelpPostInstall(installPath) } } func showHelpPostInstall(installPath string) { println("\nNEXT STEP:") println("\nWe just installed Go+ into the directory: ", installPath) message := ` To setup a better Go+ development environment, we recommend you add the above install directory into your PATH environment variable. ` println(message) } func runTestcases() { println("Start running testcases.") os.Chdir(gopRoot) coverage := "-coverprofile=coverage.txt" gopCommand := filepath.Join(detectGopBinPath(), "gop") if !checkPathExist(gopCommand, false) { println("Error: Go+ must be installed before running testcases.") os.Exit(1) } testOutput, testErr, err := execCommand(gopCommand, "test", coverage, "-covermode=atomic", "./...") println(testOutput) println(testErr) if err != nil { println(err.Error()) } println("End running testcases.") } func clean() { gopBinPath := detectGopBinPath() goBinPath := detectGoBinPath() // Clean links for _, file := range gopBinFiles { targetLink := filepath.Join(goBinPath, file) if checkPathExist(targetLink, false) { if err := os.Remove(targetLink); err != nil { log.Fatalln(err) } } } // Clean build binary files if checkPathExist(gopBinPath, true) { if err := os.RemoveAll(gopBinPath); err != nil { log.Fatalln(err) } } } func uninstall() { println("Uninstalling Go+ and related tools.") clean() println("Go+ and related tools uninstalled successfully.") } func isInChina() bool { const prefix = "LANG=\"" out, errMsg, err := execCommand("locale") if err != nil || errMsg != "" { return false } if strings.HasPrefix(out, prefix) { out = out[len(prefix):] return strings.HasPrefix(out, "zh_CN") || strings.HasPrefix(out, "zh_HK") } return false } func main() { isInstall := flag.Bool("install", false, "Install Go+") isTest := flag.Bool("test", false, "Run testcases") isUninstall := flag.Bool("uninstall", false, "Uninstall Go+") isGoProxy := flag.Bool("proxy", false, "Set GOPROXY for people in China") isAutoProxy := flag.Bool("autoproxy", false, "Check to set GOPROXY automatically") flag.Parse() useGoProxy := *isGoProxy if !useGoProxy && *isAutoProxy { useGoProxy = isInChina() } flagActionMap := map[*bool]func(){ isInstall: func() { buildGoplusTools(useGoProxy) }, isUninstall: uninstall, isTest: runTestcases, } // Sort flags, for example: install flag should be checked earlier than test flag. flags := []*bool{isInstall, isTest, isUninstall} hasActionDone := false for _, flag := range flags { if *flag { flagActionMap[flag]() hasActionDone = true } } if !hasActionDone { println("Usage:\n") flag.PrintDefaults() } }
// Package cmd defines and implements command-line commands and flags // used by Ayi. Commands and flags are implemented using Cobra. // it is generated by cobra https://github.com/spf13/cobra/tree/master/cobra // and modified following https://github.com/spf13/hugo/blob/master/commands/hugo.go package cmd import ( "fmt" "os" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/dyweb/Ayi/util" ) // Flags that are to be added to commands. var cfgFile string var ( version bool verbose bool ) // local shortcut shared among the whole cmd package, only needs to define in one file var log = util.Logger // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "Ayi", Short: "Ayi makes your life easier", Long: `Ayi is a collection of small applications and tools that speed up your develop process`, Run: func(cmd *cobra.Command, args []string) { if version { versionCmd.Run(cmd, args) return } // FIXME: print the help here // FIXME: On Windows, it works in cmd, but does not work in Git Bash color.Green("Use 'Ayi help' to see all commands") }, } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { // TODO: use logger fmt.Println(err) os.Exit(-1) } } func loadDefaultSettings() { viper.SetDefault("Verbose", false) } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ayi.yaml)") RootCmd.PersistentFlags().BoolVar(&version, "version", false, "show current version") RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.SetConfigName(".ayi") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.AddConfigPath(".") // adding current folder as second search path viper.AutomaticEnv() // read in environment variables that match err := viper.ReadInConfig() if verbose { util.UseVerboseLog() } if err == nil { log.WithField("file", viper.ConfigFileUsed()).Debug("Config file found") } else { log.Debug("Config file not found!") } loadDefaultSettings() // Update value from command line TODO: does viper support parse flag directly viper.Set("Verbose", verbose) } [lib][cobra] error message printed twice - see https://github.com/spf13/cobra/issues/304 and #44 - command might be a special case // Package cmd defines and implements command-line commands and flags // used by Ayi. Commands and flags are implemented using Cobra. // it is generated by cobra https://github.com/spf13/cobra/tree/master/cobra // and modified following https://github.com/spf13/hugo/blob/master/commands/hugo.go package cmd import ( "os" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/dyweb/Ayi/util" ) // Flags that are to be added to commands. var cfgFile string var ( version bool verbose bool ) // local shortcut shared among the whole cmd package, only needs to define in one file var log = util.Logger // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "Ayi", Short: "Ayi makes your life easier", Long: `Ayi is a collection of small applications and tools that speed up your develop process`, Run: func(cmd *cobra.Command, args []string) { if version { versionCmd.Run(cmd, args) return } // FIXME: print the help here // FIXME: On Windows, it works in cmd, but does not work in Git Bash color.Green("Use 'Ayi help' to see all commands") }, } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { // TODO: use logger // https://github.com/spf13/cobra/issues/304 // error message is printed twice for command not found // fmt.Println(err) os.Exit(-1) } } func loadDefaultSettings() { viper.SetDefault("Verbose", false) } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ayi.yaml)") RootCmd.PersistentFlags().BoolVar(&version, "version", false, "show current version") RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.SetConfigName(".ayi") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.AddConfigPath(".") // adding current folder as second search path viper.AutomaticEnv() // read in environment variables that match err := viper.ReadInConfig() if verbose { util.UseVerboseLog() } if err == nil { log.WithField("file", viper.ConfigFileUsed()).Debug("Config file found") } else { log.Debug("Config file not found!") } loadDefaultSettings() // Update value from command line TODO: does viper support parse flag directly viper.Set("Verbose", verbose) }
// Copyright © 2017 NAME HERE <EMAIL ADDRESS> // // 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" "os" "github.com/spf13/cobra" "github.com/sbueringer/kubernetes-rbacq/query" ) var RootCmd = &cobra.Command{ Use: "rbacq", Short: "rbacq simplifies querying the Kubernetes RBAC API", Long: `rbacq simplifies querying the Kubernetes RBAC API`, } func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { cobra.OnInitialize(query.InitKubeCfg) RootCmd.PersistentFlags().StringVarP(&query.KubeCfgFile, "kubeconfig", "k", os.Getenv("HOME")+"\\.kube\\config", "Path to the kubeconfig file to use for CLI requests") RootCmd.PersistentFlags().StringVarP(&query.Namespace, "namespace", "n", "default", "Specifies the Namespace in which to query") RootCmd.PersistentFlags().BoolVarP(&query.AllNamespaces, "all-namespaces", "a", false, "Specifies that all Namespaces should be queried (default \"false\")") RootCmd.PersistentFlags().BoolVarP(&query.System, "system", "s", false, "Show also System Objects (default \"false\")") RootCmd.PersistentFlags().BoolVarP(&query.ClusterWide, "cluster-wide", "c", false, "Search cluster-wide (which includes ClusterRoles & ClusterRolebindings)") } fixed Bug with Linux Path Separator // Copyright © 2017 NAME HERE <EMAIL ADDRESS> // // 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" "os" "github.com/spf13/cobra" "github.com/sbueringer/kubernetes-rbacq/query" ) var RootCmd = &cobra.Command{ Use: "rbacq", Short: "rbacq simplifies querying the Kubernetes RBAC API", Long: `rbacq simplifies querying the Kubernetes RBAC API`, } func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { cobra.OnInitialize(query.InitKubeCfg) RootCmd.PersistentFlags().StringVarP(&query.KubeCfgFile, "kubeconfig", "k", fmt.Sprintf("%s%s.kube%sconfig",os.Getenv("HOME"),string(os.PathSeparator), string(os.PathSeparator)), "Path to the kubeconfig file to use for CLI requests") RootCmd.PersistentFlags().StringVarP(&query.Namespace, "namespace", "n", "default", "Specifies the Namespace in which to query") RootCmd.PersistentFlags().BoolVarP(&query.AllNamespaces, "all-namespaces", "a", false, "Specifies that all Namespaces should be queried (default \"false\")") RootCmd.PersistentFlags().BoolVarP(&query.System, "system", "s", false, "Show also System Objects (default \"false\")") RootCmd.PersistentFlags().BoolVarP(&query.ClusterWide, "cluster-wide", "c", false, "Search cluster-wide (which includes ClusterRoles & ClusterRolebindings)") }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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" "errors" "fmt" "github.com/apache/incubator-openwhisk-client-go/whisk" "github.com/apache/incubator-openwhisk-wskdeploy/deployers" "github.com/apache/incubator-openwhisk-wskdeploy/utils" "github.com/apache/incubator-openwhisk-wskdeploy/wski18n" "github.com/spf13/cobra" "os" "path" "path/filepath" "regexp" "strings" ) var stderr = "" var stdout = "" var RootCmd = &cobra.Command{ Use: "wskdeploy", Short: "A tool set to help deploy your openwhisk packages in batch.", Long: `A tool to deploy openwhisk packages with a manifest and/or deployment yaml file. wskdeploy without any commands or flags deploys openwhisk package in the current directory if manifest.yaml exists. `, // Uncomment the following line if your bare application // has an action associated with it: RunE: RootCmdImp, } func RootCmdImp(cmd *cobra.Command, args []string) error { return Deploy() } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if utils.Flags.WithinOpenWhisk { err := substCmdArgs() if err != nil { utils.PrintOpenWhiskError(err) return } } if err := RootCmd.Execute(); err != nil { utils.PrintOpenWhiskError(err) os.Exit(-1) } else { if utils.Flags.WithinOpenWhisk { fmt.Print(`{"deploy":"success"}`) // maybe return report of what has been deployed. } } } func substCmdArgs() error { // Extract arguments from input JSON string // { "cmd": ".." } // space-separated arguments arg := os.Args[1] fmt.Println("arg is " + arg) // unmarshal the string to a JSON object var obj map[string]interface{} json.Unmarshal([]byte(arg), &obj) if v, ok := obj["cmd"].(string); ok { regex, _ := regexp.Compile("[ ]+") os.Args = regex.Split("wskdeploy "+strings.TrimSpace(v), -1) } else { return errors.New(wski18n.T("Missing cmd key")) } return nil } func init() { utils.Flags.WithinOpenWhisk = len(os.Getenv("__OW_API_HOST")) > 0 cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&utils.Flags.CfgFile, "config", "", "config file (default is $HOME/.wskprops)") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") RootCmd.Flags().StringVarP(&utils.Flags.ProjectPath, "pathpath", "p", ".", "path to serverless project") RootCmd.Flags().StringVarP(&utils.Flags.ManifestPath, "manifest", "m", "", "path to manifest file") RootCmd.Flags().StringVarP(&utils.Flags.DeploymentPath, "deployment", "d", "", "path to deployment file") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.Strict,"strict", "s", false, "allow user defined runtime version") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.UseInteractive, "allow-interactive", "i", false, "allow interactive prompts") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.UseDefaults, "allow-defaults", "a", false, "allow defaults") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.Verbose, "verbose", "v", false, "verbose output") RootCmd.PersistentFlags().StringVarP(&utils.Flags.ApiHost, "apihost", "", "", wski18n.T("whisk API HOST")) RootCmd.PersistentFlags().StringVarP(&utils.Flags.Namespace, "namespace", "n", "", wski18n.T("namespace")) RootCmd.PersistentFlags().StringVarP(&utils.Flags.Auth, "auth", "u", "", wski18n.T("authorization `KEY`")) RootCmd.PersistentFlags().StringVar(&utils.Flags.ApiVersion, "apiversion", "", wski18n.T("whisk API `VERSION`")) } // initConfig reads in config file and ENV variables if set. func initConfig() { userHome := utils.GetHomeDirectory() defaultPath := path.Join(userHome, whisk.DEFAULT_LOCAL_CONFIG) if utils.Flags.CfgFile != "" { // Read the file as a wskprops file, to check if it is valid. _, err := whisk.ReadProps(utils.Flags.CfgFile) if err != nil { utils.Flags.CfgFile = defaultPath utils.PrintOpenWhiskOutputln("Invalid config file detected, so by bdefault it is set to " + utils.Flags.CfgFile) } } else { utils.Flags.CfgFile = defaultPath } } func setSupportedRuntimes(apiHost string) { op, error := utils.ParseOpenWhisk(apiHost) if error == nil { utils.Rts = utils.ConvertToMap(op) } else { utils.Rts = utils.DefaultRts } } func Deploy() error { whisk.SetVerbose(utils.Flags.Verbose) // Verbose mode is the only mode for wskdeploy to turn on all the debug messages, so the currenty Verbose mode // also set debug mode to true. whisk.SetDebug(utils.Flags.Verbose) project_Path := strings.TrimSpace(utils.Flags.ProjectPath) if len(project_Path) == 0 { project_Path = utils.DEFAULT_PROJECT_PATH } projectPath, _ := filepath.Abs(project_Path) if utils.Flags.ManifestPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYaml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYaml) stdout = wski18n.T("Using {{.manifestPath}} for deployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYml) stdout = wski18n.T("Using {{.manifestPath}} for deployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else { stderr = wski18n.T("Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"projectPath": projectPath}) whisk.Debug(whisk.DbgError, stderr) errString := wski18n.T("Missing {{.yaml}}/{{.yml}} file. Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"yaml": utils.ManifestFileNameYaml, "yml": utils.ManifestFileNameYml, "projectPath": projectPath}) return utils.NewErrorManifestFileNotFound(errString) } whisk.Debug(whisk.DbgInfo, stdout) } if utils.Flags.DeploymentPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYaml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYaml) } else if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYml) } } if utils.MayExists(utils.Flags.ManifestPath) { var deployer = deployers.NewServiceDeployer() deployer.ProjectPath = projectPath deployer.ManifestPath = utils.Flags.ManifestPath deployer.DeploymentPath = utils.Flags.DeploymentPath deployer.IsDefault = utils.Flags.UseDefaults deployer.IsInteractive = utils.Flags.UseInteractive // master record of any dependency that has been downloaded deployer.DependencyMaster = make(map[string]utils.DependencyRecord) clientConfig, error := deployers.NewWhiskConfig(utils.Flags.CfgFile, utils.Flags.DeploymentPath, utils.Flags.ManifestPath, deployer.IsInteractive) if error != nil { return error } whiskClient, error := deployers.CreateNewClient(clientConfig) if error != nil { return error } deployer.Client = whiskClient deployer.ClientConfig = clientConfig // The auth, apihost and namespace have been chosen, so that we can check the supported runtimes here. setSupportedRuntimes(clientConfig.Host) err := deployer.ConstructDeploymentPlan() if err != nil { return err } err = deployer.Deploy() if err != nil { return err } else { return nil } } else { errString := wski18n.T("Manifest file is not found at the path [{{.filePath}}].\n", map[string]interface{}{"filePath": utils.Flags.ManifestPath}) whisk.Debug(whisk.DbgError, errString) return utils.NewErrorManifestFileNotFound(errString) } } func Undeploy() error { whisk.SetVerbose(utils.Flags.Verbose) // Verbose mode is the only mode for wskdeploy to turn on all the debug messages, so the currenty Verbose mode // also set debug mode to true. whisk.SetDebug(utils.Flags.Verbose) project_Path := strings.TrimSpace(utils.Flags.ProjectPath) if len(project_Path) == 0 { project_Path = utils.DEFAULT_PROJECT_PATH } projectPath, _ := filepath.Abs(project_Path) if utils.Flags.ManifestPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYaml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYaml) stdout = wski18n.T("Using {{.manifestPath}} for undeployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYml) stdout = wski18n.T("Using {{.manifestPath}} for undeployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else { stderr = wski18n.T("Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"projectPath": projectPath}) whisk.Debug(whisk.DbgError, stderr) errString := wski18n.T("Missing {{.yaml}}/{{.yml}} file. Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"yaml": utils.ManifestFileNameYaml, "yml": utils.ManifestFileNameYml, "projectPath": projectPath}) return utils.NewErrorManifestFileNotFound(errString) } whisk.Debug(whisk.DbgInfo, stdout) } if utils.Flags.DeploymentPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYaml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYaml) fmt.Printf("Using %s for undeployment \n", utils.Flags.DeploymentPath) } else if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYml) fmt.Printf("Using %s for undeployment \n", utils.Flags.DeploymentPath) } } if utils.FileExists(utils.Flags.ManifestPath) { var deployer = deployers.NewServiceDeployer() deployer.ProjectPath = utils.Flags.ProjectPath deployer.ManifestPath = utils.Flags.ManifestPath deployer.DeploymentPath = utils.Flags.DeploymentPath deployer.IsInteractive = utils.Flags.UseInteractive deployer.IsDefault = utils.Flags.UseDefaults clientConfig, error := deployers.NewWhiskConfig(utils.Flags.CfgFile, utils.Flags.DeploymentPath, utils.Flags.ManifestPath, deployer.IsInteractive) if error != nil { return error } whiskClient, error := deployers.CreateNewClient(clientConfig) if error != nil { return error } deployer.Client = whiskClient deployer.ClientConfig = clientConfig // The auth, apihost and namespace have been chosen, so that we can check the supported runtimes here. setSupportedRuntimes(clientConfig.Host) verifiedPlan, err := deployer.ConstructUnDeploymentPlan() err = deployer.UnDeploy(verifiedPlan) if err != nil { return err } else { return nil } } else { errString := wski18n.T("Manifest file is not found at the path [{{.filePath}}].\n", map[string]interface{}{"filePath": utils.Flags.ManifestPath}) whisk.Debug(whisk.DbgError, errString) return utils.NewErrorManifestFileNotFound(errString) } } fixing typo in cmdline arg - project (#564) /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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" "errors" "fmt" "github.com/apache/incubator-openwhisk-client-go/whisk" "github.com/apache/incubator-openwhisk-wskdeploy/deployers" "github.com/apache/incubator-openwhisk-wskdeploy/utils" "github.com/apache/incubator-openwhisk-wskdeploy/wski18n" "github.com/spf13/cobra" "os" "path" "path/filepath" "regexp" "strings" ) var stderr = "" var stdout = "" var RootCmd = &cobra.Command{ Use: "wskdeploy", Short: "A tool set to help deploy your openwhisk packages in batch.", Long: `A tool to deploy openwhisk packages with a manifest and/or deployment yaml file. wskdeploy without any commands or flags deploys openwhisk package in the current directory if manifest.yaml exists. `, // Uncomment the following line if your bare application // has an action associated with it: RunE: RootCmdImp, } func RootCmdImp(cmd *cobra.Command, args []string) error { return Deploy() } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if utils.Flags.WithinOpenWhisk { err := substCmdArgs() if err != nil { utils.PrintOpenWhiskError(err) return } } if err := RootCmd.Execute(); err != nil { utils.PrintOpenWhiskError(err) os.Exit(-1) } else { if utils.Flags.WithinOpenWhisk { fmt.Print(`{"deploy":"success"}`) // maybe return report of what has been deployed. } } } func substCmdArgs() error { // Extract arguments from input JSON string // { "cmd": ".." } // space-separated arguments arg := os.Args[1] fmt.Println("arg is " + arg) // unmarshal the string to a JSON object var obj map[string]interface{} json.Unmarshal([]byte(arg), &obj) if v, ok := obj["cmd"].(string); ok { regex, _ := regexp.Compile("[ ]+") os.Args = regex.Split("wskdeploy "+strings.TrimSpace(v), -1) } else { return errors.New(wski18n.T("Missing cmd key")) } return nil } func init() { utils.Flags.WithinOpenWhisk = len(os.Getenv("__OW_API_HOST")) > 0 cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&utils.Flags.CfgFile, "config", "", "config file (default is $HOME/.wskprops)") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") RootCmd.Flags().StringVarP(&utils.Flags.ProjectPath, "project", "p", ".", "path to serverless project") RootCmd.Flags().StringVarP(&utils.Flags.ManifestPath, "manifest", "m", "", "path to manifest file") RootCmd.Flags().StringVarP(&utils.Flags.DeploymentPath, "deployment", "d", "", "path to deployment file") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.Strict,"strict", "s", false, "allow user defined runtime version") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.UseInteractive, "allow-interactive", "i", false, "allow interactive prompts") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.UseDefaults, "allow-defaults", "a", false, "allow defaults") RootCmd.PersistentFlags().BoolVarP(&utils.Flags.Verbose, "verbose", "v", false, "verbose output") RootCmd.PersistentFlags().StringVarP(&utils.Flags.ApiHost, "apihost", "", "", wski18n.T("whisk API HOST")) RootCmd.PersistentFlags().StringVarP(&utils.Flags.Namespace, "namespace", "n", "", wski18n.T("namespace")) RootCmd.PersistentFlags().StringVarP(&utils.Flags.Auth, "auth", "u", "", wski18n.T("authorization `KEY`")) RootCmd.PersistentFlags().StringVar(&utils.Flags.ApiVersion, "apiversion", "", wski18n.T("whisk API `VERSION`")) } // initConfig reads in config file and ENV variables if set. func initConfig() { userHome := utils.GetHomeDirectory() defaultPath := path.Join(userHome, whisk.DEFAULT_LOCAL_CONFIG) if utils.Flags.CfgFile != "" { // Read the file as a wskprops file, to check if it is valid. _, err := whisk.ReadProps(utils.Flags.CfgFile) if err != nil { utils.Flags.CfgFile = defaultPath utils.PrintOpenWhiskOutputln("Invalid config file detected, so by bdefault it is set to " + utils.Flags.CfgFile) } } else { utils.Flags.CfgFile = defaultPath } } func setSupportedRuntimes(apiHost string) { op, error := utils.ParseOpenWhisk(apiHost) if error == nil { utils.Rts = utils.ConvertToMap(op) } else { utils.Rts = utils.DefaultRts } } func Deploy() error { whisk.SetVerbose(utils.Flags.Verbose) // Verbose mode is the only mode for wskdeploy to turn on all the debug messages, so the currenty Verbose mode // also set debug mode to true. whisk.SetDebug(utils.Flags.Verbose) project_Path := strings.TrimSpace(utils.Flags.ProjectPath) if len(project_Path) == 0 { project_Path = utils.DEFAULT_PROJECT_PATH } projectPath, _ := filepath.Abs(project_Path) if utils.Flags.ManifestPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYaml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYaml) stdout = wski18n.T("Using {{.manifestPath}} for deployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYml) stdout = wski18n.T("Using {{.manifestPath}} for deployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else { stderr = wski18n.T("Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"projectPath": projectPath}) whisk.Debug(whisk.DbgError, stderr) errString := wski18n.T("Missing {{.yaml}}/{{.yml}} file. Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"yaml": utils.ManifestFileNameYaml, "yml": utils.ManifestFileNameYml, "projectPath": projectPath}) return utils.NewErrorManifestFileNotFound(errString) } whisk.Debug(whisk.DbgInfo, stdout) } if utils.Flags.DeploymentPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYaml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYaml) } else if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYml) } } if utils.MayExists(utils.Flags.ManifestPath) { var deployer = deployers.NewServiceDeployer() deployer.ProjectPath = projectPath deployer.ManifestPath = utils.Flags.ManifestPath deployer.DeploymentPath = utils.Flags.DeploymentPath deployer.IsDefault = utils.Flags.UseDefaults deployer.IsInteractive = utils.Flags.UseInteractive // master record of any dependency that has been downloaded deployer.DependencyMaster = make(map[string]utils.DependencyRecord) clientConfig, error := deployers.NewWhiskConfig(utils.Flags.CfgFile, utils.Flags.DeploymentPath, utils.Flags.ManifestPath, deployer.IsInteractive) if error != nil { return error } whiskClient, error := deployers.CreateNewClient(clientConfig) if error != nil { return error } deployer.Client = whiskClient deployer.ClientConfig = clientConfig // The auth, apihost and namespace have been chosen, so that we can check the supported runtimes here. setSupportedRuntimes(clientConfig.Host) err := deployer.ConstructDeploymentPlan() if err != nil { return err } err = deployer.Deploy() if err != nil { return err } else { return nil } } else { errString := wski18n.T("Manifest file is not found at the path [{{.filePath}}].\n", map[string]interface{}{"filePath": utils.Flags.ManifestPath}) whisk.Debug(whisk.DbgError, errString) return utils.NewErrorManifestFileNotFound(errString) } } func Undeploy() error { whisk.SetVerbose(utils.Flags.Verbose) // Verbose mode is the only mode for wskdeploy to turn on all the debug messages, so the currenty Verbose mode // also set debug mode to true. whisk.SetDebug(utils.Flags.Verbose) project_Path := strings.TrimSpace(utils.Flags.ProjectPath) if len(project_Path) == 0 { project_Path = utils.DEFAULT_PROJECT_PATH } projectPath, _ := filepath.Abs(project_Path) if utils.Flags.ManifestPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYaml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYaml) stdout = wski18n.T("Using {{.manifestPath}} for undeployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else if _, err := os.Stat(path.Join(projectPath, utils.ManifestFileNameYml)); err == nil { utils.Flags.ManifestPath = path.Join(projectPath, utils.ManifestFileNameYml) stdout = wski18n.T("Using {{.manifestPath}} for undeployment.\n", map[string]interface{}{"manifestPath": utils.Flags.ManifestPath}) } else { stderr = wski18n.T("Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"projectPath": projectPath}) whisk.Debug(whisk.DbgError, stderr) errString := wski18n.T("Missing {{.yaml}}/{{.yml}} file. Manifest file not found at path {{.projectPath}}.\n", map[string]interface{}{"yaml": utils.ManifestFileNameYaml, "yml": utils.ManifestFileNameYml, "projectPath": projectPath}) return utils.NewErrorManifestFileNotFound(errString) } whisk.Debug(whisk.DbgInfo, stdout) } if utils.Flags.DeploymentPath == "" { if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYaml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYaml) fmt.Printf("Using %s for undeployment \n", utils.Flags.DeploymentPath) } else if _, err := os.Stat(path.Join(projectPath, utils.DeploymentFileNameYml)); err == nil { utils.Flags.DeploymentPath = path.Join(projectPath, utils.DeploymentFileNameYml) fmt.Printf("Using %s for undeployment \n", utils.Flags.DeploymentPath) } } if utils.FileExists(utils.Flags.ManifestPath) { var deployer = deployers.NewServiceDeployer() deployer.ProjectPath = utils.Flags.ProjectPath deployer.ManifestPath = utils.Flags.ManifestPath deployer.DeploymentPath = utils.Flags.DeploymentPath deployer.IsInteractive = utils.Flags.UseInteractive deployer.IsDefault = utils.Flags.UseDefaults clientConfig, error := deployers.NewWhiskConfig(utils.Flags.CfgFile, utils.Flags.DeploymentPath, utils.Flags.ManifestPath, deployer.IsInteractive) if error != nil { return error } whiskClient, error := deployers.CreateNewClient(clientConfig) if error != nil { return error } deployer.Client = whiskClient deployer.ClientConfig = clientConfig // The auth, apihost and namespace have been chosen, so that we can check the supported runtimes here. setSupportedRuntimes(clientConfig.Host) verifiedPlan, err := deployer.ConstructUnDeploymentPlan() err = deployer.UnDeploy(verifiedPlan) if err != nil { return err } else { return nil } } else { errString := wski18n.T("Manifest file is not found at the path [{{.filePath}}].\n", map[string]interface{}{"filePath": utils.Flags.ManifestPath}) whisk.Debug(whisk.DbgError, errString) return utils.NewErrorManifestFileNotFound(errString) } }
package cmd import ( "bytes" "fmt" "io/ioutil" "os" "github.com/Sirupsen/logrus" "github.com/spf13/cobra" "gopkg.in/yaml.v2" "github.com/emc-advanced-dev/unik/pkg/config" "github.com/emc-advanced-dev/unik/pkg/types" ) var clientConfigFile, host string var port int var RootCmd = &cobra.Command{ Use: "unik", Short: "The unikernel compilation, deployment, and management tool", Long: `Unik is a tool for compiling application source code into bootable disk images. Unik also runs and manages unikernel instances across infrastructures. Create a client configuration file with 'unik target' You may set a custom client configuration file w ith the global flag --client-config=<path>`, } func init() { RootCmd.PersistentFlags().StringVar(&clientConfigFile, "client-config", os.Getenv("HOME")+"/.unik/client-config.yaml", "client config file (default is $HOME/.unik/client-config.yaml)") RootCmd.PersistentFlags().StringVar(&host, "host", "", "<string, optional>: host/ip address of the host running the unik daemon") targetCmd.Flags().IntVar(&port, "port", 3000, "<int, optional>: port the daemon is running on (default: 3000)") } var clientConfig config.ClientConfig func readClientConfig() error { data, err := ioutil.ReadFile(clientConfigFile) if err != nil { logrus.WithError(err).Errorf("failed to read client configuration file at " + clientConfigFile + `\n Try setting your config with 'unik target --host HOST_URL'`) return err } data = bytes.Replace(data, []byte("\n"), []byte{}, -1) if err := yaml.Unmarshal(data, &clientConfig); err != nil { logrus.WithError(err).Errorf("failed to parse client configuration yaml at " + clientConfigFile + `\n Please ensure config file contains valid yaml.'\n Try setting your config with 'unik target --host HOST_URL'`) return err } return nil } func printImages(images ...*types.Image) { fmt.Printf("%-20s %-20s %-15s %-30s %-6s %-20s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "SIZE(MB)", "MOUNTPOINTS") for _, image := range images { printImage(image) } } func printImage(image *types.Image) { for i, deviceMapping := range image.RunSpec.DeviceMappings { //ignore root device mount point if deviceMapping.MountPoint == "/" { image.RunSpec.DeviceMappings = append(image.RunSpec.DeviceMappings[:i], image.RunSpec.DeviceMappings[i+1:]...) } } if len(image.RunSpec.DeviceMappings) == 0 { fmt.Printf("%-20.20s %-20.20s %-15.15s %-30.30s %-8.0d \n", image.Name, image.Id, image.Infrastructure, image.Created.String(), image.SizeMb) } else if len(image.RunSpec.DeviceMappings) > 0 { fmt.Printf("%-20.20s %-20.20s %-15.15s %-30.30s %-8.0d %-20.20s\n", image.Name, image.Id, image.Infrastructure, image.Created.String(), image.SizeMb, image.RunSpec.DeviceMappings[0].MountPoint) if len(image.RunSpec.DeviceMappings) > 1 { for i := 1; i < len(image.RunSpec.DeviceMappings); i++ { fmt.Printf("%102s\n", image.RunSpec.DeviceMappings[i].MountPoint) } } } } func printInstances(instance ...*types.Instance) { fmt.Printf("%-15s %-20s %-14s %-30s %-20s %-15s %-12s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "IMAGE", "IPADDRESS", "STATE") for _, instance := range instance { printInstance(instance) } } func printInstance(instance *types.Instance) { fmt.Printf("%-15.15s %-20.20s %-14.14s %-30.30s %-20.20v %-15.15s %-12.12s\n", instance.Name, instance.Id, instance.Infrastructure, instance.Created.String(), instance.ImageId, instance.IpAddress, instance.State) } func printVolumes(volume ...*types.Volume) { fmt.Printf("%-15.15s %-15.15s %-14.14s %-30.30s %-20.20v %-12.12s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "ATTACHED-INSTANCE", "SIZE(MB)") for _, volume := range volume { printVolume(volume) } } func printVolume(volume *types.Volume) { fmt.Printf("%-15.15s %-15.15s %-14.14s %-30.30s %-20.20v %-12.12d\n", volume.Name, volume.Id, volume.Infrastructure, volume.Created.String(), volume.Attachment, volume.SizeMb) } fix readClientConfig error message output package cmd import ( "bytes" "fmt" "io/ioutil" "os" "github.com/Sirupsen/logrus" "github.com/spf13/cobra" "gopkg.in/yaml.v2" "github.com/emc-advanced-dev/unik/pkg/config" "github.com/emc-advanced-dev/unik/pkg/types" ) var clientConfigFile, host string var port int var RootCmd = &cobra.Command{ Use: "unik", Short: "The unikernel compilation, deployment, and management tool", Long: `Unik is a tool for compiling application source code into bootable disk images. Unik also runs and manages unikernel instances across infrastructures. Create a client configuration file with 'unik target' You may set a custom client configuration file w ith the global flag --client-config=<path>`, } func init() { RootCmd.PersistentFlags().StringVar(&clientConfigFile, "client-config", os.Getenv("HOME")+"/.unik/client-config.yaml", "client config file (default is $HOME/.unik/client-config.yaml)") RootCmd.PersistentFlags().StringVar(&host, "host", "", "<string, optional>: host/ip address of the host running the unik daemon") targetCmd.Flags().IntVar(&port, "port", 3000, "<int, optional>: port the daemon is running on (default: 3000)") } var clientConfig config.ClientConfig func readClientConfig() error { data, err := ioutil.ReadFile(clientConfigFile) if err != nil { logrus.WithError(err).Errorf("failed to read client configuration file at " + clientConfigFile + ` Try setting your config with 'unik target --host HOST_URL'`) return err } data = bytes.Replace(data, []byte("\n"), []byte{}, -1) if err := yaml.Unmarshal(data, &clientConfig); err != nil { logrus.WithError(err).Errorf("failed to parse client configuration yaml at " + clientConfigFile + ` Please ensure config file contains valid yaml.'\n Try setting your config with 'unik target --host HOST_URL'`) return err } return nil } func printImages(images ...*types.Image) { fmt.Printf("%-20s %-20s %-15s %-30s %-6s %-20s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "SIZE(MB)", "MOUNTPOINTS") for _, image := range images { printImage(image) } } func printImage(image *types.Image) { for i, deviceMapping := range image.RunSpec.DeviceMappings { //ignore root device mount point if deviceMapping.MountPoint == "/" { image.RunSpec.DeviceMappings = append(image.RunSpec.DeviceMappings[:i], image.RunSpec.DeviceMappings[i+1:]...) } } if len(image.RunSpec.DeviceMappings) == 0 { fmt.Printf("%-20.20s %-20.20s %-15.15s %-30.30s %-8.0d \n", image.Name, image.Id, image.Infrastructure, image.Created.String(), image.SizeMb) } else if len(image.RunSpec.DeviceMappings) > 0 { fmt.Printf("%-20.20s %-20.20s %-15.15s %-30.30s %-8.0d %-20.20s\n", image.Name, image.Id, image.Infrastructure, image.Created.String(), image.SizeMb, image.RunSpec.DeviceMappings[0].MountPoint) if len(image.RunSpec.DeviceMappings) > 1 { for i := 1; i < len(image.RunSpec.DeviceMappings); i++ { fmt.Printf("%102s\n", image.RunSpec.DeviceMappings[i].MountPoint) } } } } func printInstances(instance ...*types.Instance) { fmt.Printf("%-15s %-20s %-14s %-30s %-20s %-15s %-12s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "IMAGE", "IPADDRESS", "STATE") for _, instance := range instance { printInstance(instance) } } func printInstance(instance *types.Instance) { fmt.Printf("%-15.15s %-20.20s %-14.14s %-30.30s %-20.20v %-15.15s %-12.12s\n", instance.Name, instance.Id, instance.Infrastructure, instance.Created.String(), instance.ImageId, instance.IpAddress, instance.State) } func printVolumes(volume ...*types.Volume) { fmt.Printf("%-15.15s %-15.15s %-14.14s %-30.30s %-20.20v %-12.12s\n", "NAME", "ID", "INFRASTRUCTURE", "CREATED", "ATTACHED-INSTANCE", "SIZE(MB)") for _, volume := range volume { printVolume(volume) } } func printVolume(volume *types.Volume) { fmt.Printf("%-15.15s %-15.15s %-14.14s %-30.30s %-20.20v %-12.12d\n", volume.Name, volume.Id, volume.Infrastructure, volume.Created.String(), volume.Attachment, volume.SizeMb) }
// // Copyright 2015 Gregory Trubetskoy. All Rights Reserved. // // 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. // // Data layout notes. // // So we store datapoints as an array, and we know the latest // timestamp. Every time we advance to the next point, so does the // latest timestamp. By knowing the latest timestamp and the size of // the array, we can identify which array element is last, it is: // slots_since_epoch % slots // // If we take a slot with a number slot_n, its distance from the // latest slot can be calculated by this formula: // // distance = (total_slots + last_slot_n - slot_n) % total_slots // // E.g. with total_slots 100, slot_n 55 and last_slot_n 50: // // (100 + 50 - 55) % 100 => 95 // // This means that if we advance forward from 55 by 95 slots, which // means at step 45 we'll reach the end of the array, and start from // the beginning, we'll arrive at 50. // // Or with total_slots 100, slot_n 45 and last_slot_n 50: // // (100 + 50 - 45) % 100 => 5 // package serde import ( "bytes" "database/sql" "fmt" "github.com/lib/pq" "github.com/tgres/tgres/dsl" "github.com/tgres/tgres/rrd" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) type pgSerDe struct { dbConn *sql.DB sql1, sql2, sql3, sql4, sql5, sql6, sql7, sql8, sql9 *sql.Stmt prefix string } func sqlOpen(a, b string) (*sql.DB, error) { return sql.Open(a, b) } func InitDb(connect_string, prefix string) (SerDe, error) { if dbConn, err := sql.Open("postgres", connect_string); err != nil { return nil, err } else { p := &pgSerDe{dbConn: dbConn, prefix: prefix} if err := p.dbConn.Ping(); err != nil { return nil, err } if err := p.createTablesIfNotExist(); err != nil { return nil, err } if err := p.prepareSqlStatements(); err != nil { return nil, err } return SerDe(p), nil } } // A hack to use the DB to see who else is connected func (p *pgSerDe) ListDbClientIps() ([]string, error) { const sql = "SELECT DISTINCT(client_addr) FROM pg_stat_activity" rows, err := p.dbConn.Query(sql) if err != nil { log.Printf("ListDbClientIps(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]string, 0) for rows.Next() { var addr *string if err := rows.Scan(&addr); err != nil { log.Printf("ListDbClientIps(): error scanning row: %v", err) return nil, err } if addr != nil { result = append(result, *addr) } } return result, nil } func (p *pgSerDe) MyDbAddr() (*string, error) { hostname, _ := os.Hostname() randToken := fmt.Sprintf("%s%d", hostname, rand.Intn(1000000000)) sql := fmt.Sprintf("SELECT client_addr FROM pg_stat_activity WHERE query LIKE '%%%s%%'", randToken) rows, err := p.dbConn.Query(sql) if err != nil { log.Printf("myPostgresAddr(): error querying database: %v", err) return nil, err } defer rows.Close() for rows.Next() { var addr *string if err := rows.Scan(&addr); err != nil { log.Printf("myPostgresAddr(): error scanning row: %v", err) return nil, err } if addr != nil { log.Printf("myPostgresAddr(): %s", *addr) return addr, nil } } return nil, nil } func (p *pgSerDe) prepareSqlStatements() error { var err error if p.sql1, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sts ts SET dp[$1:$2] = $3 WHERE rra_id = $4 AND n = $5", p.prefix)); err != nil { return err } if p.sql2, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]srra rra SET value = $1, unknown_ms = $2, latest = $3 WHERE id = $4", p.prefix)); err != nil { return err } if p.sql3, err = p.dbConn.Prepare(fmt.Sprintf("SELECT max(tg) mt, avg(r) ar FROM generate_series($1, $2, ($3)::interval) AS tg "+ "LEFT OUTER JOIN (SELECT t, r FROM %[1]stv tv WHERE ds_id = $4 AND rra_id = $5 "+ " AND t >= $6 AND t <= $7) s ON tg = s.t GROUP BY trunc((extract(epoch from tg)*1000-1))::bigint/$8 ORDER BY mt", p.prefix)); err != nil { return err } if p.sql4, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sds AS ds (name, step_ms, heartbeat_ms) VALUES ($1, $2, $3) "+ // PG 9.5 required. NB: DO NOTHING causes RETURNING to return nothing, so we're using this dummy UPDATE to work around. "ON CONFLICT (name) DO UPDATE SET step_ms = ds.step_ms "+ "RETURNING id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms", p.prefix)); err != nil { return err } if p.sql5, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]srra AS rra (ds_id, cf, steps_per_row, size, xff) VALUES ($1, $2, $3, $4, $5) "+ "ON CONFLICT (ds_id, cf, steps_per_row, size, xff) DO UPDATE SET ds_id = rra.ds_id "+ "RETURNING id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest", p.prefix)); err != nil { return err } if p.sql6, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sts (rra_id, n) VALUES ($1, $2) ON CONFLICT(rra_id, n) DO NOTHING", p.prefix)); err != nil { return err } if p.sql7, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sds SET lastupdate = $1, last_ds = $2, value = $3, unknown_ms = $4 WHERE id = $5", p.prefix)); err != nil { return err } if p.sql8, err = p.dbConn.Prepare(fmt.Sprintf("SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds AS ds WHERE id = $1", p.prefix)); err != nil { return err } if p.sql9, err = p.dbConn.Prepare(fmt.Sprintf("SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds AS ds WHERE name = $1", p.prefix)); err != nil { return err } return nil } func (p *pgSerDe) createTablesIfNotExist() error { create_sql := ` CREATE TABLE IF NOT EXISTS %[1]sds ( id SERIAL NOT NULL PRIMARY KEY, name TEXT NOT NULL, step_ms BIGINT NOT NULL, heartbeat_ms BIGINT NOT NULL, lastupdate TIMESTAMPTZ, last_ds NUMERIC DEFAULT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_ds_name ON %[1]sds (name); CREATE TABLE IF NOT EXISTS %[1]srra ( id SERIAL NOT NULL PRIMARY KEY, ds_id INT NOT NULL, cf TEXT NOT NULL, steps_per_row INT NOT NULL, size INT NOT NULL, width INT NOT NULL DEFAULT 768, xff REAL NOT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0, latest TIMESTAMPTZ DEFAULT NULL); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_rra_ds_id ON %[1]srra (ds_id, cf, steps_per_row, size, xff); CREATE TABLE IF NOT EXISTS %[1]sts ( rra_id INT NOT NULL, n INT NOT NULL, dp DOUBLE PRECISION[] NOT NULL DEFAULT '{}'); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_ts_rra_id_n ON %[1]sts (rra_id, n); ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { log.Printf("ERROR: initial CREATE TABLE failed: %v", err) return err } else { rows.Close() } create_sql = ` CREATE VIEW %[1]stv AS SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, UNNEST(dp) AS r FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id; CREATE VIEW %[1]stvd AS SELECT ds_id, rra_id, tstzrange(lag(t, 1) OVER (PARTITION BY ds_id, rra_id ORDER BY t), t, '(]') tr, r, step, row, row_n, abs_n, last_n, last_t, slot_distance FROM ( SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, extract(epoch from (latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size))) AS tu, UNNEST(dp) AS r, interval '1 millisecond' * ds.step_ms * rra.steps_per_row AS step, n AS row, generate_subscripts(dp,1) AS row_n, generate_subscripts(dp,1) + n * width AS abs_n, mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 AS last_n, extract(epoch from rra.latest)::bigint*1000 AS last_t, mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS slot_distance FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id) foo; ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE VIEW failed: %v", err) return err } } else { rows.Close() } return nil } // This implements the Series interface type dbSeries struct { ds *rrd.DataSource rra *rrd.RoundRobinArchive // Current Value value float64 posBegin time.Time // pos begins after posEnd time.Time // pos ends on // Time boundary from time.Time to time.Time // Db stuff db *pgSerDe rows *sql.Rows // These are not the same: maxPoints int64 // max points we want groupByMs int64 // requested alignment latest time.Time // Alias alias string } func (dps *dbSeries) StepMs() int64 { return dps.ds.StepMs * int64(dps.rra.StepsPerRow) } func (dps *dbSeries) GroupByMs(ms ...int64) int64 { if len(ms) > 0 { defer func() { dps.groupByMs = ms[0] }() } if dps.groupByMs == 0 { return dps.StepMs() } return dps.groupByMs } func (dps *dbSeries) TimeRange(t ...time.Time) (time.Time, time.Time) { if len(t) == 1 { defer func() { dps.from = t[0] }() } else if len(t) == 2 { defer func() { dps.from, dps.to = t[0], t[1] }() } return dps.from, dps.to } func (dps *dbSeries) LastUpdate() time.Time { return dps.ds.LastUpdate } func (dps *dbSeries) MaxPoints(n ...int64) int64 { if len(n) > 0 { // setter defer func() { dps.maxPoints = n[0] }() } return dps.maxPoints // getter } func (dps *dbSeries) Align() {} func (dps *dbSeries) Alias(s ...string) string { if len(s) > 0 { dps.alias = s[0] } return dps.alias } func (dps *dbSeries) seriesQuerySqlUsingViewAndSeries() (*sql.Rows, error) { var ( rows *sql.Rows err error ) var ( finalGroupByMs int64 rraStepMs = dps.ds.StepMs * int64(dps.rra.StepsPerRow) ) if dps.groupByMs != 0 { // Specific granularity was requested for alignment, we ignore maxPoints finalGroupByMs = finalGroupByMs/dps.groupByMs*dps.groupByMs + dps.groupByMs } else if dps.maxPoints != 0 { // If maxPoints was specified, then calculate group by interval finalGroupByMs = (dps.to.Unix() - dps.from.Unix()) * 1000 / dps.maxPoints finalGroupByMs = finalGroupByMs/rraStepMs*rraStepMs + rraStepMs } else { // Otherwise, group by will equal the rrastep finalGroupByMs = rraStepMs } if finalGroupByMs == 0 { finalGroupByMs = 1000 // TODO Why would this happen (it did)? } // Ensure that the true group by interval is reflected in the series. if finalGroupByMs != dps.groupByMs { dps.groupByMs = finalGroupByMs } // Ensure that we never return data beyond lastUpdate (it would // cause us to return bogus data because the RRD would wrap // around). We do this *after* calculating groupBy because groupBy // should be based on the screen resolution, not what we have in // the db. if dps.to.After(dps.LastUpdate()) { dps.to = dps.LastUpdate() } // TODO: support milliseconds? aligned_from := time.Unix(dps.from.Unix()/(finalGroupByMs/1000)*(finalGroupByMs/1000), 0) //log.Printf("sql3 %v %v %v %v %v %v %v %v", aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) rows, err = dps.db.sql3.Query(aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) if err != nil { log.Printf("seriesQuery(): error %v", err) return nil, err } return rows, nil } func (dps *dbSeries) Next() bool { if dps.rows == nil { // First Next() rows, err := dps.seriesQuerySqlUsingViewAndSeries() if err == nil { dps.rows = rows } else { log.Printf("dbSeries.Next(): database error: %v", err) return false } } if dps.rows.Next() { if ts, value, err := timeValueFromRow(dps.rows); err != nil { log.Printf("dbSeries.Next(): database error: %v", err) return false } else { dps.posBegin = dps.latest dps.posEnd = ts dps.value = value dps.latest = dps.posEnd } return true } else { // See if we have data points that haven't been synced yet if len(dps.rra.DPs) > 0 && dps.latest.Before(dps.rra.Latest) { // TODO this is kinda ugly? // Should RRA's implement Series interface perhaps? // because rra.DPs is a map there is no quick way to find the // earliest entry, we have to traverse the map. It seems // tempting to come with an alternative solution, but it's not // as simple as it seems, and given that this is mostly about // the tip of the series, this is good enough. // we do not provide averaging points here for the same reason for len(dps.rra.DPs) > 0 { earliest := dps.rra.Latest.Add(time.Millisecond) earliestSlotN := int64(-1) for n, _ := range dps.rra.DPs { ts := dps.rra.SlotTimeStamp(dps.ds, n) if ts.Before(earliest) && ts.After(dps.latest) { earliest, earliestSlotN = ts, n } } if earliestSlotN != -1 { dps.posBegin = dps.latest dps.posEnd = earliest dps.value = dps.rra.DPs[earliestSlotN] dps.latest = earliest delete(dps.rra.DPs, earliestSlotN) var from, to time.Time if dps.from.IsZero() { from = time.Unix(0, 0) } else { from = dps.from } if dps.to.IsZero() { to = dps.rra.Latest.Add(time.Millisecond) } else { to = dps.to } if earliest.Add(time.Millisecond).After(from) && earliest.Before(to.Add(time.Millisecond)) { return true } } else { return false } } } } return false } func (dps *dbSeries) CurrentValue() float64 { return dps.value } func (dps *dbSeries) CurrentPosBeginsAfter() time.Time { return dps.posBegin } func (dps *dbSeries) CurrentPosEndsOn() time.Time { return dps.posEnd } func (dps *dbSeries) Close() error { result := dps.rows.Close() dps.rows = nil // next Next() will re-open return result } func timeValueFromRow(rows *sql.Rows) (time.Time, float64, error) { var ( value sql.NullFloat64 ts time.Time ) if err := rows.Scan(&ts, &value); err == nil { if value.Valid { return ts, value.Float64, nil } else { return ts, math.NaN(), nil } } else { return time.Time{}, math.NaN(), err } } func dataSourceFromRow(rows *sql.Rows) (*rrd.DataSource, error) { var ( ds rrd.DataSource last_ds sql.NullFloat64 lastupdate pq.NullTime ) err := rows.Scan(&ds.Id, &ds.Name, &ds.StepMs, &ds.HeartbeatMs, &lastupdate, &last_ds, &ds.Value, &ds.UnknownMs) if err != nil { log.Printf("dataSourceFromRow(): error scanning row: %v", err) return nil, err } if last_ds.Valid { ds.LastDs = last_ds.Float64 } else { ds.LastDs = math.NaN() } if lastupdate.Valid { ds.LastUpdate = lastupdate.Time } else { ds.LastUpdate = time.Unix(0, 0) // Not to be confused with time.Time{} ! } return &ds, err } func roundRobinArchiveFromRow(rows *sql.Rows) (*rrd.RoundRobinArchive, error) { var ( latest pq.NullTime rra rrd.RoundRobinArchive ) err := rows.Scan(&rra.Id, &rra.DsId, &rra.Cf, &rra.StepsPerRow, &rra.Size, &rra.Width, &rra.Xff, &rra.Value, &rra.UnknownMs, &latest) if err != nil { log.Printf("roundRoundRobinArchiveFromRow(): error scanning row: %v", err) return nil, err } if latest.Valid { rra.Latest = latest.Time } else { rra.Latest = time.Unix(0, 0) } rra.DPs = make(map[int64]float64) return &rra, err } func (p *pgSerDe) FetchDataSourceNames() (map[string]int64, error) { const sql = `SELECT id, name FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("FetchDataSourceNames(): error querying database: %v", err) return nil, err } defer rows.Close() result := make(map[string]int64, 0) for rows.Next() { var ( id int64 name string ) err := rows.Scan(&id, &name) if err != nil { log.Printf("FetchDataSourceNames(): error scanning row: %v", err) return nil, err } result[name] = id } return result, nil } func (p *pgSerDe) FetchDataSource(id int64) (*rrd.DataSource, error) { rows, err := p.sql8.Query(id) if err != nil { log.Printf("FetchDataSource(): error querying database: %v", err) return nil, err } defer rows.Close() if rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSource(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } return ds, nil } return nil, nil } func (p *pgSerDe) FetchDataSourceByName(name string) (*rrd.DataSource, error) { rows, err := p.sql9.Query(name) if err != nil { log.Printf("FetchDataSourceByName(): error querying database: %v", err) return nil, err } defer rows.Close() if rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSourceByName(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } return ds, nil } return nil, nil } func (p *pgSerDe) FetchDataSources() ([]*rrd.DataSource, error) { const sql = `SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("FetchDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]*rrd.DataSource, 0) for rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSources(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } result = append(result, ds) } return result, nil } func (p *pgSerDe) fetchRoundRobinArchives(ds_id int64) ([]*rrd.RoundRobinArchive, error) { const sql = `SELECT id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest FROM %[1]srra rra WHERE ds_id = $1` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix), ds_id) if err != nil { log.Printf("fetchRoundRobinArchives(): error querying database: %v", err) return nil, err } defer rows.Close() var rras []*rrd.RoundRobinArchive for rows.Next() { if rra, err := roundRobinArchiveFromRow(rows); err == nil { rras = append(rras, rra) } else { log.Printf("fetchRoundRobinArchives(): error: %v", err) return nil, err } } return rras, nil } func dpsAsString(dps map[int64]float64, start, end int64) string { var b bytes.Buffer b.WriteString("{") for i := start; i <= end; i++ { b.WriteString(strconv.FormatFloat(dps[int64(i)], 'f', -1, 64)) if i != end { b.WriteString(",") } } b.WriteString("}") return b.String() } func (p *pgSerDe) flushRoundRobinArchive(rra *rrd.RoundRobinArchive) error { var n int64 rraSize := int64(rra.Size) if int32(len(rra.DPs)) == rra.Size { // The whole thing for n = 0; n < rra.SlotRow(rraSize); n++ { end := rra.Width - 1 if n == rraSize/int64(rra.Width) { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*int64(rra.Width), n*int64(rra.Width)+rra.Width-1) if rows, err := p.sql1.Query(1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(1): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, 1, end+1, len(dps), n) rows.Close() } else { return err } } } else if rra.Start <= rra.End { // Single range for n = rra.Start / int64(rra.Width); n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(2): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } } else { // Double range (wrap-around, end < start) // range 1: 0 -> end for n = 0; n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(3): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } // range 2: start -> Size for n = rra.Start / rra.Width; n < rra.SlotRow(rraSize); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rraSize/rra.Width { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(4): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } } if rows, err := p.sql2.Query(rra.Value, rra.UnknownMs, rra.Latest, rra.Id); err == nil { rows.Close() } else { return err } return nil } func (p *pgSerDe) FlushDataSource(ds *rrd.DataSource) error { for _, rra := range ds.RRAs { if len(rra.DPs) > 0 { if err := p.flushRoundRobinArchive(rra); err != nil { log.Printf("flushDataSource(): error flushing RRA, probable data loss: %v", err) return err } } } if rows, err := p.sql7.Query(ds.LastUpdate, ds.LastDs, ds.Value, ds.UnknownMs, ds.Id); err != nil { log.Printf("flushDataSource(): database error: %v flushing data source %#v", err, ds) return err } else { rows.Close() } return nil } // CreateOrReturnDataSource loads or returns an existing DS. This is // done by using upsertss first on the ds table, then for each // RRA. This method also attempt to create the TS empty rows with ON // CONFLICT DO NOTHING. (There is no reason to ever load TS data // because of the nature of an RRD - we accumulate data points and // surgically write them to the proper slots in the TS table).Since // PostgreSQL 9.5 introduced upserts and we changed CreateDataSource // to CreateOrReturnDataSource the code in this module is a little // functionally overlapping and should probably be re-worked, // e.g. sql1/sql2 could be upsert and we wouldn't need to bother with // pre-inserting rows in ts here. func (p *pgSerDe) CreateOrReturnDataSource(name string, dsSpec *rrd.DSSpec) (*rrd.DataSource, error) { rows, err := p.sql4.Query(name, dsSpec.Step.Nanoseconds()/1000000, dsSpec.Heartbeat.Nanoseconds()/1000000) if err != nil { log.Printf("CreateOrReturnDataSource(): error querying database: %v", err) return nil, err } defer rows.Close() rows.Next() ds, err := dataSourceFromRow(rows) if err != nil { log.Printf("CreateOrReturnDataSource(): error: %v", err) return nil, err } // RRAs for _, rraSpec := range dsSpec.RRAs { steps := rraSpec.Step.Nanoseconds() / (ds.StepMs * 1000000) size := rraSpec.Size.Nanoseconds() / rraSpec.Step.Nanoseconds() rraRows, err := p.sql5.Query(ds.Id, rraSpec.Function, steps, size, rraSpec.Xff) if err != nil { log.Printf("CreateOrReturnDataSource(): error creating RRAs: %v", err) return nil, err } rraRows.Next() rra, err := roundRobinArchiveFromRow(rraRows) if err != nil { log.Printf("CreateOrReturnDataSource(): error2: %v", err) return nil, err } ds.RRAs = append(ds.RRAs, rra) for n := int64(0); n <= (int64(rra.Size)/rra.Width + int64(rra.Size)%rra.Width/rra.Width); n++ { r, err := p.sql6.Query(rra.Id, n) if err != nil { log.Printf("CreateOrReturnDataSource(): error creating TSs: %v", err) return nil, err } r.Close() } rraRows.Close() } log.Printf("ZZZ CreateOrReturnDataSource(): returning ds.id %d: %#v", ds.Id, ds) return ds, nil } func (p *pgSerDe) SeriesQuery(ds *rrd.DataSource, from, to time.Time, maxPoints int64) (dsl.Series, error) { rra := ds.BestRRA(from, to, maxPoints) // If from/to are nil - assign the rra boundaries rraEarliest := time.Unix(rra.GetStartGivenEndMs(ds, rra.Latest.Unix()*1000)/1000, 0) if from.IsZero() || rraEarliest.After(from) { from = rraEarliest } // Note that seriesQuerySqlUsingViewAndSeries() will modify "to" // to be the earliest of "to" or "LastUpdate". dps := &dbSeries{db: p, ds: ds, rra: rra, from: from, to: to, maxPoints: maxPoints} return dsl.Series(dps), nil } More debugging info // // Copyright 2015 Gregory Trubetskoy. All Rights Reserved. // // 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. // // Data layout notes. // // So we store datapoints as an array, and we know the latest // timestamp. Every time we advance to the next point, so does the // latest timestamp. By knowing the latest timestamp and the size of // the array, we can identify which array element is last, it is: // slots_since_epoch % slots // // If we take a slot with a number slot_n, its distance from the // latest slot can be calculated by this formula: // // distance = (total_slots + last_slot_n - slot_n) % total_slots // // E.g. with total_slots 100, slot_n 55 and last_slot_n 50: // // (100 + 50 - 55) % 100 => 95 // // This means that if we advance forward from 55 by 95 slots, which // means at step 45 we'll reach the end of the array, and start from // the beginning, we'll arrive at 50. // // Or with total_slots 100, slot_n 45 and last_slot_n 50: // // (100 + 50 - 45) % 100 => 5 // package serde import ( "bytes" "database/sql" "fmt" "github.com/lib/pq" "github.com/tgres/tgres/dsl" "github.com/tgres/tgres/rrd" "log" "math" "math/rand" "os" "strconv" "strings" "time" ) type pgSerDe struct { dbConn *sql.DB sql1, sql2, sql3, sql4, sql5, sql6, sql7, sql8, sql9 *sql.Stmt prefix string } func sqlOpen(a, b string) (*sql.DB, error) { return sql.Open(a, b) } func InitDb(connect_string, prefix string) (SerDe, error) { if dbConn, err := sql.Open("postgres", connect_string); err != nil { return nil, err } else { p := &pgSerDe{dbConn: dbConn, prefix: prefix} if err := p.dbConn.Ping(); err != nil { return nil, err } if err := p.createTablesIfNotExist(); err != nil { return nil, err } if err := p.prepareSqlStatements(); err != nil { return nil, err } return SerDe(p), nil } } // A hack to use the DB to see who else is connected func (p *pgSerDe) ListDbClientIps() ([]string, error) { const sql = "SELECT DISTINCT(client_addr) FROM pg_stat_activity" rows, err := p.dbConn.Query(sql) if err != nil { log.Printf("ListDbClientIps(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]string, 0) for rows.Next() { var addr *string if err := rows.Scan(&addr); err != nil { log.Printf("ListDbClientIps(): error scanning row: %v", err) return nil, err } if addr != nil { result = append(result, *addr) } } return result, nil } func (p *pgSerDe) MyDbAddr() (*string, error) { hostname, _ := os.Hostname() randToken := fmt.Sprintf("%s%d", hostname, rand.Intn(1000000000)) sql := fmt.Sprintf("SELECT client_addr FROM pg_stat_activity WHERE query LIKE '%%%s%%'", randToken) rows, err := p.dbConn.Query(sql) if err != nil { log.Printf("myPostgresAddr(): error querying database: %v", err) return nil, err } defer rows.Close() for rows.Next() { var addr *string if err := rows.Scan(&addr); err != nil { log.Printf("myPostgresAddr(): error scanning row: %v", err) return nil, err } if addr != nil { log.Printf("myPostgresAddr(): %s", *addr) return addr, nil } } return nil, nil } func (p *pgSerDe) prepareSqlStatements() error { var err error if p.sql1, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sts ts SET dp[$1:$2] = $3 WHERE rra_id = $4 AND n = $5", p.prefix)); err != nil { return err } if p.sql2, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]srra rra SET value = $1, unknown_ms = $2, latest = $3 WHERE id = $4", p.prefix)); err != nil { return err } if p.sql3, err = p.dbConn.Prepare(fmt.Sprintf("SELECT max(tg) mt, avg(r) ar FROM generate_series($1, $2, ($3)::interval) AS tg "+ "LEFT OUTER JOIN (SELECT t, r FROM %[1]stv tv WHERE ds_id = $4 AND rra_id = $5 "+ " AND t >= $6 AND t <= $7) s ON tg = s.t GROUP BY trunc((extract(epoch from tg)*1000-1))::bigint/$8 ORDER BY mt", p.prefix)); err != nil { return err } if p.sql4, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sds AS ds (name, step_ms, heartbeat_ms) VALUES ($1, $2, $3) "+ // PG 9.5 required. NB: DO NOTHING causes RETURNING to return nothing, so we're using this dummy UPDATE to work around. "ON CONFLICT (name) DO UPDATE SET step_ms = ds.step_ms "+ "RETURNING id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms", p.prefix)); err != nil { return err } if p.sql5, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]srra AS rra (ds_id, cf, steps_per_row, size, xff) VALUES ($1, $2, $3, $4, $5) "+ "ON CONFLICT (ds_id, cf, steps_per_row, size, xff) DO UPDATE SET ds_id = rra.ds_id "+ "RETURNING id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest", p.prefix)); err != nil { return err } if p.sql6, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sts (rra_id, n) VALUES ($1, $2) ON CONFLICT(rra_id, n) DO NOTHING", p.prefix)); err != nil { return err } if p.sql7, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sds SET lastupdate = $1, last_ds = $2, value = $3, unknown_ms = $4 WHERE id = $5", p.prefix)); err != nil { return err } if p.sql8, err = p.dbConn.Prepare(fmt.Sprintf("SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds AS ds WHERE id = $1", p.prefix)); err != nil { return err } if p.sql9, err = p.dbConn.Prepare(fmt.Sprintf("SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds AS ds WHERE name = $1", p.prefix)); err != nil { return err } return nil } func (p *pgSerDe) createTablesIfNotExist() error { create_sql := ` CREATE TABLE IF NOT EXISTS %[1]sds ( id SERIAL NOT NULL PRIMARY KEY, name TEXT NOT NULL, step_ms BIGINT NOT NULL, heartbeat_ms BIGINT NOT NULL, lastupdate TIMESTAMPTZ, last_ds NUMERIC DEFAULT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_ds_name ON %[1]sds (name); CREATE TABLE IF NOT EXISTS %[1]srra ( id SERIAL NOT NULL PRIMARY KEY, ds_id INT NOT NULL, cf TEXT NOT NULL, steps_per_row INT NOT NULL, size INT NOT NULL, width INT NOT NULL DEFAULT 768, xff REAL NOT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0, latest TIMESTAMPTZ DEFAULT NULL); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_rra_ds_id ON %[1]srra (ds_id, cf, steps_per_row, size, xff); CREATE TABLE IF NOT EXISTS %[1]sts ( rra_id INT NOT NULL, n INT NOT NULL, dp DOUBLE PRECISION[] NOT NULL DEFAULT '{}'); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_ts_rra_id_n ON %[1]sts (rra_id, n); ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { log.Printf("ERROR: initial CREATE TABLE failed: %v", err) return err } else { rows.Close() } create_sql = ` CREATE VIEW %[1]stv AS SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, UNNEST(dp) AS r FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id; CREATE VIEW %[1]stvd AS SELECT ds_id, rra_id, tstzrange(lag(t, 1) OVER (PARTITION BY ds_id, rra_id ORDER BY t), t, '(]') tr, r, step, row, row_n, abs_n, last_n, last_t, slot_distance FROM ( SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, extract(epoch from (latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size))) AS tu, UNNEST(dp) AS r, interval '1 millisecond' * ds.step_ms * rra.steps_per_row AS step, n AS row, generate_subscripts(dp,1) AS row_n, generate_subscripts(dp,1) + n * width AS abs_n, mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 AS last_n, extract(epoch from rra.latest)::bigint*1000 AS last_t, mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS slot_distance FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id) foo; ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE VIEW failed: %v", err) return err } } else { rows.Close() } return nil } // This implements the Series interface type dbSeries struct { ds *rrd.DataSource rra *rrd.RoundRobinArchive // Current Value value float64 posBegin time.Time // pos begins after posEnd time.Time // pos ends on // Time boundary from time.Time to time.Time // Db stuff db *pgSerDe rows *sql.Rows // These are not the same: maxPoints int64 // max points we want groupByMs int64 // requested alignment latest time.Time // Alias alias string } func (dps *dbSeries) StepMs() int64 { return dps.ds.StepMs * int64(dps.rra.StepsPerRow) } func (dps *dbSeries) GroupByMs(ms ...int64) int64 { if len(ms) > 0 { defer func() { dps.groupByMs = ms[0] }() } if dps.groupByMs == 0 { return dps.StepMs() } return dps.groupByMs } func (dps *dbSeries) TimeRange(t ...time.Time) (time.Time, time.Time) { if len(t) == 1 { defer func() { dps.from = t[0] }() } else if len(t) == 2 { defer func() { dps.from, dps.to = t[0], t[1] }() } return dps.from, dps.to } func (dps *dbSeries) LastUpdate() time.Time { return dps.ds.LastUpdate } func (dps *dbSeries) MaxPoints(n ...int64) int64 { if len(n) > 0 { // setter defer func() { dps.maxPoints = n[0] }() } return dps.maxPoints // getter } func (dps *dbSeries) Align() {} func (dps *dbSeries) Alias(s ...string) string { if len(s) > 0 { dps.alias = s[0] } return dps.alias } func (dps *dbSeries) seriesQuerySqlUsingViewAndSeries() (*sql.Rows, error) { var ( rows *sql.Rows err error ) var ( finalGroupByMs int64 rraStepMs = dps.ds.StepMs * int64(dps.rra.StepsPerRow) ) if dps.groupByMs != 0 { // Specific granularity was requested for alignment, we ignore maxPoints finalGroupByMs = finalGroupByMs/dps.groupByMs*dps.groupByMs + dps.groupByMs } else if dps.maxPoints != 0 { // If maxPoints was specified, then calculate group by interval finalGroupByMs = (dps.to.Unix() - dps.from.Unix()) * 1000 / dps.maxPoints finalGroupByMs = finalGroupByMs/rraStepMs*rraStepMs + rraStepMs } else { // Otherwise, group by will equal the rrastep finalGroupByMs = rraStepMs } if finalGroupByMs == 0 { finalGroupByMs = 1000 // TODO Why would this happen (it did)? } // Ensure that the true group by interval is reflected in the series. if finalGroupByMs != dps.groupByMs { dps.groupByMs = finalGroupByMs } // Ensure that we never return data beyond lastUpdate (it would // cause us to return bogus data because the RRD would wrap // around). We do this *after* calculating groupBy because groupBy // should be based on the screen resolution, not what we have in // the db. if dps.to.After(dps.LastUpdate()) { dps.to = dps.LastUpdate() } // TODO: support milliseconds? aligned_from := time.Unix(dps.from.Unix()/(finalGroupByMs/1000)*(finalGroupByMs/1000), 0) //log.Printf("sql3 %v %v %v %v %v %v %v %v", aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) rows, err = dps.db.sql3.Query(aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) if err != nil { log.Printf("seriesQuery(): error %v", err) return nil, err } return rows, nil } func (dps *dbSeries) Next() bool { if dps.rows == nil { // First Next() rows, err := dps.seriesQuerySqlUsingViewAndSeries() if err == nil { dps.rows = rows } else { log.Printf("dbSeries.Next(): database error: %v", err) return false } } if dps.rows.Next() { if ts, value, err := timeValueFromRow(dps.rows); err != nil { log.Printf("dbSeries.Next(): database error: %v", err) return false } else { dps.posBegin = dps.latest dps.posEnd = ts dps.value = value dps.latest = dps.posEnd } return true } else { // See if we have data points that haven't been synced yet if len(dps.rra.DPs) > 0 && dps.latest.Before(dps.rra.Latest) { // TODO this is kinda ugly? // Should RRA's implement Series interface perhaps? // because rra.DPs is a map there is no quick way to find the // earliest entry, we have to traverse the map. It seems // tempting to come with an alternative solution, but it's not // as simple as it seems, and given that this is mostly about // the tip of the series, this is good enough. // we do not provide averaging points here for the same reason for len(dps.rra.DPs) > 0 { earliest := dps.rra.Latest.Add(time.Millisecond) earliestSlotN := int64(-1) for n, _ := range dps.rra.DPs { ts := dps.rra.SlotTimeStamp(dps.ds, n) if ts.Before(earliest) && ts.After(dps.latest) { earliest, earliestSlotN = ts, n } } if earliestSlotN != -1 { dps.posBegin = dps.latest dps.posEnd = earliest dps.value = dps.rra.DPs[earliestSlotN] dps.latest = earliest delete(dps.rra.DPs, earliestSlotN) var from, to time.Time if dps.from.IsZero() { from = time.Unix(0, 0) } else { from = dps.from } if dps.to.IsZero() { to = dps.rra.Latest.Add(time.Millisecond) } else { to = dps.to } if earliest.Add(time.Millisecond).After(from) && earliest.Before(to.Add(time.Millisecond)) { return true } } else { return false } } } } return false } func (dps *dbSeries) CurrentValue() float64 { return dps.value } func (dps *dbSeries) CurrentPosBeginsAfter() time.Time { return dps.posBegin } func (dps *dbSeries) CurrentPosEndsOn() time.Time { return dps.posEnd } func (dps *dbSeries) Close() error { result := dps.rows.Close() dps.rows = nil // next Next() will re-open return result } func timeValueFromRow(rows *sql.Rows) (time.Time, float64, error) { var ( value sql.NullFloat64 ts time.Time ) if err := rows.Scan(&ts, &value); err == nil { if value.Valid { return ts, value.Float64, nil } else { return ts, math.NaN(), nil } } else { return time.Time{}, math.NaN(), err } } func dataSourceFromRow(rows *sql.Rows) (*rrd.DataSource, error) { var ( ds rrd.DataSource last_ds sql.NullFloat64 lastupdate pq.NullTime ) err := rows.Scan(&ds.Id, &ds.Name, &ds.StepMs, &ds.HeartbeatMs, &lastupdate, &last_ds, &ds.Value, &ds.UnknownMs) if err != nil { log.Printf("dataSourceFromRow(): error scanning row: %v", err) return nil, err } if last_ds.Valid { ds.LastDs = last_ds.Float64 } else { ds.LastDs = math.NaN() } if lastupdate.Valid { ds.LastUpdate = lastupdate.Time } else { ds.LastUpdate = time.Unix(0, 0) // Not to be confused with time.Time{} ! } return &ds, err } func roundRobinArchiveFromRow(rows *sql.Rows) (*rrd.RoundRobinArchive, error) { var ( latest pq.NullTime rra rrd.RoundRobinArchive ) err := rows.Scan(&rra.Id, &rra.DsId, &rra.Cf, &rra.StepsPerRow, &rra.Size, &rra.Width, &rra.Xff, &rra.Value, &rra.UnknownMs, &latest) if err != nil { log.Printf("roundRoundRobinArchiveFromRow(): error scanning row: %v", err) return nil, err } if latest.Valid { rra.Latest = latest.Time } else { rra.Latest = time.Unix(0, 0) } rra.DPs = make(map[int64]float64) return &rra, err } func (p *pgSerDe) FetchDataSourceNames() (map[string]int64, error) { const sql = `SELECT id, name FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("FetchDataSourceNames(): error querying database: %v", err) return nil, err } defer rows.Close() result := make(map[string]int64, 0) for rows.Next() { var ( id int64 name string ) err := rows.Scan(&id, &name) if err != nil { log.Printf("FetchDataSourceNames(): error scanning row: %v", err) return nil, err } result[name] = id } return result, nil } func (p *pgSerDe) FetchDataSource(id int64) (*rrd.DataSource, error) { rows, err := p.sql8.Query(id) if err != nil { log.Printf("FetchDataSource(): error querying database: %v", err) return nil, err } defer rows.Close() if rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSource(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } return ds, nil } return nil, nil } func (p *pgSerDe) FetchDataSourceByName(name string) (*rrd.DataSource, error) { rows, err := p.sql9.Query(name) if err != nil { log.Printf("FetchDataSourceByName(): error querying database: %v", err) return nil, err } defer rows.Close() if rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSourceByName(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } return ds, nil } return nil, nil } func (p *pgSerDe) FetchDataSources() ([]*rrd.DataSource, error) { const sql = `SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("FetchDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]*rrd.DataSource, 0) for rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("FetchDataSources(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } result = append(result, ds) } return result, nil } func (p *pgSerDe) fetchRoundRobinArchives(ds_id int64) ([]*rrd.RoundRobinArchive, error) { const sql = `SELECT id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest FROM %[1]srra rra WHERE ds_id = $1` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix), ds_id) if err != nil { log.Printf("fetchRoundRobinArchives(): error querying database: %v", err) return nil, err } defer rows.Close() var rras []*rrd.RoundRobinArchive for rows.Next() { if rra, err := roundRobinArchiveFromRow(rows); err == nil { rras = append(rras, rra) } else { log.Printf("fetchRoundRobinArchives(): error: %v", err) return nil, err } } return rras, nil } func dpsAsString(dps map[int64]float64, start, end int64) string { var b bytes.Buffer b.WriteString("{") for i := start; i <= end; i++ { b.WriteString(strconv.FormatFloat(dps[int64(i)], 'f', -1, 64)) if i != end { b.WriteString(",") } } b.WriteString("}") return b.String() } func (p *pgSerDe) flushRoundRobinArchive(rra *rrd.RoundRobinArchive) error { var n int64 rraSize := int64(rra.Size) if int32(len(rra.DPs)) == rra.Size { // The whole thing for n = 0; n < rra.SlotRow(rraSize); n++ { end := rra.Width - 1 if n == rraSize/int64(rra.Width) { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*int64(rra.Width), n*int64(rra.Width)+rra.Width-1) if rows, err := p.sql1.Query(1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(1): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, 1, end+1, len(dps), n) rows.Close() } else { return err } } } else if rra.Start <= rra.End { // Single range for n = rra.Start / int64(rra.Width); n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(2): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } } else { // Double range (wrap-around, end < start) // range 1: 0 -> end for n = 0; n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(3): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } // range 2: start -> Size for n = rra.Start / rra.Width; n < rra.SlotRow(rraSize); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rraSize/rra.Width { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { log.Printf("ZZZ flushRoundRobinArchive(4): rra.Id: %d rra.Start: %d rra.End: %d params: s: %d e: %d len: %d n: %d", rra.Id, rra.Start, rra.End, start+1, end+1, len(dps), n) rows.Close() } else { return err } } } if rows, err := p.sql2.Query(rra.Value, rra.UnknownMs, rra.Latest, rra.Id); err == nil { rows.Close() } else { return err } return nil } func (p *pgSerDe) FlushDataSource(ds *rrd.DataSource) error { for _, rra := range ds.RRAs { if len(rra.DPs) > 0 { if err := p.flushRoundRobinArchive(rra); err != nil { log.Printf("FlushDataSource(): error flushing RRA, probable data loss: %v", err) return err } } } log.Printf("ZZZ FlushDataSource(): Id %d: LastUpdate: %v, LastDs: %v, Value: %v, UnknownMs: %v", ds.Id, ds.LastUpdate, ds.LastDs, ds.Value, ds.UnknownMs) if rows, err := p.sql7.Query(ds.LastUpdate, ds.LastDs, ds.Value, ds.UnknownMs, ds.Id); err != nil { log.Printf("FlushDataSource(): database error: %v flushing data source %#v", err, ds) return err } else { rows.Close() } return nil } // CreateOrReturnDataSource loads or returns an existing DS. This is // done by using upsertss first on the ds table, then for each // RRA. This method also attempt to create the TS empty rows with ON // CONFLICT DO NOTHING. (There is no reason to ever load TS data // because of the nature of an RRD - we accumulate data points and // surgically write them to the proper slots in the TS table).Since // PostgreSQL 9.5 introduced upserts and we changed CreateDataSource // to CreateOrReturnDataSource the code in this module is a little // functionally overlapping and should probably be re-worked, // e.g. sql1/sql2 could be upsert and we wouldn't need to bother with // pre-inserting rows in ts here. func (p *pgSerDe) CreateOrReturnDataSource(name string, dsSpec *rrd.DSSpec) (*rrd.DataSource, error) { rows, err := p.sql4.Query(name, dsSpec.Step.Nanoseconds()/1000000, dsSpec.Heartbeat.Nanoseconds()/1000000) if err != nil { log.Printf("CreateOrReturnDataSource(): error querying database: %v", err) return nil, err } defer rows.Close() rows.Next() ds, err := dataSourceFromRow(rows) if err != nil { log.Printf("CreateOrReturnDataSource(): error: %v", err) return nil, err } // RRAs for _, rraSpec := range dsSpec.RRAs { steps := rraSpec.Step.Nanoseconds() / (ds.StepMs * 1000000) size := rraSpec.Size.Nanoseconds() / rraSpec.Step.Nanoseconds() rraRows, err := p.sql5.Query(ds.Id, rraSpec.Function, steps, size, rraSpec.Xff) if err != nil { log.Printf("CreateOrReturnDataSource(): error creating RRAs: %v", err) return nil, err } rraRows.Next() rra, err := roundRobinArchiveFromRow(rraRows) if err != nil { log.Printf("CreateOrReturnDataSource(): error2: %v", err) return nil, err } ds.RRAs = append(ds.RRAs, rra) for n := int64(0); n <= (int64(rra.Size)/rra.Width + int64(rra.Size)%rra.Width/rra.Width); n++ { r, err := p.sql6.Query(rra.Id, n) if err != nil { log.Printf("CreateOrReturnDataSource(): error creating TSs: %v", err) return nil, err } r.Close() } rraRows.Close() } log.Printf("ZZZ CreateOrReturnDataSource(): returning ds.id %d: %#v", ds.Id, ds) return ds, nil } func (p *pgSerDe) SeriesQuery(ds *rrd.DataSource, from, to time.Time, maxPoints int64) (dsl.Series, error) { rra := ds.BestRRA(from, to, maxPoints) // If from/to are nil - assign the rra boundaries rraEarliest := time.Unix(rra.GetStartGivenEndMs(ds, rra.Latest.Unix()*1000)/1000, 0) if from.IsZero() || rraEarliest.After(from) { from = rraEarliest } // Note that seriesQuerySqlUsingViewAndSeries() will modify "to" // to be the earliest of "to" or "LastUpdate". dps := &dbSeries{db: p, ds: ds, rra: rra, from: from, to: to, maxPoints: maxPoints} return dsl.Series(dps), nil }
// Copyright 2022 Google LLC // // 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 // // https://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 ( "context" _ "embed" "errors" "fmt" "net" "net/http" "net/url" "os" "os/signal" "strconv" "strings" "syscall" "time" "contrib.go.opencensus.io/exporter/prometheus" "contrib.go.opencensus.io/exporter/stackdriver" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/cloudsql" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/healthcheck" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/log" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/proxy" "github.com/spf13/cobra" "go.opencensus.io/trace" ) var ( // versionString indicates the version of this library. //go:embed version.txt versionString string userAgent string ) func init() { versionString = strings.TrimSpace(versionString) userAgent = "cloud-sql-proxy/" + versionString } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := NewCommand().Execute(); err != nil { exit := 1 if terr, ok := err.(*exitError); ok { exit = terr.Code } os.Exit(exit) } } // Command represents an invocation of the Cloud SQL Auth Proxy. type Command struct { *cobra.Command conf *proxy.Config logger cloudsql.Logger dialer cloudsql.Dialer cleanup func() error disableTraces bool telemetryTracingSampleRate int disableMetrics bool telemetryProject string telemetryPrefix string prometheus bool prometheusNamespace string healthCheck bool httpPort string } // Option is a function that configures a Command. type Option func(*Command) // WithLogger overrides the default logger. func WithLogger(l cloudsql.Logger) Option { return func(c *Command) { c.logger = l } } // WithDialer configures the Command to use the provided dialer to connect to // Cloud SQL instances. func WithDialer(d cloudsql.Dialer) Option { return func(c *Command) { c.dialer = d } } var longHelp = ` The Cloud SQL Auth proxy is a utility for ensuring secure connections to your Cloud SQL instances. It provides IAM authorization, allowing you to control who can connect to your instance through IAM permissions, and TLS 1.3 encryption, without having to manage certificates. NOTE: The proxy does not configure the network. You MUST ensure the proxy can reach your Cloud SQL instance, either by deploying it in a VPC that has access to your Private IP instance, or by configuring Public IP. For every provided instance connection name, the proxy creates: - a socket that mimics a database running locally, and - an encrypted connection using TLS 1.3 back to your Cloud SQL instance. The proxy uses an ephemeral certificate to establish a secure connection to your Cloud SQL instance. The proxy will refresh those certificates on an hourly basis. Existing client connections are unaffected by the refresh cycle. To start the proxy, you will need your instance connection name, which may be found in the Cloud SQL instance overview page or by using gcloud with the following command: gcloud sql instances describe INSTANCE --format='value(connectionName)' For example, if your instance connection name is "my-project:us-central1:my-db-server", starting the proxy will be: ./cloud-sql-proxy my-project:us-central1:my-db-server By default, the proxy will determine the database engine and start a listener on localhost using the default database engine's port, i.e., MySQL is 3306, Postgres is 5432, SQL Server is 1433. If multiple instances are specified which all use the same database engine, the first will be started on the default database port and subsequent instances will be incremented from there (e.g., 3306, 3307, 3308, etc). To disable this behavior (and reduce startup time), use the --port flag. All subsequent listeners will increment from the provided value. All socket listeners use the localhost network interface. To override this behavior, use the --address flag. The proxy supports overriding configuration on an instance-level with an optional query string syntax using the corresponding full flag name. The query string takes the form of a URL query string and should be appended to the INSTANCE_CONNECTION_NAME, e.g., 'my-project:us-central1:my-db-server?key1=value1&key2=value2' When using the optional query string syntax, quotes must wrap the instance connection name and query string to prevent conflicts with the shell. For example, to override the address and port for one instance but otherwise use the default behavior, use: ./cloud-sql-proxy \ my-project:us-central1:my-db-server \ 'my-project:us-central1:my-other-server?address=0.0.0.0&port=7000' (*) indicates a flag that may be used as a query parameter ` // NewCommand returns a Command object representing an invocation of the proxy. func NewCommand(opts ...Option) *Command { cmd := &cobra.Command{ Use: "cloud-sql-proxy INSTANCE_CONNECTION_NAME...", Version: versionString, Short: "cloud-sql-proxy authorizes and encrypts connections to Cloud SQL.", Long: longHelp, } logger := log.NewStdLogger(os.Stdout, os.Stderr) c := &Command{ Command: cmd, logger: logger, cleanup: func() error { return nil }, conf: &proxy.Config{ UserAgent: userAgent, }, } for _, o := range opts { o(c) } cmd.Args = func(cmd *cobra.Command, args []string) error { // Handle logger separately from config if c.conf.StructuredLogs { c.logger, c.cleanup = log.NewStructuredLogger() } err := parseConfig(c, c.conf, args) if err != nil { return err } // The arguments are parsed. Usage is no longer needed. cmd.SilenceUsage = true // Errors will be handled by logging from here on. cmd.SilenceErrors = true return nil } cmd.RunE = func(*cobra.Command, []string) error { return runSignalWrapper(c) } // Override Cobra's default messages. cmd.PersistentFlags().BoolP("help", "h", false, "Display help information for cloud-sql-proxy") cmd.PersistentFlags().BoolP("version", "v", false, "Print the cloud-sql-proxy version") // Global-only flags cmd.PersistentFlags().StringVarP(&c.conf.Token, "token", "t", "", "Use bearer token as a source of IAM credentials.") cmd.PersistentFlags().StringVarP(&c.conf.CredentialsFile, "credentials-file", "c", "", "Use service account key file as a source of IAM credentials.") cmd.PersistentFlags().BoolVarP(&c.conf.GcloudAuth, "gcloud-auth", "g", false, "Use gcloud's user credentials as a source of IAM credentials.") cmd.PersistentFlags().BoolVarP(&c.conf.StructuredLogs, "structured-logs", "l", false, "Enable structured logging with LogEntry format") cmd.PersistentFlags().Uint64Var(&c.conf.MaxConnections, "max-connections", 0, "Limit the number of connections. Default is no limit.") cmd.PersistentFlags().DurationVar(&c.conf.WaitOnClose, "max-sigterm-delay", 0, "Maximum number of seconds to wait for connections to close after receiving a TERM signal.") cmd.PersistentFlags().StringVar(&c.telemetryProject, "telemetry-project", "", "Enable Cloud Monitoring and Cloud Trace with the provided project ID.") cmd.PersistentFlags().BoolVar(&c.disableTraces, "disable-traces", false, "Disable Cloud Trace integration (used with --telemetry-project)") cmd.PersistentFlags().IntVar(&c.telemetryTracingSampleRate, "telemetry-sample-rate", 10_000, "Set the Cloud Trace sample rate. A smaller number means more traces.") cmd.PersistentFlags().BoolVar(&c.disableMetrics, "disable-metrics", false, "Disable Cloud Monitoring integration (used with --telemetry-project)") cmd.PersistentFlags().StringVar(&c.telemetryPrefix, "telemetry-prefix", "", "Prefix for Cloud Monitoring metrics.") cmd.PersistentFlags().BoolVar(&c.prometheus, "prometheus", false, "Enable Prometheus HTTP endpoint /metrics on localhost") cmd.PersistentFlags().StringVar(&c.prometheusNamespace, "prometheus-namespace", "", "Use the provided Prometheus namespace for metrics") cmd.PersistentFlags().StringVar(&c.httpPort, "http-port", "9090", "Port for Prometheus and health check server") cmd.PersistentFlags().BoolVar(&c.healthCheck, "health-check", false, "Enables health check endpoints /startup, /liveness, and /readiness on localhost.") cmd.PersistentFlags().StringVar(&c.conf.APIEndpointURL, "sqladmin-api-endpoint", "", "API endpoint for all Cloud SQL Admin API requests. (default: https://sqladmin.googleapis.com)") cmd.PersistentFlags().StringVar(&c.conf.QuotaProject, "quota-project", "", `Specifies the project for Cloud SQL Admin API quota tracking. Must have "serviceusage.service.use" IAM permission.`) // Global and per instance flags cmd.PersistentFlags().StringVarP(&c.conf.Addr, "address", "a", "127.0.0.1", "(*) Address to bind Cloud SQL instance listeners.") cmd.PersistentFlags().IntVarP(&c.conf.Port, "port", "p", 0, "(*) Initial port for listeners. Subsequent listeners increment from this value.") cmd.PersistentFlags().StringVarP(&c.conf.UnixSocket, "unix-socket", "u", "", `(*) Enables Unix sockets for all listeners with the provided directory.`) cmd.PersistentFlags().BoolVarP(&c.conf.IAMAuthN, "auto-iam-authn", "i", false, "(*) Enables Automatic IAM Authentication for all instances") cmd.PersistentFlags().BoolVar(&c.conf.PrivateIP, "private-ip", false, "(*) Connect to the private ip address for all instances") return c } func parseConfig(cmd *Command, conf *proxy.Config, args []string) error { // If no instance connection names were provided, error. if len(args) == 0 { return newBadCommandError("missing instance_connection_name (e.g., project:region:instance)") } userHasSet := func(f string) bool { return cmd.PersistentFlags().Lookup(f).Changed } if userHasSet("address") && userHasSet("unix-socket") { return newBadCommandError("cannot specify --unix-socket and --address together") } if userHasSet("port") && userHasSet("unix-socket") { return newBadCommandError("cannot specify --unix-socket and --port together") } if ip := net.ParseIP(conf.Addr); ip == nil { return newBadCommandError(fmt.Sprintf("not a valid IP address: %q", conf.Addr)) } // If more than one auth method is set, error. if conf.Token != "" && conf.CredentialsFile != "" { return newBadCommandError("cannot specify --token and --credentials-file flags at the same time") } if conf.Token != "" && conf.GcloudAuth { return newBadCommandError("cannot specify --token and --gcloud-auth flags at the same time") } if conf.CredentialsFile != "" && conf.GcloudAuth { return newBadCommandError("cannot specify --credentials-file and --gcloud-auth flags at the same time") } if userHasSet("http-port") && !userHasSet("prometheus") && !userHasSet("health-check") { cmd.logger.Infof("Ignoring --http-port because --prometheus or --health-check was not set") } if !userHasSet("telemetry-project") && userHasSet("telemetry-prefix") { cmd.logger.Infof("Ignoring --telementry-prefix because --telemetry-project was not set") } if !userHasSet("telemetry-project") && userHasSet("disable-metrics") { cmd.logger.Infof("Ignoring --disable-metrics because --telemetry-project was not set") } if !userHasSet("telemetry-project") && userHasSet("disable-traces") { cmd.logger.Infof("Ignoring --disable-traces because --telemetry-project was not set") } if userHasSet("sqladmin-api-endpoint") && conf.APIEndpointURL != "" { _, err := url.Parse(conf.APIEndpointURL) if err != nil { return newBadCommandError(fmt.Sprintf("the value provided for --sqladmin-api-endpoint is not a valid URL, %v", conf.APIEndpointURL)) } // add a trailing '/' if omitted if !strings.HasSuffix(conf.APIEndpointURL, "/") { conf.APIEndpointURL = conf.APIEndpointURL + "/" } } var ics []proxy.InstanceConnConfig for _, a := range args { // Assume no query params initially ic := proxy.InstanceConnConfig{ Name: a, } // If there are query params, update instance config. if res := strings.SplitN(a, "?", 2); len(res) > 1 { ic.Name = res[0] q, err := url.ParseQuery(res[1]) if err != nil { return newBadCommandError(fmt.Sprintf("could not parse query: %q", res[1])) } a, aok := q["address"] p, pok := q["port"] u, uok := q["unix-socket"] if aok && uok { return newBadCommandError("cannot specify both address and unix-socket query params") } if pok && uok { return newBadCommandError("cannot specify both port and unix-socket query params") } if aok { if len(a) != 1 { return newBadCommandError(fmt.Sprintf("address query param should be only one value: %q", a)) } if ip := net.ParseIP(a[0]); ip == nil { return newBadCommandError( fmt.Sprintf("address query param is not a valid IP address: %q", a[0], )) } ic.Addr = a[0] } if pok { if len(p) != 1 { return newBadCommandError(fmt.Sprintf("port query param should be only one value: %q", a)) } pp, err := strconv.Atoi(p[0]) if err != nil { return newBadCommandError( fmt.Sprintf("port query param is not a valid integer: %q", p[0], )) } ic.Port = pp } if uok { if len(u) != 1 { return newBadCommandError(fmt.Sprintf("unix query param should be only one value: %q", a)) } ic.UnixSocket = u[0] } ic.IAMAuthN, err = parseBoolOpt(q, "auto-iam-authn") if err != nil { return err } ic.PrivateIP, err = parseBoolOpt(q, "private-ip") if err != nil { return err } } ics = append(ics, ic) } conf.Instances = ics return nil } // parseBoolOpt parses a boolean option from the query string, returning // // true if the value is "t" or "true" case-insensitive // false if the value is "f" or "false" case-insensitive func parseBoolOpt(q url.Values, name string) (*bool, error) { iam, ok := q[name] if !ok { return nil, nil } if len(iam) != 1 { return nil, newBadCommandError(fmt.Sprintf("%v param should be only one value: %q", name, iam)) } switch strings.ToLower(iam[0]) { case "true", "t", "": enable := true return &enable, nil case "false", "f": disable := false return &disable, nil default: // value is not recognized return nil, newBadCommandError( fmt.Sprintf("%v query param should be true or false, got: %q", name, iam[0], )) } } // runSignalWrapper watches for SIGTERM and SIGINT and interupts execution if necessary. func runSignalWrapper(cmd *Command) error { defer cmd.cleanup() ctx, cancel := context.WithCancel(cmd.Context()) defer cancel() // Configure collectors before the proxy has started to ensure we are // collecting metrics before *ANY* Cloud SQL Admin API calls are made. enableMetrics := !cmd.disableMetrics enableTraces := !cmd.disableTraces if cmd.telemetryProject != "" && (enableMetrics || enableTraces) { sd, err := stackdriver.NewExporter(stackdriver.Options{ ProjectID: cmd.telemetryProject, MetricPrefix: cmd.telemetryPrefix, }) if err != nil { return err } if enableMetrics { err = sd.StartMetricsExporter() if err != nil { return err } } if enableTraces { s := trace.ProbabilitySampler(1 / float64(cmd.telemetryTracingSampleRate)) trace.ApplyConfig(trace.Config{DefaultSampler: s}) trace.RegisterExporter(sd) } defer func() { sd.Flush() sd.StopMetricsExporter() }() } var ( needsHTTPServer bool mux = http.NewServeMux() ) if cmd.prometheus { needsHTTPServer = true e, err := prometheus.NewExporter(prometheus.Options{ Namespace: cmd.prometheusNamespace, }) if err != nil { return err } mux.Handle("/metrics", e) } shutdownCh := make(chan error) // watch for sigterm / sigint signals signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT) go func() { var s os.Signal select { case s = <-signals: case <-ctx.Done(): // this should only happen when the context supplied in tests in canceled s = syscall.SIGINT } switch s { case syscall.SIGINT: shutdownCh <- errSigInt case syscall.SIGTERM: shutdownCh <- errSigTerm } }() // Start the proxy asynchronously, so we can exit early if a shutdown signal is sent startCh := make(chan *proxy.Client) go func() { defer close(startCh) p, err := proxy.NewClient(ctx, cmd.dialer, cmd.logger, cmd.conf) if err != nil { shutdownCh <- fmt.Errorf("unable to start: %v", err) return } startCh <- p }() // Wait for either startup to finish or a signal to interupt var p *proxy.Client select { case err := <-shutdownCh: cmd.logger.Errorf("The proxy has encountered a terminal error: %v", err) return err case p = <-startCh: cmd.logger.Infof("The proxy has started successfully and is ready for new connections!") } defer func() { if cErr := p.Close(); cErr != nil { cmd.logger.Errorf("error during shutdown: %v", cErr) } }() notify := func() {} if cmd.healthCheck { needsHTTPServer = true hc := healthcheck.NewCheck(p, cmd.logger) mux.HandleFunc("/startup", hc.HandleStartup) mux.HandleFunc("/readiness", hc.HandleReadiness) mux.HandleFunc("/liveness", hc.HandleLiveness) notify = hc.NotifyStarted } // Start the HTTP server if anything requiring HTTP is specified. if needsHTTPServer { server := &http.Server{ Addr: fmt.Sprintf("localhost:%s", cmd.httpPort), Handler: mux, } // Start the HTTP server. go func() { err := server.ListenAndServe() if err == http.ErrServerClosed { return } if err != nil { shutdownCh <- fmt.Errorf("failed to start HTTP server: %v", err) } }() // Handle shutdown of the HTTP server gracefully. go func() { select { case <-ctx.Done(): // Give the HTTP server a second to shutdown cleanly. ctx2, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := server.Shutdown(ctx2); err != nil { cmd.logger.Errorf("failed to shutdown Prometheus HTTP server: %v\n", err) } } }() } go func() { shutdownCh <- p.Serve(ctx, notify) }() err := <-shutdownCh switch { case errors.Is(err, errSigInt): cmd.logger.Errorf("SIGINT signal received. Shutting down...") case errors.Is(err, errSigTerm): cmd.logger.Errorf("SIGTERM signal received. Shutting down...") default: cmd.logger.Errorf("The proxy has encountered a terminal error: %v", err) } return err } fix: support configuration of HTTP server address (#1365) In Kubernetes, the convention is to bind HTTP probes and Prometheus endpoints to 0.0.0.0 (both lo and eth0). Since people might want to run this code on a GCE VM, default to localhost, but otherwise support binding to both interfaces. Fixes #1359. // Copyright 2022 Google LLC // // 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 // // https://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 ( "context" _ "embed" "errors" "fmt" "net" "net/http" "net/url" "os" "os/signal" "strconv" "strings" "syscall" "time" "contrib.go.opencensus.io/exporter/prometheus" "contrib.go.opencensus.io/exporter/stackdriver" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/cloudsql" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/healthcheck" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/log" "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/proxy" "github.com/spf13/cobra" "go.opencensus.io/trace" ) var ( // versionString indicates the version of this library. //go:embed version.txt versionString string userAgent string ) func init() { versionString = strings.TrimSpace(versionString) userAgent = "cloud-sql-proxy/" + versionString } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := NewCommand().Execute(); err != nil { exit := 1 if terr, ok := err.(*exitError); ok { exit = terr.Code } os.Exit(exit) } } // Command represents an invocation of the Cloud SQL Auth Proxy. type Command struct { *cobra.Command conf *proxy.Config logger cloudsql.Logger dialer cloudsql.Dialer cleanup func() error disableTraces bool telemetryTracingSampleRate int disableMetrics bool telemetryProject string telemetryPrefix string prometheus bool prometheusNamespace string healthCheck bool httpAddress string httpPort string } // Option is a function that configures a Command. type Option func(*Command) // WithLogger overrides the default logger. func WithLogger(l cloudsql.Logger) Option { return func(c *Command) { c.logger = l } } // WithDialer configures the Command to use the provided dialer to connect to // Cloud SQL instances. func WithDialer(d cloudsql.Dialer) Option { return func(c *Command) { c.dialer = d } } var longHelp = ` The Cloud SQL Auth proxy is a utility for ensuring secure connections to your Cloud SQL instances. It provides IAM authorization, allowing you to control who can connect to your instance through IAM permissions, and TLS 1.3 encryption, without having to manage certificates. NOTE: The proxy does not configure the network. You MUST ensure the proxy can reach your Cloud SQL instance, either by deploying it in a VPC that has access to your Private IP instance, or by configuring Public IP. For every provided instance connection name, the proxy creates: - a socket that mimics a database running locally, and - an encrypted connection using TLS 1.3 back to your Cloud SQL instance. The proxy uses an ephemeral certificate to establish a secure connection to your Cloud SQL instance. The proxy will refresh those certificates on an hourly basis. Existing client connections are unaffected by the refresh cycle. To start the proxy, you will need your instance connection name, which may be found in the Cloud SQL instance overview page or by using gcloud with the following command: gcloud sql instances describe INSTANCE --format='value(connectionName)' For example, if your instance connection name is "my-project:us-central1:my-db-server", starting the proxy will be: ./cloud-sql-proxy my-project:us-central1:my-db-server By default, the proxy will determine the database engine and start a listener on localhost using the default database engine's port, i.e., MySQL is 3306, Postgres is 5432, SQL Server is 1433. If multiple instances are specified which all use the same database engine, the first will be started on the default database port and subsequent instances will be incremented from there (e.g., 3306, 3307, 3308, etc). To disable this behavior (and reduce startup time), use the --port flag. All subsequent listeners will increment from the provided value. All socket listeners use the localhost network interface. To override this behavior, use the --address flag. The proxy supports overriding configuration on an instance-level with an optional query string syntax using the corresponding full flag name. The query string takes the form of a URL query string and should be appended to the INSTANCE_CONNECTION_NAME, e.g., 'my-project:us-central1:my-db-server?key1=value1&key2=value2' When using the optional query string syntax, quotes must wrap the instance connection name and query string to prevent conflicts with the shell. For example, to override the address and port for one instance but otherwise use the default behavior, use: ./cloud-sql-proxy \ my-project:us-central1:my-db-server \ 'my-project:us-central1:my-other-server?address=0.0.0.0&port=7000' (*) indicates a flag that may be used as a query parameter ` // NewCommand returns a Command object representing an invocation of the proxy. func NewCommand(opts ...Option) *Command { cmd := &cobra.Command{ Use: "cloud-sql-proxy INSTANCE_CONNECTION_NAME...", Version: versionString, Short: "cloud-sql-proxy authorizes and encrypts connections to Cloud SQL.", Long: longHelp, } logger := log.NewStdLogger(os.Stdout, os.Stderr) c := &Command{ Command: cmd, logger: logger, cleanup: func() error { return nil }, conf: &proxy.Config{ UserAgent: userAgent, }, } for _, o := range opts { o(c) } cmd.Args = func(cmd *cobra.Command, args []string) error { // Handle logger separately from config if c.conf.StructuredLogs { c.logger, c.cleanup = log.NewStructuredLogger() } err := parseConfig(c, c.conf, args) if err != nil { return err } // The arguments are parsed. Usage is no longer needed. cmd.SilenceUsage = true // Errors will be handled by logging from here on. cmd.SilenceErrors = true return nil } cmd.RunE = func(*cobra.Command, []string) error { return runSignalWrapper(c) } // Override Cobra's default messages. cmd.PersistentFlags().BoolP("help", "h", false, "Display help information for cloud-sql-proxy") cmd.PersistentFlags().BoolP("version", "v", false, "Print the cloud-sql-proxy version") // Global-only flags cmd.PersistentFlags().StringVarP(&c.conf.Token, "token", "t", "", "Use bearer token as a source of IAM credentials.") cmd.PersistentFlags().StringVarP(&c.conf.CredentialsFile, "credentials-file", "c", "", "Use service account key file as a source of IAM credentials.") cmd.PersistentFlags().BoolVarP(&c.conf.GcloudAuth, "gcloud-auth", "g", false, "Use gcloud's user credentials as a source of IAM credentials.") cmd.PersistentFlags().BoolVarP(&c.conf.StructuredLogs, "structured-logs", "l", false, "Enable structured logging with LogEntry format") cmd.PersistentFlags().Uint64Var(&c.conf.MaxConnections, "max-connections", 0, "Limit the number of connections. Default is no limit.") cmd.PersistentFlags().DurationVar(&c.conf.WaitOnClose, "max-sigterm-delay", 0, "Maximum number of seconds to wait for connections to close after receiving a TERM signal.") cmd.PersistentFlags().StringVar(&c.telemetryProject, "telemetry-project", "", "Enable Cloud Monitoring and Cloud Trace with the provided project ID.") cmd.PersistentFlags().BoolVar(&c.disableTraces, "disable-traces", false, "Disable Cloud Trace integration (used with --telemetry-project)") cmd.PersistentFlags().IntVar(&c.telemetryTracingSampleRate, "telemetry-sample-rate", 10_000, "Set the Cloud Trace sample rate. A smaller number means more traces.") cmd.PersistentFlags().BoolVar(&c.disableMetrics, "disable-metrics", false, "Disable Cloud Monitoring integration (used with --telemetry-project)") cmd.PersistentFlags().StringVar(&c.telemetryPrefix, "telemetry-prefix", "", "Prefix for Cloud Monitoring metrics.") cmd.PersistentFlags().BoolVar(&c.prometheus, "prometheus", false, "Enable Prometheus HTTP endpoint /metrics on localhost") cmd.PersistentFlags().StringVar(&c.prometheusNamespace, "prometheus-namespace", "", "Use the provided Prometheus namespace for metrics") cmd.PersistentFlags().StringVar(&c.httpAddress, "http-address", "localhost", "Address for Prometheus and health check server") cmd.PersistentFlags().StringVar(&c.httpPort, "http-port", "9090", "Port for Prometheus and health check server") cmd.PersistentFlags().BoolVar(&c.healthCheck, "health-check", false, "Enables health check endpoints /startup, /liveness, and /readiness on localhost.") cmd.PersistentFlags().StringVar(&c.conf.APIEndpointURL, "sqladmin-api-endpoint", "", "API endpoint for all Cloud SQL Admin API requests. (default: https://sqladmin.googleapis.com)") cmd.PersistentFlags().StringVar(&c.conf.QuotaProject, "quota-project", "", `Specifies the project for Cloud SQL Admin API quota tracking. Must have "serviceusage.service.use" IAM permission.`) // Global and per instance flags cmd.PersistentFlags().StringVarP(&c.conf.Addr, "address", "a", "127.0.0.1", "(*) Address to bind Cloud SQL instance listeners.") cmd.PersistentFlags().IntVarP(&c.conf.Port, "port", "p", 0, "(*) Initial port for listeners. Subsequent listeners increment from this value.") cmd.PersistentFlags().StringVarP(&c.conf.UnixSocket, "unix-socket", "u", "", `(*) Enables Unix sockets for all listeners with the provided directory.`) cmd.PersistentFlags().BoolVarP(&c.conf.IAMAuthN, "auto-iam-authn", "i", false, "(*) Enables Automatic IAM Authentication for all instances") cmd.PersistentFlags().BoolVar(&c.conf.PrivateIP, "private-ip", false, "(*) Connect to the private ip address for all instances") return c } func parseConfig(cmd *Command, conf *proxy.Config, args []string) error { // If no instance connection names were provided, error. if len(args) == 0 { return newBadCommandError("missing instance_connection_name (e.g., project:region:instance)") } userHasSet := func(f string) bool { return cmd.PersistentFlags().Lookup(f).Changed } if userHasSet("address") && userHasSet("unix-socket") { return newBadCommandError("cannot specify --unix-socket and --address together") } if userHasSet("port") && userHasSet("unix-socket") { return newBadCommandError("cannot specify --unix-socket and --port together") } if ip := net.ParseIP(conf.Addr); ip == nil { return newBadCommandError(fmt.Sprintf("not a valid IP address: %q", conf.Addr)) } // If more than one auth method is set, error. if conf.Token != "" && conf.CredentialsFile != "" { return newBadCommandError("cannot specify --token and --credentials-file flags at the same time") } if conf.Token != "" && conf.GcloudAuth { return newBadCommandError("cannot specify --token and --gcloud-auth flags at the same time") } if conf.CredentialsFile != "" && conf.GcloudAuth { return newBadCommandError("cannot specify --credentials-file and --gcloud-auth flags at the same time") } if userHasSet("http-port") && !userHasSet("prometheus") && !userHasSet("health-check") { cmd.logger.Infof("Ignoring --http-port because --prometheus or --health-check was not set") } if !userHasSet("telemetry-project") && userHasSet("telemetry-prefix") { cmd.logger.Infof("Ignoring --telementry-prefix because --telemetry-project was not set") } if !userHasSet("telemetry-project") && userHasSet("disable-metrics") { cmd.logger.Infof("Ignoring --disable-metrics because --telemetry-project was not set") } if !userHasSet("telemetry-project") && userHasSet("disable-traces") { cmd.logger.Infof("Ignoring --disable-traces because --telemetry-project was not set") } if userHasSet("sqladmin-api-endpoint") && conf.APIEndpointURL != "" { _, err := url.Parse(conf.APIEndpointURL) if err != nil { return newBadCommandError(fmt.Sprintf("the value provided for --sqladmin-api-endpoint is not a valid URL, %v", conf.APIEndpointURL)) } // add a trailing '/' if omitted if !strings.HasSuffix(conf.APIEndpointURL, "/") { conf.APIEndpointURL = conf.APIEndpointURL + "/" } } var ics []proxy.InstanceConnConfig for _, a := range args { // Assume no query params initially ic := proxy.InstanceConnConfig{ Name: a, } // If there are query params, update instance config. if res := strings.SplitN(a, "?", 2); len(res) > 1 { ic.Name = res[0] q, err := url.ParseQuery(res[1]) if err != nil { return newBadCommandError(fmt.Sprintf("could not parse query: %q", res[1])) } a, aok := q["address"] p, pok := q["port"] u, uok := q["unix-socket"] if aok && uok { return newBadCommandError("cannot specify both address and unix-socket query params") } if pok && uok { return newBadCommandError("cannot specify both port and unix-socket query params") } if aok { if len(a) != 1 { return newBadCommandError(fmt.Sprintf("address query param should be only one value: %q", a)) } if ip := net.ParseIP(a[0]); ip == nil { return newBadCommandError( fmt.Sprintf("address query param is not a valid IP address: %q", a[0], )) } ic.Addr = a[0] } if pok { if len(p) != 1 { return newBadCommandError(fmt.Sprintf("port query param should be only one value: %q", a)) } pp, err := strconv.Atoi(p[0]) if err != nil { return newBadCommandError( fmt.Sprintf("port query param is not a valid integer: %q", p[0], )) } ic.Port = pp } if uok { if len(u) != 1 { return newBadCommandError(fmt.Sprintf("unix query param should be only one value: %q", a)) } ic.UnixSocket = u[0] } ic.IAMAuthN, err = parseBoolOpt(q, "auto-iam-authn") if err != nil { return err } ic.PrivateIP, err = parseBoolOpt(q, "private-ip") if err != nil { return err } } ics = append(ics, ic) } conf.Instances = ics return nil } // parseBoolOpt parses a boolean option from the query string, returning // // true if the value is "t" or "true" case-insensitive // false if the value is "f" or "false" case-insensitive func parseBoolOpt(q url.Values, name string) (*bool, error) { iam, ok := q[name] if !ok { return nil, nil } if len(iam) != 1 { return nil, newBadCommandError(fmt.Sprintf("%v param should be only one value: %q", name, iam)) } switch strings.ToLower(iam[0]) { case "true", "t", "": enable := true return &enable, nil case "false", "f": disable := false return &disable, nil default: // value is not recognized return nil, newBadCommandError( fmt.Sprintf("%v query param should be true or false, got: %q", name, iam[0], )) } } // runSignalWrapper watches for SIGTERM and SIGINT and interupts execution if necessary. func runSignalWrapper(cmd *Command) error { defer cmd.cleanup() ctx, cancel := context.WithCancel(cmd.Context()) defer cancel() // Configure collectors before the proxy has started to ensure we are // collecting metrics before *ANY* Cloud SQL Admin API calls are made. enableMetrics := !cmd.disableMetrics enableTraces := !cmd.disableTraces if cmd.telemetryProject != "" && (enableMetrics || enableTraces) { sd, err := stackdriver.NewExporter(stackdriver.Options{ ProjectID: cmd.telemetryProject, MetricPrefix: cmd.telemetryPrefix, }) if err != nil { return err } if enableMetrics { err = sd.StartMetricsExporter() if err != nil { return err } } if enableTraces { s := trace.ProbabilitySampler(1 / float64(cmd.telemetryTracingSampleRate)) trace.ApplyConfig(trace.Config{DefaultSampler: s}) trace.RegisterExporter(sd) } defer func() { sd.Flush() sd.StopMetricsExporter() }() } var ( needsHTTPServer bool mux = http.NewServeMux() ) if cmd.prometheus { needsHTTPServer = true e, err := prometheus.NewExporter(prometheus.Options{ Namespace: cmd.prometheusNamespace, }) if err != nil { return err } mux.Handle("/metrics", e) } shutdownCh := make(chan error) // watch for sigterm / sigint signals signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT) go func() { var s os.Signal select { case s = <-signals: case <-ctx.Done(): // this should only happen when the context supplied in tests in canceled s = syscall.SIGINT } switch s { case syscall.SIGINT: shutdownCh <- errSigInt case syscall.SIGTERM: shutdownCh <- errSigTerm } }() // Start the proxy asynchronously, so we can exit early if a shutdown signal is sent startCh := make(chan *proxy.Client) go func() { defer close(startCh) p, err := proxy.NewClient(ctx, cmd.dialer, cmd.logger, cmd.conf) if err != nil { shutdownCh <- fmt.Errorf("unable to start: %v", err) return } startCh <- p }() // Wait for either startup to finish or a signal to interupt var p *proxy.Client select { case err := <-shutdownCh: cmd.logger.Errorf("The proxy has encountered a terminal error: %v", err) return err case p = <-startCh: cmd.logger.Infof("The proxy has started successfully and is ready for new connections!") } defer func() { if cErr := p.Close(); cErr != nil { cmd.logger.Errorf("error during shutdown: %v", cErr) } }() notify := func() {} if cmd.healthCheck { needsHTTPServer = true hc := healthcheck.NewCheck(p, cmd.logger) mux.HandleFunc("/startup", hc.HandleStartup) mux.HandleFunc("/readiness", hc.HandleReadiness) mux.HandleFunc("/liveness", hc.HandleLiveness) notify = hc.NotifyStarted } // Start the HTTP server if anything requiring HTTP is specified. if needsHTTPServer { server := &http.Server{ Addr: fmt.Sprintf("%s:%s", cmd.httpAddress, cmd.httpPort), Handler: mux, } // Start the HTTP server. go func() { err := server.ListenAndServe() if err == http.ErrServerClosed { return } if err != nil { shutdownCh <- fmt.Errorf("failed to start HTTP server: %v", err) } }() // Handle shutdown of the HTTP server gracefully. go func() { select { case <-ctx.Done(): // Give the HTTP server a second to shutdown cleanly. ctx2, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := server.Shutdown(ctx2); err != nil { cmd.logger.Errorf("failed to shutdown Prometheus HTTP server: %v\n", err) } } }() } go func() { shutdownCh <- p.Serve(ctx, notify) }() err := <-shutdownCh switch { case errors.Is(err, errSigInt): cmd.logger.Errorf("SIGINT signal received. Shutting down...") case errors.Is(err, errSigTerm): cmd.logger.Errorf("SIGTERM signal received. Shutting down...") default: cmd.logger.Errorf("The proxy has encountered a terminal error: %v", err) } return err }
package orm import "gopkg.in/mgo.v2/bson" import "github.com/lfq7413/tomato/utils" import "regexp" import "strings" // transformKey 把 key 转换为数据库中保存的格式 func transformKey(schema *Schema, className, key string) string { k, _ := transformKeyValue(schema, className, key, nil, nil) return k } // transformKeyValue 把传入的键值对转换为数据库中保存的格式 func transformKeyValue(schema *Schema, className, restKey string, restValue interface{}, options bson.M) (string, interface{}) { if options == nil { options = bson.M{} } // 检测 key 是否为 内置字段 key := restKey timeField := false switch key { case "objectId", "_id": key = "_id" case "createdAt", "_created_at": key = "_created_at" timeField = true case "updatedAt", "_updated_at": key = "_updated_at" timeField = true case "_email_verify_token": key = "_email_verify_token" case "_perishable_token": key = "_perishable_token" case "sessionToken", "_session_token": key = "_session_token" case "expiresAt", "_expiresAt": key = "_expiresAt" timeField = true case "_rperm", "_wperm": return key, restValue case "$or": if options["query"] == nil { // TODO 只有查询时才能使用 or return "", nil } querys := utils.SliceInterface(restValue) if querys == nil { // TODO 待转换值必须为数组类型 return "", nil } mongoSubqueries := []interface{}{} for _, v := range querys { query := transformWhere(schema, className, utils.MapInterface(v)) mongoSubqueries = append(mongoSubqueries, query) } return "$or", mongoSubqueries case "$and": if options["query"] == nil { // TODO 只有查询时才能使用 and return "", nil } querys := utils.SliceInterface(restValue) if querys == nil { // TODO 待转换值必须为数组类型 return "", nil } mongoSubqueries := []interface{}{} for _, v := range querys { query := transformWhere(schema, className, utils.MapInterface(v)) mongoSubqueries = append(mongoSubqueries, query) } return "$and", mongoSubqueries default: // 处理第三方 auth 数据 authDataMatch, _ := regexp.MatchString(`^authData\.([a-zA-Z0-9_]+)\.id$`, key) if authDataMatch { if options["query"] != nil { provider := key[len("authData."):(len(key) - len(".id"))] return "_auth_data_" + provider + ".id", restKey } // TODO 只能将其应用查询操作 return "", nil } // 默认处理 if options["validate"] != nil { keyMatch, _ := regexp.MatchString(`^[a-zA-Z][a-zA-Z0-9_\.]*$`, key) if keyMatch == false { // TODO 无效的键名 return "", nil } } } // 处理特殊键值 expected := "" if schema != nil { expected = schema.getExpectedType(className, key) } // 处理指向其他对象的字段 if expected != "" && strings.HasPrefix(expected, "*") { key = "_p_" + key } if expected == "" && restValue != nil { op := utils.MapInterface(restValue) if op != nil && op["__type"] != nil { if utils.String(op["__type"]) == "Pointer" { key = "_p_" + key } } } inArray := false if expected == "array" { inArray = true } // 处理查询操作 if options["query"] != nil { value := transformConstraint(restValue, inArray) if value != cannotTransform() { return key, value } } if inArray && options["query"] != nil && utils.SliceInterface(restValue) == nil { return key, bson.M{"$all": []interface{}{restValue}} } // 处理原子数据 value := transformAtom(restValue, false, options) if value != cannotTransform() { if timeField && utils.String(value) != "" { value, _ = utils.StringtoTime(utils.String(value)) } return key, value } // ACL 在此之前处理,如果依然出现,则返回错误 if key == "ACL" { // TODO 不能在此转换 ACL return "", nil } // 处理数组类型 if valueArray, ok := restValue.([]interface{}); ok { if options["query"] != nil { // TODO 查询时不能为数组 return "", nil } outValue := []interface{}{} for _, restObj := range valueArray { _, v := transformKeyValue(schema, className, restKey, restObj, bson.M{"inArray": true}) outValue = append(outValue, v) } return key, outValue } // 处理更新操作 var flatten bool if options["update"] == nil { flatten = true } else { flatten = false } value = transformUpdateOperator(restValue, flatten) if value != cannotTransform() { return key, value } // 处理正常的对象 normalValue := bson.M{} for subRestKey, subRestValue := range utils.MapInterface(restValue) { k, v := transformKeyValue(schema, className, subRestKey, subRestValue, bson.M{"inObject": true}) normalValue[k] = v } return key, normalValue } func transformConstraint(constraint interface{}, inArray bool) interface{} { // TODO return nil } func transformAtom(atom interface{}, force bool, options bson.M) interface{} { // TODO return nil } func transformUpdateOperator(operator interface{}, flatten bool) interface{} { // TODO return nil } // transformCreate ... func transformCreate(schema *Schema, className string, create bson.M) bson.M { // TODO return nil } func transformWhere(schema *Schema, className string, where bson.M) bson.M { // TODO return nil } func transformUpdate(schema *Schema, className string, update bson.M) bson.M { // TODO return nil } func untransformObjectT(schema *Schema, className string, mongoObject interface{}, isNestedObject bool) interface{} { // TODO return nil } func cannotTransform() interface{} { return nil } 完成 transformConstraint package orm import "gopkg.in/mgo.v2/bson" import "github.com/lfq7413/tomato/utils" import "regexp" import "strings" import "sort" // transformKey 把 key 转换为数据库中保存的格式 func transformKey(schema *Schema, className, key string) string { k, _ := transformKeyValue(schema, className, key, nil, nil) return k } // transformKeyValue 把传入的键值对转换为数据库中保存的格式 func transformKeyValue(schema *Schema, className, restKey string, restValue interface{}, options bson.M) (string, interface{}) { if options == nil { options = bson.M{} } // 检测 key 是否为 内置字段 key := restKey timeField := false switch key { case "objectId", "_id": key = "_id" case "createdAt", "_created_at": key = "_created_at" timeField = true case "updatedAt", "_updated_at": key = "_updated_at" timeField = true case "_email_verify_token": key = "_email_verify_token" case "_perishable_token": key = "_perishable_token" case "sessionToken", "_session_token": key = "_session_token" case "expiresAt", "_expiresAt": key = "_expiresAt" timeField = true case "_rperm", "_wperm": return key, restValue case "$or": if options["query"] == nil { // TODO 只有查询时才能使用 or return "", nil } querys := utils.SliceInterface(restValue) if querys == nil { // TODO 待转换值必须为数组类型 return "", nil } mongoSubqueries := []interface{}{} for _, v := range querys { query := transformWhere(schema, className, utils.MapInterface(v)) mongoSubqueries = append(mongoSubqueries, query) } return "$or", mongoSubqueries case "$and": if options["query"] == nil { // TODO 只有查询时才能使用 and return "", nil } querys := utils.SliceInterface(restValue) if querys == nil { // TODO 待转换值必须为数组类型 return "", nil } mongoSubqueries := []interface{}{} for _, v := range querys { query := transformWhere(schema, className, utils.MapInterface(v)) mongoSubqueries = append(mongoSubqueries, query) } return "$and", mongoSubqueries default: // 处理第三方 auth 数据 authDataMatch, _ := regexp.MatchString(`^authData\.([a-zA-Z0-9_]+)\.id$`, key) if authDataMatch { if options["query"] != nil { provider := key[len("authData."):(len(key) - len(".id"))] return "_auth_data_" + provider + ".id", restKey } // TODO 只能将其应用查询操作 return "", nil } // 默认处理 if options["validate"] != nil { keyMatch, _ := regexp.MatchString(`^[a-zA-Z][a-zA-Z0-9_\.]*$`, key) if keyMatch == false { // TODO 无效的键名 return "", nil } } } // 处理特殊键值 expected := "" if schema != nil { expected = schema.getExpectedType(className, key) } // 处理指向其他对象的字段 if expected != "" && strings.HasPrefix(expected, "*") { key = "_p_" + key } if expected == "" && restValue != nil { op := utils.MapInterface(restValue) if op != nil && op["__type"] != nil { if utils.String(op["__type"]) == "Pointer" { key = "_p_" + key } } } inArray := false if expected == "array" { inArray = true } // 处理查询操作 if options["query"] != nil { value := transformConstraint(restValue, inArray) if value != cannotTransform() { return key, value } } if inArray && options["query"] != nil && utils.SliceInterface(restValue) == nil { return key, bson.M{"$all": []interface{}{restValue}} } // 处理原子数据 value := transformAtom(restValue, false, options) if value != cannotTransform() { if timeField && utils.String(value) != "" { value, _ = utils.StringtoTime(utils.String(value)) } return key, value } // ACL 在此之前处理,如果依然出现,则返回错误 if key == "ACL" { // TODO 不能在此转换 ACL return "", nil } // 处理数组类型 if valueArray, ok := restValue.([]interface{}); ok { if options["query"] != nil { // TODO 查询时不能为数组 return "", nil } outValue := []interface{}{} for _, restObj := range valueArray { _, v := transformKeyValue(schema, className, restKey, restObj, bson.M{"inArray": true}) outValue = append(outValue, v) } return key, outValue } // 处理更新操作 var flatten bool if options["update"] == nil { flatten = true } else { flatten = false } value = transformUpdateOperator(restValue, flatten) if value != cannotTransform() { return key, value } // 处理正常的对象 normalValue := bson.M{} for subRestKey, subRestValue := range utils.MapInterface(restValue) { k, v := transformKeyValue(schema, className, subRestKey, subRestValue, bson.M{"inObject": true}) normalValue[k] = v } return key, normalValue } func transformConstraint(constraint interface{}, inArray bool) interface{} { // TODO 需要根据 MongoDB 文档修正参数 if constraint == nil && utils.MapInterface(constraint) == nil { return cannotTransform() } // keys is the constraints in reverse alphabetical order. // This is a hack so that: // $regex is handled before $options // $nearSphere is handled before $maxDistance object := utils.MapInterface(constraint) keys := []string{} for k := range object { keys = append(keys, k) } sort.Sort(sort.Reverse(sort.StringSlice(keys))) answer := bson.M{} for _, key := range keys { switch key { case "$lt", "$lte", "$gt", "$gte", "$exists", "$ne", "$eq": answer[key] = transformAtom(object[key], true, bson.M{"inArray": inArray}) case "$in", "$nin": arr := utils.SliceInterface(object[key]) if arr == nil { // TODO 必须为数组 return nil } answerArr := []interface{}{} for _, v := range arr { answerArr = append(answerArr, transformAtom(v, true, bson.M{})) } answer[key] = answerArr case "$all": arr := utils.SliceInterface(object[key]) if arr == nil { // TODO 必须为数组 return nil } answerArr := []interface{}{} for _, v := range arr { answerArr = append(answerArr, transformAtom(v, true, bson.M{"inArray": true})) } answer[key] = answerArr case "$regex": s := utils.String(object[key]) if s == "" { // TODO 必须为字符串 return nil } answer[key] = s case "$options": options := utils.String(object[key]) if answer["$regex"] == nil || options == "" { // TODO 无效值 return nil } b, _ := regexp.MatchString(`^[imxs]+$`, options) if b == false { // TODO 无效值 return nil } answer[key] = options case "$nearSphere": point := utils.MapInterface(object[key]) answer[key] = []interface{}{point["longitude"], point["latitude"]} case "$maxDistance": answer[key] = object[key] // 以下三项在 SDK 中未使用,但是在 REST API 中使用了 case "$maxDistanceInRadians": answer["$maxDistance"] = object[key] case "$maxDistanceInMiles": var distance float64 if v, ok := object[key].(float64); ok { distance = v / 3959 } answer["$maxDistance"] = distance case "$maxDistanceInKilometers": var distance float64 if v, ok := object[key].(float64); ok { distance = v / 6371 } answer["$maxDistance"] = distance case "$select", "$dontSelect": // TODO 暂时不支持该参数 return nil case "$within": within := utils.MapInterface(object[key]) box := utils.SliceInterface(within["$box"]) if box == nil || len(box) != 2 { // TODO 参数不正确 return nil } box1 := utils.MapInterface(box[0]) box2 := utils.MapInterface(box[1]) answer[key] = bson.M{ "$box": []interface{}{ []interface{}{box1["longitude"], box1["latitude"]}, []interface{}{box2["longitude"], box2["latitude"]}, }, } default: b, _ := regexp.MatchString(`^\$+`, key) if b { // TODO 无效参数 return nil } return cannotTransform() } } return answer } func transformAtom(atom interface{}, force bool, options bson.M) interface{} { // TODO return nil } func transformUpdateOperator(operator interface{}, flatten bool) interface{} { // TODO return nil } // transformCreate ... func transformCreate(schema *Schema, className string, create bson.M) bson.M { // TODO return nil } func transformWhere(schema *Schema, className string, where bson.M) bson.M { // TODO return nil } func transformUpdate(schema *Schema, className string, update bson.M) bson.M { // TODO return nil } func untransformObjectT(schema *Schema, className string, mongoObject interface{}, isNestedObject bool) interface{} { // TODO return nil } func cannotTransform() interface{} { return nil }
// // Copyright 2015 Gregory Trubetskoy. All Rights Reserved. // // 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 serde import ( "bytes" "database/sql" "fmt" "github.com/lib/pq" "github.com/tgres/tgres/rrd" "log" "math" "strconv" "strings" "time" ) type pgSerDe struct { dbConn *sql.DB sql1, sql2, sql3, sql4, sql5, sql6, sql7 *sql.Stmt prefix string } func sqlOpen(a, b string) (*sql.DB, error) { return sql.Open(a, b) } func InitDb(connect_string, prefix string) (rrd.SerDe, error) { if dbConn, err := sql.Open("postgres", connect_string); err != nil { return nil, err } else { p := &pgSerDe{dbConn: dbConn, prefix: prefix} if err := p.dbConn.Ping(); err != nil { return nil, err } if err := p.createTablesIfNotExist(); err != nil { return nil, err } if err := p.prepareSqlStatements(); err != nil { return nil, err } return rrd.SerDe(p), nil } } func (p *pgSerDe) prepareSqlStatements() error { var err error if p.sql1, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sts ts SET dp[$1:$2] = $3 WHERE rra_id = $4 AND n = $5", p.prefix)); err != nil { return err } if p.sql2, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]srra rra SET value = $1, unknown_ms = $2, latest = $3 WHERE id = $4", p.prefix)); err != nil { return err } if p.sql3, err = p.dbConn.Prepare(fmt.Sprintf("SELECT max(tg) mt, avg(r) ar FROM generate_series($1, $2, ($3)::interval) AS tg "+ "LEFT OUTER JOIN (SELECT t, r FROM %[1]stv tv WHERE ds_id = $4 AND rra_id = $5 "+ " AND t >= $6 AND t <= $7) s ON tg = s.t GROUP BY trunc((extract(epoch from tg)*1000-1))::bigint/$8 ORDER BY mt", p.prefix)); err != nil { return err } if p.sql4, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sds AS ds (name, step_ms, heartbeat_ms) VALUES ($1, $2, $3) "+ // PG 9.5 required. NB: DO NOTHING causes RETURNING to return nothing, so we're using this dummy UPDATE to work around. "ON CONFLICT (name) DO UPDATE SET step_ms = ds.step_ms "+ "RETURNING id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms", p.prefix)); err != nil { return err } if p.sql5, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]srra (ds_id, cf, steps_per_row, size, xff) VALUES ($1, $2, $3, $4, $5) "+ "RETURNING id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest", p.prefix)); err != nil { return err } if p.sql6, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sts (rra_id, n) VALUES ($1, $2)", p.prefix)); err != nil { return err } if p.sql7, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sds SET lastupdate = $1, last_ds = $2, value = $3, unknown_ms = $4 WHERE id = $5", p.prefix)); err != nil { return err } return nil } func (p *pgSerDe) createTablesIfNotExist() error { create_sql := ` CREATE TABLE IF NOT EXISTS %[1]sds ( id SERIAL NOT NULL PRIMARY KEY, name TEXT NOT NULL, step_ms BIGINT NOT NULL, heartbeat_ms BIGINT NOT NULL, lastupdate TIMESTAMPTZ, last_ds NUMERIC DEFAULT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS %[1]srra ( id SERIAL NOT NULL PRIMARY KEY, ds_id INT NOT NULL, cf TEXT NOT NULL, steps_per_row INT NOT NULL, size INT NOT NULL, width INT NOT NULL DEFAULT 768, xff REAL NOT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0, latest TIMESTAMPTZ DEFAULT NULL); CREATE TABLE IF NOT EXISTS %[1]sts ( rra_id INT NOT NULL, n INT NOT NULL, dp DOUBLE PRECISION[] NOT NULL DEFAULT '{}'); ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { log.Printf("ERROR: initial CREATE TABLE failed: %v", err) return err } else { rows.Close() } create_sql = ` CREATE VIEW %[1]stv AS SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, UNNEST(dp) AS r FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id; CREATE VIEW %[1]stvd AS SELECT ds_id, rra_id, tstzrange(lag(t, 1) OVER (PARTITION BY ds_id, rra_id ORDER BY t), t, '(]') tr, r, step, row, row_n, abs_n, last_n, last_t, slot_distance FROM ( SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, extract(epoch from (latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size))) AS tu, UNNEST(dp) AS r, interval '1 millisecond' * ds.step_ms * rra.steps_per_row AS step, n AS row, generate_subscripts(dp,1) AS row_n, generate_subscripts(dp,1) + n * width AS abs_n, mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 AS last_n, extract(epoch from rra.latest)::bigint*1000 AS last_t, mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS slot_distance FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id) foo; ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE VIEW failed: %v", err) return err } } else { rows.Close() } create_sql = ` CREATE UNIQUE INDEX idx_ds_name ON %[1]sds (name); ` // There is no IF NOT EXISTS for CREATE INDEX until 9.5 if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE INDEX failed: %v", err) return err } } else { rows.Close() } create_sql = ` CREATE UNIQUE INDEX idx_rra_rra_id_n ON %[1]sts (rra_id, n); ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE INDEX failed: %v", err) return err } } else { rows.Close() } return nil } // This implements the Series interface type dbSeries struct { ds *rrd.DataSource rra *rrd.RoundRobinArchive // Current Value value float64 posBegin time.Time // pos begins after posEnd time.Time // pos ends on // Time boundary from time.Time to time.Time // Db stuff db *pgSerDe rows *sql.Rows // These are not the same: maxPoints int64 // max points we want groupByMs int64 // requested alignment latest time.Time // Alias alias string } func (dps *dbSeries) StepMs() int64 { return dps.ds.StepMs * int64(dps.rra.StepsPerRow) } func (dps *dbSeries) GroupByMs(ms ...int64) int64 { if len(ms) > 0 { defer func() { dps.groupByMs = ms[0] }() } if dps.groupByMs == 0 { return dps.StepMs() } return dps.groupByMs } func (dps *dbSeries) TimeRange(t ...time.Time) (time.Time, time.Time) { if len(t) == 1 { defer func() { dps.from = t[0] }() } else if len(t) == 2 { defer func() { dps.from, dps.to = t[0], t[1] }() } return dps.from, dps.to } func (dps *dbSeries) LastUpdate() time.Time { return dps.ds.LastUpdate } func (dps *dbSeries) MaxPoints(n ...int64) int64 { if len(n) > 0 { // setter defer func() { dps.maxPoints = n[0] }() } return dps.maxPoints // getter } func (dps *dbSeries) Align() {} func (dps *dbSeries) Alias(s ...string) string { if len(s) > 0 { dps.alias = s[0] } return dps.alias } func (dps *dbSeries) seriesQuerySqlUsingViewAndSeries() (*sql.Rows, error) { var ( rows *sql.Rows err error ) var ( finalGroupByMs int64 rraStepMs = dps.ds.StepMs * int64(dps.rra.StepsPerRow) ) if dps.groupByMs != 0 { // Specific granularity was requested for alignment, we ignore maxPoints finalGroupByMs = finalGroupByMs/dps.groupByMs*dps.groupByMs + dps.groupByMs } else if dps.maxPoints != 0 { // If maxPoints was specified, then calculate group by interval finalGroupByMs = (dps.to.Unix() - dps.from.Unix()) * 1000 / dps.maxPoints finalGroupByMs = finalGroupByMs/rraStepMs*rraStepMs + rraStepMs } else { // Otherwise, group by will equal the rrastep finalGroupByMs = rraStepMs } if finalGroupByMs == 0 { finalGroupByMs = 1000 // TODO Why would this happen (it did)? } // Ensure that the true group by interval is reflected in the series. if finalGroupByMs != dps.groupByMs { dps.groupByMs = finalGroupByMs } // TODO: support milliseconds? aligned_from := time.Unix(dps.from.Unix()/(finalGroupByMs/1000)*(finalGroupByMs/1000), 0) //log.Printf("sql3 %v %v %v %v %v %v %v %v", aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) rows, err = dps.db.sql3.Query(aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) if err != nil { log.Printf("seriesQuery(): error %v", err) return nil, err } return rows, nil } func (dps *dbSeries) Next() bool { if dps.rows == nil { // First Next() rows, err := dps.seriesQuerySqlUsingViewAndSeries() if err == nil { dps.rows = rows } else { log.Printf("dbSeries.Next(): database error: %v", err) return false } } if dps.rows.Next() { if ts, value, err := timeValueFromRow(dps.rows); err != nil { log.Printf("dbSeries.Next(): database error: %v", err) return false } else { dps.posBegin = dps.latest dps.posEnd = ts dps.value = value dps.latest = dps.posEnd } return true } else { // See if we have data points that haven't been synced yet if len(dps.rra.DPs) > 0 && dps.latest.Before(dps.rra.Latest) { // TODO this is kinda ugly? // Should RRA's implement Series interface perhaps? // because rra.DPs is a map there is no quick way to find the // earliest entry, we have to traverse the map. It seems // tempting to come with an alternative solution, but it's not // as simple as it seems, and given that this is mostly about // the tip of the series, this is good enough. // we do not provide averaging points here for the same reason for len(dps.rra.DPs) > 0 { earliest := dps.rra.Latest.Add(time.Millisecond) earliestSlotN := int64(-1) for n, _ := range dps.rra.DPs { ts := dps.rra.SlotTimeStamp(dps.ds, n) if ts.Before(earliest) && ts.After(dps.latest) { earliest, earliestSlotN = ts, n } } if earliestSlotN != -1 { dps.posBegin = dps.latest dps.posEnd = earliest dps.value = dps.rra.DPs[earliestSlotN] dps.latest = earliest delete(dps.rra.DPs, earliestSlotN) var from, to time.Time if dps.from.IsZero() { from = time.Unix(0, 0) } else { from = dps.from } if dps.to.IsZero() { to = dps.rra.Latest.Add(time.Millisecond) } else { to = dps.to } if earliest.Add(time.Millisecond).After(from) && earliest.Before(to.Add(time.Millisecond)) { return true } } else { return false } } } } return false } func (dps *dbSeries) CurrentValue() float64 { return dps.value } func (dps *dbSeries) CurrentPosBeginsAfter() time.Time { return dps.posBegin } func (dps *dbSeries) CurrentPosEndsOn() time.Time { return dps.posEnd } func (dps *dbSeries) Close() error { result := dps.rows.Close() dps.rows = nil // next Next() will re-open return result } func timeValueFromRow(rows *sql.Rows) (time.Time, float64, error) { var ( value sql.NullFloat64 ts time.Time ) if err := rows.Scan(&ts, &value); err == nil { if value.Valid { return ts, value.Float64, nil } else { return ts, math.NaN(), nil } } else { return time.Time{}, math.NaN(), err } } func dataSourceFromRow(rows *sql.Rows) (*rrd.DataSource, error) { var ( ds rrd.DataSource last_ds sql.NullFloat64 lastupdate pq.NullTime ) err := rows.Scan(&ds.Id, &ds.Name, &ds.StepMs, &ds.HeartbeatMs, &lastupdate, &last_ds, &ds.Value, &ds.UnknownMs) if err != nil { log.Printf("dataSourceFromRow(): error scanning row: %v", err) return nil, err } if last_ds.Valid { ds.LastDs = last_ds.Float64 } else { ds.LastDs = math.NaN() } if lastupdate.Valid { ds.LastUpdate = lastupdate.Time } else { ds.LastUpdate = time.Unix(0, 0) } return &ds, err } func roundRobinArchiveFromRow(rows *sql.Rows) (*rrd.RoundRobinArchive, error) { var ( latest pq.NullTime rra rrd.RoundRobinArchive ) err := rows.Scan(&rra.Id, &rra.DsId, &rra.Cf, &rra.StepsPerRow, &rra.Size, &rra.Width, &rra.Xff, &rra.Value, &rra.UnknownMs, &latest) if err != nil { log.Printf("roundRoundRobinArchiveFromRow(): error scanning row: %v", err) return nil, err } if latest.Valid { rra.Latest = latest.Time } else { rra.Latest = time.Unix(0, 0) } rra.DPs = make(map[int64]float64) return &rra, err } func (p *pgSerDe) FetchDataSources() ([]*rrd.DataSource, error) { const sql = `SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("fetchDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]*rrd.DataSource, 0) for rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("fetchDataSources(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } result = append(result, ds) } return result, nil } func (p *pgSerDe) fetchRoundRobinArchives(ds_id int64) ([]*rrd.RoundRobinArchive, error) { const sql = `SELECT id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest FROM %[1]srra rra WHERE ds_id = $1` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix), ds_id) if err != nil { log.Printf("fetchRoundRobinArchives(): error querying database: %v", err) return nil, err } defer rows.Close() var rras []*rrd.RoundRobinArchive for rows.Next() { if rra, err := roundRobinArchiveFromRow(rows); err == nil { rras = append(rras, rra) } else { log.Printf("fetchRoundRobinArchives(): error: %v", err) return nil, err } } return rras, nil } func dpsAsString(dps map[int64]float64, start, end int64) string { var b bytes.Buffer b.WriteString("{") for i := start; i <= end; i++ { b.WriteString(strconv.FormatFloat(dps[int64(i)], 'f', -1, 64)) if i != end { b.WriteString(",") } } b.WriteString("}") return b.String() } func (p *pgSerDe) FlushRoundRobinArchive(rra *rrd.RoundRobinArchive) error { var n int64 rraSize := int64(rra.Size) if int32(len(rra.DPs)) == rra.Size { // The whole thing for n = 0; n < rra.SlotRow(rraSize); n++ { end := rra.Width - 1 if n == rraSize/int64(rra.Width) { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*int64(rra.Width), n*int64(rra.Width)+rra.Width-1) if rows, err := p.sql1.Query(1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } else if rra.Start <= rra.End { // Single range for n = rra.Start / int64(rra.Width); n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } else { // Double range (wrap-around, end < start) // range 1: 0 -> end for n = 0; n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } // range 2: start -> Size for n = rra.Start / rra.Width; n < rra.SlotRow(rraSize); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rraSize/rra.Width { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } if rows, err := p.sql2.Query(rra.Value, rra.UnknownMs, rra.Latest, rra.Id); err == nil { rows.Close() } else { return err } return nil } func (p *pgSerDe) FlushDataSource(ds *rrd.DataSource) error { for _, rra := range ds.RRAs { if len(rra.DPs) > 0 { if err := p.FlushRoundRobinArchive(rra); err != nil { log.Printf("flushDataSource(): error flushing RRA, probable data loss: %v", err) return err } } } if rows, err := p.sql7.Query(ds.LastUpdate, ds.LastDs, ds.Value, ds.UnknownMs, ds.Id); err != nil { log.Printf("flushDataSource(): database error: %v", err) } else { rows.Close() } return nil } func (p *pgSerDe) CreateOrReturnDataSource(name string, dsSpec *rrd.DSSpec) (*rrd.DataSource, error) { rows, err := p.sql4.Query(name, dsSpec.Step.Nanoseconds()/1000000, dsSpec.Heartbeat.Nanoseconds()/1000000) if err != nil { log.Printf("createDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() rows.Next() ds, err := dataSourceFromRow(rows) if err != nil { log.Printf("createDataSources(): error: %v", err) return nil, err } // RRAs for _, rraSpec := range dsSpec.RRAs { steps := rraSpec.Step.Nanoseconds() / (ds.StepMs * 1000000) size := rraSpec.Size.Nanoseconds() / rraSpec.Step.Nanoseconds() rraRows, err := p.sql5.Query(ds.Id, rraSpec.Function, steps, size, rraSpec.Xff) if err != nil { log.Printf("createDataSources(): error creating RRAs: %v", err) return nil, err } rraRows.Next() rra, err := roundRobinArchiveFromRow(rraRows) if err != nil { log.Printf("createDataSources(): error2: %v", err) return nil, err } ds.RRAs = append(ds.RRAs, rra) for n := int64(0); n <= (int64(rra.Size)/rra.Width + int64(rra.Size)%rra.Width/rra.Width); n++ { r, err := p.sql6.Query(rra.Id, n) if err != nil { log.Printf("createDataSources(): error creating TSs: %v", err) return nil, err } r.Close() } rraRows.Close() } return ds, nil } // // Data layout notes. // // So we store datapoints as an array, and we know the latest // timestamp. Every time we advance to the next point, so does the // latest timestamp. By knowing the latest timestamp and the size of // the array, we can identify which array element is last, it is: // slots_since_epoch % slots // // If we take a slot with a number slot_n, its distance from the // latest slot can be calculated by this formula: // // distance = (total_slots + last_slot_n - slot_n) % total_slots // // E.g. with total_slots 100, slot_n 55 and last_slot_n 50: // // (100 + 50 - 55) % 100 => 95 // // This means that if we advance forward from 55 by 95 slots, which // means at step 45 we'll reach the end of the array, and start from // the beginning, we'll arrive at 50. // // Or with total_slots 100, slot_n 45 and last_slot_n 50: // // (100 + 50 - 45) % 100 => 5 // func (p *pgSerDe) SeriesQuery(ds *rrd.DataSource, from, to time.Time, maxPoints int64) (rrd.Series, error) { rra := ds.BestRRA(from, to, maxPoints) // If from/to are nil - assign the rra boundaries rraEarliest := time.Unix(rra.GetStartGivenEndMs(ds, rra.Latest.Unix()*1000)/1000, 0) if from.IsZero() || rraEarliest.After(from) { from = rraEarliest } if to.IsZero() || to.After(rra.Latest) { to = rra.Latest } dps := &dbSeries{db: p, ds: ds, rra: rra, from: from, to: to, maxPoints: maxPoints} return rrd.Series(dps), nil } Switch to create index if not exists // // Copyright 2015 Gregory Trubetskoy. All Rights Reserved. // // 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 serde import ( "bytes" "database/sql" "fmt" "github.com/lib/pq" "github.com/tgres/tgres/rrd" "log" "math" "strconv" "strings" "time" ) type pgSerDe struct { dbConn *sql.DB sql1, sql2, sql3, sql4, sql5, sql6, sql7 *sql.Stmt prefix string } func sqlOpen(a, b string) (*sql.DB, error) { return sql.Open(a, b) } func InitDb(connect_string, prefix string) (rrd.SerDe, error) { if dbConn, err := sql.Open("postgres", connect_string); err != nil { return nil, err } else { p := &pgSerDe{dbConn: dbConn, prefix: prefix} if err := p.dbConn.Ping(); err != nil { return nil, err } if err := p.createTablesIfNotExist(); err != nil { return nil, err } if err := p.prepareSqlStatements(); err != nil { return nil, err } return rrd.SerDe(p), nil } } func (p *pgSerDe) prepareSqlStatements() error { var err error if p.sql1, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sts ts SET dp[$1:$2] = $3 WHERE rra_id = $4 AND n = $5", p.prefix)); err != nil { return err } if p.sql2, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]srra rra SET value = $1, unknown_ms = $2, latest = $3 WHERE id = $4", p.prefix)); err != nil { return err } if p.sql3, err = p.dbConn.Prepare(fmt.Sprintf("SELECT max(tg) mt, avg(r) ar FROM generate_series($1, $2, ($3)::interval) AS tg "+ "LEFT OUTER JOIN (SELECT t, r FROM %[1]stv tv WHERE ds_id = $4 AND rra_id = $5 "+ " AND t >= $6 AND t <= $7) s ON tg = s.t GROUP BY trunc((extract(epoch from tg)*1000-1))::bigint/$8 ORDER BY mt", p.prefix)); err != nil { return err } if p.sql4, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sds AS ds (name, step_ms, heartbeat_ms) VALUES ($1, $2, $3) "+ // PG 9.5 required. NB: DO NOTHING causes RETURNING to return nothing, so we're using this dummy UPDATE to work around. "ON CONFLICT (name) DO UPDATE SET step_ms = ds.step_ms "+ "RETURNING id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms", p.prefix)); err != nil { return err } if p.sql5, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]srra (ds_id, cf, steps_per_row, size, xff) VALUES ($1, $2, $3, $4, $5) "+ "RETURNING id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest", p.prefix)); err != nil { return err } if p.sql6, err = p.dbConn.Prepare(fmt.Sprintf("INSERT INTO %[1]sts (rra_id, n) VALUES ($1, $2)", p.prefix)); err != nil { return err } if p.sql7, err = p.dbConn.Prepare(fmt.Sprintf("UPDATE %[1]sds SET lastupdate = $1, last_ds = $2, value = $3, unknown_ms = $4 WHERE id = $5", p.prefix)); err != nil { return err } return nil } func (p *pgSerDe) createTablesIfNotExist() error { create_sql := ` CREATE TABLE IF NOT EXISTS %[1]sds ( id SERIAL NOT NULL PRIMARY KEY, name TEXT NOT NULL, step_ms BIGINT NOT NULL, heartbeat_ms BIGINT NOT NULL, lastupdate TIMESTAMPTZ, last_ds NUMERIC DEFAULT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_ds_name ON %[1]sds (name); CREATE TABLE IF NOT EXISTS %[1]srra ( id SERIAL NOT NULL PRIMARY KEY, ds_id INT NOT NULL, cf TEXT NOT NULL, steps_per_row INT NOT NULL, size INT NOT NULL, width INT NOT NULL DEFAULT 768, xff REAL NOT NULL, value DOUBLE PRECISION NOT NULL DEFAULT 'NaN', unknown_ms BIGINT NOT NULL DEFAULT 0, latest TIMESTAMPTZ DEFAULT NULL); CREATE TABLE IF NOT EXISTS %[1]sts ( rra_id INT NOT NULL, n INT NOT NULL, dp DOUBLE PRECISION[] NOT NULL DEFAULT '{}'); CREATE UNIQUE INDEX IF NOT EXISTS %[1]s_idx_rra_rra_id_n ON %[1]sts (rra_id, n); ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { log.Printf("ERROR: initial CREATE TABLE failed: %v", err) return err } else { rows.Close() } create_sql = ` CREATE VIEW %[1]stv AS SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, UNNEST(dp) AS r FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id; CREATE VIEW %[1]stvd AS SELECT ds_id, rra_id, tstzrange(lag(t, 1) OVER (PARTITION BY ds_id, rra_id ORDER BY t), t, '(]') tr, r, step, row, row_n, abs_n, last_n, last_t, slot_distance FROM ( SELECT ds.id ds_id, rra.id rra_id, latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS t, extract(epoch from (latest - interval '1 millisecond' * ds.step_ms * rra.steps_per_row * mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size))) AS tu, UNNEST(dp) AS r, interval '1 millisecond' * ds.step_ms * rra.steps_per_row AS step, n AS row, generate_subscripts(dp,1) AS row_n, generate_subscripts(dp,1) + n * width AS abs_n, mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 AS last_n, extract(epoch from rra.latest)::bigint*1000 AS last_t, mod(rra.size + mod(extract(epoch from rra.latest)::bigint*1000/(ds.step_ms * rra.steps_per_row), size) + 1 - (generate_subscripts(dp,1) + n * width), rra.size) AS slot_distance FROM %[1]sds ds INNER JOIN %[1]srra rra ON rra.ds_id = ds.id INNER JOIN %[1]sts ts ON ts.rra_id = rra.id) foo; ` if rows, err := p.dbConn.Query(fmt.Sprintf(create_sql, p.prefix)); err != nil { if !strings.Contains(err.Error(), "already exists") { log.Printf("ERROR: initial CREATE VIEW failed: %v", err) return err } } else { rows.Close() } return nil } // This implements the Series interface type dbSeries struct { ds *rrd.DataSource rra *rrd.RoundRobinArchive // Current Value value float64 posBegin time.Time // pos begins after posEnd time.Time // pos ends on // Time boundary from time.Time to time.Time // Db stuff db *pgSerDe rows *sql.Rows // These are not the same: maxPoints int64 // max points we want groupByMs int64 // requested alignment latest time.Time // Alias alias string } func (dps *dbSeries) StepMs() int64 { return dps.ds.StepMs * int64(dps.rra.StepsPerRow) } func (dps *dbSeries) GroupByMs(ms ...int64) int64 { if len(ms) > 0 { defer func() { dps.groupByMs = ms[0] }() } if dps.groupByMs == 0 { return dps.StepMs() } return dps.groupByMs } func (dps *dbSeries) TimeRange(t ...time.Time) (time.Time, time.Time) { if len(t) == 1 { defer func() { dps.from = t[0] }() } else if len(t) == 2 { defer func() { dps.from, dps.to = t[0], t[1] }() } return dps.from, dps.to } func (dps *dbSeries) LastUpdate() time.Time { return dps.ds.LastUpdate } func (dps *dbSeries) MaxPoints(n ...int64) int64 { if len(n) > 0 { // setter defer func() { dps.maxPoints = n[0] }() } return dps.maxPoints // getter } func (dps *dbSeries) Align() {} func (dps *dbSeries) Alias(s ...string) string { if len(s) > 0 { dps.alias = s[0] } return dps.alias } func (dps *dbSeries) seriesQuerySqlUsingViewAndSeries() (*sql.Rows, error) { var ( rows *sql.Rows err error ) var ( finalGroupByMs int64 rraStepMs = dps.ds.StepMs * int64(dps.rra.StepsPerRow) ) if dps.groupByMs != 0 { // Specific granularity was requested for alignment, we ignore maxPoints finalGroupByMs = finalGroupByMs/dps.groupByMs*dps.groupByMs + dps.groupByMs } else if dps.maxPoints != 0 { // If maxPoints was specified, then calculate group by interval finalGroupByMs = (dps.to.Unix() - dps.from.Unix()) * 1000 / dps.maxPoints finalGroupByMs = finalGroupByMs/rraStepMs*rraStepMs + rraStepMs } else { // Otherwise, group by will equal the rrastep finalGroupByMs = rraStepMs } if finalGroupByMs == 0 { finalGroupByMs = 1000 // TODO Why would this happen (it did)? } // Ensure that the true group by interval is reflected in the series. if finalGroupByMs != dps.groupByMs { dps.groupByMs = finalGroupByMs } // TODO: support milliseconds? aligned_from := time.Unix(dps.from.Unix()/(finalGroupByMs/1000)*(finalGroupByMs/1000), 0) //log.Printf("sql3 %v %v %v %v %v %v %v %v", aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) rows, err = dps.db.sql3.Query(aligned_from, dps.to, fmt.Sprintf("%d milliseconds", rraStepMs), dps.ds.Id, dps.rra.Id, dps.from, dps.to, finalGroupByMs) if err != nil { log.Printf("seriesQuery(): error %v", err) return nil, err } return rows, nil } func (dps *dbSeries) Next() bool { if dps.rows == nil { // First Next() rows, err := dps.seriesQuerySqlUsingViewAndSeries() if err == nil { dps.rows = rows } else { log.Printf("dbSeries.Next(): database error: %v", err) return false } } if dps.rows.Next() { if ts, value, err := timeValueFromRow(dps.rows); err != nil { log.Printf("dbSeries.Next(): database error: %v", err) return false } else { dps.posBegin = dps.latest dps.posEnd = ts dps.value = value dps.latest = dps.posEnd } return true } else { // See if we have data points that haven't been synced yet if len(dps.rra.DPs) > 0 && dps.latest.Before(dps.rra.Latest) { // TODO this is kinda ugly? // Should RRA's implement Series interface perhaps? // because rra.DPs is a map there is no quick way to find the // earliest entry, we have to traverse the map. It seems // tempting to come with an alternative solution, but it's not // as simple as it seems, and given that this is mostly about // the tip of the series, this is good enough. // we do not provide averaging points here for the same reason for len(dps.rra.DPs) > 0 { earliest := dps.rra.Latest.Add(time.Millisecond) earliestSlotN := int64(-1) for n, _ := range dps.rra.DPs { ts := dps.rra.SlotTimeStamp(dps.ds, n) if ts.Before(earliest) && ts.After(dps.latest) { earliest, earliestSlotN = ts, n } } if earliestSlotN != -1 { dps.posBegin = dps.latest dps.posEnd = earliest dps.value = dps.rra.DPs[earliestSlotN] dps.latest = earliest delete(dps.rra.DPs, earliestSlotN) var from, to time.Time if dps.from.IsZero() { from = time.Unix(0, 0) } else { from = dps.from } if dps.to.IsZero() { to = dps.rra.Latest.Add(time.Millisecond) } else { to = dps.to } if earliest.Add(time.Millisecond).After(from) && earliest.Before(to.Add(time.Millisecond)) { return true } } else { return false } } } } return false } func (dps *dbSeries) CurrentValue() float64 { return dps.value } func (dps *dbSeries) CurrentPosBeginsAfter() time.Time { return dps.posBegin } func (dps *dbSeries) CurrentPosEndsOn() time.Time { return dps.posEnd } func (dps *dbSeries) Close() error { result := dps.rows.Close() dps.rows = nil // next Next() will re-open return result } func timeValueFromRow(rows *sql.Rows) (time.Time, float64, error) { var ( value sql.NullFloat64 ts time.Time ) if err := rows.Scan(&ts, &value); err == nil { if value.Valid { return ts, value.Float64, nil } else { return ts, math.NaN(), nil } } else { return time.Time{}, math.NaN(), err } } func dataSourceFromRow(rows *sql.Rows) (*rrd.DataSource, error) { var ( ds rrd.DataSource last_ds sql.NullFloat64 lastupdate pq.NullTime ) err := rows.Scan(&ds.Id, &ds.Name, &ds.StepMs, &ds.HeartbeatMs, &lastupdate, &last_ds, &ds.Value, &ds.UnknownMs) if err != nil { log.Printf("dataSourceFromRow(): error scanning row: %v", err) return nil, err } if last_ds.Valid { ds.LastDs = last_ds.Float64 } else { ds.LastDs = math.NaN() } if lastupdate.Valid { ds.LastUpdate = lastupdate.Time } else { ds.LastUpdate = time.Unix(0, 0) } return &ds, err } func roundRobinArchiveFromRow(rows *sql.Rows) (*rrd.RoundRobinArchive, error) { var ( latest pq.NullTime rra rrd.RoundRobinArchive ) err := rows.Scan(&rra.Id, &rra.DsId, &rra.Cf, &rra.StepsPerRow, &rra.Size, &rra.Width, &rra.Xff, &rra.Value, &rra.UnknownMs, &latest) if err != nil { log.Printf("roundRoundRobinArchiveFromRow(): error scanning row: %v", err) return nil, err } if latest.Valid { rra.Latest = latest.Time } else { rra.Latest = time.Unix(0, 0) } rra.DPs = make(map[int64]float64) return &rra, err } func (p *pgSerDe) FetchDataSources() ([]*rrd.DataSource, error) { const sql = `SELECT id, name, step_ms, heartbeat_ms, lastupdate, last_ds, value, unknown_ms FROM %[1]sds ds` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix)) if err != nil { log.Printf("fetchDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() result := make([]*rrd.DataSource, 0) for rows.Next() { ds, err := dataSourceFromRow(rows) rras, err := p.fetchRoundRobinArchives(ds.Id) if err != nil { log.Printf("fetchDataSources(): error fetching RRAs: %v", err) return nil, err } else { ds.RRAs = rras } result = append(result, ds) } return result, nil } func (p *pgSerDe) fetchRoundRobinArchives(ds_id int64) ([]*rrd.RoundRobinArchive, error) { const sql = `SELECT id, ds_id, cf, steps_per_row, size, width, xff, value, unknown_ms, latest FROM %[1]srra rra WHERE ds_id = $1` rows, err := p.dbConn.Query(fmt.Sprintf(sql, p.prefix), ds_id) if err != nil { log.Printf("fetchRoundRobinArchives(): error querying database: %v", err) return nil, err } defer rows.Close() var rras []*rrd.RoundRobinArchive for rows.Next() { if rra, err := roundRobinArchiveFromRow(rows); err == nil { rras = append(rras, rra) } else { log.Printf("fetchRoundRobinArchives(): error: %v", err) return nil, err } } return rras, nil } func dpsAsString(dps map[int64]float64, start, end int64) string { var b bytes.Buffer b.WriteString("{") for i := start; i <= end; i++ { b.WriteString(strconv.FormatFloat(dps[int64(i)], 'f', -1, 64)) if i != end { b.WriteString(",") } } b.WriteString("}") return b.String() } func (p *pgSerDe) FlushRoundRobinArchive(rra *rrd.RoundRobinArchive) error { var n int64 rraSize := int64(rra.Size) if int32(len(rra.DPs)) == rra.Size { // The whole thing for n = 0; n < rra.SlotRow(rraSize); n++ { end := rra.Width - 1 if n == rraSize/int64(rra.Width) { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*int64(rra.Width), n*int64(rra.Width)+rra.Width-1) if rows, err := p.sql1.Query(1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } else if rra.Start <= rra.End { // Single range for n = rra.Start / int64(rra.Width); n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } else { // Double range (wrap-around, end < start) // range 1: 0 -> end for n = 0; n < rra.SlotRow(rra.End); n++ { start, end := int64(0), rra.Width-1 if n == rra.End/rra.Width { end = rra.End % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } // range 2: start -> Size for n = rra.Start / rra.Width; n < rra.SlotRow(rraSize); n++ { start, end := int64(0), rra.Width-1 if n == rra.Start/rra.Width { start = rra.Start % rra.Width } if n == rraSize/rra.Width { end = (rraSize - 1) % rra.Width } dps := dpsAsString(rra.DPs, n*rra.Width+start, n*rra.Width+end) if rows, err := p.sql1.Query(start+1, end+1, dps, rra.Id, n); err == nil { rows.Close() } else { return err } } } if rows, err := p.sql2.Query(rra.Value, rra.UnknownMs, rra.Latest, rra.Id); err == nil { rows.Close() } else { return err } return nil } func (p *pgSerDe) FlushDataSource(ds *rrd.DataSource) error { for _, rra := range ds.RRAs { if len(rra.DPs) > 0 { if err := p.FlushRoundRobinArchive(rra); err != nil { log.Printf("flushDataSource(): error flushing RRA, probable data loss: %v", err) return err } } } if rows, err := p.sql7.Query(ds.LastUpdate, ds.LastDs, ds.Value, ds.UnknownMs, ds.Id); err != nil { log.Printf("flushDataSource(): database error: %v", err) } else { rows.Close() } return nil } func (p *pgSerDe) CreateOrReturnDataSource(name string, dsSpec *rrd.DSSpec) (*rrd.DataSource, error) { rows, err := p.sql4.Query(name, dsSpec.Step.Nanoseconds()/1000000, dsSpec.Heartbeat.Nanoseconds()/1000000) if err != nil { log.Printf("createDataSources(): error querying database: %v", err) return nil, err } defer rows.Close() rows.Next() ds, err := dataSourceFromRow(rows) if err != nil { log.Printf("createDataSources(): error: %v", err) return nil, err } // RRAs for _, rraSpec := range dsSpec.RRAs { steps := rraSpec.Step.Nanoseconds() / (ds.StepMs * 1000000) size := rraSpec.Size.Nanoseconds() / rraSpec.Step.Nanoseconds() rraRows, err := p.sql5.Query(ds.Id, rraSpec.Function, steps, size, rraSpec.Xff) if err != nil { log.Printf("createDataSources(): error creating RRAs: %v", err) return nil, err } rraRows.Next() rra, err := roundRobinArchiveFromRow(rraRows) if err != nil { log.Printf("createDataSources(): error2: %v", err) return nil, err } ds.RRAs = append(ds.RRAs, rra) for n := int64(0); n <= (int64(rra.Size)/rra.Width + int64(rra.Size)%rra.Width/rra.Width); n++ { r, err := p.sql6.Query(rra.Id, n) if err != nil { log.Printf("createDataSources(): error creating TSs: %v", err) return nil, err } r.Close() } rraRows.Close() } return ds, nil } // // Data layout notes. // // So we store datapoints as an array, and we know the latest // timestamp. Every time we advance to the next point, so does the // latest timestamp. By knowing the latest timestamp and the size of // the array, we can identify which array element is last, it is: // slots_since_epoch % slots // // If we take a slot with a number slot_n, its distance from the // latest slot can be calculated by this formula: // // distance = (total_slots + last_slot_n - slot_n) % total_slots // // E.g. with total_slots 100, slot_n 55 and last_slot_n 50: // // (100 + 50 - 55) % 100 => 95 // // This means that if we advance forward from 55 by 95 slots, which // means at step 45 we'll reach the end of the array, and start from // the beginning, we'll arrive at 50. // // Or with total_slots 100, slot_n 45 and last_slot_n 50: // // (100 + 50 - 45) % 100 => 5 // func (p *pgSerDe) SeriesQuery(ds *rrd.DataSource, from, to time.Time, maxPoints int64) (rrd.Series, error) { rra := ds.BestRRA(from, to, maxPoints) // If from/to are nil - assign the rra boundaries rraEarliest := time.Unix(rra.GetStartGivenEndMs(ds, rra.Latest.Unix()*1000)/1000, 0) if from.IsZero() || rraEarliest.After(from) { from = rraEarliest } if to.IsZero() || to.After(rra.Latest) { to = rra.Latest } dps := &dbSeries{db: p, ds: ds, rra: rra, from: from, to: to, maxPoints: maxPoints} return rrd.Series(dps), nil }
// Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com> // // 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 ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "io/ioutil" "log" "net" "os" "os/signal" "strings" "syscall" "time" "github.com/karimra/gnmic/collector" homedir "github.com/mitchellh/go-homedir" "github.com/mitchellh/mapstructure" "github.com/openconfig/gnmi/proto/gnmi" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" "golang.org/x/crypto/ssh/terminal" "google.golang.org/grpc" "google.golang.org/grpc/grpclog" "google.golang.org/protobuf/proto" ) const ( defaultGrpcPort = "57400" ) const ( msgSize = 512 * 1024 * 1024 ) var encodings = []string{"json", "bytes", "proto", "ascii", "json_ietf"} var cfgFile string var f io.WriteCloser var logger *log.Logger // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "gnmic", Short: "run gnmi rpcs from the terminal (https://gnmic.kmrd.dev)", PersistentPreRun: func(cmd *cobra.Command, args []string) { if viper.GetString("log-file") != "" { var err error f, err = os.OpenFile(viper.GetString("log-file"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { logger.Fatalf("error opening file: %v", err) } } else { if viper.GetBool("debug") { viper.Set("log", true) } switch viper.GetBool("log") { case true: f = os.Stderr case false: f = myWriteCloser{ioutil.Discard} } } loggingFlags := log.LstdFlags | log.Lmicroseconds if viper.GetBool("debug") { loggingFlags |= log.Llongfile } logger = log.New(f, "gnmic ", loggingFlags) if viper.GetBool("debug") { grpclog.SetLogger(logger) //lint:ignore SA1019 see https://github.com/karimra/gnmic/issues/59 } }, PersistentPostRun: func(cmd *cobra.Command, args []string) { if !viper.GetBool("log") || viper.GetString("log-file") != "" { f.Close() } }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { //fmt.Println(err) os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/gnmic.yaml)") rootCmd.PersistentFlags().StringSliceP("address", "a", []string{}, "comma separated gnmi targets addresses") rootCmd.PersistentFlags().StringP("username", "u", "", "username") rootCmd.PersistentFlags().StringP("password", "p", "", "password") rootCmd.PersistentFlags().StringP("port", "", defaultGrpcPort, "gRPC port") rootCmd.PersistentFlags().StringP("encoding", "e", "json", fmt.Sprintf("one of %+v. Case insensitive", encodings)) rootCmd.PersistentFlags().BoolP("insecure", "", false, "insecure connection") rootCmd.PersistentFlags().StringP("tls-ca", "", "", "tls certificate authority") rootCmd.PersistentFlags().StringP("tls-cert", "", "", "tls certificate") rootCmd.PersistentFlags().StringP("tls-key", "", "", "tls key") rootCmd.PersistentFlags().DurationP("timeout", "", 10*time.Second, "grpc timeout, valid formats: 10s, 1m30s, 1h") rootCmd.PersistentFlags().BoolP("debug", "d", false, "debug mode") rootCmd.PersistentFlags().BoolP("skip-verify", "", false, "skip verify tls connection") rootCmd.PersistentFlags().BoolP("no-prefix", "", false, "do not add [ip:port] prefix to print output in case of multiple targets") rootCmd.PersistentFlags().BoolP("proxy-from-env", "", false, "use proxy from environment") rootCmd.PersistentFlags().StringP("format", "", "", "output format, one of: [protojson, prototext, json, event]") rootCmd.PersistentFlags().StringP("log-file", "", "", "log file path") rootCmd.PersistentFlags().BoolP("log", "", false, "show log messages in stderr") rootCmd.PersistentFlags().IntP("max-msg-size", "", msgSize, "max grpc msg size") rootCmd.PersistentFlags().StringP("prometheus-address", "", "", "prometheus server address") rootCmd.PersistentFlags().BoolP("print-request", "", false, "print request as well as the response(s)") // viper.BindPFlag("address", rootCmd.PersistentFlags().Lookup("address")) viper.BindPFlag("username", rootCmd.PersistentFlags().Lookup("username")) viper.BindPFlag("password", rootCmd.PersistentFlags().Lookup("password")) viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port")) viper.BindPFlag("encoding", rootCmd.PersistentFlags().Lookup("encoding")) viper.BindPFlag("insecure", rootCmd.PersistentFlags().Lookup("insecure")) viper.BindPFlag("tls-ca", rootCmd.PersistentFlags().Lookup("tls-ca")) viper.BindPFlag("tls-cert", rootCmd.PersistentFlags().Lookup("tls-cert")) viper.BindPFlag("tls-key", rootCmd.PersistentFlags().Lookup("tls-key")) viper.BindPFlag("timeout", rootCmd.PersistentFlags().Lookup("timeout")) viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) viper.BindPFlag("skip-verify", rootCmd.PersistentFlags().Lookup("skip-verify")) viper.BindPFlag("no-prefix", rootCmd.PersistentFlags().Lookup("no-prefix")) viper.BindPFlag("proxy-from-env", rootCmd.PersistentFlags().Lookup("proxy-from-env")) viper.BindPFlag("format", rootCmd.PersistentFlags().Lookup("format")) viper.BindPFlag("log-file", rootCmd.PersistentFlags().Lookup("log-file")) viper.BindPFlag("log", rootCmd.PersistentFlags().Lookup("log")) viper.BindPFlag("max-msg-size", rootCmd.PersistentFlags().Lookup("max-msg-size")) viper.BindPFlag("prometheus-address", rootCmd.PersistentFlags().Lookup("prometheus-address")) viper.BindPFlag("print-request", rootCmd.PersistentFlags().Lookup("print-request")) } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".gnmic" (without extension). viper.AddConfigPath(home) viper.SetConfigName("gnmic") } //viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. viper.ReadInConfig() postInitCommands(rootCmd.Commands()) } func postInitCommands(commands []*cobra.Command) { for _, cmd := range commands { presetRequiredFlags(cmd) if cmd.HasSubCommands() { postInitCommands(cmd.Commands()) } } } func presetRequiredFlags(cmd *cobra.Command) { cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { flagName := fmt.Sprintf("%s-%s", cmd.Name(), f.Name) value := viper.Get(flagName) if value != nil && viper.IsSet(flagName) && !f.Changed { var err error switch value := value.(type) { case string: err = cmd.LocalFlags().Set(f.Name, value) case []interface{}: ls := make([]string, len(value)) for i := range value { ls[i] = value[i].(string) } err = cmd.LocalFlags().Set(f.Name, strings.Join(ls, ",")) case []string: err = cmd.LocalFlags().Set(f.Name, strings.Join(value, ",")) default: fmt.Printf("unexpected config value type, value=%v, type=%T\n", value, value) } if err != nil { fmt.Printf("failed setting flag '%s' from viper: %v\n", flagName, err) } } }) } func readUsername() (string, error) { var username string fmt.Print("username: ") _, err := fmt.Scan(&username) if err != nil { return "", err } return username, nil } func readPassword() (string, error) { fmt.Print("password: ") pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return "", err } fmt.Println() return string(pass), nil } func loadCerts(tlscfg *tls.Config) error { tlsCert := viper.GetString("tls-cert") tlsKey := viper.GetString("tls-key") if tlsCert != "" && tlsKey != "" { certificate, err := tls.LoadX509KeyPair(tlsCert, tlsKey) if err != nil { return err } tlscfg.Certificates = []tls.Certificate{certificate} tlscfg.BuildNameToCertificate() } return nil } func loadCACerts(tlscfg *tls.Config) error { tlsCa := viper.GetString("tls-ca") certPool := x509.NewCertPool() if tlsCa != "" { caFile, err := ioutil.ReadFile(tlsCa) if err != nil { return err } if ok := certPool.AppendCertsFromPEM(caFile); !ok { return errors.New("failed to append certificate") } tlscfg.RootCAs = certPool } return nil } func printer(ctx context.Context, c chan string) { for { select { case m := <-c: fmt.Println(m) case <-ctx.Done(): return } } } func gather(ctx context.Context, c chan string, ls *[]string) { for { select { case m := <-c: *ls = append(*ls, m) case <-ctx.Done(): return } } } type myWriteCloser struct { io.Writer } func (myWriteCloser) Close() error { return nil } func indent(prefix, s string) string { if prefix == "" { return s } prefix = "\n" + strings.TrimRight(prefix, "\n") lines := strings.Split(s, "\n") return strings.TrimLeft(fmt.Sprintf("%s%s", prefix, strings.Join(lines, prefix)), "\n") } func filterModels(ctx context.Context, t *collector.Target, modelsNames []string) (map[string]*gnmi.ModelData, []string, error) { capResp, err := t.Capabilities(ctx) if err != nil { return nil, nil, err } unsupportedModels := make([]string, 0) supportedModels := make(map[string]*gnmi.ModelData) var found bool for _, m := range modelsNames { found = false for _, tModel := range capResp.SupportedModels { if m == tModel.Name { supportedModels[m] = tModel found = true break } } if !found { unsupportedModels = append(unsupportedModels, m) } } return supportedModels, unsupportedModels, nil } func setupCloseHandler(cancelFn context.CancelFunc) { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) go func() { sig := <-c fmt.Printf("\nreceived signal '%s'. terminating...\n", sig.String()) cancelFn() os.Exit(0) }() } func numTargets() int { addressesLength := len(viper.GetStringSlice("address")) if addressesLength > 0 { return addressesLength } targets := viper.Get("targets") switch targets := targets.(type) { case string: return len(strings.Split(targets, " ")) case map[string]interface{}: return len(targets) } return 0 } func createTargets() (map[string]*collector.TargetConfig, error) { addresses := viper.GetStringSlice("address") targets := make(map[string]*collector.TargetConfig) defGrpcPort := viper.GetString("port") // case address is defined in config file if len(addresses) > 0 { if viper.GetString("username") == "" { defUsername, err := readUsername() if err != nil { return nil, err } viper.Set("username", defUsername) } if viper.GetString("password") == "" { defPassword, err := readPassword() if err != nil { return nil, err } viper.Set("password", defPassword) } for _, addr := range addresses { tc := new(collector.TargetConfig) if !strings.HasPrefix(addr, "unix://") { _, _, err := net.SplitHostPort(addr) if err != nil { if strings.Contains(err.Error(), "missing port in address") { addr = net.JoinHostPort(addr, defGrpcPort) } else { logger.Printf("error parsing address '%s': %v", addr, err) return nil, fmt.Errorf("error parsing address '%s': %v", addr, err) } } } tc.Address = addr setTargetConfigDefaults(tc) targets[tc.Name] = tc } return targets, nil } // case targets is defined in config file targetsInt := viper.Get("targets") targetsMap := make(map[string]interface{}) switch targetsInt := targetsInt.(type) { case string: for _, addr := range strings.Split(targetsInt, " ") { targetsMap[addr] = nil } case map[string]interface{}: targetsMap = targetsInt default: return nil, fmt.Errorf("unexpected targets format, got: %T", targetsInt) } if len(targetsMap) == 0 { return nil, fmt.Errorf("no targets found") } for addr, t := range targetsMap { if !strings.HasPrefix(addr, "unix://") { _, _, err := net.SplitHostPort(addr) if err != nil { if strings.Contains(err.Error(), "missing port in address") { addr = net.JoinHostPort(addr, defGrpcPort) } else { logger.Printf("error parsing address '%s': %v", addr, err) return nil, fmt.Errorf("error parsing address '%s': %v", addr, err) } } } tc := new(collector.TargetConfig) switch t := t.(type) { case map[string]interface{}: decoder, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ DecodeHook: mapstructure.StringToTimeDurationHookFunc(), Result: tc, }, ) if err != nil { return nil, err } err = decoder.Decode(t) if err != nil { return nil, err } case nil: default: return nil, fmt.Errorf("unexpected targets format, got a %T", t) } tc.Address = addr setTargetConfigDefaults(tc) if viper.GetBool("debug") { logger.Printf("read target config: %s", tc) } targets[tc.Name] = tc } subNames := viper.GetStringSlice("subscribe-name") if len(subNames) == 0 { return targets, nil } for n := range targets { targets[n].Subscriptions = subNames } return targets, nil } func setTargetConfigDefaults(tc *collector.TargetConfig) { if tc.Name == "" { tc.Name = tc.Address } if tc.Username == nil { s := viper.GetString("username") tc.Username = &s } if tc.Password == nil { s := viper.GetString("password") tc.Password = &s } if tc.Timeout == 0 { tc.Timeout = viper.GetDuration("timeout") } if tc.Insecure == nil { b := viper.GetBool("insecure") tc.Insecure = &b } if tc.SkipVerify == nil { b := viper.GetBool("skip-verify") tc.SkipVerify = &b } if tc.Insecure != nil && !*tc.Insecure { if tc.TLSCA == nil { s := viper.GetString("tls-ca") if s != "" { tc.TLSCA = &s } } if tc.TLSCert == nil { s := viper.GetString("tls-cert") tc.TLSCert = &s } if tc.TLSKey == nil { s := viper.GetString("tls-key") tc.TLSKey = &s } } } func createCollectorDialOpts() []grpc.DialOption { opts := []grpc.DialOption{} opts = append(opts, grpc.WithBlock()) if viper.GetInt("max-msg-size") > 0 { opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(viper.GetInt("max-msg-size")))) } if !viper.GetBool("proxy-from-env") { opts = append(opts, grpc.WithNoProxy()) } return opts } func printMsg(address string, msg proto.Message) error { printPrefix := "" if numTargets() > 1 && !viper.GetBool("no-prefix") { printPrefix = fmt.Sprintf("[%s] ", address) } switch msg := msg.ProtoReflect().Interface().(type) { case *gnmi.CapabilityResponse: if len(viper.GetString("format")) == 0 { printCapResponse(printPrefix, msg) return nil } } mo := collector.MarshalOptions{ Multiline: true, Indent: " ", Format: viper.GetString("format"), } b, err := mo.Marshal(msg, map[string]string{"address": address}) if err != nil { return err } sb := strings.Builder{} sb.Write(b) fmt.Printf("%s\n", indent(printPrefix, sb.String())) return nil } func printCapResponse(printPrefix string, msg *gnmi.CapabilityResponse) { sb := strings.Builder{} sb.WriteString(printPrefix) sb.WriteString("gNMI version: ") sb.WriteString(msg.GNMIVersion) sb.WriteString("\n") if viper.GetBool("version") { return } sb.WriteString(printPrefix) sb.WriteString("supported models:\n") for _, sm := range msg.SupportedModels { sb.WriteString(printPrefix) sb.WriteString(" - ") sb.WriteString(sm.GetName()) sb.WriteString(", ") sb.WriteString(sm.GetOrganization()) sb.WriteString(", ") sb.WriteString(sm.GetVersion()) sb.WriteString("\n") } sb.WriteString(printPrefix) sb.WriteString("supported encodings:\n") for _, se := range msg.SupportedEncodings { sb.WriteString(printPrefix) sb.WriteString(" - ") sb.WriteString(se.String()) sb.WriteString("\n") } fmt.Printf("%s\n", indent(printPrefix, sb.String())) } log config file used, print it if debug // Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com> // // 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 ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "io/ioutil" "log" "net" "os" "os/signal" "strings" "syscall" "time" "github.com/karimra/gnmic/collector" homedir "github.com/mitchellh/go-homedir" "github.com/mitchellh/mapstructure" "github.com/openconfig/gnmi/proto/gnmi" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" "golang.org/x/crypto/ssh/terminal" "google.golang.org/grpc" "google.golang.org/grpc/grpclog" "google.golang.org/protobuf/proto" ) const ( defaultGrpcPort = "57400" ) const ( msgSize = 512 * 1024 * 1024 ) var encodings = []string{"json", "bytes", "proto", "ascii", "json_ietf"} var cfgFile string var f io.WriteCloser var logger *log.Logger // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "gnmic", Short: "run gnmi rpcs from the terminal (https://gnmic.kmrd.dev)", PersistentPreRun: func(cmd *cobra.Command, args []string) { debug := viper.GetBool("debug") if viper.GetString("log-file") != "" { var err error f, err = os.OpenFile(viper.GetString("log-file"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { logger.Fatalf("error opening file: %v", err) } } else { if debug { viper.Set("log", true) } switch viper.GetBool("log") { case true: f = os.Stderr case false: f = myWriteCloser{ioutil.Discard} } } loggingFlags := log.LstdFlags | log.Lmicroseconds if debug { loggingFlags |= log.Llongfile } logger = log.New(f, "gnmic ", loggingFlags) if debug { grpclog.SetLogger(logger) //lint:ignore SA1019 see https://github.com/karimra/gnmic/issues/59 } cfgFile := viper.ConfigFileUsed() if len(cfgFile) != 0 { logger.Printf("using config file %s", cfgFile) if debug { b, err := ioutil.ReadFile(cfgFile) if err != nil { logger.Printf("failed reading config file %s: %v", cfgFile, err) return } logger.Printf("config file:\n%s", string(b)) } } }, PersistentPostRun: func(cmd *cobra.Command, args []string) { if !viper.GetBool("log") || viper.GetString("log-file") != "" { f.Close() } }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { //fmt.Println(err) os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/gnmic.yaml)") rootCmd.PersistentFlags().StringSliceP("address", "a", []string{}, "comma separated gnmi targets addresses") rootCmd.PersistentFlags().StringP("username", "u", "", "username") rootCmd.PersistentFlags().StringP("password", "p", "", "password") rootCmd.PersistentFlags().StringP("port", "", defaultGrpcPort, "gRPC port") rootCmd.PersistentFlags().StringP("encoding", "e", "json", fmt.Sprintf("one of %+v. Case insensitive", encodings)) rootCmd.PersistentFlags().BoolP("insecure", "", false, "insecure connection") rootCmd.PersistentFlags().StringP("tls-ca", "", "", "tls certificate authority") rootCmd.PersistentFlags().StringP("tls-cert", "", "", "tls certificate") rootCmd.PersistentFlags().StringP("tls-key", "", "", "tls key") rootCmd.PersistentFlags().DurationP("timeout", "", 10*time.Second, "grpc timeout, valid formats: 10s, 1m30s, 1h") rootCmd.PersistentFlags().BoolP("debug", "d", false, "debug mode") rootCmd.PersistentFlags().BoolP("skip-verify", "", false, "skip verify tls connection") rootCmd.PersistentFlags().BoolP("no-prefix", "", false, "do not add [ip:port] prefix to print output in case of multiple targets") rootCmd.PersistentFlags().BoolP("proxy-from-env", "", false, "use proxy from environment") rootCmd.PersistentFlags().StringP("format", "", "", "output format, one of: [protojson, prototext, json, event]") rootCmd.PersistentFlags().StringP("log-file", "", "", "log file path") rootCmd.PersistentFlags().BoolP("log", "", false, "show log messages in stderr") rootCmd.PersistentFlags().IntP("max-msg-size", "", msgSize, "max grpc msg size") rootCmd.PersistentFlags().StringP("prometheus-address", "", "", "prometheus server address") rootCmd.PersistentFlags().BoolP("print-request", "", false, "print request as well as the response(s)") // viper.BindPFlag("address", rootCmd.PersistentFlags().Lookup("address")) viper.BindPFlag("username", rootCmd.PersistentFlags().Lookup("username")) viper.BindPFlag("password", rootCmd.PersistentFlags().Lookup("password")) viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port")) viper.BindPFlag("encoding", rootCmd.PersistentFlags().Lookup("encoding")) viper.BindPFlag("insecure", rootCmd.PersistentFlags().Lookup("insecure")) viper.BindPFlag("tls-ca", rootCmd.PersistentFlags().Lookup("tls-ca")) viper.BindPFlag("tls-cert", rootCmd.PersistentFlags().Lookup("tls-cert")) viper.BindPFlag("tls-key", rootCmd.PersistentFlags().Lookup("tls-key")) viper.BindPFlag("timeout", rootCmd.PersistentFlags().Lookup("timeout")) viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) viper.BindPFlag("skip-verify", rootCmd.PersistentFlags().Lookup("skip-verify")) viper.BindPFlag("no-prefix", rootCmd.PersistentFlags().Lookup("no-prefix")) viper.BindPFlag("proxy-from-env", rootCmd.PersistentFlags().Lookup("proxy-from-env")) viper.BindPFlag("format", rootCmd.PersistentFlags().Lookup("format")) viper.BindPFlag("log-file", rootCmd.PersistentFlags().Lookup("log-file")) viper.BindPFlag("log", rootCmd.PersistentFlags().Lookup("log")) viper.BindPFlag("max-msg-size", rootCmd.PersistentFlags().Lookup("max-msg-size")) viper.BindPFlag("prometheus-address", rootCmd.PersistentFlags().Lookup("prometheus-address")) viper.BindPFlag("print-request", rootCmd.PersistentFlags().Lookup("print-request")) } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".gnmic" (without extension). viper.AddConfigPath(home) viper.SetConfigName("gnmic") } //viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. viper.ReadInConfig() postInitCommands(rootCmd.Commands()) } func postInitCommands(commands []*cobra.Command) { for _, cmd := range commands { presetRequiredFlags(cmd) if cmd.HasSubCommands() { postInitCommands(cmd.Commands()) } } } func presetRequiredFlags(cmd *cobra.Command) { cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { flagName := fmt.Sprintf("%s-%s", cmd.Name(), f.Name) value := viper.Get(flagName) if value != nil && viper.IsSet(flagName) && !f.Changed { var err error switch value := value.(type) { case string: err = cmd.LocalFlags().Set(f.Name, value) case []interface{}: ls := make([]string, len(value)) for i := range value { ls[i] = value[i].(string) } err = cmd.LocalFlags().Set(f.Name, strings.Join(ls, ",")) case []string: err = cmd.LocalFlags().Set(f.Name, strings.Join(value, ",")) default: fmt.Printf("unexpected config value type, value=%v, type=%T\n", value, value) } if err != nil { fmt.Printf("failed setting flag '%s' from viper: %v\n", flagName, err) } } }) } func readUsername() (string, error) { var username string fmt.Print("username: ") _, err := fmt.Scan(&username) if err != nil { return "", err } return username, nil } func readPassword() (string, error) { fmt.Print("password: ") pass, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return "", err } fmt.Println() return string(pass), nil } func loadCerts(tlscfg *tls.Config) error { tlsCert := viper.GetString("tls-cert") tlsKey := viper.GetString("tls-key") if tlsCert != "" && tlsKey != "" { certificate, err := tls.LoadX509KeyPair(tlsCert, tlsKey) if err != nil { return err } tlscfg.Certificates = []tls.Certificate{certificate} tlscfg.BuildNameToCertificate() } return nil } func loadCACerts(tlscfg *tls.Config) error { tlsCa := viper.GetString("tls-ca") certPool := x509.NewCertPool() if tlsCa != "" { caFile, err := ioutil.ReadFile(tlsCa) if err != nil { return err } if ok := certPool.AppendCertsFromPEM(caFile); !ok { return errors.New("failed to append certificate") } tlscfg.RootCAs = certPool } return nil } func printer(ctx context.Context, c chan string) { for { select { case m := <-c: fmt.Println(m) case <-ctx.Done(): return } } } func gather(ctx context.Context, c chan string, ls *[]string) { for { select { case m := <-c: *ls = append(*ls, m) case <-ctx.Done(): return } } } type myWriteCloser struct { io.Writer } func (myWriteCloser) Close() error { return nil } func indent(prefix, s string) string { if prefix == "" { return s } prefix = "\n" + strings.TrimRight(prefix, "\n") lines := strings.Split(s, "\n") return strings.TrimLeft(fmt.Sprintf("%s%s", prefix, strings.Join(lines, prefix)), "\n") } func filterModels(ctx context.Context, t *collector.Target, modelsNames []string) (map[string]*gnmi.ModelData, []string, error) { capResp, err := t.Capabilities(ctx) if err != nil { return nil, nil, err } unsupportedModels := make([]string, 0) supportedModels := make(map[string]*gnmi.ModelData) var found bool for _, m := range modelsNames { found = false for _, tModel := range capResp.SupportedModels { if m == tModel.Name { supportedModels[m] = tModel found = true break } } if !found { unsupportedModels = append(unsupportedModels, m) } } return supportedModels, unsupportedModels, nil } func setupCloseHandler(cancelFn context.CancelFunc) { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) go func() { sig := <-c fmt.Printf("\nreceived signal '%s'. terminating...\n", sig.String()) cancelFn() os.Exit(0) }() } func numTargets() int { addressesLength := len(viper.GetStringSlice("address")) if addressesLength > 0 { return addressesLength } targets := viper.Get("targets") switch targets := targets.(type) { case string: return len(strings.Split(targets, " ")) case map[string]interface{}: return len(targets) } return 0 } func createTargets() (map[string]*collector.TargetConfig, error) { addresses := viper.GetStringSlice("address") targets := make(map[string]*collector.TargetConfig) defGrpcPort := viper.GetString("port") // case address is defined in config file if len(addresses) > 0 { if viper.GetString("username") == "" { defUsername, err := readUsername() if err != nil { return nil, err } viper.Set("username", defUsername) } if viper.GetString("password") == "" { defPassword, err := readPassword() if err != nil { return nil, err } viper.Set("password", defPassword) } for _, addr := range addresses { tc := new(collector.TargetConfig) if !strings.HasPrefix(addr, "unix://") { _, _, err := net.SplitHostPort(addr) if err != nil { if strings.Contains(err.Error(), "missing port in address") { addr = net.JoinHostPort(addr, defGrpcPort) } else { logger.Printf("error parsing address '%s': %v", addr, err) return nil, fmt.Errorf("error parsing address '%s': %v", addr, err) } } } tc.Address = addr setTargetConfigDefaults(tc) targets[tc.Name] = tc } return targets, nil } // case targets is defined in config file targetsInt := viper.Get("targets") targetsMap := make(map[string]interface{}) switch targetsInt := targetsInt.(type) { case string: for _, addr := range strings.Split(targetsInt, " ") { targetsMap[addr] = nil } case map[string]interface{}: targetsMap = targetsInt default: return nil, fmt.Errorf("unexpected targets format, got: %T", targetsInt) } if len(targetsMap) == 0 { return nil, fmt.Errorf("no targets found") } for addr, t := range targetsMap { if !strings.HasPrefix(addr, "unix://") { _, _, err := net.SplitHostPort(addr) if err != nil { if strings.Contains(err.Error(), "missing port in address") { addr = net.JoinHostPort(addr, defGrpcPort) } else { logger.Printf("error parsing address '%s': %v", addr, err) return nil, fmt.Errorf("error parsing address '%s': %v", addr, err) } } } tc := new(collector.TargetConfig) switch t := t.(type) { case map[string]interface{}: decoder, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ DecodeHook: mapstructure.StringToTimeDurationHookFunc(), Result: tc, }, ) if err != nil { return nil, err } err = decoder.Decode(t) if err != nil { return nil, err } case nil: default: return nil, fmt.Errorf("unexpected targets format, got a %T", t) } tc.Address = addr setTargetConfigDefaults(tc) if viper.GetBool("debug") { logger.Printf("read target config: %s", tc) } targets[tc.Name] = tc } subNames := viper.GetStringSlice("subscribe-name") if len(subNames) == 0 { return targets, nil } for n := range targets { targets[n].Subscriptions = subNames } return targets, nil } func setTargetConfigDefaults(tc *collector.TargetConfig) { if tc.Name == "" { tc.Name = tc.Address } if tc.Username == nil { s := viper.GetString("username") tc.Username = &s } if tc.Password == nil { s := viper.GetString("password") tc.Password = &s } if tc.Timeout == 0 { tc.Timeout = viper.GetDuration("timeout") } if tc.Insecure == nil { b := viper.GetBool("insecure") tc.Insecure = &b } if tc.SkipVerify == nil { b := viper.GetBool("skip-verify") tc.SkipVerify = &b } if tc.Insecure != nil && !*tc.Insecure { if tc.TLSCA == nil { s := viper.GetString("tls-ca") if s != "" { tc.TLSCA = &s } } if tc.TLSCert == nil { s := viper.GetString("tls-cert") tc.TLSCert = &s } if tc.TLSKey == nil { s := viper.GetString("tls-key") tc.TLSKey = &s } } } func createCollectorDialOpts() []grpc.DialOption { opts := []grpc.DialOption{} opts = append(opts, grpc.WithBlock()) if viper.GetInt("max-msg-size") > 0 { opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(viper.GetInt("max-msg-size")))) } if !viper.GetBool("proxy-from-env") { opts = append(opts, grpc.WithNoProxy()) } return opts } func printMsg(address string, msg proto.Message) error { printPrefix := "" if numTargets() > 1 && !viper.GetBool("no-prefix") { printPrefix = fmt.Sprintf("[%s] ", address) } switch msg := msg.ProtoReflect().Interface().(type) { case *gnmi.CapabilityResponse: if len(viper.GetString("format")) == 0 { printCapResponse(printPrefix, msg) return nil } } mo := collector.MarshalOptions{ Multiline: true, Indent: " ", Format: viper.GetString("format"), } b, err := mo.Marshal(msg, map[string]string{"address": address}) if err != nil { return err } sb := strings.Builder{} sb.Write(b) fmt.Printf("%s\n", indent(printPrefix, sb.String())) return nil } func printCapResponse(printPrefix string, msg *gnmi.CapabilityResponse) { sb := strings.Builder{} sb.WriteString(printPrefix) sb.WriteString("gNMI version: ") sb.WriteString(msg.GNMIVersion) sb.WriteString("\n") if viper.GetBool("version") { return } sb.WriteString(printPrefix) sb.WriteString("supported models:\n") for _, sm := range msg.SupportedModels { sb.WriteString(printPrefix) sb.WriteString(" - ") sb.WriteString(sm.GetName()) sb.WriteString(", ") sb.WriteString(sm.GetOrganization()) sb.WriteString(", ") sb.WriteString(sm.GetVersion()) sb.WriteString("\n") } sb.WriteString(printPrefix) sb.WriteString("supported encodings:\n") for _, se := range msg.SupportedEncodings { sb.WriteString(printPrefix) sb.WriteString(" - ") sb.WriteString(se.String()) sb.WriteString("\n") } fmt.Printf("%s\n", indent(printPrefix, sb.String())) }
// Copyright © 2016 See CONTRIBUTORS <ignasi.fosch@gmail.com> // // 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" "os" "github.com/gophergala2016/reviewer/reviewer" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string var DryRun bool type config struct { Authorization struct { Token string } Repositories map[string]struct { Username string Status bool Required int } } // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "reviewer", Short: "Code review your pull requests", Long: `By running reviewer your repo's pull requests will get merged according to the configuration file.`, Run: func(cmd *cobra.Command, args []string) { reviewer.Execute(DryRun) }, } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.reviewer.yaml)") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolVarP(&DryRun, "dry-run", "d", false, "Won't merge if enabled. Default: disabled.") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.SetConfigName(".reviewer") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.SetEnvPrefix("reviewer") // so viper.AutomaticEnv will get matching envvars starting with REVIEWER_ viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } } Fix golint // Copyright © 2016 See CONTRIBUTORS <ignasi.fosch@gmail.com> // // 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" "os" "github.com/gophergala2016/reviewer/reviewer" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string // DryRun defines whether the program must actually act, or just give feedback as acting. var DryRun bool type config struct { Authorization struct { Token string } Repositories map[string]struct { Username string Status bool Required int } } // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ Use: "reviewer", Short: "Code review your pull requests", Long: `By running reviewer your repo's pull requests will get merged according to the configuration file.`, Run: func(cmd *cobra.Command, args []string) { reviewer.Execute(DryRun) }, } // Execute adds all child commands to the root command sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { cobra.OnInitialize(initConfig) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags, which, if defined here, // will be global for your application. RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.reviewer.yaml)") // Cobra also supports local flags, which will only run // when this action is called directly. RootCmd.Flags().BoolVarP(&DryRun, "dry-run", "d", false, "Won't merge if enabled. Default: disabled.") } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.SetConfigName(".reviewer") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.SetEnvPrefix("reviewer") // so viper.AutomaticEnv will get matching envvars starting with REVIEWER_ viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
package cmd import ( "fmt" "github.com/dtan4/valec/aws" "github.com/dtan4/valec/msg" "github.com/dtan4/valec/secret" "github.com/dtan4/valec/util" "github.com/pkg/errors" "github.com/spf13/cobra" ) // syncCmd represents the sync command var syncCmd = &cobra.Command{ Use: "sync SECRETDIR [NAMESPACE]", Short: "Synchronize secrets between local file and DynamoDB", RunE: doSync, } var syncOpts = struct { dryRun bool }{} func doSync(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("Please specify secret directory.") } dirname := args[0] if rootOpts.noColor { msg.DisableColor() } files, err := util.ListYAMLFiles(dirname) if err != nil { return errors.Wrapf(err, "Failed to read directory. dirname=%s", dirname) } srcNamespaces, err := aws.DynamoDB.ListNamespaces(rootOpts.tableName) if err != nil { return errors.Wrap(err, "Failed to retrieve namespaces.") } dstNamespaces := []string{} for _, file := range files { namespace, err := util.NamespaceFromPath(file, dirname) if err != nil { return errors.Wrap(err, "Failed to get namespace.") } dstNamespaces = append(dstNamespaces, namespace) if err := syncFile(file, namespace); err != nil { return errors.Wrapf(err, "Failed to synchronize file. filename=%s", file) } } added, deleted := util.CompareStrings(srcNamespaces, dstNamespaces) for _, namespace := range added { msg.GreenBold.Printf("+ %s\n", namespace) } if len(added) > 0 { fmt.Printf("%d namespaces will be added.\n", len(added)) } for _, namespace := range deleted { msg.RedBold.Printf("- %s\n", namespace) } if len(deleted) > 0 { fmt.Printf("%d namespaces will be deleted.\n", len(deleted)) if !syncOpts.dryRun { for _, namespace := range deleted { if err := aws.DynamoDB.DeleteNamespace(rootOpts.tableName, namespace); err != nil { return errors.Wrapf(err, "Failed to delete namespace. namespace=%s", namespace) } } fmt.Printf(" %d namespaces were successfully deleted.\n", len(deleted)) } } return nil } func syncFile(filename, namespace string) error { msg.Bold.Println(namespace) _, srcSecrets, err := secret.LoadFromYAML(filename) if err != nil { return errors.Wrapf(err, "Failed to load secrets. filename=%s", filename) } dstSecrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace) if err != nil { return errors.Wrapf(err, "Failed to retrieve secrets. namespace=%s", namespace) } added, updated, deleted := srcSecrets.CompareList(dstSecrets) if len(deleted) > 0 { fmt.Printf("% d secrets will be deleted.\n", len(deleted)) for _, secret := range deleted { msg.Red.Printf(" - %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Delete(rootOpts.tableName, namespace, deleted); err != nil { return errors.Wrapf(err, "Failed to delete secrets. namespace=%s", namespace) } fmt.Printf(" %d secrets were successfully deleted.\n", len(deleted)) } } if len(updated) > 0 { fmt.Printf(" %d secrets will be updated.\n", len(updated)) for _, secret := range updated { msg.Yellow.Printf(" + %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, updated); err != nil { return errors.Wrapf(err, "Failed to insert secrets. namespace=%s") } fmt.Printf(" %d secrets were successfully updated.\n", len(updated)) } } if len(added) > 0 { fmt.Printf(" %d secrets will be added.\n", len(added)) for _, secret := range added { msg.Green.Printf(" + %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, added); err != nil { return errors.Wrapf(err, "Failed to insert secrets. namespace=%s") } fmt.Printf(" %d secrets were successfully added.\n", len(added)) } } return nil } func init() { RootCmd.AddCommand(syncCmd) syncCmd.Flags().BoolVar(&syncOpts.dryRun, "dry-run", false, "Dry run") } Stop printing namespaces to add package cmd import ( "fmt" "github.com/dtan4/valec/aws" "github.com/dtan4/valec/msg" "github.com/dtan4/valec/secret" "github.com/dtan4/valec/util" "github.com/pkg/errors" "github.com/spf13/cobra" ) // syncCmd represents the sync command var syncCmd = &cobra.Command{ Use: "sync SECRETDIR [NAMESPACE]", Short: "Synchronize secrets between local file and DynamoDB", RunE: doSync, } var syncOpts = struct { dryRun bool }{} func doSync(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("Please specify secret directory.") } dirname := args[0] if rootOpts.noColor { msg.DisableColor() } files, err := util.ListYAMLFiles(dirname) if err != nil { return errors.Wrapf(err, "Failed to read directory. dirname=%s", dirname) } srcNamespaces, err := aws.DynamoDB.ListNamespaces(rootOpts.tableName) if err != nil { return errors.Wrap(err, "Failed to retrieve namespaces.") } dstNamespaces := []string{} for _, file := range files { namespace, err := util.NamespaceFromPath(file, dirname) if err != nil { return errors.Wrap(err, "Failed to get namespace.") } dstNamespaces = append(dstNamespaces, namespace) if err := syncFile(file, namespace); err != nil { return errors.Wrapf(err, "Failed to synchronize file. filename=%s", file) } } _, deleted := util.CompareStrings(srcNamespaces, dstNamespaces) for _, namespace := range deleted { msg.RedBold.Printf("- %s\n", namespace) } if len(deleted) > 0 { fmt.Printf("%d namespaces will be deleted.\n", len(deleted)) if !syncOpts.dryRun { for _, namespace := range deleted { if err := aws.DynamoDB.DeleteNamespace(rootOpts.tableName, namespace); err != nil { return errors.Wrapf(err, "Failed to delete namespace. namespace=%s", namespace) } } fmt.Printf(" %d namespaces were successfully deleted.\n", len(deleted)) } } return nil } func syncFile(filename, namespace string) error { msg.Bold.Println(namespace) _, srcSecrets, err := secret.LoadFromYAML(filename) if err != nil { return errors.Wrapf(err, "Failed to load secrets. filename=%s", filename) } dstSecrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace) if err != nil { return errors.Wrapf(err, "Failed to retrieve secrets. namespace=%s", namespace) } added, updated, deleted := srcSecrets.CompareList(dstSecrets) if len(deleted) > 0 { fmt.Printf("% d secrets will be deleted.\n", len(deleted)) for _, secret := range deleted { msg.Red.Printf(" - %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Delete(rootOpts.tableName, namespace, deleted); err != nil { return errors.Wrapf(err, "Failed to delete secrets. namespace=%s", namespace) } fmt.Printf(" %d secrets were successfully deleted.\n", len(deleted)) } } if len(updated) > 0 { fmt.Printf(" %d secrets will be updated.\n", len(updated)) for _, secret := range updated { msg.Yellow.Printf(" + %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, updated); err != nil { return errors.Wrapf(err, "Failed to insert secrets. namespace=%s") } fmt.Printf(" %d secrets were successfully updated.\n", len(updated)) } } if len(added) > 0 { fmt.Printf(" %d secrets will be added.\n", len(added)) for _, secret := range added { msg.Green.Printf(" + %s\n", secret.Key) } if !syncOpts.dryRun { if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, added); err != nil { return errors.Wrapf(err, "Failed to insert secrets. namespace=%s") } fmt.Printf(" %d secrets were successfully added.\n", len(added)) } } return nil } func init() { RootCmd.AddCommand(syncCmd) syncCmd.Flags().BoolVar(&syncOpts.dryRun, "dry-run", false, "Dry run") }
// Copyright 2016 The Cockroach Authors. // // 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 acceptance import "testing" func TestDockerReadWriteReferenceVersion(t *testing.T) { testDockerSuccess(t, "reference", []string{"/bin/bash", "-c", ` set -xe mkdir /old cd /old export PGHOST=localhost export PGPORT="" bin=/reference-version/cockroach $bin start & sleep 1 echo "Use the reference binary to write a couple rows, then render its output to a file and shut down." $bin sql -e "CREATE DATABASE old" $bin sql -d old -e "CREATE TABLE testing (i int primary key, b bool, s string unique, d decimal, f float, t timestamp, v interval, index sb (s, b))" $bin sql -d old -e "INSERT INTO testing values (1, true, 'hello', decimal '3.14159', 3.14159, NOW(), interval '1h')" $bin sql -d old -e "INSERT INTO testing values (2, false, 'world', decimal '0.14159', 0.14159, NOW(), interval '234h45m2s234ms')" $bin sql -d old -e "SELECT * FROM testing" > old.everything $bin quit && wait # wait will block until all background jobs finish. bin=/cockroach $bin start & sleep 1 echo "Read data written by referencce version using new binary" $bin sql -d old -e "SELECT * FROM testing" > new.everything # diff returns non-zero if different. With set -e above, that would exit here. diff new.everything old.everything echo "Add a row with the new binary and render the updated data before shutting down." $bin sql -d old -e "INSERT INTO testing values (3, false, '!', decimal '2.14159', 2.14159, NOW(), interval '3h')" $bin sql -d old -e "SELECT * FROM testing" > new.everything $bin quit && wait echo "Read the modified data using the reference binary again." bin=/reference-version/cockroach $bin start & sleep 1 $bin sql -d old -e "SELECT * FROM testing" > old.everything # diff returns non-zero if different. With set -e above, that would exit here. diff new.everything old.everything $bin quit && wait `}) } acceptance: skip failing test to get master green // Copyright 2016 The Cockroach Authors. // // 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 acceptance import "testing" func TestDockerReadWriteReferenceVersion(t *testing.T) { t.Skip("TODO(dt): breaking deploy-time tests, where the binds are different in the container.") testDockerSuccess(t, "reference", []string{"/bin/bash", "-c", ` set -xe mkdir /old cd /old export PGHOST=localhost export PGPORT="" bin=/reference-version/cockroach $bin start & sleep 1 echo "Use the reference binary to write a couple rows, then render its output to a file and shut down." $bin sql -e "CREATE DATABASE old" $bin sql -d old -e "CREATE TABLE testing (i int primary key, b bool, s string unique, d decimal, f float, t timestamp, v interval, index sb (s, b))" $bin sql -d old -e "INSERT INTO testing values (1, true, 'hello', decimal '3.14159', 3.14159, NOW(), interval '1h')" $bin sql -d old -e "INSERT INTO testing values (2, false, 'world', decimal '0.14159', 0.14159, NOW(), interval '234h45m2s234ms')" $bin sql -d old -e "SELECT * FROM testing" > old.everything $bin quit && wait # wait will block until all background jobs finish. bin=/cockroach $bin start & sleep 1 echo "Read data written by referencce version using new binary" $bin sql -d old -e "SELECT * FROM testing" > new.everything # diff returns non-zero if different. With set -e above, that would exit here. diff new.everything old.everything echo "Add a row with the new binary and render the updated data before shutting down." $bin sql -d old -e "INSERT INTO testing values (3, false, '!', decimal '2.14159', 2.14159, NOW(), interval '3h')" $bin sql -d old -e "SELECT * FROM testing" > new.everything $bin quit && wait echo "Read the modified data using the reference binary again." bin=/reference-version/cockroach $bin start & sleep 1 $bin sql -d old -e "SELECT * FROM testing" > old.everything # diff returns non-zero if different. With set -e above, that would exit here. diff new.everything old.everything $bin quit && wait `}) }
// Copyright © 2017 Compose, an IBM Company // // 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/hex" "encoding/json" "fmt" "log" "os" "strings" "time" composeAPI "github.com/compose/gocomposeapi" ) func getComposeAPI() (client *composeAPI.Client) { if apiToken == "Your API Token" { ostoken := os.Getenv("COMPOSEAPITOKEN") if ostoken == "" { log.Fatal("Token not set and COMPOSEAPITOKEN environment variable not set") } apiToken = ostoken } var err error client, err = composeAPI.NewClient(apiToken) if err != nil { log.Fatalf("Could not create compose client: %s", err.Error()) } return client } func resolveDepID(client *composeAPI.Client, arg string) (depid string, err error) { // Test for being just deployment id if len(arg) == 24 && isHexString(arg) { return arg, nil } // Get all the deployments and search deployments, errs := client.GetDeployments() if errs != nil { bailOnErrs(errs) return "", errs[0] } for _, deployment := range *deployments { if deployment.Name == arg { return deployment.ID, nil } } return "", fmt.Errorf("deployment not found: %s", arg) } func isHexString(s string) bool { _, err := hex.DecodeString(s) if err == nil { return true } return false } func watchRecipeTillComplete(client *composeAPI.Client, recipeid string) { var lastRecipe *composeAPI.Recipe for { time.Sleep(time.Duration(5) * time.Second) recipe, errs := client.GetRecipe(recipeid) bailOnErrs(errs) if lastRecipe == nil { lastRecipe = recipe if !recipewait { fmt.Println() printShortRecipe(*recipe) } } else { if lastRecipe.Status == recipe.Status && lastRecipe.UpdatedAt == recipe.UpdatedAt && lastRecipe.StatusDetail == recipe.StatusDetail { if !recipewait { fmt.Print(".") } } else { lastRecipe = recipe if !recipewait { fmt.Println() printShortRecipe(*recipe) } } } if recipe.Status == "complete" || recipe.Status == "failed" { return } } } func bailOnErrs(errs []error) { if errs != nil { log.Fatal(errs) } } func printAsJSON(toprint interface{}) { jsonstr, _ := json.MarshalIndent(toprint, "", " ") fmt.Println(string(jsonstr)) } func getLink(link composeAPI.Link) string { return strings.Replace(link.HREF, "{?embed}", "", -1) // TODO: This should mangle the HREF properly } var savedVersion string //SaveVersion called from outside to retain version string func SaveVersion(version string) { savedVersion = version } func getVersion() string { return savedVersion } Point users at URL for tokens // Copyright © 2017 Compose, an IBM Company // // 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/hex" "encoding/json" "fmt" "log" "os" "strings" "time" composeAPI "github.com/compose/gocomposeapi" ) func getComposeAPI() (client *composeAPI.Client) { if apiToken == "Your API Token" { ostoken := os.Getenv("COMPOSEAPITOKEN") if ostoken == "" { log.Fatal("Token not set and COMPOSEAPITOKEN environment variable not set - Get your token at https://app.compose.io/oauth/api_tokens") } apiToken = ostoken } var err error client, err = composeAPI.NewClient(apiToken) if err != nil { log.Fatalf("Could not create compose client: %s", err.Error()) } return client } func resolveDepID(client *composeAPI.Client, arg string) (depid string, err error) { // Test for being just deployment id if len(arg) == 24 && isHexString(arg) { return arg, nil } // Get all the deployments and search deployments, errs := client.GetDeployments() if errs != nil { bailOnErrs(errs) return "", errs[0] } for _, deployment := range *deployments { if deployment.Name == arg { return deployment.ID, nil } } return "", fmt.Errorf("deployment not found: %s", arg) } func isHexString(s string) bool { _, err := hex.DecodeString(s) if err == nil { return true } return false } func watchRecipeTillComplete(client *composeAPI.Client, recipeid string) { var lastRecipe *composeAPI.Recipe for { time.Sleep(time.Duration(5) * time.Second) recipe, errs := client.GetRecipe(recipeid) bailOnErrs(errs) if lastRecipe == nil { lastRecipe = recipe if !recipewait { fmt.Println() printShortRecipe(*recipe) } } else { if lastRecipe.Status == recipe.Status && lastRecipe.UpdatedAt == recipe.UpdatedAt && lastRecipe.StatusDetail == recipe.StatusDetail { if !recipewait { fmt.Print(".") } } else { lastRecipe = recipe if !recipewait { fmt.Println() printShortRecipe(*recipe) } } } if recipe.Status == "complete" || recipe.Status == "failed" { return } } } func bailOnErrs(errs []error) { if errs != nil { log.Fatal(errs) } } func printAsJSON(toprint interface{}) { jsonstr, _ := json.MarshalIndent(toprint, "", " ") fmt.Println(string(jsonstr)) } func getLink(link composeAPI.Link) string { return strings.Replace(link.HREF, "{?embed}", "", -1) // TODO: This should mangle the HREF properly } var savedVersion string //SaveVersion called from outside to retain version string func SaveVersion(version string) { savedVersion = version } func getVersion() string { return savedVersion }
package cmd import ( "encoding/json" "os" "path" "github.com/containerum/chkit/pkg/chkitErrors" kubeClientModels "git.containerum.net/ch/kube-client/pkg/model" "github.com/BurntSushi/toml" "github.com/containerum/chkit/pkg/client" "github.com/containerum/chkit/pkg/model" "github.com/sirupsen/logrus" "gopkg.in/urfave/cli.v2" ) const ( ErrUnableToSaveConfig chkitErrors.Err = "unable to save config" ) func getLog(ctx *cli.Context) *logrus.Logger { return ctx.App.Metadata["log"].(*logrus.Logger) } func getConfig(ctx *cli.Context) model.Config { return ctx.App.Metadata["config"].(model.Config) } func setConfig(ctx *cli.Context, config model.Config) { ctx.App.Metadata["config"] = config } func saveConfig(ctx *cli.Context) error { err := writeConfig(ctx) if err != nil { return ErrUnableToSaveConfig.Wrap(err) } return nil } func getClient(ctx *cli.Context) chClient.Client { return ctx.App.Metadata["client"].(chClient.Client) } func setClient(ctx *cli.Context, client chClient.Client) { ctx.App.Metadata["client"] = client } func getConfigPath(ctx *cli.Context) string { return ctx.App.Metadata["configPath"].(string) } func exitOnErr(log *logrus.Logger, err error) { if err != nil { log.WithError(err).Fatal(err) os.Exit(1) } } func loadConfig(configFilePath string, config *model.Config) error { _, err := toml.DecodeFile(configFilePath, &config.UserInfo) if err != nil { return err } return nil } func writeConfig(ctx *cli.Context) error { configPath := getConfigPath(ctx) err := os.MkdirAll(configPath, os.ModePerm) if err != nil && !os.IsExist(err) { return err } file, err := os.Create(path.Join(configPath, "config.toml")) if err != nil { return err } config := getConfig(ctx) return toml.NewEncoder(file).Encode(config.UserInfo) } func getTokens(ctx *cli.Context) kubeClientModels.Tokens { return ctx.App.Metadata["tokens"].(kubeClientModels.Tokens) } func setTokens(ctx *cli.Context, tokens kubeClientModels.Tokens) { ctx.App.Metadata["tokens"] = tokens } func saveTokens(ctx *cli.Context, tokens kubeClientModels.Tokens) error { file, err := os.Create(path.Join(getConfigPath(ctx), "tokens")) if err != nil { return err } return json.NewEncoder(file).Encode(tokens) } func loadTokens(ctx *cli.Context) (kubeClientModels.Tokens, error) { tokens := kubeClientModels.Tokens{} file, err := os.Open(path.Join(getConfigPath(ctx), "tokens")) if err != nil { return tokens, err } return tokens, json.NewDecoder(file).Decode(&tokens) } use chkkit models package cmd import ( "encoding/json" "os" "path" "github.com/BurntSushi/toml" "github.com/containerum/chkit/pkg/chkitErrors" "github.com/containerum/chkit/pkg/client" "github.com/containerum/chkit/pkg/model" "github.com/sirupsen/logrus" "gopkg.in/urfave/cli.v2" ) const ( ErrUnableToSaveConfig chkitErrors.Err = "unable to save config" ) func getLog(ctx *cli.Context) *logrus.Logger { return ctx.App.Metadata["log"].(*logrus.Logger) } func getConfig(ctx *cli.Context) model.Config { return ctx.App.Metadata["config"].(model.Config) } func setConfig(ctx *cli.Context, config model.Config) { ctx.App.Metadata["config"] = config } func saveConfig(ctx *cli.Context) error { err := writeConfig(ctx) if err != nil { return ErrUnableToSaveConfig.Wrap(err) } return nil } func getClient(ctx *cli.Context) chClient.Client { return ctx.App.Metadata["client"].(chClient.Client) } func setClient(ctx *cli.Context, client chClient.Client) { ctx.App.Metadata["client"] = client } func getConfigPath(ctx *cli.Context) string { return ctx.App.Metadata["configPath"].(string) } func exitOnErr(log *logrus.Logger, err error) { if err != nil { log.WithError(err).Fatal(err) os.Exit(1) } } func loadConfig(configFilePath string, config *model.Config) error { _, err := toml.DecodeFile(configFilePath, &config.UserInfo) if err != nil { return err } return nil } func writeConfig(ctx *cli.Context) error { configPath := getConfigPath(ctx) err := os.MkdirAll(configPath, os.ModePerm) if err != nil && !os.IsExist(err) { return err } file, err := os.Create(path.Join(configPath, "config.toml")) if err != nil { return err } config := getConfig(ctx) return toml.NewEncoder(file).Encode(config.UserInfo) } func getTokens(ctx *cli.Context) model.Tokens { return ctx.App.Metadata["tokens"].(model.Tokens) } func setTokens(ctx *cli.Context, tokens model.Tokens) { ctx.App.Metadata["tokens"] = tokens } func saveTokens(ctx *cli.Context, tokens model.Tokens) error { file, err := os.Create(path.Join(getConfigPath(ctx), "tokens")) if err != nil { return err } return json.NewEncoder(file).Encode(tokens) } func loadTokens(ctx *cli.Context) (model.Tokens, error) { tokens := model.Tokens{} file, err := os.Open(path.Join(getConfigPath(ctx), "tokens")) if err != nil { return tokens, err } return tokens, json.NewDecoder(file).Decode(&tokens) }
package solver import ( "bufio" "fmt" "io" "strconv" "strings" ) // ParseSlice parse a slice of slice of lits and returns the equivalent problem. // The argument is supposed to be a well-formed CNF. func ParseSlice(cnf [][]int) *Problem { var pb Problem for _, line := range cnf { switch len(line) { case 0: pb.Status = Unsat return &pb case 1: if line[0] == 0 { panic("null unit clause") } lit := IntToLit(int32(line[0])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) default: lits := make([]Lit, len(line)) for j, val := range line { if val == 0 { panic("null literal in clause %q") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewClause(lits)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplify() return &pb } // ParseCardConstrs parses the given cardinality constraints. // Will panic if a zero value appears in the literals. func ParseCardConstrs(constrs []CardConstr) *Problem { var pb Problem for _, constr := range constrs { card := constr.AtLeast if card <= 0 { // Clause is trivially SAT, ignore continue } if len(constr.Lits) < card { // Clause cannot be satsfied pb.Status = Unsat return &pb } if len(constr.Lits) == card { // All lits must be true for i := range constr.Lits { if constr.Lits[i] == 0 { panic("literal 0 found in clause") } lit := IntToLit(int32(constr.Lits[i])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) } } else { lits := make([]Lit, len(constr.Lits)) for j, val := range constr.Lits { if val == 0 { panic("literal 0 found in clause") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewCardClause(lits, card)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplify() return &pb } // ParsePBConstrs parses and returns a PB problem from PBConstr values. func ParsePBConstrs(constrs []PBConstr) *Problem { var pb Problem for _, constr := range constrs { card := constr.AtLeast if card <= 0 { // Clause is trivially SAT, ignore continue } sumW := constr.WeightSum() if sumW < card { // Clause cannot be satsfied pb.Status = Unsat return &pb } if sumW == card { // All lits must be true for i := range constr.Lits { if constr.Lits[i] == 0 { panic("literal 0 found in clause") } lit := IntToLit(int32(constr.Lits[i])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) } } else { lits := make([]Lit, len(constr.Lits)) for j, val := range constr.Lits { if val == 0 { panic("literal 0 found in clause") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewPBClause(lits, constr.Weights, card)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplifyPB() return &pb } // Parses a CNF line containing a clause and adds it to the problem. func (pb *Problem) parseClause(line string) error { fields := strings.Fields(line) lits := make([]Lit, len(fields)-1) for i, field := range fields { if i == len(fields)-1 { // Ignore last field: it is the 0 clause terminator break } if field == "" { continue } cnfLit, err := strconv.Atoi(field) if err != nil { return fmt.Errorf("Invalid literal %q in CNF clause %q", field, line) } lits[i] = IntToLit(int32(cnfLit)) } switch len(lits) { case 0: pb.Status = Unsat pb.Clauses = nil case 1: lit := lits[0] pb.Units = append(pb.Units, lit) v := lit.Var() if pb.Model[v] == 0 { if lit.IsPositive() { pb.Model[lit.Var()] = 1 } else { pb.Model[lit.Var()] = -1 } } else if pb.Model[v] > 0 != lit.IsPositive() { pb.Status = Unsat } default: pb.Clauses = append(pb.Clauses, NewClause(lits)) } return nil } // ParseCNF parses a CNF file and returns the corresponding Problem. func ParseCNF(f io.Reader) (*Problem, error) { scanner := bufio.NewScanner(f) var nbClauses int var pb Problem for scanner.Scan() { line := scanner.Text() if line == "" { continue } if line[0] == 'p' { fields := strings.Split(line, " ") if len(fields) < 4 { return nil, fmt.Errorf("invalid syntax %q in CNF file", line) } var err error pb.NbVars, err = strconv.Atoi(fields[2]) if err != nil { return nil, fmt.Errorf("nbvars not an int : '%s'", fields[2]) } pb.Model = make([]decLevel, pb.NbVars) nbClauses, err = strconv.Atoi(fields[3]) if err != nil { return nil, fmt.Errorf("nbClauses not an int : '%s'", fields[3]) } pb.Clauses = make([]*Clause, 0, nbClauses) } else if line[0] != 'c' { // Not a header, not a comment : a clause if err := pb.parseClause(line); err != nil { return nil, err } } } pb.simplify() return &pb, nil } func (pb *Problem) parsePBLine(line string) error { fields := strings.Fields(line) if len(fields) == 0 { return fmt.Errorf("empty line in file") } if len(fields) < 4 || fields[len(fields)-1] != ";" || len(fields)%2 != 1 { return fmt.Errorf("invalid syntax %q", line) } operator := fields[len(fields)-3] if operator != ">=" && operator != "=" { return fmt.Errorf("invalid operator %q in %q: expected \">=\" or \"=\"", operator, line) } rhs, err := strconv.Atoi(fields[len(fields)-2]) if err != nil { return fmt.Errorf("invalid value %q in %q: %v", fields[len(fields)-2], line, err) } terms := fields[:len(fields)-3] weights := make([]int, len(terms)/2) lits := make([]int, len(terms)/2) for i := range weights { w, err := strconv.Atoi(terms[i*2]) if err != nil { return fmt.Errorf("invalid weight %q in %q: %v", terms[i*2], line, err) } weights[i] = w l := terms[i*2+1] if l[0] != 'x' || len(l) < 2 { return fmt.Errorf("invalid variable name %q in %q", l, line) } if l[1] == '~' { lits[i], err = strconv.Atoi(l[2:]) } else { lits[i], err = strconv.Atoi(l[1:]) } if err != nil { return fmt.Errorf("invalid variable %q in %q: %v", l, line, err) } if lits[i] >= pb.NbVars { pb.NbVars = lits[i] + 1 } if l[1] == '~' { lits[i] = -lits[i] } } if operator == ">=" { pb.Clauses = append(pb.Clauses, GtEq(lits, weights, rhs).Clause()) } else { for _, constr := range Eq(lits, weights, rhs) { pb.Clauses = append(pb.Clauses, constr.Clause()) } } return nil } // ParsePBS parses a file corresponding to the PBS syntax. // See http://www.cril.univ-artois.fr/PB16/format.pdf for more details. func ParsePBS(f io.Reader) (*Problem, error) { scanner := bufio.NewScanner(f) var pb Problem for scanner.Scan() { line := scanner.Text() if line == "" || line[0] == '*' { continue } if err := pb.parsePBLine(line); err != nil { return nil, err } } pb.Model = make([]decLevel, pb.NbVars) pb.simplifyPB() return &pb, nil } refactored parser package solver import ( "bufio" "fmt" "io" "strconv" "strings" ) // ParseSlice parse a slice of slice of lits and returns the equivalent problem. // The argument is supposed to be a well-formed CNF. func ParseSlice(cnf [][]int) *Problem { var pb Problem for _, line := range cnf { switch len(line) { case 0: pb.Status = Unsat return &pb case 1: if line[0] == 0 { panic("null unit clause") } lit := IntToLit(int32(line[0])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) default: lits := make([]Lit, len(line)) for j, val := range line { if val == 0 { panic("null literal in clause %q") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewClause(lits)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplify() return &pb } // ParseCardConstrs parses the given cardinality constraints. // Will panic if a zero value appears in the literals. func ParseCardConstrs(constrs []CardConstr) *Problem { var pb Problem for _, constr := range constrs { card := constr.AtLeast if card <= 0 { // Clause is trivially SAT, ignore continue } if len(constr.Lits) < card { // Clause cannot be satsfied pb.Status = Unsat return &pb } if len(constr.Lits) == card { // All lits must be true for i := range constr.Lits { if constr.Lits[i] == 0 { panic("literal 0 found in clause") } lit := IntToLit(int32(constr.Lits[i])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) } } else { lits := make([]Lit, len(constr.Lits)) for j, val := range constr.Lits { if val == 0 { panic("literal 0 found in clause") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewCardClause(lits, card)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplify() return &pb } // ParsePBConstrs parses and returns a PB problem from PBConstr values. func ParsePBConstrs(constrs []PBConstr) *Problem { var pb Problem for _, constr := range constrs { card := constr.AtLeast if card <= 0 { // Clause is trivially SAT, ignore continue } sumW := constr.WeightSum() if sumW < card { // Clause cannot be satsfied pb.Status = Unsat return &pb } if sumW == card { // All lits must be true for i := range constr.Lits { if constr.Lits[i] == 0 { panic("literal 0 found in clause") } lit := IntToLit(int32(constr.Lits[i])) v := lit.Var() if int(v) >= pb.NbVars { pb.NbVars = int(v) + 1 } pb.Units = append(pb.Units, lit) } } else { lits := make([]Lit, len(constr.Lits)) for j, val := range constr.Lits { if val == 0 { panic("literal 0 found in clause") } lits[j] = IntToLit(int32(val)) if v := int(lits[j].Var()); v >= pb.NbVars { pb.NbVars = v + 1 } } pb.Clauses = append(pb.Clauses, NewPBClause(lits, constr.Weights, card)) } } pb.Model = make([]decLevel, pb.NbVars) for _, unit := range pb.Units { v := unit.Var() if pb.Model[v] == 0 { if unit.IsPositive() { pb.Model[v] = 1 } else { pb.Model[v] = -1 } } else if pb.Model[v] > 0 != unit.IsPositive() { pb.Status = Unsat return &pb } } pb.simplifyPB() return &pb } // Parses a CNF line containing a clause and adds it to the problem. func (pb *Problem) parseClause(line string) error { fields := strings.Fields(line) lits := make([]Lit, len(fields)-1) for i, field := range fields { if i == len(fields)-1 { // Ignore last field: it is the 0 clause terminator break } if field == "" { continue } cnfLit, err := strconv.Atoi(field) if err != nil { return fmt.Errorf("Invalid literal %q in CNF clause %q", field, line) } lits[i] = IntToLit(int32(cnfLit)) } switch len(lits) { case 0: pb.Status = Unsat pb.Clauses = nil case 1: lit := lits[0] pb.Units = append(pb.Units, lit) v := lit.Var() if pb.Model[v] == 0 { if lit.IsPositive() { pb.Model[lit.Var()] = 1 } else { pb.Model[lit.Var()] = -1 } } else if pb.Model[v] > 0 != lit.IsPositive() { pb.Status = Unsat } default: pb.Clauses = append(pb.Clauses, NewClause(lits)) } return nil } // ParseCNF parses a CNF file and returns the corresponding Problem. func ParseCNF(f io.Reader) (*Problem, error) { scanner := bufio.NewScanner(f) var nbClauses int var pb Problem for scanner.Scan() { line := scanner.Text() if line == "" { continue } if line[0] == 'p' { fields := strings.Split(line, " ") if len(fields) < 4 { return nil, fmt.Errorf("invalid syntax %q in CNF file", line) } var err error pb.NbVars, err = strconv.Atoi(fields[2]) if err != nil { return nil, fmt.Errorf("nbvars not an int : '%s'", fields[2]) } pb.Model = make([]decLevel, pb.NbVars) nbClauses, err = strconv.Atoi(fields[3]) if err != nil { return nil, fmt.Errorf("nbClauses not an int : '%s'", fields[3]) } pb.Clauses = make([]*Clause, 0, nbClauses) } else if line[0] != 'c' { // Not a header, not a comment : a clause if err := pb.parseClause(line); err != nil { return nil, err } } } pb.simplify() return &pb, nil } func (pb *Problem) parsePBLine(line string) error { fields := strings.Fields(line) if len(fields) == 0 { return fmt.Errorf("empty line in file") } if len(fields) < 4 || fields[len(fields)-1] != ";" || len(fields)%2 != 1 { return fmt.Errorf("invalid syntax %q", line) } operator := fields[len(fields)-3] if operator != ">=" && operator != "=" { return fmt.Errorf("invalid operator %q in %q: expected \">=\" or \"=\"", operator, line) } rhs, err := strconv.Atoi(fields[len(fields)-2]) if err != nil { return fmt.Errorf("invalid value %q in %q: %v", fields[len(fields)-2], line, err) } weights, lits, err := pb.parseTerms(fields, line) if err != nil { return nil } if operator == ">=" { pb.Clauses = append(pb.Clauses, GtEq(lits, weights, rhs).Clause()) } else { for _, constr := range Eq(lits, weights, rhs) { pb.Clauses = append(pb.Clauses, constr.Clause()) } } return nil } func (pb *Problem) parseTerms(fields []string, line string) (weights []int, lits []int, err error) { terms := fields[:len(fields)-3] weights = make([]int, len(terms)/2) lits = make([]int, len(terms)/2) for i := range weights { w, err := strconv.Atoi(terms[i*2]) if err != nil { return nil, nil, fmt.Errorf("invalid weight %q in %q: %v", terms[i*2], line, err) } weights[i] = w l := terms[i*2+1] if l[0] != 'x' || len(l) < 2 { return nil, nil, fmt.Errorf("invalid variable name %q in %q", l, line) } if l[1] == '~' { lits[i], err = strconv.Atoi(l[2:]) } else { lits[i], err = strconv.Atoi(l[1:]) } if err != nil { return nil, nil, fmt.Errorf("invalid variable %q in %q: %v", l, line, err) } if lits[i] >= pb.NbVars { pb.NbVars = lits[i] + 1 } if l[1] == '~' { lits[i] = -lits[i] } } return weights, lits, nil } // ParsePBS parses a file corresponding to the PBS syntax. // See http://www.cril.univ-artois.fr/PB16/format.pdf for more details. func ParsePBS(f io.Reader) (*Problem, error) { scanner := bufio.NewScanner(f) var pb Problem for scanner.Scan() { line := scanner.Text() if line == "" || line[0] == '*' { continue } if err := pb.parsePBLine(line); err != nil { return nil, err } } pb.Model = make([]decLevel, pb.NbVars) pb.simplifyPB() return &pb, nil }
package solver import ( "fmt" "sort" "strings" "time" ) const ( initNbMaxClauses = 2000 // Maximum # of learned clauses, at first. incrNbMaxClauses = 300 // By how much # of learned clauses is incremented at each conflict. incrPostponeNbMax = 1000 // By how much # of learned is increased when lots of good clauses are currently learned. clauseDecay = 0.999 // By how much clauses bumping decays over time. defaultVarDecay = 0.8 // On each var decay, how much the varInc should be decayed at startup ) // Stats are statistics about the resolution of the problem. // They are provided for information purpose only. type Stats struct { NbRestarts int NbConflicts int NbDecisions int NbUnitLearned int // How many unit clauses were learned NbBinaryLearned int // How many binary clauses were learned NbLearned int // How many clauses were learned NbDeleted int // How many clauses were deleted } // The level a decision was made. // A negative value means "negative assignement at that level". // A positive value means "positive assignment at that level". type decLevel int // A Model is a binding for several variables. // It can be totally bound (i.e all vars have a true or false binding) // or only partially (i.e some vars have no binding yet or their binding has no impact). // Each var, in order, is associated with a binding. Binding are implemented as // decision levels: // - a 0 value means the variable is free, // - a positive value means the variable was set to true at the given decLevel, // - a negative value means the variable was set to false at the given decLevel. type Model []decLevel func (m Model) String() string { bound := make(map[int]decLevel) for i := range m { if m[i] != 0 { bound[i+1] = m[i] } } return fmt.Sprintf("%v", bound) } // A Solver solves a given problem. It is the main data structure. type Solver struct { Verbose bool // Indicates whether the solver should display information during solving or not. False by default nbVars int status Status wl watcherList trail []Lit // Current assignment stack model Model // 0 means unbound, other value is a binding lastModel Model // Placeholder for last model found, useful when looking for several models activity []float64 // How often each var is involved in conflicts polarity []bool // Preferred sign for each var // For each var, clause considered when it was unified // If the var is not bound yet, or if it was bound by a decision, value is nil. reason []*Clause varQueue queue varInc float64 // On each var bump, how big the increment should be clauseInc float32 // On each var bump, how big the increment should be lbdStats lbdStats Stats Stats // Statistics about the solving process. minLits []Lit // Lits to minimize if the problem was an optimization problem. minWeights []int // Weight of each lit to minimize if the problem was an optimization problem. asumptions []Lit // Literals that are, ideally, true. Useful when trying to minimize a function. localNbRestarts int // How many restarts since Solve() was called? varDecay float64 // On each var decay, how much the varInc should be decayed trailBuf []int // A buffer while cleaning bindings } // New makes a solver, given a number of variables and a set of clauses. // nbVars should be consistent with the content of clauses, i.e. // the biggest variable in clauses should be >= nbVars. func New(problem *Problem) *Solver { if problem.Status == Unsat { return &Solver{status: Unsat} } nbVars := problem.NbVars s := &Solver{ nbVars: nbVars, status: problem.Status, trail: make([]Lit, len(problem.Units), nbVars), model: problem.Model, activity: make([]float64, nbVars), polarity: make([]bool, nbVars), reason: make([]*Clause, nbVars), varInc: 1.0, clauseInc: 1.0, minLits: problem.minLits, minWeights: problem.minWeights, varDecay: defaultVarDecay, trailBuf: make([]int, nbVars), } s.resetOptimPolarity() s.initOptimActivity() s.initWatcherList(problem.Clauses) s.varQueue = newQueue(s.activity) for i, lit := range problem.Units { if lit.IsPositive() { s.model[lit.Var()] = 1 } else { s.model[lit.Var()] = -1 } s.trail[i] = lit } return s } // sets initial activity for optimization variables, if any. func (s *Solver) initOptimActivity() { for i, lit := range s.minLits { w := 1 if s.minWeights != nil { w = s.minWeights[i] } s.activity[lit.Var()] += float64(w) } } // resets polarity of optimization lits so that they are negated by default. func (s *Solver) resetOptimPolarity() { if s.minLits != nil { for _, lit := range s.minLits { s.polarity[lit.Var()] = !lit.IsPositive() // Try to make lits from the optimization clause false } } } // Optim returns true iff the underlying problem is an optimization problem (rather than a satisfaction one). func (s *Solver) Optim() bool { return s.minLits != nil } // OutputModel outputs the model for the problem on stdout. func (s *Solver) OutputModel() { if s.status == Sat || s.lastModel != nil { fmt.Printf("s SATISFIABLE\nv ") model := s.model if s.lastModel != nil { model = s.lastModel } for i, val := range model { if val < 0 { fmt.Printf("%d ", -i-1) } else { fmt.Printf("%d ", i+1) } } fmt.Printf("\n") } else if s.status == Unsat { fmt.Printf("s UNSATISFIABLE\n") } else { fmt.Printf("s INDETERMINATE\n") } } // litStatus returns whether the literal is made true (Sat) or false (Unsat) by the // current bindings, or if it is unbounded (Indet). func (s *Solver) litStatus(l Lit) Status { assign := s.model[l.Var()] if assign == 0 { return Indet } if assign > 0 == l.IsPositive() { return Sat } return Unsat } func (s *Solver) varDecayActivity() { s.varInc *= 1 / s.varDecay } func (s *Solver) varBumpActivity(v Var) { s.activity[v] += s.varInc if s.activity[v] > 1e100 { // Rescaling is needed to avoid overflowing for i := range s.activity { s.activity[i] *= 1e-100 } s.varInc *= 1e-100 } if s.varQueue.contains(int(v)) { s.varQueue.decrease(int(v)) } } // Decays each clause's activity func (s *Solver) clauseDecayActivity() { s.clauseInc *= 1 / clauseDecay } // Bumps the given clause's activity. func (s *Solver) clauseBumpActivity(c *Clause) { if c.Learned() { c.activity += s.clauseInc if c.activity > 1e30 { // Rescale to avoid overflow for _, c2 := range s.wl.learned { c2.activity *= 1e-30 } s.clauseInc *= 1e-30 } } } // Chooses an unbound literal to be tested, or -1 // if all the variables are already bound. func (s *Solver) chooseLit() Lit { v := Var(-1) for v == -1 && !s.varQueue.empty() { if v2 := Var(s.varQueue.removeMin()); s.model[v2] == 0 { // Ignore already bound vars v = v2 } } if v == -1 { return Lit(-1) } s.Stats.NbDecisions++ return v.SignedLit(!s.polarity[v]) } func abs(val decLevel) decLevel { if val < 0 { return -val } return val } // Reinitializes bindings (both model & reason) for all variables bound at a decLevel >= lvl. // TODO: check this method as it has a weird behavior regarding performance. // TODO: clean-up commented-out code and understand underlying performance pattern. func (s *Solver) cleanupBindings(lvl decLevel) { i := 0 for i < len(s.trail) && abs(s.model[s.trail[i].Var()]) <= lvl { i++ } /* for j := len(s.trail) - 1; j >= i; j-- { lit2 := s.trail[j] v := lit2.Var() s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit2.IsPositive() if !s.varQueue.contains(int(v)) { s.varQueue.insert(int(v)) } } s.trail = s.trail[:i] */ toInsert := s.trailBuf[:0] // make([]int, 0, len(s.trail)-i) for j := i; j < len(s.trail); j++ { lit2 := s.trail[j] v := lit2.Var() s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit2.IsPositive() if !s.varQueue.contains(int(v)) { toInsert = append(toInsert, int(v)) s.varQueue.insert(int(v)) } } s.trail = s.trail[:i] for i := len(toInsert) - 1; i >= 0; i-- { s.varQueue.insert(toInsert[i]) } /*for i := len(s.trail) - 1; i >= 0; i-- { lit := s.trail[i] v := lit.Var() if abs(s.model[v]) <= lvl { // All lits in trail before here must keep their status. s.trail = s.trail[:i+1] break } s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit.IsPositive() if !s.varQueue.contains(int(v)) { s.varQueue.insert(int(v)) } }*/ s.resetOptimPolarity() } // Given the last learnt clause and the levels at which vars were bound, // Returns the level to bt to and the literal to bind func backtrackData(c *Clause, model []decLevel) (btLevel decLevel, lit Lit) { btLevel = abs(model[c.Get(1).Var()]) return btLevel, c.Get(0) } func (s *Solver) rebuildOrderHeap() { ints := make([]int, s.nbVars) for v := 0; v < s.nbVars; v++ { if s.model[v] == 0 { ints = append(ints, int(v)) } } s.varQueue.build(ints) } // satClause returns true iff c is satisfied by a literal assigned at top level. func (s *Solver) satClause(c *Clause) bool { if c.Len() == 2 || c.Cardinality() != 1 || c.PseudoBoolean() { // TODO improve this, but it will be ok since we only call this function for removing useless clauses. return false } for i := 0; i < c.Len(); i++ { lit := c.Get(i) assign := s.model[lit.Var()] if assign == 1 && lit.IsPositive() || assign == -1 && !lit.IsPositive() { return true } } return false } // propagate binds the given lit, propagates it and searches for a solution, // until it is found or a restart is needed. func (s *Solver) propagateAndSearch(lit Lit, lvl decLevel) Status { for lit != -1 { if conflict := s.unifyLiteral(lit, lvl); conflict == nil { // Pick new branch or restart if s.lbdStats.mustRestart() { s.lbdStats.clear() s.cleanupBindings(1) return Indet } if s.Stats.NbConflicts >= s.wl.idxReduce*s.wl.nbMax { s.wl.idxReduce = (s.Stats.NbConflicts / s.wl.nbMax) + 1 s.reduceLearned() s.bumpNbMax() } lvl++ lit = s.chooseLit() } else { // Deal with conflict s.Stats.NbConflicts++ if s.Stats.NbConflicts%5000 == 0 && s.varDecay < 0.95 { s.varDecay += 0.01 } s.lbdStats.addConflict(len(s.trail)) learnt, unit := s.learnClause(conflict, lvl) if learnt == nil { // Unit clause was learned: this lit is known for sure s.Stats.NbUnitLearned++ s.lbdStats.addLbd(1) s.cleanupBindings(1) s.model[unit.Var()] = lvlToSignedLvl(unit, 1) if conflict = s.unifyLiteral(unit, 1); conflict != nil { // top-level conflict s.status = Unsat return Unsat } // s.rmSatClauses() s.rebuildOrderHeap() lit = s.chooseLit() lvl = 2 } else { if learnt.Len() == 2 { s.Stats.NbBinaryLearned++ } s.Stats.NbLearned++ s.lbdStats.addLbd(learnt.lbd()) s.addLearned(learnt) lvl, lit = backtrackData(learnt, s.model) s.cleanupBindings(lvl) s.reason[lit.Var()] = learnt learnt.lock() } } } return Sat } // Searches until a restart is needed. func (s *Solver) search() Status { s.localNbRestarts++ lvl := decLevel(2) // Level starts at 2, for implementation reasons : 1 is for top-level bindings; 0 means "no level assigned yet" s.status = s.propagateAndSearch(s.chooseLit(), lvl) return s.status } // Solve solves the problem associated with the solver and returns the appropriate status. func (s *Solver) Solve() Status { if s.status == Unsat { return s.status } s.status = Indet //s.lbdStats.clear() s.localNbRestarts = 0 var end chan struct{} if s.Verbose { end = make(chan struct{}) defer close(end) go func() { // Function displaying stats during resolution fmt.Printf("c ======================================================================================\n") fmt.Printf("c | Restarts | Conflicts | Learned | Deleted | Del%% | Reduce | Units learned |\n") fmt.Printf("c ======================================================================================\n") ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { // There might be concurrent access in a few places but this is okay since we are very conservative and don't modify state. select { case <-ticker.C: case <-end: return } if s.status == Indet { iter := s.Stats.NbRestarts + 1 nbConfl := s.Stats.NbConflicts nbReduce := s.wl.idxReduce - 1 nbLearned := len(s.wl.learned) nbDel := s.Stats.NbDeleted pctDel := int(100 * float64(nbDel) / float64(s.Stats.NbLearned)) nbUnit := s.Stats.NbUnitLearned fmt.Printf("c | %8d | %11d | %9d | %9d | %3d%% | %6d | %8d/%8d |\n", iter, nbConfl, nbLearned, nbDel, pctDel, nbReduce, nbUnit, s.nbVars) } } }() } for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ s.rebuildOrderHeap() } } if s.status == Sat { s.lastModel = make(Model, len(s.model)) copy(s.lastModel, s.model) } if s.Verbose { end <- struct{}{} fmt.Printf("c ======================================================================================\n") } return s.status } // Enumerate returns the total number of models for the given problems. // if "models" is non-nil, it will write models on it as soon as it discovers them. // models will be closed at the end of the method. func (s *Solver) Enumerate(models chan []bool, stop chan struct{}) int { if models != nil { defer close(models) } s.lastModel = make(Model, len(s.model)) nb := 0 lit := s.chooseLit() var lvl decLevel for s.status != Unsat { for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ } } if s.status == Sat { nb++ if models != nil { copy(s.lastModel, s.model) models <- s.Model() } s.status = Indet lits := s.decisionLits() switch len(lits) { case 0: s.status = Unsat case 1: s.propagateUnits(lits) default: c := NewClause(lits) s.appendClause(c) lit = lits[len(lits)-1] v := lit.Var() lvl = abs(s.model[v]) - 1 s.cleanupBindings(lvl) s.reason[v] = c // Must do it here because it won't be made by propagateAndSearch s.propagateAndSearch(lit, lvl) } } } return nb } // CountModels returns the total number of models for the given problem. func (s *Solver) CountModels() int { var end chan struct{} if s.Verbose { end = make(chan struct{}) defer close(end) go func() { // Function displaying stats during resolution fmt.Printf("c ======================================================================================\n") fmt.Printf("c | Restarts | Conflicts | Learned | Deleted | Del%% | Reduce | Units learned |\n") fmt.Printf("c ======================================================================================\n") ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { // There might be concurrent access in a few places but this is okay since we are very conservative and don't modify state. select { case <-ticker.C: case <-end: return } if s.status == Indet { iter := s.Stats.NbRestarts + 1 nbConfl := s.Stats.NbConflicts nbReduce := s.wl.idxReduce - 1 nbLearned := len(s.wl.learned) nbDel := s.Stats.NbDeleted pctDel := int(100 * float64(nbDel) / float64(s.Stats.NbLearned)) nbUnit := s.Stats.NbUnitLearned fmt.Printf("c | %8d | %11d | %9d | %9d | %3d%% | %6d | %8d/%8d |\n", iter, nbConfl, nbLearned, nbDel, pctDel, nbReduce, nbUnit, s.nbVars) } } }() } nb := 0 lit := s.chooseLit() var lvl decLevel for s.status != Unsat { for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ } } if s.status == Sat { nb++ if s.Verbose { fmt.Printf("c found %d model(s)\n", nb) } s.status = Indet lits := s.decisionLits() switch len(lits) { case 0: s.status = Unsat case 1: s.propagateUnits(lits) default: c := NewClause(lits) s.appendClause(c) lit = lits[len(lits)-1] v := lit.Var() lvl = abs(s.model[v]) - 1 s.cleanupBindings(lvl) s.reason[v] = c // Must do it here because it won't be made by propagateAndSearch s.propagateAndSearch(lit, lvl) } } } if s.Verbose { end <- struct{}{} fmt.Printf("c ======================================================================================\n") } return nb } // decisionLits returns the negation of all decision values once a model was found, ordered by decision levels. // This will allow for searching other models. func (s *Solver) decisionLits() []Lit { lastLit := s.trail[len(s.trail)-1] lvls := abs(s.model[lastLit.Var()]) lits := make([]Lit, lvls-1) for i, r := range s.reason { if lvl := abs(s.model[i]); r == nil && lvl > 1 { if s.model[i] < 0 { // lvl-2 : levels beside unit clauses start at 2, not 0 or 1! lits[lvl-2] = IntToLit(int32(i + 1)) } else { lits[lvl-2] = IntToLit(int32(-i - 1)) } } } return lits } func (s *Solver) propagateUnits(units []Lit) { for _, unit := range units { s.lbdStats.addLbd(1) s.Stats.NbUnitLearned++ s.cleanupBindings(1) s.model[unit.Var()] = lvlToSignedLvl(unit, 1) if s.unifyLiteral(unit, 1) != nil { s.status = Unsat return } s.rebuildOrderHeap() } } // PBString returns a representation of the solver's state as a pseudo-boolean problem. func (s *Solver) PBString() string { meta := fmt.Sprintf("* #variable= %d #constraint= %d #learned= %d\n", s.nbVars, len(s.wl.pbClauses), len(s.wl.learned)) minLine := "" if s.minLits != nil { terms := make([]string, len(s.minLits)) for i, lit := range s.minLits { weight := 1 if s.minWeights != nil { weight = s.minWeights[i] } val := lit.Int() sign := "" if val < 0 { val = -val sign = "~" } terms[i] = fmt.Sprintf("%d %sx%d", weight, sign, val) } minLine = fmt.Sprintf("min: %s ;\n", strings.Join(terms, " +")) } clauses := make([]string, len(s.wl.pbClauses)+len(s.wl.learned)) for i, c := range s.wl.pbClauses { clauses[i] = c.PBString() } for i, c := range s.wl.learned { clauses[i+len(s.wl.pbClauses)] = c.PBString() } for i := 0; i < len(s.model); i++ { if s.model[i] == 1 { clauses = append(clauses, fmt.Sprintf("1 x%d = 1 ;", i+1)) } else if s.model[i] == -1 { clauses = append(clauses, fmt.Sprintf("1 x%d = 0 ;", i+1)) } } return meta + minLine + strings.Join(clauses, "\n") } // AppendClause appends a new clause to the set of clauses. // This is not a learned clause, but a clause that is part of the problem added afterwards (during model counting, for instance). func (s *Solver) AppendClause(clause *Clause) { s.cleanupBindings(1) card := clause.Cardinality() minW := 0 maxW := 0 i := 0 for i < clause.Len() { lit := clause.Get(i) switch s.litStatus(lit) { case Sat: w := clause.Weight(i) minW += w maxW += w clause.removeLit(i) clause.updateCardinality(-w) case Unsat: clause.removeLit(i) default: maxW += clause.Weight(i) i++ } } if minW >= card { // clause is already sat return } if maxW < card { // clause cannot be satisfied s.status = Unsat return } if maxW == card { // Unit s.propagateUnits(clause.lits) } else { s.appendClause(clause) } } // Model returns a slice that associates, to each variable, its binding. // If s's status is not Sat, the method will panic. func (s *Solver) Model() []bool { if s.lastModel == nil { panic("cannot call Model() from a non-Sat solver") } res := make([]bool, s.nbVars) for i, lvl := range s.lastModel { res[i] = lvl > 0 } return res } // Optimal returns the optimal solution, if any. // If results is non-nil, all solutions will be written to it. // In any case, results will be closed at the end of the call. func (s *Solver) Optimal(results chan Result, stop chan struct{}) (res Result) { if results != nil { defer close(results) } status := s.Solve() if status == Unsat { // Problem cannot be satisfied at all res.Status = Unsat if results != nil { results <- res } return res } if s.minLits == nil { // No optimization clause: this is a decision problem, solution is optimal s.lastModel = make(Model, len(s.model)) copy(s.lastModel, s.model) res := Result{ Status: Sat, Model: s.Model(), Weight: 0, } if results != nil { results <- res } return res } maxCost := 0 if s.minWeights == nil { maxCost = len(s.minLits) } else { for _, w := range s.minWeights { maxCost += w } } s.asumptions = make([]Lit, len(s.minLits)) for i, lit := range s.minLits { s.asumptions[i] = lit.Negation() } weights := make([]int, len(s.minWeights)) copy(weights, s.minWeights) sort.Sort(wLits{lits: s.asumptions, weights: weights}) s.lastModel = make(Model, len(s.model)) var cost int for status == Sat { copy(s.lastModel, s.model) // Save this model: it might be the last one cost = 0 for i, lit := range s.minLits { if (s.model[lit.Var()] > 0) == lit.IsPositive() { if s.minWeights == nil { cost++ } else { cost += s.minWeights[i] } } } res = Result{ Status: Sat, Model: s.Model(), Weight: cost, } if results != nil { results <- res } if cost == 0 { break } // Add a constraint incrementing current best cost lits2 := make([]Lit, len(s.minLits)) weights2 := make([]int, len(s.minWeights)) copy(lits2, s.asumptions) copy(weights2, weights) s.AppendClause(NewPBClause(lits2, weights2, maxCost-cost+1)) s.rebuildOrderHeap() status = s.Solve() } return res } // Minimize tries to find a model that minimizes the weight of the clause defined as the optimisation clause in the problem. // If no model can be found, it will return a cost of -1. // Otherwise, calling s.Model() afterwards will return the model that satisfy the formula, such that no other model with a smaller cost exists. // If this function is called on a non-optimization problem, it will either return -1, or a cost of 0 associated with a // satisfying model (ie any model is an optimal model). func (s *Solver) Minimize() int { status := s.Solve() if status == Unsat { // Problem cannot be satisfied at all return -1 } if s.minLits == nil { // No optimization clause: this is a decision problem, solution is optimal return 0 } maxCost := 0 if s.minWeights == nil { maxCost = len(s.minLits) } else { for _, w := range s.minWeights { maxCost += w } } s.asumptions = make([]Lit, len(s.minLits)) for i, lit := range s.minLits { s.asumptions[i] = lit.Negation() } weights := make([]int, len(s.minWeights)) copy(weights, s.minWeights) sort.Sort(wLits{lits: s.asumptions, weights: weights}) s.lastModel = make(Model, len(s.model)) var cost int for status == Sat { copy(s.lastModel, s.model) // Save this model: it might be the last one cost = 0 for i, lit := range s.minLits { if (s.model[lit.Var()] > 0) == lit.IsPositive() { if s.minWeights == nil { cost++ } else { cost += s.minWeights[i] } } } if cost == 0 { return 0 } if s.Verbose { fmt.Printf("o %d\n", cost) } // Add a constraint incrementing current best cost lits2 := make([]Lit, len(s.minLits)) weights2 := make([]int, len(s.minWeights)) copy(lits2, s.asumptions) copy(weights2, weights) s.AppendClause(NewPBClause(lits2, weights2, maxCost-cost+1)) s.rebuildOrderHeap() status = s.Solve() } return cost } // functions to sort asumptions for pseudo-boolean minimization clause. type wLits struct { lits []Lit weights []int } func (wl wLits) Len() int { return len(wl.lits) } func (wl wLits) Less(i, j int) bool { return wl.weights[i] > wl.weights[j] } func (wl wLits) Swap(i, j int) { wl.lits[i], wl.lits[j] = wl.lits[j], wl.lits[i] wl.weights[i], wl.weights[j] = wl.weights[j], wl.weights[i] } fix tests package solver import ( "fmt" "sort" "strings" "time" ) const ( initNbMaxClauses = 2000 // Maximum # of learned clauses, at first. incrNbMaxClauses = 300 // By how much # of learned clauses is incremented at each conflict. incrPostponeNbMax = 1000 // By how much # of learned is increased when lots of good clauses are currently learned. clauseDecay = 0.999 // By how much clauses bumping decays over time. defaultVarDecay = 0.8 // On each var decay, how much the varInc should be decayed at startup ) // Stats are statistics about the resolution of the problem. // They are provided for information purpose only. type Stats struct { NbRestarts int NbConflicts int NbDecisions int NbUnitLearned int // How many unit clauses were learned NbBinaryLearned int // How many binary clauses were learned NbLearned int // How many clauses were learned NbDeleted int // How many clauses were deleted } // The level a decision was made. // A negative value means "negative assignement at that level". // A positive value means "positive assignment at that level". type decLevel int // A Model is a binding for several variables. // It can be totally bound (i.e all vars have a true or false binding) // or only partially (i.e some vars have no binding yet or their binding has no impact). // Each var, in order, is associated with a binding. Binding are implemented as // decision levels: // - a 0 value means the variable is free, // - a positive value means the variable was set to true at the given decLevel, // - a negative value means the variable was set to false at the given decLevel. type Model []decLevel func (m Model) String() string { bound := make(map[int]decLevel) for i := range m { if m[i] != 0 { bound[i+1] = m[i] } } return fmt.Sprintf("%v", bound) } // A Solver solves a given problem. It is the main data structure. type Solver struct { Verbose bool // Indicates whether the solver should display information during solving or not. False by default nbVars int status Status wl watcherList trail []Lit // Current assignment stack model Model // 0 means unbound, other value is a binding lastModel Model // Placeholder for last model found, useful when looking for several models activity []float64 // How often each var is involved in conflicts polarity []bool // Preferred sign for each var // For each var, clause considered when it was unified // If the var is not bound yet, or if it was bound by a decision, value is nil. reason []*Clause varQueue queue varInc float64 // On each var bump, how big the increment should be clauseInc float32 // On each var bump, how big the increment should be lbdStats lbdStats Stats Stats // Statistics about the solving process. minLits []Lit // Lits to minimize if the problem was an optimization problem. minWeights []int // Weight of each lit to minimize if the problem was an optimization problem. asumptions []Lit // Literals that are, ideally, true. Useful when trying to minimize a function. localNbRestarts int // How many restarts since Solve() was called? varDecay float64 // On each var decay, how much the varInc should be decayed trailBuf []int // A buffer while cleaning bindings } // New makes a solver, given a number of variables and a set of clauses. // nbVars should be consistent with the content of clauses, i.e. // the biggest variable in clauses should be >= nbVars. func New(problem *Problem) *Solver { if problem.Status == Unsat { return &Solver{status: Unsat} } nbVars := problem.NbVars trailCap := nbVars if len(problem.Units) > trailCap { trailCap = len(problem.Units) } s := &Solver{ nbVars: nbVars, status: problem.Status, trail: make([]Lit, len(problem.Units), trailCap), model: problem.Model, activity: make([]float64, nbVars), polarity: make([]bool, nbVars), reason: make([]*Clause, nbVars), varInc: 1.0, clauseInc: 1.0, minLits: problem.minLits, minWeights: problem.minWeights, varDecay: defaultVarDecay, trailBuf: make([]int, nbVars), } s.resetOptimPolarity() s.initOptimActivity() s.initWatcherList(problem.Clauses) s.varQueue = newQueue(s.activity) for i, lit := range problem.Units { if lit.IsPositive() { s.model[lit.Var()] = 1 } else { s.model[lit.Var()] = -1 } s.trail[i] = lit } return s } // sets initial activity for optimization variables, if any. func (s *Solver) initOptimActivity() { for i, lit := range s.minLits { w := 1 if s.minWeights != nil { w = s.minWeights[i] } s.activity[lit.Var()] += float64(w) } } // resets polarity of optimization lits so that they are negated by default. func (s *Solver) resetOptimPolarity() { if s.minLits != nil { for _, lit := range s.minLits { s.polarity[lit.Var()] = !lit.IsPositive() // Try to make lits from the optimization clause false } } } // Optim returns true iff the underlying problem is an optimization problem (rather than a satisfaction one). func (s *Solver) Optim() bool { return s.minLits != nil } // OutputModel outputs the model for the problem on stdout. func (s *Solver) OutputModel() { if s.status == Sat || s.lastModel != nil { fmt.Printf("s SATISFIABLE\nv ") model := s.model if s.lastModel != nil { model = s.lastModel } for i, val := range model { if val < 0 { fmt.Printf("%d ", -i-1) } else { fmt.Printf("%d ", i+1) } } fmt.Printf("\n") } else if s.status == Unsat { fmt.Printf("s UNSATISFIABLE\n") } else { fmt.Printf("s INDETERMINATE\n") } } // litStatus returns whether the literal is made true (Sat) or false (Unsat) by the // current bindings, or if it is unbounded (Indet). func (s *Solver) litStatus(l Lit) Status { assign := s.model[l.Var()] if assign == 0 { return Indet } if assign > 0 == l.IsPositive() { return Sat } return Unsat } func (s *Solver) varDecayActivity() { s.varInc *= 1 / s.varDecay } func (s *Solver) varBumpActivity(v Var) { s.activity[v] += s.varInc if s.activity[v] > 1e100 { // Rescaling is needed to avoid overflowing for i := range s.activity { s.activity[i] *= 1e-100 } s.varInc *= 1e-100 } if s.varQueue.contains(int(v)) { s.varQueue.decrease(int(v)) } } // Decays each clause's activity func (s *Solver) clauseDecayActivity() { s.clauseInc *= 1 / clauseDecay } // Bumps the given clause's activity. func (s *Solver) clauseBumpActivity(c *Clause) { if c.Learned() { c.activity += s.clauseInc if c.activity > 1e30 { // Rescale to avoid overflow for _, c2 := range s.wl.learned { c2.activity *= 1e-30 } s.clauseInc *= 1e-30 } } } // Chooses an unbound literal to be tested, or -1 // if all the variables are already bound. func (s *Solver) chooseLit() Lit { v := Var(-1) for v == -1 && !s.varQueue.empty() { if v2 := Var(s.varQueue.removeMin()); s.model[v2] == 0 { // Ignore already bound vars v = v2 } } if v == -1 { return Lit(-1) } s.Stats.NbDecisions++ return v.SignedLit(!s.polarity[v]) } func abs(val decLevel) decLevel { if val < 0 { return -val } return val } // Reinitializes bindings (both model & reason) for all variables bound at a decLevel >= lvl. // TODO: check this method as it has a weird behavior regarding performance. // TODO: clean-up commented-out code and understand underlying performance pattern. func (s *Solver) cleanupBindings(lvl decLevel) { i := 0 for i < len(s.trail) && abs(s.model[s.trail[i].Var()]) <= lvl { i++ } /* for j := len(s.trail) - 1; j >= i; j-- { lit2 := s.trail[j] v := lit2.Var() s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit2.IsPositive() if !s.varQueue.contains(int(v)) { s.varQueue.insert(int(v)) } } s.trail = s.trail[:i] */ toInsert := s.trailBuf[:0] // make([]int, 0, len(s.trail)-i) for j := i; j < len(s.trail); j++ { lit2 := s.trail[j] v := lit2.Var() s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit2.IsPositive() if !s.varQueue.contains(int(v)) { toInsert = append(toInsert, int(v)) s.varQueue.insert(int(v)) } } s.trail = s.trail[:i] for i := len(toInsert) - 1; i >= 0; i-- { s.varQueue.insert(toInsert[i]) } /*for i := len(s.trail) - 1; i >= 0; i-- { lit := s.trail[i] v := lit.Var() if abs(s.model[v]) <= lvl { // All lits in trail before here must keep their status. s.trail = s.trail[:i+1] break } s.model[v] = 0 if s.reason[v] != nil { s.reason[v].unlock() s.reason[v] = nil } s.polarity[v] = lit.IsPositive() if !s.varQueue.contains(int(v)) { s.varQueue.insert(int(v)) } }*/ s.resetOptimPolarity() } // Given the last learnt clause and the levels at which vars were bound, // Returns the level to bt to and the literal to bind func backtrackData(c *Clause, model []decLevel) (btLevel decLevel, lit Lit) { btLevel = abs(model[c.Get(1).Var()]) return btLevel, c.Get(0) } func (s *Solver) rebuildOrderHeap() { ints := make([]int, s.nbVars) for v := 0; v < s.nbVars; v++ { if s.model[v] == 0 { ints = append(ints, int(v)) } } s.varQueue.build(ints) } // satClause returns true iff c is satisfied by a literal assigned at top level. func (s *Solver) satClause(c *Clause) bool { if c.Len() == 2 || c.Cardinality() != 1 || c.PseudoBoolean() { // TODO improve this, but it will be ok since we only call this function for removing useless clauses. return false } for i := 0; i < c.Len(); i++ { lit := c.Get(i) assign := s.model[lit.Var()] if assign == 1 && lit.IsPositive() || assign == -1 && !lit.IsPositive() { return true } } return false } // propagate binds the given lit, propagates it and searches for a solution, // until it is found or a restart is needed. func (s *Solver) propagateAndSearch(lit Lit, lvl decLevel) Status { for lit != -1 { if conflict := s.unifyLiteral(lit, lvl); conflict == nil { // Pick new branch or restart if s.lbdStats.mustRestart() { s.lbdStats.clear() s.cleanupBindings(1) return Indet } if s.Stats.NbConflicts >= s.wl.idxReduce*s.wl.nbMax { s.wl.idxReduce = s.Stats.NbConflicts/s.wl.nbMax + 1 s.reduceLearned() s.bumpNbMax() } lvl++ lit = s.chooseLit() } else { // Deal with conflict s.Stats.NbConflicts++ if s.Stats.NbConflicts%5000 == 0 && s.varDecay < 0.95 { s.varDecay += 0.01 } s.lbdStats.addConflict(len(s.trail)) learnt, unit := s.learnClause(conflict, lvl) if learnt == nil { // Unit clause was learned: this lit is known for sure s.Stats.NbUnitLearned++ s.lbdStats.addLbd(1) s.cleanupBindings(1) s.model[unit.Var()] = lvlToSignedLvl(unit, 1) if conflict = s.unifyLiteral(unit, 1); conflict != nil { // top-level conflict s.status = Unsat return Unsat } // s.rmSatClauses() s.rebuildOrderHeap() lit = s.chooseLit() lvl = 2 } else { if learnt.Len() == 2 { s.Stats.NbBinaryLearned++ } s.Stats.NbLearned++ s.lbdStats.addLbd(learnt.lbd()) s.addLearned(learnt) lvl, lit = backtrackData(learnt, s.model) s.cleanupBindings(lvl) s.reason[lit.Var()] = learnt learnt.lock() } } } return Sat } // Searches until a restart is needed. func (s *Solver) search() Status { s.localNbRestarts++ lvl := decLevel(2) // Level starts at 2, for implementation reasons : 1 is for top-level bindings; 0 means "no level assigned yet" s.status = s.propagateAndSearch(s.chooseLit(), lvl) return s.status } // Solve solves the problem associated with the solver and returns the appropriate status. func (s *Solver) Solve() Status { if s.status == Unsat { return s.status } s.status = Indet //s.lbdStats.clear() s.localNbRestarts = 0 var end chan struct{} if s.Verbose { end = make(chan struct{}) defer close(end) go func() { // Function displaying stats during resolution fmt.Printf("c ======================================================================================\n") fmt.Printf("c | Restarts | Conflicts | Learned | Deleted | Del%% | Reduce | Units learned |\n") fmt.Printf("c ======================================================================================\n") ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { // There might be concurrent access in a few places but this is okay since we are very conservative and don't modify state. select { case <-ticker.C: case <-end: return } if s.status == Indet { iter := s.Stats.NbRestarts + 1 nbConfl := s.Stats.NbConflicts nbReduce := s.wl.idxReduce - 1 nbLearned := len(s.wl.learned) nbDel := s.Stats.NbDeleted pctDel := int(100 * float64(nbDel) / float64(s.Stats.NbLearned)) nbUnit := s.Stats.NbUnitLearned fmt.Printf("c | %8d | %11d | %9d | %9d | %3d%% | %6d | %8d/%8d |\n", iter, nbConfl, nbLearned, nbDel, pctDel, nbReduce, nbUnit, s.nbVars) } } }() } for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ s.rebuildOrderHeap() } } if s.status == Sat { s.lastModel = make(Model, len(s.model)) copy(s.lastModel, s.model) } if s.Verbose { end <- struct{}{} fmt.Printf("c ======================================================================================\n") } return s.status } // Enumerate returns the total number of models for the given problems. // if "models" is non-nil, it will write models on it as soon as it discovers them. // models will be closed at the end of the method. func (s *Solver) Enumerate(models chan []bool, stop chan struct{}) int { if models != nil { defer close(models) } s.lastModel = make(Model, len(s.model)) nb := 0 lit := s.chooseLit() var lvl decLevel for s.status != Unsat { for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ } } if s.status == Sat { nb++ if models != nil { copy(s.lastModel, s.model) models <- s.Model() } s.status = Indet lits := s.decisionLits() switch len(lits) { case 0: s.status = Unsat case 1: s.propagateUnits(lits) default: c := NewClause(lits) s.appendClause(c) lit = lits[len(lits)-1] v := lit.Var() lvl = abs(s.model[v]) - 1 s.cleanupBindings(lvl) s.reason[v] = c // Must do it here because it won't be made by propagateAndSearch s.propagateAndSearch(lit, lvl) } } } return nb } // CountModels returns the total number of models for the given problem. func (s *Solver) CountModels() int { var end chan struct{} if s.Verbose { end = make(chan struct{}) defer close(end) go func() { // Function displaying stats during resolution fmt.Printf("c ======================================================================================\n") fmt.Printf("c | Restarts | Conflicts | Learned | Deleted | Del%% | Reduce | Units learned |\n") fmt.Printf("c ======================================================================================\n") ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { // There might be concurrent access in a few places but this is okay since we are very conservative and don't modify state. select { case <-ticker.C: case <-end: return } if s.status == Indet { iter := s.Stats.NbRestarts + 1 nbConfl := s.Stats.NbConflicts nbReduce := s.wl.idxReduce - 1 nbLearned := len(s.wl.learned) nbDel := s.Stats.NbDeleted pctDel := int(100 * float64(nbDel) / float64(s.Stats.NbLearned)) nbUnit := s.Stats.NbUnitLearned fmt.Printf("c | %8d | %11d | %9d | %9d | %3d%% | %6d | %8d/%8d |\n", iter, nbConfl, nbLearned, nbDel, pctDel, nbReduce, nbUnit, s.nbVars) } } }() } nb := 0 lit := s.chooseLit() var lvl decLevel for s.status != Unsat { for s.status == Indet { s.search() if s.status == Indet { s.Stats.NbRestarts++ } } if s.status == Sat { nb++ if s.Verbose { fmt.Printf("c found %d model(s)\n", nb) } s.status = Indet lits := s.decisionLits() switch len(lits) { case 0: s.status = Unsat case 1: s.propagateUnits(lits) default: c := NewClause(lits) s.appendClause(c) lit = lits[len(lits)-1] v := lit.Var() lvl = abs(s.model[v]) - 1 s.cleanupBindings(lvl) s.reason[v] = c // Must do it here because it won't be made by propagateAndSearch s.propagateAndSearch(lit, lvl) } } } if s.Verbose { end <- struct{}{} fmt.Printf("c ======================================================================================\n") } return nb } // decisionLits returns the negation of all decision values once a model was found, ordered by decision levels. // This will allow for searching other models. func (s *Solver) decisionLits() []Lit { lastLit := s.trail[len(s.trail)-1] lvls := abs(s.model[lastLit.Var()]) lits := make([]Lit, lvls-1) for i, r := range s.reason { if lvl := abs(s.model[i]); r == nil && lvl > 1 { if s.model[i] < 0 { // lvl-2 : levels beside unit clauses start at 2, not 0 or 1! lits[lvl-2] = IntToLit(int32(i + 1)) } else { lits[lvl-2] = IntToLit(int32(-i - 1)) } } } return lits } func (s *Solver) propagateUnits(units []Lit) { for _, unit := range units { s.lbdStats.addLbd(1) s.Stats.NbUnitLearned++ s.cleanupBindings(1) s.model[unit.Var()] = lvlToSignedLvl(unit, 1) if s.unifyLiteral(unit, 1) != nil { s.status = Unsat return } s.rebuildOrderHeap() } } // PBString returns a representation of the solver's state as a pseudo-boolean problem. func (s *Solver) PBString() string { meta := fmt.Sprintf("* #variable= %d #constraint= %d #learned= %d\n", s.nbVars, len(s.wl.pbClauses), len(s.wl.learned)) minLine := "" if s.minLits != nil { terms := make([]string, len(s.minLits)) for i, lit := range s.minLits { weight := 1 if s.minWeights != nil { weight = s.minWeights[i] } val := lit.Int() sign := "" if val < 0 { val = -val sign = "~" } terms[i] = fmt.Sprintf("%d %sx%d", weight, sign, val) } minLine = fmt.Sprintf("min: %s ;\n", strings.Join(terms, " +")) } clauses := make([]string, len(s.wl.pbClauses)+len(s.wl.learned)) for i, c := range s.wl.pbClauses { clauses[i] = c.PBString() } for i, c := range s.wl.learned { clauses[i+len(s.wl.pbClauses)] = c.PBString() } for i := 0; i < len(s.model); i++ { if s.model[i] == 1 { clauses = append(clauses, fmt.Sprintf("1 x%d = 1 ;", i+1)) } else if s.model[i] == -1 { clauses = append(clauses, fmt.Sprintf("1 x%d = 0 ;", i+1)) } } return meta + minLine + strings.Join(clauses, "\n") } // AppendClause appends a new clause to the set of clauses. // This is not a learned clause, but a clause that is part of the problem added afterwards (during model counting, for instance). func (s *Solver) AppendClause(clause *Clause) { s.cleanupBindings(1) card := clause.Cardinality() minW := 0 maxW := 0 i := 0 for i < clause.Len() { lit := clause.Get(i) switch s.litStatus(lit) { case Sat: w := clause.Weight(i) minW += w maxW += w clause.removeLit(i) clause.updateCardinality(-w) case Unsat: clause.removeLit(i) default: maxW += clause.Weight(i) i++ } } if minW >= card { // clause is already sat return } if maxW < card { // clause cannot be satisfied s.status = Unsat return } if maxW == card { // Unit s.propagateUnits(clause.lits) } else { s.appendClause(clause) } } // Model returns a slice that associates, to each variable, its binding. // If s's status is not Sat, the method will panic. func (s *Solver) Model() []bool { if s.lastModel == nil { panic("cannot call Model() from a non-Sat solver") } res := make([]bool, s.nbVars) for i, lvl := range s.lastModel { res[i] = lvl > 0 } return res } // Optimal returns the optimal solution, if any. // If results is non-nil, all solutions will be written to it. // In any case, results will be closed at the end of the call. func (s *Solver) Optimal(results chan Result, stop chan struct{}) (res Result) { if results != nil { defer close(results) } status := s.Solve() if status == Unsat { // Problem cannot be satisfied at all res.Status = Unsat if results != nil { results <- res } return res } if s.minLits == nil { // No optimization clause: this is a decision problem, solution is optimal s.lastModel = make(Model, len(s.model)) copy(s.lastModel, s.model) res := Result{ Status: Sat, Model: s.Model(), Weight: 0, } if results != nil { results <- res } return res } maxCost := 0 if s.minWeights == nil { maxCost = len(s.minLits) } else { for _, w := range s.minWeights { maxCost += w } } s.asumptions = make([]Lit, len(s.minLits)) for i, lit := range s.minLits { s.asumptions[i] = lit.Negation() } weights := make([]int, len(s.minWeights)) copy(weights, s.minWeights) sort.Sort(wLits{lits: s.asumptions, weights: weights}) s.lastModel = make(Model, len(s.model)) var cost int for status == Sat { copy(s.lastModel, s.model) // Save this model: it might be the last one cost = 0 for i, lit := range s.minLits { if s.model[lit.Var()] > 0 == lit.IsPositive() { if s.minWeights == nil { cost++ } else { cost += s.minWeights[i] } } } res = Result{ Status: Sat, Model: s.Model(), Weight: cost, } if results != nil { results <- res } if cost == 0 { break } // Add a constraint incrementing current best cost lits2 := make([]Lit, len(s.minLits)) weights2 := make([]int, len(s.minWeights)) copy(lits2, s.asumptions) copy(weights2, weights) s.AppendClause(NewPBClause(lits2, weights2, maxCost-cost+1)) s.rebuildOrderHeap() status = s.Solve() } return res } // Minimize tries to find a model that minimizes the weight of the clause defined as the optimisation clause in the problem. // If no model can be found, it will return a cost of -1. // Otherwise, calling s.Model() afterwards will return the model that satisfy the formula, such that no other model with a smaller cost exists. // If this function is called on a non-optimization problem, it will either return -1, or a cost of 0 associated with a // satisfying model (ie any model is an optimal model). func (s *Solver) Minimize() int { status := s.Solve() if status == Unsat { // Problem cannot be satisfied at all return -1 } if s.minLits == nil { // No optimization clause: this is a decision problem, solution is optimal return 0 } maxCost := 0 if s.minWeights == nil { maxCost = len(s.minLits) } else { for _, w := range s.minWeights { maxCost += w } } s.asumptions = make([]Lit, len(s.minLits)) for i, lit := range s.minLits { s.asumptions[i] = lit.Negation() } weights := make([]int, len(s.minWeights)) copy(weights, s.minWeights) sort.Sort(wLits{lits: s.asumptions, weights: weights}) s.lastModel = make(Model, len(s.model)) var cost int for status == Sat { copy(s.lastModel, s.model) // Save this model: it might be the last one cost = 0 for i, lit := range s.minLits { if s.model[lit.Var()] > 0 == lit.IsPositive() { if s.minWeights == nil { cost++ } else { cost += s.minWeights[i] } } } if cost == 0 { return 0 } if s.Verbose { fmt.Printf("o %d\n", cost) } // Add a constraint incrementing current best cost lits2 := make([]Lit, len(s.minLits)) weights2 := make([]int, len(s.minWeights)) copy(lits2, s.asumptions) copy(weights2, weights) s.AppendClause(NewPBClause(lits2, weights2, maxCost-cost+1)) s.rebuildOrderHeap() status = s.Solve() } return cost } // functions to sort asumptions for pseudo-boolean minimization clause. type wLits struct { lits []Lit weights []int } func (wl wLits) Len() int { return len(wl.lits) } func (wl wLits) Less(i, j int) bool { return wl.weights[i] > wl.weights[j] } func (wl wLits) Swap(i, j int) { wl.lits[i], wl.lits[j] = wl.lits[j], wl.lits[i] wl.weights[i], wl.weights[j] = wl.weights[j], wl.weights[i] }
// Copyright 2016 PingCAP, 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, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "fmt" "path" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/pingcap/errcode" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" log "github.com/pingcap/log" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" syncer "github.com/pingcap/pd/server/region_syncer" "github.com/pkg/errors" "go.uber.org/zap" ) var backgroundJobInterval = time.Minute // RaftCluster is used for cluster config management. // Raft cluster key format: // cluster 1 -> /1/raft, value is metapb.Cluster // cluster 2 -> /2/raft // For cluster 1 // store 1 -> /1/raft/s/1, value is metapb.Store // region 1 -> /1/raft/r/1, value is metapb.Region type RaftCluster struct { sync.RWMutex s *Server running bool clusterID uint64 clusterRoot string // cached cluster info cachedCluster *clusterInfo coordinator *coordinator wg sync.WaitGroup quit chan struct{} regionSyncer *syncer.RegionSyncer } // ClusterStatus saves some state information type ClusterStatus struct { RaftBootstrapTime time.Time `json:"raft_bootstrap_time,omitempty"` } func newRaftCluster(s *Server, clusterID uint64) *RaftCluster { return &RaftCluster{ s: s, running: false, clusterID: clusterID, clusterRoot: s.getClusterRootPath(), regionSyncer: syncer.NewRegionSyncer(s), } } func (c *RaftCluster) loadClusterStatus() (*ClusterStatus, error) { data, err := c.s.kv.Load((c.s.kv.ClusterStatePath("raft_bootstrap_time"))) if err != nil { return nil, err } if len(data) == 0 { return &ClusterStatus{}, nil } t, err := parseTimestamp([]byte(data)) if err != nil { return nil, err } return &ClusterStatus{RaftBootstrapTime: t}, nil } func (c *RaftCluster) start() error { c.Lock() defer c.Unlock() if c.running { log.Warn("raft cluster has already been started") return nil } cluster, err := loadClusterInfo(c.s.idAlloc, c.s.kv, c.s.scheduleOpt) if err != nil { return err } if cluster == nil { return nil } err = c.s.classifier.ReloadNamespaces() if err != nil { return err } c.cachedCluster = cluster c.coordinator = newCoordinator(c.cachedCluster, c.s.hbStreams, c.s.classifier) c.cachedCluster.regionStats = newRegionStatistics(c.s.scheduleOpt, c.s.classifier) c.quit = make(chan struct{}) c.wg.Add(3) go c.runCoordinator() // gofail: var highFrequencyClusterJobs bool // if highFrequencyClusterJobs { // backgroundJobInterval = 100 * time.Microsecond // } go c.runBackgroundJobs(backgroundJobInterval) go c.syncRegions() c.running = true return nil } func (c *RaftCluster) runCoordinator() { defer logutil.LogPanic() defer c.wg.Done() defer c.coordinator.wg.Wait() c.coordinator.run() <-c.coordinator.ctx.Done() log.Info("coordinator: Stopped coordinator") } func (c *RaftCluster) syncRegions() { defer logutil.LogPanic() defer c.wg.Done() c.regionSyncer.RunServer(c.cachedCluster.changedRegionNotifier(), c.quit) } func (c *RaftCluster) stop() { c.Lock() if !c.running { c.Unlock() return } c.running = false close(c.quit) c.coordinator.stop() c.Unlock() c.wg.Wait() } func (c *RaftCluster) isRunning() bool { c.RLock() defer c.RUnlock() return c.running } func makeStoreKey(clusterRootPath string, storeID uint64) string { return path.Join(clusterRootPath, "s", fmt.Sprintf("%020d", storeID)) } func makeRegionKey(clusterRootPath string, regionID uint64) string { return path.Join(clusterRootPath, "r", fmt.Sprintf("%020d", regionID)) } func makeRaftClusterStatusPrefix(clusterRootPath string) string { return path.Join(clusterRootPath, "status") } func makeBootstrapTimeKey(clusterRootPath string) string { return path.Join(makeRaftClusterStatusPrefix(clusterRootPath), "raft_bootstrap_time") } func checkBootstrapRequest(clusterID uint64, req *pdpb.BootstrapRequest) error { // TODO: do more check for request fields validation. storeMeta := req.GetStore() if storeMeta == nil { return errors.Errorf("missing store meta for bootstrap %d", clusterID) } else if storeMeta.GetId() == 0 { return errors.New("invalid zero store id") } regionMeta := req.GetRegion() if regionMeta == nil { return errors.Errorf("missing region meta for bootstrap %d", clusterID) } else if len(regionMeta.GetStartKey()) > 0 || len(regionMeta.GetEndKey()) > 0 { // first region start/end key must be empty return errors.Errorf("invalid first region key range, must all be empty for bootstrap %d", clusterID) } else if regionMeta.GetId() == 0 { return errors.New("invalid zero region id") } peers := regionMeta.GetPeers() if len(peers) != 1 { return errors.Errorf("invalid first region peer count %d, must be 1 for bootstrap %d", len(peers), clusterID) } peer := peers[0] if peer.GetStoreId() != storeMeta.GetId() { return errors.Errorf("invalid peer store id %d != %d for bootstrap %d", peer.GetStoreId(), storeMeta.GetId(), clusterID) } if peer.GetId() == 0 { return errors.New("invalid zero peer id") } return nil } // GetRegionByKey gets region and leader peer by region key from cluster. func (c *RaftCluster) GetRegionByKey(regionKey []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.searchRegion(regionKey) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetPrevRegionByKey gets previous region and leader peer by the region key from cluster. func (c *RaftCluster) GetPrevRegionByKey(regionKey []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.searchPrevRegion(regionKey) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetRegionInfoByKey gets regionInfo by region key from cluster. func (c *RaftCluster) GetRegionInfoByKey(regionKey []byte) *core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.searchRegion(regionKey) } // ScanRegionsByKey scans region with start key, until number greater than limit. func (c *RaftCluster) ScanRegionsByKey(startKey []byte, limit int) []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.ScanRegions(startKey, limit) } // GetRegionByID gets region and leader peer by regionID from cluster. func (c *RaftCluster) GetRegionByID(regionID uint64) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.GetRegion(regionID) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetRegionInfoByID gets regionInfo by regionID from cluster. func (c *RaftCluster) GetRegionInfoByID(regionID uint64) *core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.GetRegion(regionID) } // GetMetaRegions gets regions from cluster. func (c *RaftCluster) GetMetaRegions() []*metapb.Region { c.RLock() defer c.RUnlock() return c.cachedCluster.getMetaRegions() } // GetRegions returns all regions' information in detail. func (c *RaftCluster) GetRegions() []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.getRegions() } // GetStoreRegions returns all regions' information with a given storeID. func (c *RaftCluster) GetStoreRegions(storeID uint64) []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.getStoreRegions(storeID) } // GetRegionStats returns region statistics from cluster. func (c *RaftCluster) GetRegionStats(startKey, endKey []byte) *core.RegionStats { c.RLock() defer c.RUnlock() return c.cachedCluster.getRegionStats(startKey, endKey) } // DropCacheRegion removes a region from the cache. func (c *RaftCluster) DropCacheRegion(id uint64) { c.RLock() defer c.RUnlock() c.cachedCluster.dropRegion(id) } // GetStores gets stores from cluster. func (c *RaftCluster) GetStores() []*metapb.Store { c.RLock() defer c.RUnlock() return c.cachedCluster.getMetaStores() } // GetStore gets store from cluster. func (c *RaftCluster) GetStore(storeID uint64) (*core.StoreInfo, error) { c.RLock() defer c.RUnlock() if storeID == 0 { return nil, errors.New("invalid zero store id") } store := c.cachedCluster.GetStore(storeID) if store == nil { return nil, errors.Errorf("invalid store ID %d, not found", storeID) } return store, nil } // GetAdjacentRegions returns regions' information that are adjacent with the specific region ID. func (c *RaftCluster) GetAdjacentRegions(region *core.RegionInfo) (*core.RegionInfo, *core.RegionInfo) { c.RLock() defer c.RUnlock() return c.cachedCluster.GetAdjacentRegions(region) } // UpdateStoreLabels updates a store's location labels. func (c *RaftCluster) UpdateStoreLabels(storeID uint64, labels []*metapb.StoreLabel) error { c.RLock() defer c.RUnlock() store := c.cachedCluster.GetStore(storeID) if store == nil { return errors.Errorf("invalid store ID %d, not found", storeID) } newStore := proto.Clone(store.GetMeta()).(*metapb.Store) newStore.Labels = labels // putStore will perform label merge. err := c.putStore(newStore) return err } func (c *RaftCluster) putStore(store *metapb.Store) error { c.RLock() defer c.RUnlock() if store.GetId() == 0 { return errors.Errorf("invalid put store %v", store) } v, err := ParseVersion(store.GetVersion()) if err != nil { return errors.Errorf("invalid put store %v, error: %s", store, err) } clusterVersion := c.cachedCluster.opt.loadClusterVersion() if !IsCompatible(clusterVersion, *v) { return errors.Errorf("version should compatible with version %s, got %s", clusterVersion, v) } cluster := c.cachedCluster // Store address can not be the same as other stores. for _, s := range cluster.GetStores() { // It's OK to start a new store on the same address if the old store has been removed. if s.IsTombstone() { continue } if s.GetID() != store.GetId() && s.GetAddress() == store.GetAddress() { return errors.Errorf("duplicated store address: %v, already registered by %v", store, s.GetMeta()) } } s := cluster.GetStore(store.GetId()) if s == nil { // Add a new store. s = core.NewStoreInfo(store) } else { // Update an existed store. labels := s.MergeLabels(store.GetLabels()) s = s.Clone( core.SetStoreAddress(store.Address), core.SetStoreVersion(store.Version), core.SetStoreLabels(labels), ) } // Check location labels. for _, k := range c.cachedCluster.GetLocationLabels() { if v := s.GetLabelValue(k); len(v) == 0 { log.Warn("missing location label", zap.Stringer("store", s.GetMeta()), zap.String("label-key", k)) } } return cluster.putStore(s) } // RemoveStore marks a store as offline in cluster. // State transition: Up -> Offline. func (c *RaftCluster) RemoveStore(storeID uint64) error { op := errcode.Op("store.remove") c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return op.AddTo(core.NewStoreNotFoundErr(storeID)) } // Remove an offline store should be OK, nothing to do. if store.IsOffline() { return nil } if store.IsTombstone() { return op.AddTo(core.StoreTombstonedErr{StoreID: storeID}) } newStore := store.Clone(core.SetStoreState(metapb.StoreState_Offline)) log.Warn("store has been offline", zap.Uint64("store-id", newStore.GetID()), zap.String("store-address", newStore.GetAddress())) return cluster.putStore(newStore) } // BuryStore marks a store as tombstone in cluster. // State transition: // Case 1: Up -> Tombstone (if force is true); // Case 2: Offline -> Tombstone. func (c *RaftCluster) BuryStore(storeID uint64, force bool) error { // revive:disable-line:flag-parameter c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } // Bury a tombstone store should be OK, nothing to do. if store.IsTombstone() { return nil } if store.IsUp() { if !force { return errors.New("store is still up, please remove store gracefully") } log.Warn("forcedly bury store", zap.Stringer("store", store.GetMeta())) } newStore := store.Clone(core.SetStoreState(metapb.StoreState_Tombstone)) log.Warn("store has been Tombstone", zap.Uint64("store-id", newStore.GetID()), zap.String("store-address", newStore.GetAddress())) return cluster.putStore(newStore) } // SetStoreState sets up a store's state. func (c *RaftCluster) SetStoreState(storeID uint64, state metapb.StoreState) error { c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } newStore := store.Clone(core.SetStoreState(state)) log.Warn("store update state", zap.Uint64("store-id", storeID), zap.Stringer("new-state", state)) return cluster.putStore(newStore) } // SetStoreWeight sets up a store's leader/region balance weight. func (c *RaftCluster) SetStoreWeight(storeID uint64, leaderWeight, regionWeight float64) error { c.RLock() defer c.RUnlock() store := c.cachedCluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } if err := c.s.kv.SaveStoreWeight(storeID, leaderWeight, regionWeight); err != nil { return err } newStore := store.Clone( core.SetLeaderWeight(leaderWeight), core.SetRegionWeight(regionWeight), ) return c.cachedCluster.putStore(newStore) } func (c *RaftCluster) checkStores() { var offlineStores []*metapb.Store var upStoreCount int cluster := c.cachedCluster for _, store := range cluster.GetStores() { // the store has already been tombstone if store.IsTombstone() { continue } if store.IsUp() && !store.IsLowSpace(cluster.GetLowSpaceRatio()) { upStoreCount++ continue } offlineStore := store.GetMeta() // If the store is empty, it can be buried. if cluster.getStoreRegionCount(offlineStore.GetId()) == 0 { if err := c.BuryStore(offlineStore.GetId(), false); err != nil { log.Error("bury store failed", zap.Stringer("store", offlineStore), zap.Error(err)) } } else { offlineStores = append(offlineStores, offlineStore) } } if len(offlineStores) == 0 { return } if upStoreCount < cluster.GetMaxReplicas() { for _, offlineStore := range offlineStores { log.Warn("store may not turn into Tombstone, there are no extra up node has enough space to accommodate the extra replica", zap.Stringer("store", offlineStore)) } } } func (c *RaftCluster) checkOperators() { opController := c.coordinator.opController for _, op := range opController.GetOperators() { // after region is merged, it will not heartbeat anymore // the operator of merged region will not timeout actively if c.cachedCluster.GetRegion(op.RegionID()) == nil { log.Debug("remove operator cause region is merged", zap.Uint64("region-id", op.RegionID()), zap.Stringer("operator", op)) opController.RemoveOperator(op) continue } if op.IsTimeout() { log.Info("operator timeout", zap.Uint64("region-id", op.RegionID()), zap.Stringer("operator", op)) opController.RemoveOperator(op) } } } func (c *RaftCluster) collectMetrics() { cluster := c.cachedCluster statsMap := newStoreStatisticsMap(c.cachedCluster.opt, c.GetNamespaceClassifier()) for _, s := range cluster.GetStores() { statsMap.Observe(s) } statsMap.Collect() c.coordinator.collectSchedulerMetrics() c.coordinator.collectHotSpotMetrics() cluster.collectMetrics() c.collectHealthStatus() } func (c *RaftCluster) collectHealthStatus() { client := c.s.GetClient() members, err := GetMembers(client) if err != nil { log.Error("get members error", zap.Error(err)) } unhealth := c.s.CheckHealth(members) for _, member := range members { if _, ok := unhealth[member.GetMemberId()]; ok { healthStatusGauge.WithLabelValues(member.GetName()).Set(0) continue } healthStatusGauge.WithLabelValues(member.GetName()).Set(1) } } func (c *RaftCluster) runBackgroundJobs(interval time.Duration) { defer logutil.LogPanic() defer c.wg.Done() ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-c.quit: return case <-ticker.C: c.checkOperators() c.checkStores() c.collectMetrics() c.coordinator.opController.PruneHistory() } } } // GetConfig gets config from cluster. func (c *RaftCluster) GetConfig() *metapb.Cluster { c.RLock() defer c.RUnlock() return c.cachedCluster.getMeta() } func (c *RaftCluster) putConfig(meta *metapb.Cluster) error { c.RLock() defer c.RUnlock() if meta.GetId() != c.clusterID { return errors.Errorf("invalid cluster %v, mismatch cluster id %d", meta, c.clusterID) } return c.cachedCluster.putMeta(meta) } // GetNamespaceClassifier returns current namespace classifier. func (c *RaftCluster) GetNamespaceClassifier() namespace.Classifier { return c.s.classifier } fix adding the lowspace store (#1453) Signed-off-by: rleungx <98ca95cd24c810cea97a0e53f67d648652b7b2cf@gmail.com> // Copyright 2016 PingCAP, 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, // See the License for the specific language governing permissions and // limitations under the License. package server import ( "fmt" "path" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/pingcap/errcode" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" log "github.com/pingcap/log" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" syncer "github.com/pingcap/pd/server/region_syncer" "github.com/pkg/errors" "go.uber.org/zap" ) var backgroundJobInterval = time.Minute // RaftCluster is used for cluster config management. // Raft cluster key format: // cluster 1 -> /1/raft, value is metapb.Cluster // cluster 2 -> /2/raft // For cluster 1 // store 1 -> /1/raft/s/1, value is metapb.Store // region 1 -> /1/raft/r/1, value is metapb.Region type RaftCluster struct { sync.RWMutex s *Server running bool clusterID uint64 clusterRoot string // cached cluster info cachedCluster *clusterInfo coordinator *coordinator wg sync.WaitGroup quit chan struct{} regionSyncer *syncer.RegionSyncer } // ClusterStatus saves some state information type ClusterStatus struct { RaftBootstrapTime time.Time `json:"raft_bootstrap_time,omitempty"` } func newRaftCluster(s *Server, clusterID uint64) *RaftCluster { return &RaftCluster{ s: s, running: false, clusterID: clusterID, clusterRoot: s.getClusterRootPath(), regionSyncer: syncer.NewRegionSyncer(s), } } func (c *RaftCluster) loadClusterStatus() (*ClusterStatus, error) { data, err := c.s.kv.Load((c.s.kv.ClusterStatePath("raft_bootstrap_time"))) if err != nil { return nil, err } if len(data) == 0 { return &ClusterStatus{}, nil } t, err := parseTimestamp([]byte(data)) if err != nil { return nil, err } return &ClusterStatus{RaftBootstrapTime: t}, nil } func (c *RaftCluster) start() error { c.Lock() defer c.Unlock() if c.running { log.Warn("raft cluster has already been started") return nil } cluster, err := loadClusterInfo(c.s.idAlloc, c.s.kv, c.s.scheduleOpt) if err != nil { return err } if cluster == nil { return nil } err = c.s.classifier.ReloadNamespaces() if err != nil { return err } c.cachedCluster = cluster c.coordinator = newCoordinator(c.cachedCluster, c.s.hbStreams, c.s.classifier) c.cachedCluster.regionStats = newRegionStatistics(c.s.scheduleOpt, c.s.classifier) c.quit = make(chan struct{}) c.wg.Add(3) go c.runCoordinator() // gofail: var highFrequencyClusterJobs bool // if highFrequencyClusterJobs { // backgroundJobInterval = 100 * time.Microsecond // } go c.runBackgroundJobs(backgroundJobInterval) go c.syncRegions() c.running = true return nil } func (c *RaftCluster) runCoordinator() { defer logutil.LogPanic() defer c.wg.Done() defer c.coordinator.wg.Wait() c.coordinator.run() <-c.coordinator.ctx.Done() log.Info("coordinator: Stopped coordinator") } func (c *RaftCluster) syncRegions() { defer logutil.LogPanic() defer c.wg.Done() c.regionSyncer.RunServer(c.cachedCluster.changedRegionNotifier(), c.quit) } func (c *RaftCluster) stop() { c.Lock() if !c.running { c.Unlock() return } c.running = false close(c.quit) c.coordinator.stop() c.Unlock() c.wg.Wait() } func (c *RaftCluster) isRunning() bool { c.RLock() defer c.RUnlock() return c.running } func makeStoreKey(clusterRootPath string, storeID uint64) string { return path.Join(clusterRootPath, "s", fmt.Sprintf("%020d", storeID)) } func makeRegionKey(clusterRootPath string, regionID uint64) string { return path.Join(clusterRootPath, "r", fmt.Sprintf("%020d", regionID)) } func makeRaftClusterStatusPrefix(clusterRootPath string) string { return path.Join(clusterRootPath, "status") } func makeBootstrapTimeKey(clusterRootPath string) string { return path.Join(makeRaftClusterStatusPrefix(clusterRootPath), "raft_bootstrap_time") } func checkBootstrapRequest(clusterID uint64, req *pdpb.BootstrapRequest) error { // TODO: do more check for request fields validation. storeMeta := req.GetStore() if storeMeta == nil { return errors.Errorf("missing store meta for bootstrap %d", clusterID) } else if storeMeta.GetId() == 0 { return errors.New("invalid zero store id") } regionMeta := req.GetRegion() if regionMeta == nil { return errors.Errorf("missing region meta for bootstrap %d", clusterID) } else if len(regionMeta.GetStartKey()) > 0 || len(regionMeta.GetEndKey()) > 0 { // first region start/end key must be empty return errors.Errorf("invalid first region key range, must all be empty for bootstrap %d", clusterID) } else if regionMeta.GetId() == 0 { return errors.New("invalid zero region id") } peers := regionMeta.GetPeers() if len(peers) != 1 { return errors.Errorf("invalid first region peer count %d, must be 1 for bootstrap %d", len(peers), clusterID) } peer := peers[0] if peer.GetStoreId() != storeMeta.GetId() { return errors.Errorf("invalid peer store id %d != %d for bootstrap %d", peer.GetStoreId(), storeMeta.GetId(), clusterID) } if peer.GetId() == 0 { return errors.New("invalid zero peer id") } return nil } // GetRegionByKey gets region and leader peer by region key from cluster. func (c *RaftCluster) GetRegionByKey(regionKey []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.searchRegion(regionKey) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetPrevRegionByKey gets previous region and leader peer by the region key from cluster. func (c *RaftCluster) GetPrevRegionByKey(regionKey []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.searchPrevRegion(regionKey) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetRegionInfoByKey gets regionInfo by region key from cluster. func (c *RaftCluster) GetRegionInfoByKey(regionKey []byte) *core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.searchRegion(regionKey) } // ScanRegionsByKey scans region with start key, until number greater than limit. func (c *RaftCluster) ScanRegionsByKey(startKey []byte, limit int) []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.ScanRegions(startKey, limit) } // GetRegionByID gets region and leader peer by regionID from cluster. func (c *RaftCluster) GetRegionByID(regionID uint64) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() region := c.cachedCluster.GetRegion(regionID) if region == nil { return nil, nil } return region.GetMeta(), region.GetLeader() } // GetRegionInfoByID gets regionInfo by regionID from cluster. func (c *RaftCluster) GetRegionInfoByID(regionID uint64) *core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.GetRegion(regionID) } // GetMetaRegions gets regions from cluster. func (c *RaftCluster) GetMetaRegions() []*metapb.Region { c.RLock() defer c.RUnlock() return c.cachedCluster.getMetaRegions() } // GetRegions returns all regions' information in detail. func (c *RaftCluster) GetRegions() []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.getRegions() } // GetStoreRegions returns all regions' information with a given storeID. func (c *RaftCluster) GetStoreRegions(storeID uint64) []*core.RegionInfo { c.RLock() defer c.RUnlock() return c.cachedCluster.getStoreRegions(storeID) } // GetRegionStats returns region statistics from cluster. func (c *RaftCluster) GetRegionStats(startKey, endKey []byte) *core.RegionStats { c.RLock() defer c.RUnlock() return c.cachedCluster.getRegionStats(startKey, endKey) } // DropCacheRegion removes a region from the cache. func (c *RaftCluster) DropCacheRegion(id uint64) { c.RLock() defer c.RUnlock() c.cachedCluster.dropRegion(id) } // GetStores gets stores from cluster. func (c *RaftCluster) GetStores() []*metapb.Store { c.RLock() defer c.RUnlock() return c.cachedCluster.getMetaStores() } // GetStore gets store from cluster. func (c *RaftCluster) GetStore(storeID uint64) (*core.StoreInfo, error) { c.RLock() defer c.RUnlock() if storeID == 0 { return nil, errors.New("invalid zero store id") } store := c.cachedCluster.GetStore(storeID) if store == nil { return nil, errors.Errorf("invalid store ID %d, not found", storeID) } return store, nil } // GetAdjacentRegions returns regions' information that are adjacent with the specific region ID. func (c *RaftCluster) GetAdjacentRegions(region *core.RegionInfo) (*core.RegionInfo, *core.RegionInfo) { c.RLock() defer c.RUnlock() return c.cachedCluster.GetAdjacentRegions(region) } // UpdateStoreLabels updates a store's location labels. func (c *RaftCluster) UpdateStoreLabels(storeID uint64, labels []*metapb.StoreLabel) error { c.RLock() defer c.RUnlock() store := c.cachedCluster.GetStore(storeID) if store == nil { return errors.Errorf("invalid store ID %d, not found", storeID) } newStore := proto.Clone(store.GetMeta()).(*metapb.Store) newStore.Labels = labels // putStore will perform label merge. err := c.putStore(newStore) return err } func (c *RaftCluster) putStore(store *metapb.Store) error { c.RLock() defer c.RUnlock() if store.GetId() == 0 { return errors.Errorf("invalid put store %v", store) } v, err := ParseVersion(store.GetVersion()) if err != nil { return errors.Errorf("invalid put store %v, error: %s", store, err) } clusterVersion := c.cachedCluster.opt.loadClusterVersion() if !IsCompatible(clusterVersion, *v) { return errors.Errorf("version should compatible with version %s, got %s", clusterVersion, v) } cluster := c.cachedCluster // Store address can not be the same as other stores. for _, s := range cluster.GetStores() { // It's OK to start a new store on the same address if the old store has been removed. if s.IsTombstone() { continue } if s.GetID() != store.GetId() && s.GetAddress() == store.GetAddress() { return errors.Errorf("duplicated store address: %v, already registered by %v", store, s.GetMeta()) } } s := cluster.GetStore(store.GetId()) if s == nil { // Add a new store. s = core.NewStoreInfo(store) } else { // Update an existed store. labels := s.MergeLabels(store.GetLabels()) s = s.Clone( core.SetStoreAddress(store.Address), core.SetStoreVersion(store.Version), core.SetStoreLabels(labels), ) } // Check location labels. for _, k := range c.cachedCluster.GetLocationLabels() { if v := s.GetLabelValue(k); len(v) == 0 { log.Warn("missing location label", zap.Stringer("store", s.GetMeta()), zap.String("label-key", k)) } } return cluster.putStore(s) } // RemoveStore marks a store as offline in cluster. // State transition: Up -> Offline. func (c *RaftCluster) RemoveStore(storeID uint64) error { op := errcode.Op("store.remove") c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return op.AddTo(core.NewStoreNotFoundErr(storeID)) } // Remove an offline store should be OK, nothing to do. if store.IsOffline() { return nil } if store.IsTombstone() { return op.AddTo(core.StoreTombstonedErr{StoreID: storeID}) } newStore := store.Clone(core.SetStoreState(metapb.StoreState_Offline)) log.Warn("store has been offline", zap.Uint64("store-id", newStore.GetID()), zap.String("store-address", newStore.GetAddress())) return cluster.putStore(newStore) } // BuryStore marks a store as tombstone in cluster. // State transition: // Case 1: Up -> Tombstone (if force is true); // Case 2: Offline -> Tombstone. func (c *RaftCluster) BuryStore(storeID uint64, force bool) error { // revive:disable-line:flag-parameter c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } // Bury a tombstone store should be OK, nothing to do. if store.IsTombstone() { return nil } if store.IsUp() { if !force { return errors.New("store is still up, please remove store gracefully") } log.Warn("forcedly bury store", zap.Stringer("store", store.GetMeta())) } newStore := store.Clone(core.SetStoreState(metapb.StoreState_Tombstone)) log.Warn("store has been Tombstone", zap.Uint64("store-id", newStore.GetID()), zap.String("store-address", newStore.GetAddress())) return cluster.putStore(newStore) } // SetStoreState sets up a store's state. func (c *RaftCluster) SetStoreState(storeID uint64, state metapb.StoreState) error { c.RLock() defer c.RUnlock() cluster := c.cachedCluster store := cluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } newStore := store.Clone(core.SetStoreState(state)) log.Warn("store update state", zap.Uint64("store-id", storeID), zap.Stringer("new-state", state)) return cluster.putStore(newStore) } // SetStoreWeight sets up a store's leader/region balance weight. func (c *RaftCluster) SetStoreWeight(storeID uint64, leaderWeight, regionWeight float64) error { c.RLock() defer c.RUnlock() store := c.cachedCluster.GetStore(storeID) if store == nil { return core.NewStoreNotFoundErr(storeID) } if err := c.s.kv.SaveStoreWeight(storeID, leaderWeight, regionWeight); err != nil { return err } newStore := store.Clone( core.SetLeaderWeight(leaderWeight), core.SetRegionWeight(regionWeight), ) return c.cachedCluster.putStore(newStore) } func (c *RaftCluster) checkStores() { var offlineStores []*metapb.Store var upStoreCount int cluster := c.cachedCluster for _, store := range cluster.GetStores() { // the store has already been tombstone if store.IsTombstone() { continue } if store.IsUp() { if !store.IsLowSpace(cluster.GetLowSpaceRatio()) { upStoreCount++ } continue } offlineStore := store.GetMeta() // If the store is empty, it can be buried. if cluster.getStoreRegionCount(offlineStore.GetId()) == 0 { if err := c.BuryStore(offlineStore.GetId(), false); err != nil { log.Error("bury store failed", zap.Stringer("store", offlineStore), zap.Error(err)) } } else { offlineStores = append(offlineStores, offlineStore) } } if len(offlineStores) == 0 { return } if upStoreCount < cluster.GetMaxReplicas() { for _, offlineStore := range offlineStores { log.Warn("store may not turn into Tombstone, there are no extra up node has enough space to accommodate the extra replica", zap.Stringer("store", offlineStore)) } } } func (c *RaftCluster) checkOperators() { opController := c.coordinator.opController for _, op := range opController.GetOperators() { // after region is merged, it will not heartbeat anymore // the operator of merged region will not timeout actively if c.cachedCluster.GetRegion(op.RegionID()) == nil { log.Debug("remove operator cause region is merged", zap.Uint64("region-id", op.RegionID()), zap.Stringer("operator", op)) opController.RemoveOperator(op) continue } if op.IsTimeout() { log.Info("operator timeout", zap.Uint64("region-id", op.RegionID()), zap.Stringer("operator", op)) opController.RemoveOperator(op) } } } func (c *RaftCluster) collectMetrics() { cluster := c.cachedCluster statsMap := newStoreStatisticsMap(c.cachedCluster.opt, c.GetNamespaceClassifier()) for _, s := range cluster.GetStores() { statsMap.Observe(s) } statsMap.Collect() c.coordinator.collectSchedulerMetrics() c.coordinator.collectHotSpotMetrics() cluster.collectMetrics() c.collectHealthStatus() } func (c *RaftCluster) collectHealthStatus() { client := c.s.GetClient() members, err := GetMembers(client) if err != nil { log.Error("get members error", zap.Error(err)) } unhealth := c.s.CheckHealth(members) for _, member := range members { if _, ok := unhealth[member.GetMemberId()]; ok { healthStatusGauge.WithLabelValues(member.GetName()).Set(0) continue } healthStatusGauge.WithLabelValues(member.GetName()).Set(1) } } func (c *RaftCluster) runBackgroundJobs(interval time.Duration) { defer logutil.LogPanic() defer c.wg.Done() ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-c.quit: return case <-ticker.C: c.checkOperators() c.checkStores() c.collectMetrics() c.coordinator.opController.PruneHistory() } } } // GetConfig gets config from cluster. func (c *RaftCluster) GetConfig() *metapb.Cluster { c.RLock() defer c.RUnlock() return c.cachedCluster.getMeta() } func (c *RaftCluster) putConfig(meta *metapb.Cluster) error { c.RLock() defer c.RUnlock() if meta.GetId() != c.clusterID { return errors.Errorf("invalid cluster %v, mismatch cluster id %d", meta, c.clusterID) } return c.cachedCluster.putMeta(meta) } // GetNamespaceClassifier returns current namespace classifier. func (c *RaftCluster) GetNamespaceClassifier() namespace.Classifier { return c.s.classifier }
//go:generate esc -o static.go -prefix ../web/build -pkg server ../web/build package server import ( "encoding/hex" "encoding/xml" "errors" "fmt" "io" "net/http" "net/url" "strings" "github.com/Sirupsen/logrus" "github.com/cardigann/cardigann/config" "github.com/cardigann/cardigann/indexer" "github.com/cardigann/cardigann/logger" "github.com/cardigann/cardigann/torrentpotato" "github.com/cardigann/cardigann/torznab" "github.com/gorilla/mux" ) const ( buildDir = "/web/build" ) var ( log = logger.Logger apiRoutePrefixes = []string{ "/torznab/", "/torrentpotato/", "/download/", "/xhr/", "/debug/", } ) type Params struct { BaseURL string APIKey []byte Passphrase string Config config.Config Version string } type handler struct { http.Handler Params Params FileHandler http.Handler indexers map[string]torznab.Indexer } func NewHandler(p Params) (http.Handler, error) { h := &handler{ Params: p, FileHandler: http.FileServer(FS(false)), indexers: map[string]torznab.Indexer{}, } router := mux.NewRouter() // torznab routes router.HandleFunc("/torznab/{indexer}", h.torznabHandler).Methods("GET") router.HandleFunc("/torznab/{indexer}/api", h.torznabHandler).Methods("GET") // torrentpotato routes router.HandleFunc("/torrentpotato/{indexer}", h.torrentPotatoHandler).Methods("GET") // download routes router.HandleFunc("/download/{indexer}/{token}/{filename}", h.downloadHandler).Methods("HEAD") router.HandleFunc("/download/{indexer}/{token}/{filename}", h.downloadHandler).Methods("GET") router.HandleFunc("/download/{token}/{filename}", h.downloadHandler).Methods("HEAD") router.HandleFunc("/download/{token}/{filename}", h.downloadHandler).Methods("GET") // xhr routes for the webapp router.HandleFunc("/xhr/indexers/{indexer}/test", h.getIndexerTestHandler).Methods("GET") router.HandleFunc("/xhr/indexers/{indexer}/config", h.getIndexersConfigHandler).Methods("GET") router.HandleFunc("/xhr/indexers/{indexer}/config", h.patchIndexersConfigHandler).Methods("PATCH") router.HandleFunc("/xhr/indexers", h.getIndexersHandler).Methods("GET") router.HandleFunc("/xhr/indexers", h.patchIndexersHandler).Methods("PATCH") router.HandleFunc("/xhr/auth", h.getAuthHandler).Methods("GET") router.HandleFunc("/xhr/auth", h.postAuthHandler).Methods("POST") router.HandleFunc("/xhr/version", h.getVersionHandler).Methods("GET") h.Handler = router return h, h.initialize() } func (h *handler) initialize() error { if h.Params.Passphrase == "" { pass, hasPassphrase, _ := h.Params.Config.Get("global", "passphrase") if hasPassphrase { h.Params.Passphrase = pass return nil } apiKey, hasApiKey, _ := h.Params.Config.Get("global", "apikey") if !hasApiKey { k, err := h.sharedKey() if err != nil { return err } h.Params.APIKey = k return h.Params.Config.Set("global", "apikey", fmt.Sprintf("%x", k)) } k, err := hex.DecodeString(apiKey) if err != nil { return err } h.Params.APIKey = k } return nil } func (h *handler) baseURL(r *http.Request, path string) (*url.URL, error) { if h.Params.BaseURL != "" { return url.Parse(h.Params.BaseURL) } proto := "http" if r.TLS != nil { proto = "https" } return url.Parse(fmt.Sprintf("%s://%s%s", proto, r.Host, path)) } func (h *handler) createIndexer(key string) (torznab.Indexer, error) { def, err := indexer.DefaultDefinitionLoader.Load(key) if err != nil { log.WithError(err).Warnf("Failed to load definition for %q", key) return nil, err } log.WithFields(logrus.Fields{"indexer": key}).Debugf("Loaded indexer") indexer, err := indexer.NewRunner(def, indexer.RunnerOpts{ Config: h.Params.Config, }), nil if err != nil { return nil, err } return indexer, nil } func (h *handler) lookupIndexer(key string) (torznab.Indexer, error) { if key == "aggregate" { return h.createAggregate() } if _, ok := h.indexers[key]; !ok { indexer, err := h.createIndexer(key) if err != nil { return nil, err } h.indexers[key] = indexer } return h.indexers[key], nil } func (h *handler) createAggregate() (torznab.Indexer, error) { keys, err := indexer.DefaultDefinitionLoader.List() if err != nil { return nil, err } agg := indexer.Aggregate{} for _, key := range keys { if config.IsSectionEnabled(key, h.Params.Config) { indexer, err := h.lookupIndexer(key) if err != nil { return nil, err } agg = append(agg, indexer) } } return agg, nil } func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Set("Access-Control-Allow-Headers", "Accept, Cache-Control, Content-Type, Content-Length, Accept-Encoding, Authorization, Last-Event-ID") } if r.Method == "OPTIONS" { return } log.WithFields(logrus.Fields{ "method": r.Method, "path": r.URL.RequestURI(), "remote": r.RemoteAddr, }).Debugf("%s %s", r.Method, r.URL.RequestURI()) for _, prefix := range apiRoutePrefixes { if strings.HasPrefix(r.URL.Path, prefix) { h.Handler.ServeHTTP(w, r) return } } h.FileHandler.ServeHTTP(w, r) } func (h *handler) torznabHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) indexerID := params["indexer"] apiKey := r.URL.Query().Get("apikey") if !h.checkAPIKey(apiKey) { torznab.Error(w, "Invalid apikey parameter", torznab.ErrInsufficientPrivs) return } indexer, err := h.lookupIndexer(indexerID) if err != nil { torznab.Error(w, err.Error(), torznab.ErrIncorrectParameter) return } t := r.URL.Query().Get("t") if t == "" { http.Redirect(w, r, r.URL.Path+"?t=caps", http.StatusTemporaryRedirect) return } switch t { case "caps": indexer.Capabilities().ServeHTTP(w, r) case "search", "tvsearch", "tv-search": feed, err := h.torznabSearch(r, indexer, indexerID) if err != nil { torznab.Error(w, err.Error(), torznab.ErrUnknownError) return } switch r.URL.Query().Get("format") { case "", "xml": x, err := xml.MarshalIndent(feed, "", " ") if err != nil { torznab.Error(w, err.Error(), torznab.ErrUnknownError) return } w.Header().Set("Content-Type", "application/rss+xml") w.Write(x) case "json": jsonOutput(w, feed) } default: torznab.Error(w, "Unknown type parameter", torznab.ErrIncorrectParameter) } } func (h *handler) torrentPotatoHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) indexerID := params["indexer"] apiKey := r.URL.Query().Get("passkey") if !h.checkAPIKey(apiKey) { torrentpotato.Error(w, errors.New("Invalid passkey")) return } indexer, err := h.lookupIndexer(indexerID) if err != nil { torrentpotato.Error(w, err) return } query := torznab.Query{ Type: "movie", Categories: []int{ torznab.CategoryMovies.ID, torznab.CategoryMovies_SD.ID, torznab.CategoryMovies_HD.ID, torznab.CategoryMovies_Foreign.ID, }, } qs := r.URL.Query() if search := qs.Get("search"); search != "" { query.Q = search } if imdbid := qs.Get("imdbid"); imdbid != "" { query.IMDBID = imdbid } items, err := indexer.Search(query) if err != nil { torrentpotato.Error(w, err) return } rewritten, err := h.rewriteLinks(r, items) if err != nil { torrentpotato.Error(w, err) return } torrentpotato.Output(w, rewritten) } func (h *handler) downloadHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) token := params["token"] filename := params["filename"] log.WithFields(logrus.Fields{"filename": filename}).Debugf("Processing download via handler") k, err := h.sharedKey() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t, err := decodeToken(token, k) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } indexer, err := h.lookupIndexer(t.Site) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } rc, _, err := indexer.Download(t.Link) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.Header().Set("Content-Type", "application/x-bittorrent") w.Header().Set("Content-Disposition", "attachment; filename="+filename) w.Header().Set("Content-Transfer-Encoding", "binary") defer rc.Close() io.Copy(w, rc) } func (h *handler) torznabSearch(r *http.Request, indexer torznab.Indexer, siteKey string) (*torznab.ResultFeed, error) { query, err := torznab.ParseQuery(r.URL.Query()) if err != nil { return nil, err } items, err := indexer.Search(query) if err != nil { return nil, err } feed := &torznab.ResultFeed{ Info: indexer.Info(), Items: items, } rewritten, err := h.rewriteLinks(r, items) if err != nil { return nil, err } feed.Items = rewritten return feed, err } func (h *handler) rewriteLinks(r *http.Request, items []torznab.ResultItem) ([]torznab.ResultItem, error) { baseURL, err := h.baseURL(r, "/download") if err != nil { return nil, err } k, err := h.sharedKey() if err != nil { return nil, err } // rewrite non-magnet links to use the server for idx, item := range items { if strings.HasPrefix(item.Link, "magnet:") { continue } t := &token{ Site: item.Site, Link: item.Link, } te, err := t.Encode(k) if err != nil { log.Debugf("Error encoding token: %v", err) return nil, err } items[idx].Link = fmt.Sprintf("%s/%s/%s.torrent", baseURL.String(), te, url.QueryEscape(item.Title)) } return items, nil } Fix bug where download links were incorrect //go:generate esc -o static.go -prefix ../web/build -pkg server ../web/build package server import ( "encoding/hex" "encoding/xml" "errors" "fmt" "io" "net/http" "net/url" "strings" "github.com/Sirupsen/logrus" "github.com/cardigann/cardigann/config" "github.com/cardigann/cardigann/indexer" "github.com/cardigann/cardigann/logger" "github.com/cardigann/cardigann/torrentpotato" "github.com/cardigann/cardigann/torznab" "github.com/gorilla/mux" ) const ( buildDir = "/web/build" ) var ( log = logger.Logger apiRoutePrefixes = []string{ "/torznab/", "/torrentpotato/", "/download/", "/xhr/", "/debug/", } ) type Params struct { BaseURL string APIKey []byte Passphrase string Config config.Config Version string } type handler struct { http.Handler Params Params FileHandler http.Handler indexers map[string]torznab.Indexer } func NewHandler(p Params) (http.Handler, error) { h := &handler{ Params: p, FileHandler: http.FileServer(FS(false)), indexers: map[string]torznab.Indexer{}, } router := mux.NewRouter() // torznab routes router.HandleFunc("/torznab/{indexer}", h.torznabHandler).Methods("GET") router.HandleFunc("/torznab/{indexer}/api", h.torznabHandler).Methods("GET") // torrentpotato routes router.HandleFunc("/torrentpotato/{indexer}", h.torrentPotatoHandler).Methods("GET") // download routes router.HandleFunc("/download/{indexer}/{token}/{filename}", h.downloadHandler).Methods("HEAD") router.HandleFunc("/download/{indexer}/{token}/{filename}", h.downloadHandler).Methods("GET") router.HandleFunc("/download/{token}/{filename}", h.downloadHandler).Methods("HEAD") router.HandleFunc("/download/{token}/{filename}", h.downloadHandler).Methods("GET") // xhr routes for the webapp router.HandleFunc("/xhr/indexers/{indexer}/test", h.getIndexerTestHandler).Methods("GET") router.HandleFunc("/xhr/indexers/{indexer}/config", h.getIndexersConfigHandler).Methods("GET") router.HandleFunc("/xhr/indexers/{indexer}/config", h.patchIndexersConfigHandler).Methods("PATCH") router.HandleFunc("/xhr/indexers", h.getIndexersHandler).Methods("GET") router.HandleFunc("/xhr/indexers", h.patchIndexersHandler).Methods("PATCH") router.HandleFunc("/xhr/auth", h.getAuthHandler).Methods("GET") router.HandleFunc("/xhr/auth", h.postAuthHandler).Methods("POST") router.HandleFunc("/xhr/version", h.getVersionHandler).Methods("GET") h.Handler = router return h, h.initialize() } func (h *handler) initialize() error { if h.Params.Passphrase == "" { pass, hasPassphrase, _ := h.Params.Config.Get("global", "passphrase") if hasPassphrase { h.Params.Passphrase = pass return nil } apiKey, hasApiKey, _ := h.Params.Config.Get("global", "apikey") if !hasApiKey { k, err := h.sharedKey() if err != nil { return err } h.Params.APIKey = k return h.Params.Config.Set("global", "apikey", fmt.Sprintf("%x", k)) } k, err := hex.DecodeString(apiKey) if err != nil { return err } h.Params.APIKey = k } return nil } func (h *handler) baseURL(r *http.Request, path string) (*url.URL, error) { proto := "http" if r.TLS != nil { proto = "https" } return url.Parse(fmt.Sprintf("%s://%s%s", proto, r.Host, path)) } func (h *handler) createIndexer(key string) (torznab.Indexer, error) { def, err := indexer.DefaultDefinitionLoader.Load(key) if err != nil { log.WithError(err).Warnf("Failed to load definition for %q", key) return nil, err } log.WithFields(logrus.Fields{"indexer": key}).Debugf("Loaded indexer") indexer, err := indexer.NewRunner(def, indexer.RunnerOpts{ Config: h.Params.Config, }), nil if err != nil { return nil, err } return indexer, nil } func (h *handler) lookupIndexer(key string) (torznab.Indexer, error) { if key == "aggregate" { return h.createAggregate() } if _, ok := h.indexers[key]; !ok { indexer, err := h.createIndexer(key) if err != nil { return nil, err } h.indexers[key] = indexer } return h.indexers[key], nil } func (h *handler) createAggregate() (torznab.Indexer, error) { keys, err := indexer.DefaultDefinitionLoader.List() if err != nil { return nil, err } agg := indexer.Aggregate{} for _, key := range keys { if config.IsSectionEnabled(key, h.Params.Config) { indexer, err := h.lookupIndexer(key) if err != nil { return nil, err } agg = append(agg, indexer) } } return agg, nil } func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Set("Access-Control-Allow-Headers", "Accept, Cache-Control, Content-Type, Content-Length, Accept-Encoding, Authorization, Last-Event-ID") } if r.Method == "OPTIONS" { return } log.WithFields(logrus.Fields{ "method": r.Method, "path": r.URL.RequestURI(), "remote": r.RemoteAddr, }).Debugf("%s %s", r.Method, r.URL.RequestURI()) for _, prefix := range apiRoutePrefixes { if strings.HasPrefix(r.URL.Path, prefix) { h.Handler.ServeHTTP(w, r) return } } h.FileHandler.ServeHTTP(w, r) } func (h *handler) torznabHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) indexerID := params["indexer"] apiKey := r.URL.Query().Get("apikey") if !h.checkAPIKey(apiKey) { torznab.Error(w, "Invalid apikey parameter", torznab.ErrInsufficientPrivs) return } indexer, err := h.lookupIndexer(indexerID) if err != nil { torznab.Error(w, err.Error(), torznab.ErrIncorrectParameter) return } t := r.URL.Query().Get("t") if t == "" { http.Redirect(w, r, r.URL.Path+"?t=caps", http.StatusTemporaryRedirect) return } switch t { case "caps": indexer.Capabilities().ServeHTTP(w, r) case "search", "tvsearch", "tv-search": feed, err := h.torznabSearch(r, indexer, indexerID) if err != nil { torznab.Error(w, err.Error(), torznab.ErrUnknownError) return } switch r.URL.Query().Get("format") { case "", "xml": x, err := xml.MarshalIndent(feed, "", " ") if err != nil { torznab.Error(w, err.Error(), torznab.ErrUnknownError) return } w.Header().Set("Content-Type", "application/rss+xml") w.Write(x) case "json": jsonOutput(w, feed) } default: torznab.Error(w, "Unknown type parameter", torznab.ErrIncorrectParameter) } } func (h *handler) torrentPotatoHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) indexerID := params["indexer"] apiKey := r.URL.Query().Get("passkey") if !h.checkAPIKey(apiKey) { torrentpotato.Error(w, errors.New("Invalid passkey")) return } indexer, err := h.lookupIndexer(indexerID) if err != nil { torrentpotato.Error(w, err) return } query := torznab.Query{ Type: "movie", Categories: []int{ torznab.CategoryMovies.ID, torznab.CategoryMovies_SD.ID, torznab.CategoryMovies_HD.ID, torznab.CategoryMovies_Foreign.ID, }, } qs := r.URL.Query() if search := qs.Get("search"); search != "" { query.Q = search } if imdbid := qs.Get("imdbid"); imdbid != "" { query.IMDBID = imdbid } items, err := indexer.Search(query) if err != nil { torrentpotato.Error(w, err) return } rewritten, err := h.rewriteLinks(r, items) if err != nil { torrentpotato.Error(w, err) return } torrentpotato.Output(w, rewritten) } func (h *handler) downloadHandler(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) token := params["token"] filename := params["filename"] log.WithFields(logrus.Fields{"filename": filename}).Debugf("Processing download via handler") k, err := h.sharedKey() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t, err := decodeToken(token, k) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } indexer, err := h.lookupIndexer(t.Site) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } rc, _, err := indexer.Download(t.Link) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.Header().Set("Content-Type", "application/x-bittorrent") w.Header().Set("Content-Disposition", "attachment; filename="+filename) w.Header().Set("Content-Transfer-Encoding", "binary") defer rc.Close() io.Copy(w, rc) } func (h *handler) torznabSearch(r *http.Request, indexer torznab.Indexer, siteKey string) (*torznab.ResultFeed, error) { query, err := torznab.ParseQuery(r.URL.Query()) if err != nil { return nil, err } items, err := indexer.Search(query) if err != nil { return nil, err } feed := &torznab.ResultFeed{ Info: indexer.Info(), Items: items, } rewritten, err := h.rewriteLinks(r, items) if err != nil { return nil, err } feed.Items = rewritten return feed, err } func (h *handler) rewriteLinks(r *http.Request, items []torznab.ResultItem) ([]torznab.ResultItem, error) { baseURL, err := h.baseURL(r, "/download") if err != nil { return nil, err } k, err := h.sharedKey() if err != nil { return nil, err } // rewrite non-magnet links to use the server for idx, item := range items { if strings.HasPrefix(item.Link, "magnet:") { continue } t := &token{ Site: item.Site, Link: item.Link, } te, err := t.Encode(k) if err != nil { log.Debugf("Error encoding token: %v", err) return nil, err } items[idx].Link = fmt.Sprintf("%s/%s/%s.torrent", baseURL.String(), te, url.QueryEscape(item.Title)) } return items, nil }
package server import ( "encoding/json" "io/ioutil" "log" "net/http" _ "net/http/pprof" "strconv" "github.com/absolute8511/ZanRedisDB/common" "github.com/absolute8511/ZanRedisDB/node" "github.com/coreos/etcd/raft/raftpb" ) func (self *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { key := r.RequestURI switch { case r.Method == "GET": ns, realKey, err := common.ExtractNamesapce([]byte(key)) if err != nil { http.Error(w, "Failed:"+err.Error(), http.StatusBadRequest) return } kv, ok := self.kvNodes[ns] if !ok || kv == nil { http.Error(w, "Namespace not found:"+ns, http.StatusNotFound) return } if v, err := kv.node.Lookup(realKey); err == nil { w.Write(v) } else { http.Error(w, "Failed to GET", http.StatusNotFound) } case r.Method == "POST": data, err := ioutil.ReadAll(r.Body) if err != nil { log.Printf("Failed to read on POST (%v)\n", err) http.Error(w, "Failed on POST", http.StatusBadRequest) return } nodeId, err := strconv.ParseUint(key[1:], 0, 64) if err != nil { log.Printf("Failed to convert ID for conf change (%v)\n", err) http.Error(w, "Failed on POST", http.StatusBadRequest) return } var m node.MemberInfo err = json.Unmarshal(data, &m) if err != nil { http.Error(w, "POST data decode failed", http.StatusBadRequest) return } cc := raftpb.ConfChange{ Type: raftpb.ConfChangeAddNode, NodeID: nodeId, Context: data, } self.ProposeConfChange(m.Namespace, cc) // As above, optimistic that raft will apply the conf change w.WriteHeader(http.StatusNoContent) case r.Method == "DELETE": nodeId, err := strconv.ParseUint(key[1:], 0, 64) if err != nil { log.Printf("Failed to convert ID for conf change (%v)\n", err) http.Error(w, "Failed on DELETE", http.StatusBadRequest) return } q := r.URL.Query() ns := q.Get("ns") cc := raftpb.ConfChange{ Type: raftpb.ConfChangeRemoveNode, NodeID: nodeId, } self.ProposeConfChange(ns, cc) // As above, optimistic that raft will apply the conf change w.WriteHeader(http.StatusNoContent) default: w.Header().Set("Allow", "PUT") w.Header().Add("Allow", "GET") w.Header().Add("Allow", "POST") w.Header().Add("Allow", "DELETE") http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } // serveHttpKVAPI starts a key-value server with a GET/PUT API and listens. func (self *Server) serveHttpAPI(port int, stopC <-chan struct{}) { go http.ListenAndServe("localhost:6666", nil) srv := http.Server{ Addr: ":" + strconv.Itoa(port), Handler: self, } l, err := common.NewStoppableListener(srv.Addr, stopC) if err != nil { panic(err) } err = srv.Serve(l) // exit when raft goes down log.Printf("http server stopped: %v", err) } allow remote pprof package server import ( "encoding/json" "io/ioutil" "log" "net/http" _ "net/http/pprof" "strconv" "github.com/absolute8511/ZanRedisDB/common" "github.com/absolute8511/ZanRedisDB/node" "github.com/coreos/etcd/raft/raftpb" ) func (self *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { key := r.RequestURI switch { case r.Method == "GET": ns, realKey, err := common.ExtractNamesapce([]byte(key)) if err != nil { http.Error(w, "Failed:"+err.Error(), http.StatusBadRequest) return } kv, ok := self.kvNodes[ns] if !ok || kv == nil { http.Error(w, "Namespace not found:"+ns, http.StatusNotFound) return } if v, err := kv.node.Lookup(realKey); err == nil { w.Write(v) } else { http.Error(w, "Failed to GET", http.StatusNotFound) } case r.Method == "POST": data, err := ioutil.ReadAll(r.Body) if err != nil { log.Printf("Failed to read on POST (%v)\n", err) http.Error(w, "Failed on POST", http.StatusBadRequest) return } nodeId, err := strconv.ParseUint(key[1:], 0, 64) if err != nil { log.Printf("Failed to convert ID for conf change (%v)\n", err) http.Error(w, "Failed on POST", http.StatusBadRequest) return } var m node.MemberInfo err = json.Unmarshal(data, &m) if err != nil { http.Error(w, "POST data decode failed", http.StatusBadRequest) return } cc := raftpb.ConfChange{ Type: raftpb.ConfChangeAddNode, NodeID: nodeId, Context: data, } self.ProposeConfChange(m.Namespace, cc) // As above, optimistic that raft will apply the conf change w.WriteHeader(http.StatusNoContent) case r.Method == "DELETE": nodeId, err := strconv.ParseUint(key[1:], 0, 64) if err != nil { log.Printf("Failed to convert ID for conf change (%v)\n", err) http.Error(w, "Failed on DELETE", http.StatusBadRequest) return } q := r.URL.Query() ns := q.Get("ns") cc := raftpb.ConfChange{ Type: raftpb.ConfChangeRemoveNode, NodeID: nodeId, } self.ProposeConfChange(ns, cc) // As above, optimistic that raft will apply the conf change w.WriteHeader(http.StatusNoContent) default: w.Header().Set("Allow", "PUT") w.Header().Add("Allow", "GET") w.Header().Add("Allow", "POST") w.Header().Add("Allow", "DELETE") http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } // serveHttpKVAPI starts a key-value server with a GET/PUT API and listens. func (self *Server) serveHttpAPI(port int, stopC <-chan struct{}) { go http.ListenAndServe("*:6666", nil) srv := http.Server{ Addr: ":" + strconv.Itoa(port), Handler: self, } l, err := common.NewStoppableListener(srv.Addr, stopC) if err != nil { panic(err) } err = srv.Serve(l) // exit when raft goes down log.Printf("http server stopped: %v", err) }
package server import ( "bufio" "bytes" "context" "emperror.dev/errors" "github.com/apex/log" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/client" "github.com/pterodactyl/wings/api" "github.com/pterodactyl/wings/config" "github.com/pterodactyl/wings/environment" "golang.org/x/sync/semaphore" "html/template" "io" "os" "path/filepath" "strconv" "time" ) // Executes the installation stack for a server process. Bubbles any errors up to the calling // function which should handle contacting the panel to notify it of the server state. // // Pass true as the first argument in order to execute a server sync before the process to // ensure the latest information is used. func (s *Server) Install(sync bool) error { if sync { s.Log().Info("syncing server state with remote source before executing installation process") if err := s.Sync(); err != nil { return err } } var err error if !s.Config().SkipEggScripts { // Send the start event so the Panel can automatically update. We don't send this unless the process // is actually going to run, otherwise all sorts of weird rapid UI behavior happens since there isn't // an actual install process being executed. s.Events().Publish(InstallStartedEvent, "") err = s.internalInstall() } else { s.Log().Info("server configured to skip running installation scripts for this egg, not executing process") } s.Log().Debug("notifying panel of server install state") if serr := s.SyncInstallState(err == nil); serr != nil { l := s.Log().WithField("was_successful", err == nil) // If the request was successful but there was an error with this request, attach the // error to this log entry. Otherwise ignore it in this log since whatever is calling // this function should handle the error and will end up logging the same one. if err == nil { l.WithField("error", serr) } l.Warn("failed to notify panel of server install state") } // Ensure that the server is marked as offline at this point, otherwise you end up // with a blank value which is a bit confusing. s.Environment.SetState(environment.ProcessOfflineState) // Push an event to the websocket so we can auto-refresh the information in the panel once // the install is completed. s.Events().Publish(InstallCompletedEvent, "") return err } // Reinstalls a server's software by utilizing the install script for the server egg. This // does not touch any existing files for the server, other than what the script modifies. func (s *Server) Reinstall() error { if s.Environment.State() != environment.ProcessOfflineState { s.Log().Debug("waiting for server instance to enter a stopped state") if err := s.Environment.WaitForStop(10, true); err != nil { return err } } return s.Install(true) } // Internal installation function used to simplify reporting back to the Panel. func (s *Server) internalInstall() error { script, err := api.New().GetInstallationScript(s.Id()) if err != nil { if !api.IsRequestError(err) { return errors.WithStackIf(err) } return errors.New(err.Error()) } p, err := NewInstallationProcess(s, &script) if err != nil { return errors.WithStackIf(err) } s.Log().Info("beginning installation process for server") if err := p.Run(); err != nil { return err } s.Log().Info("completed installation process for server") return nil } type InstallationProcess struct { Server *Server Script *api.InstallationScript client *client.Client context context.Context } // Generates a new installation process struct that will be used to create containers, // and otherwise perform installation commands for a server. func NewInstallationProcess(s *Server, script *api.InstallationScript) (*InstallationProcess, error) { proc := &InstallationProcess{ Script: script, Server: s, } ctx, cancel := context.WithCancel(context.Background()) s.installer.cancel = &cancel if c, err := environment.DockerClient(); err != nil { return nil, errors.WithStackIf(err) } else { proc.client = c proc.context = ctx } return proc, nil } // Try to obtain an exclusive lock on the installation process for the server. Waits up to 10 // seconds before aborting with a context timeout. func (s *Server) acquireInstallationLock() error { if s.installer.sem == nil { s.installer.sem = semaphore.NewWeighted(1) } ctx, _ := context.WithTimeout(context.Background(), time.Second*10) return s.installer.sem.Acquire(ctx, 1) } // Determines if the server is actively running the installation process by checking the status // of the semaphore lock. func (s *Server) IsInstalling() bool { if s.installer.sem == nil { return false } if s.installer.sem.TryAcquire(1) { // If we made it into this block it means we were able to obtain an exclusive lock // on the semaphore. In that case, go ahead and release that lock immediately, and // return false. s.installer.sem.Release(1) return false } return true } // Aborts the server installation process by calling the cancel function on the installer // context. func (s *Server) AbortInstallation() { if !s.IsInstalling() { return } if s.installer.cancel != nil { cancel := *s.installer.cancel s.Log().Warn("aborting running installation process") cancel() } } // Removes the installer container for the server. func (ip *InstallationProcess) RemoveContainer() { err := ip.client.ContainerRemove(ip.context, ip.Server.Id()+"_installer", types.ContainerRemoveOptions{ RemoveVolumes: true, Force: true, }) if err != nil && !client.IsErrNotFound(err) { ip.Server.Log().WithField("error", errors.WithStackIf(err)).Warn("failed to delete server install container") } } // Runs the installation process, this is done as in a background thread. This will configure // the required environment, and then spin up the installation container. // // Once the container finishes installing the results will be stored in an installation // log in the server's configuration directory. func (ip *InstallationProcess) Run() error { ip.Server.Log().Debug("acquiring installation process lock") if err := ip.Server.acquireInstallationLock(); err != nil { return err } // We now have an exclusive lock on this installation process. Ensure that whenever this // process is finished that the semaphore is released so that other processes and be executed // without encountering a wait timeout. defer func() { ip.Server.Log().Debug("releasing installation process lock") ip.Server.installer.sem.Release(1) ip.Server.installer.cancel = nil }() if err := ip.BeforeExecute(); err != nil { return errors.WithStackIf(err) } cid, err := ip.Execute() if err != nil { ip.RemoveContainer() return errors.WithStackIf(err) } // If this step fails, log a warning but don't exit out of the process. This is completely // internal to the daemon's functionality, and does not affect the status of the server itself. if err := ip.AfterExecute(cid); err != nil { ip.Server.Log().WithField("error", err).Warn("failed to complete after-execute step of installation process") } return nil } // Returns the location of the temporary data for the installation process. func (ip *InstallationProcess) tempDir() string { return filepath.Join(os.TempDir(), "pterodactyl/", ip.Server.Id()) } // Writes the installation script to a temporary file on the host machine so that it // can be properly mounted into the installation container and then executed. func (ip *InstallationProcess) writeScriptToDisk() error { // Make sure the temp directory root exists before trying to make a directory within it. The // ioutil.TempDir call expects this base to exist, it won't create it for you. if err := os.MkdirAll(ip.tempDir(), 0700); err != nil { return errors.WrapIf(err, "could not create temporary directory for install process") } f, err := os.OpenFile(filepath.Join(ip.tempDir(), "install.sh"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return errors.WrapIf(err, "failed to write server installation script to disk before mount") } defer f.Close() w := bufio.NewWriter(f) scanner := bufio.NewScanner(bytes.NewReader([]byte(ip.Script.Script))) for scanner.Scan() { w.WriteString(scanner.Text() + "\n") } if err := scanner.Err(); err != nil { return errors.WithStackIf(err) } w.Flush() return nil } // Pulls the docker image to be used for the installation container. func (ip *InstallationProcess) pullInstallationImage() error { r, err := ip.client.ImagePull(ip.context, ip.Script.ContainerImage, types.ImagePullOptions{}) if err != nil { return errors.WithStackIf(err) } // Block continuation until the image has been pulled successfully. scanner := bufio.NewScanner(r) for scanner.Scan() { log.Debug(scanner.Text()) } if err := scanner.Err(); err != nil { return errors.WithStackIf(err) } return nil } // Runs before the container is executed. This pulls down the required docker container image // as well as writes the installation script to the disk. This process is executed in an async // manner, if either one fails the error is returned. func (ip *InstallationProcess) BeforeExecute() error { if err := ip.writeScriptToDisk(); err != nil { return errors.WrapIf(err, "failed to write installation script to disk") } if err := ip.pullInstallationImage(); err != nil { return errors.WrapIf(err, "failed to pull updated installation container image for server") } opts := types.ContainerRemoveOptions{ RemoveVolumes: true, Force: true, } if err := ip.client.ContainerRemove(ip.context, ip.Server.Id()+"_installer", opts); err != nil { if !client.IsErrNotFound(err) { return errors.WrapIf(err, "failed to remove existing install container for server") } } return nil } // Returns the log path for the installation process. func (ip *InstallationProcess) GetLogPath() string { return filepath.Join(config.Get().System.GetInstallLogPath(), ip.Server.Id()+".log") } // Cleans up after the execution of the installation process. This grabs the logs from the // process to store in the server configuration directory, and then destroys the associated // installation container. func (ip *InstallationProcess) AfterExecute(containerId string) error { defer ip.RemoveContainer() ip.Server.Log().WithField("container_id", containerId).Debug("pulling installation logs for server") reader, err := ip.client.ContainerLogs(ip.context, containerId, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: false, }) if err != nil && !client.IsErrNotFound(err) { return errors.WithStackIf(err) } f, err := os.OpenFile(ip.GetLogPath(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return errors.WithStackIf(err) } defer f.Close() // We write the contents of the container output to a more "permanent" file so that they // can be referenced after this container is deleted. We'll also include the environment // variables passed into the container to make debugging things a little easier. ip.Server.Log().WithField("path", ip.GetLogPath()).Debug("writing most recent installation logs to disk") tmpl, err := template.New("header").Parse(`Pterodactyl Server Installation Log | | Details | ------------------------------ Server UUID: {{.Server.Id}} Container Image: {{.Script.ContainerImage}} Container Entrypoint: {{.Script.Entrypoint}} | | Environment Variables | ------------------------------ {{ range $key, $value := .Server.GetEnvironmentVariables }} {{ $value }} {{ end }} | | Script Output | ------------------------------ `) if err != nil { return errors.WithStackIf(err) } if err := tmpl.Execute(f, ip); err != nil { return errors.WithStackIf(err) } if _, err := io.Copy(f, reader); err != nil { return errors.WithStackIf(err) } return nil } // Executes the installation process inside a specially created docker container. func (ip *InstallationProcess) Execute() (string, error) { conf := &container.Config{ Hostname: "installer", AttachStdout: true, AttachStderr: true, AttachStdin: true, OpenStdin: true, Tty: true, Cmd: []string{ip.Script.Entrypoint, "/mnt/install/install.sh"}, Image: ip.Script.ContainerImage, Env: ip.Server.GetEnvironmentVariables(), Labels: map[string]string{ "Service": "Pterodactyl", "ContainerType": "server_installer", }, } tmpfsSize := strconv.Itoa(int(config.Get().Docker.TmpfsSize)) hostConf := &container.HostConfig{ Mounts: []mount.Mount{ { Target: "/mnt/server", Source: ip.Server.Filesystem().Path(), Type: mount.TypeBind, ReadOnly: false, }, { Target: "/mnt/install", Source: ip.tempDir(), Type: mount.TypeBind, ReadOnly: false, }, }, Tmpfs: map[string]string{ "/tmp": "rw,exec,nosuid,size=" + tmpfsSize + "M", }, DNS: config.Get().Docker.Network.Dns, LogConfig: container.LogConfig{ Type: "local", Config: map[string]string{ "max-size": "5m", "max-file": "1", "compress": "false", }, }, Privileged: true, NetworkMode: container.NetworkMode(config.Get().Docker.Network.Mode), } ip.Server.Log().WithField("install_script", ip.tempDir()+"/install.sh").Info("creating install container for server process") // Remove the temporary directory when the installation process finishes for this server container. defer func() { if err := os.RemoveAll(ip.tempDir()); err != nil { if !os.IsNotExist(err) { ip.Server.Log().WithField("error", err).Warn("failed to remove temporary data directory after install process") } } }() r, err := ip.client.ContainerCreate(ip.context, conf, hostConf, nil, ip.Server.Id()+"_installer") if err != nil { return "", errors.WithStackIf(err) } ip.Server.Log().WithField("container_id", r.ID).Info("running installation script for server in container") if err := ip.client.ContainerStart(ip.context, r.ID, types.ContainerStartOptions{}); err != nil { return "", err } go func(id string) { ip.Server.Events().Publish(DaemonMessageEvent, "Starting installation process, this could take a few minutes...") if err := ip.StreamOutput(id); err != nil { ip.Server.Log().WithField("error", err).Error("error while handling output stream for server install process") } ip.Server.Events().Publish(DaemonMessageEvent, "Installation process completed.") }(r.ID) sChan, eChan := ip.client.ContainerWait(ip.context, r.ID, container.WaitConditionNotRunning) select { case err := <-eChan: if err != nil { return "", errors.WithStackIf(err) } case <-sChan: } return r.ID, nil } // Streams the output of the installation process to a log file in the server configuration // directory, as well as to a websocket listener so that the process can be viewed in // the panel by administrators. func (ip *InstallationProcess) StreamOutput(id string) error { reader, err := ip.client.ContainerLogs(ip.context, id, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, }) if err != nil { return errors.WithStackIf(err) } defer reader.Close() s := bufio.NewScanner(reader) for s.Scan() { ip.Server.Events().Publish(InstallOutputEvent, s.Text()) } if err := s.Err(); err != nil { ip.Server.Log().WithFields(log.Fields{ "container_id": id, "error": errors.WithStackIf(err), }).Warn("error processing scanner line in installation output for server") } return nil } // Makes a HTTP request to the Panel instance notifying it that the server has // completed the installation process, and what the state of the server is. A boolean // value of "true" means everything was successful, "false" means something went // wrong and the server must be deleted and re-created. func (s *Server) SyncInstallState(successful bool) error { err := api.New().SendInstallationStatus(s.Id(), successful) if err != nil { if !api.IsRequestError(err) { return errors.WithStackIf(err) } return errors.New(err.Error()) } return nil } Use registry authentication when pulling install image, fixes https://github.com/pterodactyl/panel/issues/2589 package server import ( "bufio" "bytes" "context" "emperror.dev/errors" "github.com/apex/log" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/client" "github.com/pterodactyl/wings/api" "github.com/pterodactyl/wings/config" "github.com/pterodactyl/wings/environment" "golang.org/x/sync/semaphore" "html/template" "io" "os" "path/filepath" "strconv" "strings" "time" ) // Executes the installation stack for a server process. Bubbles any errors up to the calling // function which should handle contacting the panel to notify it of the server state. // // Pass true as the first argument in order to execute a server sync before the process to // ensure the latest information is used. func (s *Server) Install(sync bool) error { if sync { s.Log().Info("syncing server state with remote source before executing installation process") if err := s.Sync(); err != nil { return err } } var err error if !s.Config().SkipEggScripts { // Send the start event so the Panel can automatically update. We don't send this unless the process // is actually going to run, otherwise all sorts of weird rapid UI behavior happens since there isn't // an actual install process being executed. s.Events().Publish(InstallStartedEvent, "") err = s.internalInstall() } else { s.Log().Info("server configured to skip running installation scripts for this egg, not executing process") } s.Log().Debug("notifying panel of server install state") if serr := s.SyncInstallState(err == nil); serr != nil { l := s.Log().WithField("was_successful", err == nil) // If the request was successful but there was an error with this request, attach the // error to this log entry. Otherwise ignore it in this log since whatever is calling // this function should handle the error and will end up logging the same one. if err == nil { l.WithField("error", serr) } l.Warn("failed to notify panel of server install state") } // Ensure that the server is marked as offline at this point, otherwise you end up // with a blank value which is a bit confusing. s.Environment.SetState(environment.ProcessOfflineState) // Push an event to the websocket so we can auto-refresh the information in the panel once // the install is completed. s.Events().Publish(InstallCompletedEvent, "") return err } // Reinstalls a server's software by utilizing the install script for the server egg. This // does not touch any existing files for the server, other than what the script modifies. func (s *Server) Reinstall() error { if s.Environment.State() != environment.ProcessOfflineState { s.Log().Debug("waiting for server instance to enter a stopped state") if err := s.Environment.WaitForStop(10, true); err != nil { return err } } return s.Install(true) } // Internal installation function used to simplify reporting back to the Panel. func (s *Server) internalInstall() error { script, err := api.New().GetInstallationScript(s.Id()) if err != nil { if !api.IsRequestError(err) { return errors.WithStackIf(err) } return errors.New(err.Error()) } p, err := NewInstallationProcess(s, &script) if err != nil { return errors.WithStackIf(err) } s.Log().Info("beginning installation process for server") if err := p.Run(); err != nil { return err } s.Log().Info("completed installation process for server") return nil } type InstallationProcess struct { Server *Server Script *api.InstallationScript client *client.Client context context.Context } // Generates a new installation process struct that will be used to create containers, // and otherwise perform installation commands for a server. func NewInstallationProcess(s *Server, script *api.InstallationScript) (*InstallationProcess, error) { proc := &InstallationProcess{ Script: script, Server: s, } ctx, cancel := context.WithCancel(context.Background()) s.installer.cancel = &cancel if c, err := environment.DockerClient(); err != nil { return nil, errors.WithStackIf(err) } else { proc.client = c proc.context = ctx } return proc, nil } // Try to obtain an exclusive lock on the installation process for the server. Waits up to 10 // seconds before aborting with a context timeout. func (s *Server) acquireInstallationLock() error { if s.installer.sem == nil { s.installer.sem = semaphore.NewWeighted(1) } ctx, _ := context.WithTimeout(context.Background(), time.Second*10) return s.installer.sem.Acquire(ctx, 1) } // Determines if the server is actively running the installation process by checking the status // of the semaphore lock. func (s *Server) IsInstalling() bool { if s.installer.sem == nil { return false } if s.installer.sem.TryAcquire(1) { // If we made it into this block it means we were able to obtain an exclusive lock // on the semaphore. In that case, go ahead and release that lock immediately, and // return false. s.installer.sem.Release(1) return false } return true } // Aborts the server installation process by calling the cancel function on the installer // context. func (s *Server) AbortInstallation() { if !s.IsInstalling() { return } if s.installer.cancel != nil { cancel := *s.installer.cancel s.Log().Warn("aborting running installation process") cancel() } } // Removes the installer container for the server. func (ip *InstallationProcess) RemoveContainer() { err := ip.client.ContainerRemove(ip.context, ip.Server.Id()+"_installer", types.ContainerRemoveOptions{ RemoveVolumes: true, Force: true, }) if err != nil && !client.IsErrNotFound(err) { ip.Server.Log().WithField("error", errors.WithStackIf(err)).Warn("failed to delete server install container") } } // Runs the installation process, this is done as in a background thread. This will configure // the required environment, and then spin up the installation container. // // Once the container finishes installing the results will be stored in an installation // log in the server's configuration directory. func (ip *InstallationProcess) Run() error { ip.Server.Log().Debug("acquiring installation process lock") if err := ip.Server.acquireInstallationLock(); err != nil { return err } // We now have an exclusive lock on this installation process. Ensure that whenever this // process is finished that the semaphore is released so that other processes and be executed // without encountering a wait timeout. defer func() { ip.Server.Log().Debug("releasing installation process lock") ip.Server.installer.sem.Release(1) ip.Server.installer.cancel = nil }() if err := ip.BeforeExecute(); err != nil { return errors.WithStackIf(err) } cid, err := ip.Execute() if err != nil { ip.RemoveContainer() return errors.WithStackIf(err) } // If this step fails, log a warning but don't exit out of the process. This is completely // internal to the daemon's functionality, and does not affect the status of the server itself. if err := ip.AfterExecute(cid); err != nil { ip.Server.Log().WithField("error", err).Warn("failed to complete after-execute step of installation process") } return nil } // Returns the location of the temporary data for the installation process. func (ip *InstallationProcess) tempDir() string { return filepath.Join(os.TempDir(), "pterodactyl/", ip.Server.Id()) } // Writes the installation script to a temporary file on the host machine so that it // can be properly mounted into the installation container and then executed. func (ip *InstallationProcess) writeScriptToDisk() error { // Make sure the temp directory root exists before trying to make a directory within it. The // ioutil.TempDir call expects this base to exist, it won't create it for you. if err := os.MkdirAll(ip.tempDir(), 0700); err != nil { return errors.WrapIf(err, "could not create temporary directory for install process") } f, err := os.OpenFile(filepath.Join(ip.tempDir(), "install.sh"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return errors.WrapIf(err, "failed to write server installation script to disk before mount") } defer f.Close() w := bufio.NewWriter(f) scanner := bufio.NewScanner(bytes.NewReader([]byte(ip.Script.Script))) for scanner.Scan() { w.WriteString(scanner.Text() + "\n") } if err := scanner.Err(); err != nil { return errors.WithStackIf(err) } w.Flush() return nil } // Pulls the docker image to be used for the installation container. func (ip *InstallationProcess) pullInstallationImage() error { // Get a registry auth configuration from the config. var registryAuth *config.RegistryConfiguration for registry, c := range config.Get().Docker.Registries { if !strings.HasPrefix(ip.Script.ContainerImage, registry) { continue } log.WithField("registry", registry).Debug("using authentication for registry") registryAuth = &c break } // Get the ImagePullOptions. imagePullOptions := types.ImagePullOptions{All: false} if registryAuth != nil { b64, err := registryAuth.Base64() if err != nil { log.WithError(err).Error("failed to get registry auth credentials") } // b64 is a string so if there is an error it will just be empty, not nil. imagePullOptions.RegistryAuth = b64 } r, err := ip.client.ImagePull(context.Background(), ip.Script.ContainerImage, imagePullOptions) if err != nil { images, ierr := ip.client.ImageList(context.Background(), types.ImageListOptions{}) if ierr != nil { // Well damn, something has gone really wrong here, just go ahead and abort there // isn't much anything we can do to try and self-recover from this. return ierr } for _, img := range images { for _, t := range img.RepoTags { if t != ip.Script.ContainerImage { continue } log.WithFields(log.Fields{ "image": ip.Script.ContainerImage, "err": err.Error(), }).Warn("unable to pull requested image from remote source, however the image exists locally") // Okay, we found a matching container image, in that case just go ahead and return // from this function, since there is nothing else we need to do here. return nil } } return err } defer r.Close() log.WithField("image", ip.Script.ContainerImage).Debug("pulling docker image... this could take a bit of time") // Block continuation until the image has been pulled successfully. scanner := bufio.NewScanner(r) for scanner.Scan() { log.Debug(scanner.Text()) } if err := scanner.Err(); err != nil { return errors.WithStackIf(err) } return nil } // Runs before the container is executed. This pulls down the required docker container image // as well as writes the installation script to the disk. This process is executed in an async // manner, if either one fails the error is returned. func (ip *InstallationProcess) BeforeExecute() error { if err := ip.writeScriptToDisk(); err != nil { return errors.WrapIf(err, "failed to write installation script to disk") } if err := ip.pullInstallationImage(); err != nil { return errors.WrapIf(err, "failed to pull updated installation container image for server") } opts := types.ContainerRemoveOptions{ RemoveVolumes: true, Force: true, } if err := ip.client.ContainerRemove(ip.context, ip.Server.Id()+"_installer", opts); err != nil { if !client.IsErrNotFound(err) { return errors.WrapIf(err, "failed to remove existing install container for server") } } return nil } // Returns the log path for the installation process. func (ip *InstallationProcess) GetLogPath() string { return filepath.Join(config.Get().System.GetInstallLogPath(), ip.Server.Id()+".log") } // Cleans up after the execution of the installation process. This grabs the logs from the // process to store in the server configuration directory, and then destroys the associated // installation container. func (ip *InstallationProcess) AfterExecute(containerId string) error { defer ip.RemoveContainer() ip.Server.Log().WithField("container_id", containerId).Debug("pulling installation logs for server") reader, err := ip.client.ContainerLogs(ip.context, containerId, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: false, }) if err != nil && !client.IsErrNotFound(err) { return errors.WithStackIf(err) } f, err := os.OpenFile(ip.GetLogPath(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return errors.WithStackIf(err) } defer f.Close() // We write the contents of the container output to a more "permanent" file so that they // can be referenced after this container is deleted. We'll also include the environment // variables passed into the container to make debugging things a little easier. ip.Server.Log().WithField("path", ip.GetLogPath()).Debug("writing most recent installation logs to disk") tmpl, err := template.New("header").Parse(`Pterodactyl Server Installation Log | | Details | ------------------------------ Server UUID: {{.Server.Id}} Container Image: {{.Script.ContainerImage}} Container Entrypoint: {{.Script.Entrypoint}} | | Environment Variables | ------------------------------ {{ range $key, $value := .Server.GetEnvironmentVariables }} {{ $value }} {{ end }} | | Script Output | ------------------------------ `) if err != nil { return errors.WithStackIf(err) } if err := tmpl.Execute(f, ip); err != nil { return errors.WithStackIf(err) } if _, err := io.Copy(f, reader); err != nil { return errors.WithStackIf(err) } return nil } // Executes the installation process inside a specially created docker container. func (ip *InstallationProcess) Execute() (string, error) { conf := &container.Config{ Hostname: "installer", AttachStdout: true, AttachStderr: true, AttachStdin: true, OpenStdin: true, Tty: true, Cmd: []string{ip.Script.Entrypoint, "/mnt/install/install.sh"}, Image: ip.Script.ContainerImage, Env: ip.Server.GetEnvironmentVariables(), Labels: map[string]string{ "Service": "Pterodactyl", "ContainerType": "server_installer", }, } tmpfsSize := strconv.Itoa(int(config.Get().Docker.TmpfsSize)) hostConf := &container.HostConfig{ Mounts: []mount.Mount{ { Target: "/mnt/server", Source: ip.Server.Filesystem().Path(), Type: mount.TypeBind, ReadOnly: false, }, { Target: "/mnt/install", Source: ip.tempDir(), Type: mount.TypeBind, ReadOnly: false, }, }, Tmpfs: map[string]string{ "/tmp": "rw,exec,nosuid,size=" + tmpfsSize + "M", }, DNS: config.Get().Docker.Network.Dns, LogConfig: container.LogConfig{ Type: "local", Config: map[string]string{ "max-size": "5m", "max-file": "1", "compress": "false", }, }, Privileged: true, NetworkMode: container.NetworkMode(config.Get().Docker.Network.Mode), } ip.Server.Log().WithField("install_script", ip.tempDir()+"/install.sh").Info("creating install container for server process") // Remove the temporary directory when the installation process finishes for this server container. defer func() { if err := os.RemoveAll(ip.tempDir()); err != nil { if !os.IsNotExist(err) { ip.Server.Log().WithField("error", err).Warn("failed to remove temporary data directory after install process") } } }() r, err := ip.client.ContainerCreate(ip.context, conf, hostConf, nil, ip.Server.Id()+"_installer") if err != nil { return "", errors.WithStackIf(err) } ip.Server.Log().WithField("container_id", r.ID).Info("running installation script for server in container") if err := ip.client.ContainerStart(ip.context, r.ID, types.ContainerStartOptions{}); err != nil { return "", err } go func(id string) { ip.Server.Events().Publish(DaemonMessageEvent, "Starting installation process, this could take a few minutes...") if err := ip.StreamOutput(id); err != nil { ip.Server.Log().WithField("error", err).Error("error while handling output stream for server install process") } ip.Server.Events().Publish(DaemonMessageEvent, "Installation process completed.") }(r.ID) sChan, eChan := ip.client.ContainerWait(ip.context, r.ID, container.WaitConditionNotRunning) select { case err := <-eChan: if err != nil { return "", errors.WithStackIf(err) } case <-sChan: } return r.ID, nil } // Streams the output of the installation process to a log file in the server configuration // directory, as well as to a websocket listener so that the process can be viewed in // the panel by administrators. func (ip *InstallationProcess) StreamOutput(id string) error { reader, err := ip.client.ContainerLogs(ip.context, id, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, }) if err != nil { return errors.WithStackIf(err) } defer reader.Close() s := bufio.NewScanner(reader) for s.Scan() { ip.Server.Events().Publish(InstallOutputEvent, s.Text()) } if err := s.Err(); err != nil { ip.Server.Log().WithFields(log.Fields{ "container_id": id, "error": errors.WithStackIf(err), }).Warn("error processing scanner line in installation output for server") } return nil } // Makes a HTTP request to the Panel instance notifying it that the server has // completed the installation process, and what the state of the server is. A boolean // value of "true" means everything was successful, "false" means something went // wrong and the server must be deleted and re-created. func (s *Server) SyncInstallState(successful bool) error { err := api.New().SendInstallationStatus(s.Id(), successful) if err != nil { if !api.IsRequestError(err) { return errors.WithStackIf(err) } return errors.New(err.Error()) } return nil }
package colprint import ( "io" "os" "reflect" "strconv" "fmt" "strings" "math" "sort" "github.com/ryanuber/columnize" ) const TagName = "colprint" const ( TagValueEmpty = "" TagValueSkip = "-" TagValueTraverse = "=>" ) // Config holds configuration used when printing columns type Config struct { // MaxPrintedSliceItems represents the maximum number og slice items to list. MaxPrintedSliceItems *int // FloatPrecision represents the precision used when printing floats. FloatPrecision *int } // Print prints a struct or slice of structs to stdout using default config func Print(s interface{}) error { return Fprint(os.Stdout, s) } // Fprint prints struct or slice to provided io.Writer using provided config. // If config is nil, default config will be used. func Fprint(w io.Writer, s interface{}, c ... *Config) error { var conf *Config if len(c) > 0 { conf = c[0] } cp := cPrinter{config: mergeConfig(createDefaultConfig(), conf)} val := reflect.ValueOf(s) kind := val.Kind() // If its a pointer, do an indirect... if kind == reflect.Ptr { val = reflect.Indirect(reflect.ValueOf(s)) kind = val.Kind() } // Check if s is a slice/array or not if kind == reflect.Slice || kind == reflect.Array { // add each item in slice to cPrinter for i := 0; i < val.Len(); i ++ { if err := cp.add(val.Index(i).Interface()); err != nil { return err } } } else { // add the item to cPrinter if err := cp.add(val.Interface()); err != nil { return err } } // Print to provided Writer cp.fprint(w) return nil } // column represents a column that will be printed by cPrinter type column struct { fieldIndex *[]int label string order int } // columns is a sortable list of column structs type columns []column func (s columns) Len() int { return len(s) } func (s columns) Less(i, j int) bool { return s[i].order < s[j].order } func (s columns) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // cPrinter is the data structure used to print columns type cPrinter struct { // columns (ordered) cols columns // Map containing values for all columns values map[column][]string // Keeps track of number of items appended to the ColPrinter itemCount int // Configuration for the printer config *Config } // add adds a struct columns and values func (cp *cPrinter) add(s interface{}) error { // Init columns if it's not already done if cp.cols == nil { cp.init() err := cp.findColumns(s) if err != nil { return err } for _, col := range cp.cols { cp.initColumn(col) } } // Add values for _, col := range cp.cols { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } val := cp.valueOf(v.FieldByIndex(*col.fieldIndex).Interface()) cp.values[col] = append(cp.values[col], val) } cp.itemCount++ return nil } //fprint prints the columns to the provided io.Writer. func (cp *cPrinter) fprint(w io.Writer) { // Add header line str := []string{} headers := "" for i, col := range cp.cols { headers += col.label if i != len(cp.cols)-1 { headers += "|" } } str = append(str, headers) // Add a line for each item appended for i := 0; i < cp.itemCount; i++ { vals := "" for j, col := range cp.cols { vals += cp.values[col][i] if j != len(cp.cols)-1 { vals += "|" } } str = append(str, vals) } // Print to given Writer fmt.Fprint(w, columnize.SimpleFormat(str)+"\n") } // init initializes the array containing columns, and the map containing the values for each column. func (cp *cPrinter) init() { cp.cols = columns{} cp.values = make(map[column][]string) } // initColumn initializes the array containing column values. func (cp *cPrinter) initColumn(col column) { cp.values[col] = make([]string, 0) } // findColumns extracts which columns should be printed and adds them to columns. Returns an error if any field // contains a incomplete tag. func (cp *cPrinter) findColumns(s interface{}, fieldIndex ... int) error { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } for i := 0; i < v.NumField(); i++ { fIndex := append(fieldIndex, i) field := v.Type().Field(i) tag := field.Tag.Get(TagName) switch tag { case TagValueEmpty, TagValueSkip: // Do nothing case TagValueTraverse: if err := cp.traverseStruct(v.FieldByIndex([]int{i}), fIndex...); err != nil { return err } default: if err := cp.appendColumn(tag, field, &fIndex); err != nil { return err } } } sort.Sort(cp.cols) return nil } // appendColumn appends a tagged field to the list of columns. func (cp *cPrinter) appendColumn(tag string, field reflect.StructField, fieldIndex *[]int) error { args := strings.Split(tag, ",") switch len(args) { case 1: cp.cols = append(cp.cols, column{fieldIndex, args[0], math.MaxInt32}) case 2: order, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("Invalid order on field %s", field.Name) } cp.cols = append(cp.cols, column{fieldIndex, args[0], order}) default: return fmt.Errorf("Invalid number of tag arguments on field %s", field.Name) } return nil } // traverseStruct traverses field of kind reflect.Struct and finds columns func (cp *cPrinter) traverseStruct(v reflect.Value, fieldIndex ... int) error { val := reflect.ValueOf(v.Interface()) if val.Kind() == reflect.Ptr { val = reflect.Indirect(v) } if val.Kind() == reflect.Struct { err := cp.findColumns(v.Interface(), fieldIndex...) if err != nil { return err } } return nil } // valueOf returns a string representation of a field. func (cp *cPrinter) valueOf(i interface{}) string { v := reflect.ValueOf(i) kind := v.Kind() switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(v.Int(), 10) case reflect.Array, reflect.Slice: return cp.valueOfSlice(i) case reflect.Bool: return strconv.FormatBool(v.Bool()) case reflect.Float32, reflect.Float64: return strconv.FormatFloat(v.Float(), 'f', *cp.config.FloatPrecision, 64) case reflect.String: return v.String() case reflect.Ptr: if v.IsNil() { return "" } return cp.valueOf(reflect.Indirect(v).Interface()) } return "<Unsupported kind:" + kind.String() + ">" } // valueOfSlice returns a string representation of the values in a slice field. // Returns a maximum of Config.MaxPrintedSliceItems. func (cp *cPrinter) valueOfSlice(s interface{}) string { sliceValue := reflect.ValueOf(s) values := "" for i := 0; i < sliceValue.Len(); i++ { values += cp.valueOf(sliceValue.Index(i).Interface()) if i == *cp.config.MaxPrintedSliceItems-1 && sliceValue.Len() > *cp.config.MaxPrintedSliceItems { values += ",..." break } else if i < sliceValue.Len()-1 { values += ", " } } return values } // createDefaultConfig creates a default configuration. func createDefaultConfig() *Config { dMPSI := 3 dFP := 2 return &Config{ MaxPrintedSliceItems: &dMPSI, FloatPrecision: &dFP, } } // mergeConfig merges the second argument config into the first. func mergeConfig(a, c *Config) *Config { if c != nil { if c.MaxPrintedSliceItems != nil { *a.MaxPrintedSliceItems = *c.MaxPrintedSliceItems } if c.FloatPrecision != nil { *a.FloatPrecision = *c.FloatPrecision } } return a } Removed newline after print package colprint import ( "io" "os" "reflect" "strconv" "fmt" "strings" "math" "sort" "github.com/ryanuber/columnize" ) const TagName = "colprint" const ( TagValueEmpty = "" TagValueSkip = "-" TagValueTraverse = "=>" ) // Config holds configuration used when printing columns type Config struct { // MaxPrintedSliceItems represents the maximum number og slice items to list. MaxPrintedSliceItems *int // FloatPrecision represents the precision used when printing floats. FloatPrecision *int } // Print prints a struct or slice of structs to stdout using default config func Print(s interface{}) error { return Fprint(os.Stdout, s) } // Fprint prints struct or slice to provided io.Writer using provided config. // If config is nil, default config will be used. func Fprint(w io.Writer, s interface{}, c ... *Config) error { var conf *Config if len(c) > 0 { conf = c[0] } cp := cPrinter{config: mergeConfig(createDefaultConfig(), conf)} val := reflect.ValueOf(s) kind := val.Kind() // If its a pointer, do an indirect... if kind == reflect.Ptr { val = reflect.Indirect(reflect.ValueOf(s)) kind = val.Kind() } // Check if s is a slice/array or not if kind == reflect.Slice || kind == reflect.Array { // add each item in slice to cPrinter for i := 0; i < val.Len(); i ++ { if err := cp.add(val.Index(i).Interface()); err != nil { return err } } } else { // add the item to cPrinter if err := cp.add(val.Interface()); err != nil { return err } } // Print to provided Writer cp.fprint(w) return nil } // column represents a column that will be printed by cPrinter type column struct { fieldIndex *[]int label string order int } // columns is a sortable list of column structs type columns []column func (s columns) Len() int { return len(s) } func (s columns) Less(i, j int) bool { return s[i].order < s[j].order } func (s columns) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // cPrinter is the data structure used to print columns type cPrinter struct { // columns (ordered) cols columns // Map containing values for all columns values map[column][]string // Keeps track of number of items appended to the ColPrinter itemCount int // Configuration for the printer config *Config } // add adds a struct columns and values func (cp *cPrinter) add(s interface{}) error { // Init columns if it's not already done if cp.cols == nil { cp.init() err := cp.findColumns(s) if err != nil { return err } for _, col := range cp.cols { cp.initColumn(col) } } // Add values for _, col := range cp.cols { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } val := cp.valueOf(v.FieldByIndex(*col.fieldIndex).Interface()) cp.values[col] = append(cp.values[col], val) } cp.itemCount++ return nil } //fprint prints the columns to the provided io.Writer. func (cp *cPrinter) fprint(w io.Writer) { // Add header line str := []string{} headers := "" for i, col := range cp.cols { headers += col.label if i != len(cp.cols)-1 { headers += "|" } } str = append(str, headers) // Add a line for each item appended for i := 0; i < cp.itemCount; i++ { vals := "" for j, col := range cp.cols { vals += cp.values[col][i] if j != len(cp.cols)-1 { vals += "|" } } str = append(str, vals) } // Print to given Writer fmt.Fprint(w, columnize.SimpleFormat(str)) } // init initializes the array containing columns, and the map containing the values for each column. func (cp *cPrinter) init() { cp.cols = columns{} cp.values = make(map[column][]string) } // initColumn initializes the array containing column values. func (cp *cPrinter) initColumn(col column) { cp.values[col] = make([]string, 0) } // findColumns extracts which columns should be printed and adds them to columns. Returns an error if any field // contains a incomplete tag. func (cp *cPrinter) findColumns(s interface{}, fieldIndex ... int) error { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = reflect.Indirect(v) } for i := 0; i < v.NumField(); i++ { fIndex := append(fieldIndex, i) field := v.Type().Field(i) tag := field.Tag.Get(TagName) switch tag { case TagValueEmpty, TagValueSkip: // Do nothing case TagValueTraverse: if err := cp.traverseStruct(v.FieldByIndex([]int{i}), fIndex...); err != nil { return err } default: if err := cp.appendColumn(tag, field, &fIndex); err != nil { return err } } } sort.Sort(cp.cols) return nil } // appendColumn appends a tagged field to the list of columns. func (cp *cPrinter) appendColumn(tag string, field reflect.StructField, fieldIndex *[]int) error { args := strings.Split(tag, ",") switch len(args) { case 1: cp.cols = append(cp.cols, column{fieldIndex, args[0], math.MaxInt32}) case 2: order, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("Invalid order on field %s", field.Name) } cp.cols = append(cp.cols, column{fieldIndex, args[0], order}) default: return fmt.Errorf("Invalid number of tag arguments on field %s", field.Name) } return nil } // traverseStruct traverses field of kind reflect.Struct and finds columns func (cp *cPrinter) traverseStruct(v reflect.Value, fieldIndex ... int) error { val := reflect.ValueOf(v.Interface()) if val.Kind() == reflect.Ptr { val = reflect.Indirect(v) } if val.Kind() == reflect.Struct { err := cp.findColumns(v.Interface(), fieldIndex...) if err != nil { return err } } return nil } // valueOf returns a string representation of a field. func (cp *cPrinter) valueOf(i interface{}) string { v := reflect.ValueOf(i) kind := v.Kind() switch kind { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(v.Int(), 10) case reflect.Array, reflect.Slice: return cp.valueOfSlice(i) case reflect.Bool: return strconv.FormatBool(v.Bool()) case reflect.Float32, reflect.Float64: return strconv.FormatFloat(v.Float(), 'f', *cp.config.FloatPrecision, 64) case reflect.String: return v.String() case reflect.Ptr: if v.IsNil() { return "" } return cp.valueOf(reflect.Indirect(v).Interface()) } return "<Unsupported kind:" + kind.String() + ">" } // valueOfSlice returns a string representation of the values in a slice field. // Returns a maximum of Config.MaxPrintedSliceItems. func (cp *cPrinter) valueOfSlice(s interface{}) string { sliceValue := reflect.ValueOf(s) values := "" for i := 0; i < sliceValue.Len(); i++ { values += cp.valueOf(sliceValue.Index(i).Interface()) if i == *cp.config.MaxPrintedSliceItems-1 && sliceValue.Len() > *cp.config.MaxPrintedSliceItems { values += ",..." break } else if i < sliceValue.Len()-1 { values += ", " } } return values } // createDefaultConfig creates a default configuration. func createDefaultConfig() *Config { dMPSI := 3 dFP := 2 return &Config{ MaxPrintedSliceItems: &dMPSI, FloatPrecision: &dFP, } } // mergeConfig merges the second argument config into the first. func mergeConfig(a, c *Config) *Config { if c != nil { if c.MaxPrintedSliceItems != nil { *a.MaxPrintedSliceItems = *c.MaxPrintedSliceItems } if c.FloatPrecision != nil { *a.FloatPrecision = *c.FloatPrecision } } return a }
package main import ( "io/ioutil" "log" "os" "strings" "github.com/serbe/ncp" ) var ( urls = []string{ "/forum/viewforum.php?f=218", // Зарубежные Новинки (HD*Rip/LQ, DVDRip) "/forum/viewforum.php?f=221", // Отечественные Фильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=225", // Зарубежные Фильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=230", // Отечественные Мультфильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=231", // Зарубежные Мультфильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=270", // Отечественные Новинки (HD*Rip/LQ, DVDRip) "/forum/viewforum.php?f=319", // Зарубежная Классика (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=320", // Отечественная Классика (HD*Rip/LQ, DVDRip, SATRip, VHSRip) } ) func (a *App) get() error { var ( err error i int ) for _, parseurl := range urls { topics, err := a.net.ParseForumTree(parseurl) if err != nil { log.Println("ParseForumTree ", parseurl, err) return err } for _, topic := range topics { _, err := a.getTorrentByHref(topic.Href) if err != nil { film, err := a.net.ParseTopic(topic) if err == nil && film.Description == "" { i++ film = a.checkName(film) _, err = a.createTorrent(film) if err != nil { log.Println("createTorrent ", err) } } else { log.Println("ParseTopic ", err) } } } } if i > 0 { log.Println("Adding", i, "new films") } else { log.Println("No adding new films") } return err } func (a *App) update() error { var ( i int err error torrents []Torrent ) torrents, err = a.getWithDownload() if err != nil { return err } for _, tor := range torrents { var topic ncp.Topic topic.Href = tor.Href f, err := a.net.ParseTopic(topic) if err == nil { if f.NNM != tor.NNM || f.Seeders != tor.Seeders || f.Leechers != tor.Leechers || f.Torrent != tor.Torrent { i++ a.updateTorrent(tor.ID, f) } } else { return err } } if i > 0 { log.Println("Update", i, "movies") } else { log.Println("No movies update") } return nil } func (a *App) name() error { var i int movies, err := a.getMovies() if err != nil { return err } for _, movie := range movies { if movie.Name == strings.ToUpper(movie.Name) { lowerName, err := a.getUpperName(movie) if err == nil { i++ a.updateName(movie.ID, lowerName) } } } if i > 0 { log.Println(i, "name fixed") } else { log.Println("No fixed names") } return nil } func (a *App) rating() error { var ( i int ) movies, err := a.getNoRating() if err != nil { return err } for _, movie := range movies { if movie.Kinopoisk == 0 || movie.IMDb == 0 || movie.Duration == "" { kp, err := a.getRating(movie) if err == nil { i++ _ = a.updateRating(movie, kp) } } } if i > 0 { log.Println(i, "ratings update") } else { log.Println("No update ratings") } return nil } func (a *App) poster() error { var ( i int files []string ) movies, err := a.getMovies() if err != nil { return err } filesInDir, _ := ioutil.ReadDir(a.hd) for _, file := range filesInDir { files = append(files, file.Name()) } for _, movie := range movies { if movie.PosterURL != "" { if movie.Poster != "" { if !existsFile(a.hd + movie.Poster) { poster, err := a.getPoster(movie.PosterURL) if err == nil { i++ err = a.updatePoster(movie, poster) if err != nil { log.Println("updatePoster ", poster, err) } } else { log.Println("getPoster ", poster, err) } } else { files = deleteFromSlice(files, movie.Poster) } } else { poster, err := a.getPoster(movie.PosterURL) if err == nil { i++ _ = a.updatePoster(movie, poster) } } } else { tor, err := a.getTorrentByMovieID(movie.ID) if err == nil { var topic ncp.Topic topic.Href = tor.Href tempFilm, err := a.net.ParseTopic(topic) if err == nil { if tempFilm.Poster != "" { err = a.updatePosterURL(movie, tempFilm.Poster) if err == nil { poster, err := a.getPoster(tempFilm.Poster) if err == nil { i++ _ = a.updatePoster(movie, poster) } } } } } } } for _, file := range files { _ = os.Remove(a.hd + file) } if i > 0 { log.Println(i, "posters update") } else { log.Println("No update posters") } if len(files) > 0 { log.Println("Remove", len(files), "unused images") } return nil } fix check description package main import ( "io/ioutil" "log" "os" "strings" "github.com/serbe/ncp" ) var ( urls = []string{ "/forum/viewforum.php?f=218", // Зарубежные Новинки (HD*Rip/LQ, DVDRip) "/forum/viewforum.php?f=221", // Отечественные Фильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=225", // Зарубежные Фильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=230", // Отечественные Мультфильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=231", // Зарубежные Мультфильмы (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=270", // Отечественные Новинки (HD*Rip/LQ, DVDRip) "/forum/viewforum.php?f=319", // Зарубежная Классика (HD*Rip/LQ, DVDRip, SATRip, VHSRip) "/forum/viewforum.php?f=320", // Отечественная Классика (HD*Rip/LQ, DVDRip, SATRip, VHSRip) } ) func (a *App) get() error { var ( err error i int ) for _, parseurl := range urls { topics, err := a.net.ParseForumTree(parseurl) if err != nil { log.Println("ParseForumTree ", parseurl, err) return err } for _, topic := range topics { _, err := a.getTorrentByHref(topic.Href) if err != nil { film, err := a.net.ParseTopic(topic) if err == nil { if film.Description != "" { i++ film = a.checkName(film) _, err = a.createTorrent(film) if err != nil { log.Println("createTorrent ", err) } } else { log.Println("empty Description ", film.Href) } } else { log.Println("ParseTopic ", err) } } } } if i > 0 { log.Println("Adding", i, "new films") } else { log.Println("No adding new films") } return err } func (a *App) update() error { var ( i int err error torrents []Torrent ) torrents, err = a.getWithDownload() if err != nil { return err } for _, tor := range torrents { var topic ncp.Topic topic.Href = tor.Href f, err := a.net.ParseTopic(topic) if err == nil { if f.NNM != tor.NNM || f.Seeders != tor.Seeders || f.Leechers != tor.Leechers || f.Torrent != tor.Torrent { i++ a.updateTorrent(tor.ID, f) } } else { return err } } if i > 0 { log.Println("Update", i, "movies") } else { log.Println("No movies update") } return nil } func (a *App) name() error { var i int movies, err := a.getMovies() if err != nil { return err } for _, movie := range movies { if movie.Name == strings.ToUpper(movie.Name) { lowerName, err := a.getUpperName(movie) if err == nil { i++ a.updateName(movie.ID, lowerName) } } } if i > 0 { log.Println(i, "name fixed") } else { log.Println("No fixed names") } return nil } func (a *App) rating() error { var ( i int ) movies, err := a.getNoRating() if err != nil { return err } for _, movie := range movies { if movie.Kinopoisk == 0 || movie.IMDb == 0 || movie.Duration == "" { kp, err := a.getRating(movie) if err == nil { i++ _ = a.updateRating(movie, kp) } } } if i > 0 { log.Println(i, "ratings update") } else { log.Println("No update ratings") } return nil } func (a *App) poster() error { var ( i int files []string ) movies, err := a.getMovies() if err != nil { return err } filesInDir, _ := ioutil.ReadDir(a.hd) for _, file := range filesInDir { files = append(files, file.Name()) } for _, movie := range movies { if movie.PosterURL != "" { if movie.Poster != "" { if !existsFile(a.hd + movie.Poster) { poster, err := a.getPoster(movie.PosterURL) if err == nil { i++ err = a.updatePoster(movie, poster) if err != nil { log.Println("updatePoster ", poster, err) } } else { log.Println("getPoster ", poster, err) } } else { files = deleteFromSlice(files, movie.Poster) } } else { poster, err := a.getPoster(movie.PosterURL) if err == nil { i++ _ = a.updatePoster(movie, poster) } } } else { tor, err := a.getTorrentByMovieID(movie.ID) if err == nil { var topic ncp.Topic topic.Href = tor.Href tempFilm, err := a.net.ParseTopic(topic) if err == nil { if tempFilm.Poster != "" { err = a.updatePosterURL(movie, tempFilm.Poster) if err == nil { poster, err := a.getPoster(tempFilm.Poster) if err == nil { i++ _ = a.updatePoster(movie, poster) } } } } } } } for _, file := range files { _ = os.Remove(a.hd + file) } if i > 0 { log.Println(i, "posters update") } else { log.Println("No update posters") } if len(files) > 0 { log.Println("Remove", len(files), "unused images") } return nil }
package main import ( "context" "fmt" ap "github.com/gopasspw/gopass/pkg/action" "github.com/gopasspw/gopass/pkg/action/binary" "github.com/gopasspw/gopass/pkg/action/create" "github.com/gopasspw/gopass/pkg/action/xc" "github.com/gopasspw/gopass/pkg/agent" "github.com/gopasspw/gopass/pkg/agent/client" "github.com/gopasspw/gopass/pkg/config" "github.com/gopasspw/gopass/pkg/ctxutil" "github.com/urfave/cli" ) func getCommands(ctx context.Context, action *ap.Action, app *cli.App) []cli.Command { return []cli.Command{ { Name: "agent", Usage: "Start gopass-agent", Description: "" + "This command starts the gopass agent that will cache passphrases " + "so they don't have to be entered repeatedly.", Action: func(c *cli.Context) error { ec := make(chan error) go func() { ec <- agent.New(config.Directory()).ListenAndServe(ctx) }() select { case <-ctx.Done(): return fmt.Errorf("aborted") case e := <-ec: return e } }, Subcommands: []cli.Command{ { Name: "client", Usage: "Start a simple agent test client", Hidden: true, Action: func(c *cli.Context) error { pw, err := client.New(config.Directory()).Passphrase(ctx, "test", "test") if err != nil { return err } fmt.Println("Passphrase:" + pw) return nil }, }, }, }, { Name: "audit", Usage: "Scan for weak passwords", Description: "" + "This command decrypts all secrets and checks for common flaws and (optionally) " + "against a list of previously leaked passwords.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Audit(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.IntFlag{ Name: "jobs, j", Usage: "The number of jobs to run concurrently when auditing", Value: 1, }, }, Subcommands: []cli.Command{ { Name: "hibp", Usage: "Detect leaked passwords", Description: "" + "This command will decrypt all secrets and check the passwords against the public " + "havibeenpwned.com v2 API or dumps. " + "To use the dumps you need to download the dumps from https://haveibeenpwned.com/passwords first. Be sure to grab the one that says '(ordered by hash)'. " + "This is a very expensive operation, for advanced users. " + "Most users should probably use the API. " + "If you want to use the dumps you need to use 7z to extract the dump: 7z x pwned-passwords-ordered-2.0.txt.7z.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.HIBP(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, cli.BoolFlag{ Name: "api, a", Usage: "Use HIBP API", }, cli.StringSliceFlag{ Name: "dumps", Usage: "One or more HIBP v1/v2 dumps", }, }, }, }, }, { Name: "binary", Usage: "Assist with Binary/Base64 content", Description: "" + "These commands directly convert binary files from/to base64 encoding.", Aliases: []string{"bin"}, Subcommands: []cli.Command{ { Name: "cat", Usage: "Print content of a secret to stdout, or insert from stdin", Description: "" + "This command is similar to the way cat works on the command line. " + "It can either be used to retrieve the decoded content of a secret " + "similar to 'cat file' or vice versa to encode the content from STDIN " + "to a secret.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return binary.Cat(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, }, { Name: "sum", Usage: "Compute the SHA256 checksum", Description: "" + "This command decodes an Base64 encoded secret and computes the SHA256 checksum " + "over the decoded data. This is useful to verify the integrity of an " + "inserted secret.", Aliases: []string{"sha", "sha256"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return binary.Sum(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, }, { Name: "copy", Usage: "Copy files from or to the password store", Description: "" + "This command either reads a file from the filesystem and writes the " + "encoded and encrypted version in the store or it decrypts and decodes " + "a secret and writes the result to a file. Either source or destination " + "must be a file and the other one a secret. If you want the source to " + "be securely removed after copying, use 'gopass binary move'", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Aliases: []string{"cp"}, Action: func(c *cli.Context) error { return binary.Copy(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, { Name: "move", Usage: "Move files from or to the password store", Description: "" + "This command either reads a file from the filesystem and writes the " + "encoded and encrypted version in the store or it decrypts and decodes " + "a secret and writes the result to a file. Either source or destination " + "must be a file and the other one a secret. The source will be wiped " + "from disk or from the store after it has been copied successfully " + "and validated. If you don't want the source to be removed use " + "'gopass binary copy'", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Aliases: []string{"mv"}, Action: func(c *cli.Context) error { return binary.Move(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, }, }, { Name: "clone", Usage: "Clone a store from git", Description: "" + "This command clones an existing password store from a git remote to " + "a local password store. Can be either used to initialize a new root store " + "or to add a new mounted sub-store." + "" + "Needs at least one argument (git URL) to clone from. " + "Accepts a second argument (mount location) to clone and mount a sub-store, e.g. " + "'gopass clone git@example.com/store.git foo/bar'", Action: func(c *cli.Context) error { return action.Clone(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "path", Usage: "Path to clone the repo to", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "sync", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "completion", Usage: "Bash and ZSH completion", Description: "" + "Source the output of this command with bash or zsh to get auto completion", Subcommands: []cli.Command{{ Name: "bash", Usage: "Source for auto completion in bash", Action: action.CompletionBash, }, { Name: "zsh", Usage: "Source for auto completion in zsh", Action: func(c *cli.Context) error { return action.CompletionZSH(c, app) }, }, { Name: "fish", Usage: "Source for auto completion in fish", Action: func(c *cli.Context) error { return action.CompletionFish(c, app) }, }, { Name: "openbsdksh", Usage: "Source for auto completion in OpenBSD's ksh", Action: func(c *cli.Context) error { return action.CompletionOpenBSDKsh(c, app) }, }}, }, { Name: "config", Usage: "Edit configuration", Description: "" + "This command allows for easy printing and editing of the configuration" + "without argument, the entire config is printed" + "with a single argument, a single key can be printend" + "with two arguments a setting specified by key can be set to value", Action: func(c *cli.Context) error { return action.Config(withGlobalFlags(ctx, c), c) }, BashComplete: action.ConfigComplete, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Set value to substore config", }, }, }, { Name: "copy", Aliases: []string{"cp"}, Usage: "Copy secrets from one location to another", Description: "" + "This command copies an existing secret in the store to another location. " + "This also works across different sub-stores. If the source is a directory it will " + "automatically copy recursively. In that case, the source directory is re-created " + "at the destination if no trailing slash is found, otherwise the contents are " + "flattened (similar to rsync).", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Copy(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to copy the secret and overwrite existing one", }, }, }, { Name: "create", Aliases: []string{"new"}, Usage: "Easy creation of new secrets", Description: "" + "This command starts a wizard to aid in creation of new secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return create.Create(withGlobalFlags(ctx, c), c, action.Store) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store, s", Usage: "Which store to use", }, }, }, { Name: "delete", Usage: "Remove secrets", Description: "" + "This command removes secrets. It can work recursively on folders. " + "Recursing across stores is purposefully not supported.", Aliases: []string{"remove", "rm"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Delete(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "recursive, r", Usage: "Recursive delete files and folders", }, cli.BoolFlag{ Name: "force, f", Usage: "Force to delete the secret", }, }, }, { Name: "edit", Usage: "Edit new or existing secrets", Description: "" + "Use this command to insert a new secret or edit an existing one using " + "your $EDITOR. It will attempt to create a secure temporary directory " + "for storing your secret while the editor is accessing it. Please make " + "sure your editor doesn't leak sensitive data to other locations while " + "editing.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Edit(withGlobalFlags(ctx, c), c) }, Aliases: []string{"set"}, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "editor, e", Usage: "Use this editor binary", }, cli.BoolFlag{ Name: "create, c", Usage: "Create a new secret if none found", }, }, }, { Name: "find", Usage: "Search for secrets", Description: "" + "This command will first attempt a simple pattern match on the name of the " + "secret. If that yields no results, it will trigger a fuzzy search. " + "If there is an exact match it will be shown directly; if there are " + "multiple matches, a selection will be shown.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Find(withGlobalFlags(ctxutil.WithFuzzySearch(ctx, false), c), c) }, Aliases: []string{"search"}, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the password into the clipboard", }, }, }, { Name: "fsck", Usage: "Check store integrity", Description: "" + "Check the integrity of the given sub-store or all stores if none are specified. " + "Will automatically fix all issues found.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Fsck(withGlobalFlags(ctx, c), c) }, BashComplete: action.MountsComplete, }, { Name: "generate", Usage: "Generate a new password", Description: "" + "Generate a new password of the specified length, optionally with no symbols. " + "Alternatively, a xkcd style password can be generated (https://xkcd.com/936/). " + "Optionally put it on the clipboard and clear clipboard after 45 seconds. " + "Prompt before overwriting existing password unless forced. " + "It will replace only the first line of an existing file with a new password.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Generate(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.CompleteGenerate(ctx, c) }, Flags: []cli.Flag{ cli.BoolTFlag{ Name: "clip, c", Usage: "Copy the generated password to the clipboard", }, cli.BoolFlag{ Name: "print, p", Usage: "Print the generated password to the terminal", }, cli.BoolFlag{ Name: "force, f", Usage: "Force to overwrite existing password", }, cli.BoolFlag{ Name: "edit, e", Usage: "Open secret for editing after generating a password", }, cli.BoolFlag{ Name: "symbols, s", Usage: "Use symbols in the password", }, cli.BoolFlag{ Name: "xkcd, x", Usage: "Use multiple random english words combined to a password. By default, space is used as separator and all words are lowercase", }, cli.StringFlag{ Name: "xkcdsep, xs", Usage: "Word separator for generated xkcd style password. If no separator is specified, the words are combined without spaces/separator and the first character of words is capitalised. This flag implies -xkcd", Value: "", }, cli.StringFlag{ Name: "xkcdlang, xl", Usage: "Language to generate password from, currently de (german) and en (english, default) are supported", Value: "en", }, }, }, { Name: "git-credential", Usage: `Use "!gopass git-credential $@" as git's credential.helper`, Description: "" + "This command allows you to cache your git-credentials with gopass." + "Activate by using `git config --global credential.helper \"!gopass git-credential $@\"`", Subcommands: []cli.Command{ { Name: "get", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialGet(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "store", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialStore(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "erase", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialErase(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "configure", Description: "This command configures gopass as git's credential.helper", Action: func(c *cli.Context) error { return action.GitCredentialConfigure(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "global", Usage: "Install for current user", }, cli.BoolFlag{ Name: "local", Usage: "Install for current repository only", }, cli.BoolFlag{ Name: "system", Usage: "Install for all users, requires superuser rights", }, }, }, }, }, { Name: "jsonapi", Usage: "Run and configure gopass as jsonapi e.g. for browser plugins", Description: "Setup and run gopass as native messaging hosts, e.g. for browser plugins.", Hidden: false, Subcommands: []cli.Command{ { Name: "listen", Usage: "Listen and respond to messages via stdin/stdout", Description: "Gopass is started in listen mode from browser plugins using a wrapper specified in native messaging host manifests", Action: func(c *cli.Context) error { return action.JSONAPI(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, }, { Name: "configure", Usage: "Setup gopass native messaging manifest for selected browser", Description: "To access gopass from browser plugins, a native app manifest must be installed at the correct location", Action: func(c *cli.Context) error { return action.SetupNativeMessaging(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "browser", Usage: "One of 'chrome' and 'firefox'", }, cli.StringFlag{ Name: "path", Usage: "Path to install 'gopass_wrapper.sh' to", }, cli.StringFlag{ Name: "manifest-path", Usage: "Path to install 'com.justwatch.gopass.json' to", }, cli.BoolFlag{ Name: "global", Usage: "Install for all users, requires superuser rights", }, cli.StringFlag{ Name: "libpath", Usage: "Library path for global installation on linux. Default is /usr/lib", }, cli.StringFlag{ Name: "gopass-path", Usage: "Path to gopass binary. Default is auto detected", }, cli.BoolTFlag{ Name: "print", Usage: "Print installation summary before creating any files", }, }, }, }, }, { Name: "otp", Usage: "Generate time- or hmac-based tokens", Aliases: []string{"totp", "hotp"}, Description: "" + "Tries to parse an OTP URL (otpauth://). URL can be TOTP or HOTP. " + "The URL can be provided on its own line or on a key value line with a key named 'totp'.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.OTP(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the time-based token into the clipboard", }, cli.StringFlag{ Name: "qr, q", Usage: "Write QR code to FILE", }, cli.BoolFlag{ Name: "password, o", Usage: "Only display the token", }, }, }, { Name: "git", Usage: "Run a git command inside a password store (init, remote, push, pull)", Description: "" + "If the password store is a git repository, execute a git command " + "specified by git-command-args.", Subcommands: []cli.Command{ { Name: "init", Usage: "Init git repo", Description: "Create and initialize a new git repo in the store", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitInit(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.StringFlag{ Name: "sign-key", Usage: "GPG Key to sign commits", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "remote", Usage: "Manage git remotes", Description: "These subcommands can be used to manage git remotes", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Usage: "Add git remote", Description: "Add a new git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitAddRemote(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, { Name: "remove", Usage: "Remove git remote", Description: "Remove a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitRemoveRemote(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, }, }, { Name: "push", Usage: "Push to remote", Description: "Push to a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitPush(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, { Name: "pull", Usage: "Pull from remote", Description: "Pull from a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitPull(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, }, }, { Name: "grep", Usage: "Search for secrets files containing search-string when decrypted.", Description: "" + "This command decrypts all secrets and performs a pattern matching on the " + "content.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Grep(withGlobalFlags(ctx, c), c) }, }, { Name: "history", Usage: "Show password history", Aliases: []string{"hist"}, Description: "" + "Display the change history for a secret", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.History(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "password, p", Usage: "Include passwords in output", }, }, }, { Name: "init", Usage: "Initialize new password store.", Description: "" + "Initialize new password storage and use gpg-id for encryption.", Action: func(c *cli.Context) error { return action.Init(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "path, p", Usage: "Set the sub-store path to operate on", }, cli.StringFlag{ Name: "store, s", Usage: "Set the name of the sub-store", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, cli.BoolFlag{ Name: "nogit", Usage: "(DEPRECATED): Select noop RCS backend. Use '--rcs noop' instead", Hidden: true, }, }, }, { Name: "insert", Usage: "Insert a new secret", Description: "" + "Insert a new secret. Optionally, echo the secret back to the console during entry. " + "Or, optionally, the entry may be multiline. " + "Prompt before overwriting existing secret unless forced.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Insert(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "echo, e", Usage: "Display secret while typing", }, cli.BoolFlag{ Name: "multiline, m", Usage: "Insert using $EDITOR", }, cli.BoolFlag{ Name: "force, f", Usage: "Overwrite any existing secret and do not prompt to confirm recipients", }, cli.BoolFlag{ Name: "append, a", Usage: "Append to any existing data", }, }, }, { Name: "list", Usage: "List existing secrets", Description: "" + "This command will list all existing secrets. Provide a folder prefix to list " + "only certain subfolders of the store.", Aliases: []string{"ls"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.List(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.IntFlag{ Name: "limit, l", Usage: "Max tree depth", }, cli.BoolFlag{ Name: "flat, f", Usage: "Print flat list", }, cli.BoolFlag{ Name: "folders, fo", Usage: "Print flat list of folders", }, cli.BoolFlag{ Name: "strip-prefix, s", Usage: "Strip prefix from filtered entries", }, }, }, { Name: "move", Aliases: []string{"mv"}, Usage: "Move secrets from one location to another", Description: "" + "This command moves a secret from one path to another. This also works " + "across different sub-stores. If the source is a directory, the source directory " + "is re-created at the destination if no trailing slash is found, otherwise the " + "contents are flattened (similar to rsync).", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Move(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, { Name: "mounts", Usage: "Edit mounted stores", Description: "" + "This command displays all mounted password stores. It offers several " + "subcommands to create or remove mounts.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountsPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Aliases: []string{"mount"}, Usage: "Mount a password store", Description: "" + "This command allows for mounting an existing or new password store " + "at any path in an existing root store.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountAdd(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "init, i", Usage: "Init the store with the given recipient key", }, }, }, { Name: "remove", Aliases: []string{"rm", "unmount", "umount"}, Usage: "Umount an mounted password store", Description: "" + "This command allows to unmount an mounted password store. This will " + "only updated the configuration and not delete the password store.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountRemove(withGlobalFlags(ctx, c), c) }, BashComplete: action.MountsComplete, }, }, }, { Name: "recipients", Usage: "Edit recipient permissions", Description: "" + "This command displays all existing recipients for all mounted stores. " + "The subcommands allow adding or removing recipients.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Aliases: []string{"authorize"}, Usage: "Add any number of Recipients to any store", Description: "" + "This command adds any number of recipients to any existing store. " + "If none are given it will display a list of usable public keys. " + "After adding the recipient to the list it will re-encrypt the whole " + "affected store to make sure the recipient has access to all existing " + "secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsAdd(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.BoolFlag{ Name: "force", Usage: "Force adding non-existing keys", }, }, }, { Name: "remove", Aliases: []string{"rm", "deauthorize"}, Usage: "Remove any number of Recipients from any store", Description: "" + "This command removes any number of recipients from any existing store. " + "If no recipients are provided, it will show a list of existing recipients " + "to choose from. It will refuse to remove the current user's key from the " + "store to avoid losing access. After removing the keys it will re-encrypt " + "all existing secrets. Please note that the removed recipients will still " + "be able to decrypt old revisions of the password store and any local " + "copies they might have. The only way to reliably remove a recipient is to " + "rotate all existing secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsRemove(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.RecipientsComplete(ctx, c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.BoolFlag{ Name: "force", Usage: "Force adding non-existing keys", }, }, }, { Name: "update", Usage: "Recompute the saved recipient list checksums", Description: "" + "This command will recompute the saved recipient checksum" + "and save them to the config.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsUpdate(withGlobalFlags(ctx, c), c) }, }, }, }, { Name: "setup", Usage: "Initialize a new password store", Description: "" + "This command is automatically invoked if gopass is started without any " + "existing password store. This command exists so users can be provided with " + "simple one-command setup instructions.", Hidden: true, Action: func(c *cli.Context) error { return action.InitOnboarding(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "remote", Usage: "URL to a git remote, will attempt to join this team", }, cli.StringFlag{ Name: "alias", Usage: "Local mount point for the given remote", }, cli.BoolFlag{ Name: "create", Usage: "Create a new team (default: false, i.e. join an existing team)", }, cli.StringFlag{ Name: "name", Usage: "Firstname and Lastname for unattended GPG key generation", }, cli.StringFlag{ Name: "email", Usage: "EMail for unattended GPG key generation", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "show", Usage: "Display a secret", Description: "" + "Show an existing secret and optionally put its first line on the clipboard. " + "If put on the clipboard, it will be cleared after 45 seconds.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Show(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the first line of the secret into the clipboard", }, cli.BoolFlag{ Name: "qr", Usage: "Print the first line of the secret as QR Code", }, cli.BoolFlag{ Name: "force, f", Usage: "Display the password even if safecontent is enabled", }, cli.BoolFlag{ Name: "password, o", Usage: "Display only the password", }, cli.BoolFlag{ Name: "sync, s", Usage: "Sync before attempting to display the secret", }, cli.StringFlag{ Name: "revision", Usage: "Show a past revision", }, }, }, { Name: "sync", Usage: "Sync all local stores with their remotes", Description: "" + "Sync all local stores with their git remotes, if any, and check " + "any possibly affected gpg keys.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Sync(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store, s", Usage: "Select the store to sync", }, }, }, { Name: "templates", Usage: "Edit templates", Description: "" + "List existing templates in the password store and allow for editing " + "and creating them.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplatesPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "show", Usage: "Show a secret template.", Description: "Display an existing template", Aliases: []string{"cat"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplatePrint(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, { Name: "edit", Usage: "Edit secret templates.", Description: "Edit an existing or new template", Aliases: []string{"create", "new"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplateEdit(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, { Name: "remove", Aliases: []string{"rm"}, Usage: "Remove secret templates.", Description: "Remove an existing template", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplateRemove(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, }, }, { Name: "unclip", Usage: "Internal command to clear clipboard", Description: "Clear the clipboard if the content matches the checksum.", Action: func(c *cli.Context) error { return action.Unclip(withGlobalFlags(ctx, c), c) }, Hidden: true, Flags: []cli.Flag{ cli.IntFlag{ Name: "timeout", Usage: "Time to wait", }, cli.BoolFlag{ Name: "force", Usage: "Clear clipboard even if checksum mismatches", }, }, }, { Name: "update", Usage: "Check for updates", Description: "" + "This command checks for gopass updates at GitHub and automatically " + "downloads and installs any missing update.", Action: func(c *cli.Context) error { return action.Update(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "pre", Usage: "Update to prereleases", }, }, }, { Name: "version", Usage: "Display version", Description: "" + "This command displays version and build time information " + "along with version information of important external commands. " + "Please provide the output when reporting issues.", Action: func(c *cli.Context) error { return action.Version(withGlobalFlags(ctx, c), c) }, }, { Name: "xc", Usage: "Experimental Crypto", Description: "" + "These subcommands are used to control and test the experimental crypto" + "implementation.", Subcommands: []cli.Command{ { Name: "list-private-keys", Action: func(c *cli.Context) error { return xc.ListPrivateKeys(withGlobalFlags(ctx, c), c) }, }, { Name: "list-public-keys", Action: func(c *cli.Context) error { return xc.ListPublicKeys(withGlobalFlags(ctx, c), c) }, }, { Name: "generate", Action: func(c *cli.Context) error { return xc.GenerateKeypair(withGlobalFlags(ctx, c), c) }, }, { Name: "export", Action: func(c *cli.Context) error { return xc.ExportPublicKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "import", Action: func(c *cli.Context) error { return xc.ImportPublicKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "export-private-key", Action: func(c *cli.Context) error { return xc.ExportPrivateKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "import-private-key", Action: func(c *cli.Context) error { return xc.ImportPrivateKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "remove", Action: func(c *cli.Context) error { return xc.RemoveKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, }, }, { Name: "encrypt", Action: func(c *cli.Context) error { return xc.EncryptFile(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "file", }, cli.StringSliceFlag{ Name: "recipients", }, cli.BoolFlag{ Name: "stream", }, }, }, { Name: "decrypt", Action: func(c *cli.Context) error { return xc.DecryptFile(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "file", }, cli.BoolFlag{ Name: "stream", }, }, }, }, }, } } fix typo and whitespace for config help (#1159) Signed-off-by: Stephen Hassard <9ce5770b3bb4b2a1d59be2d97e34379cd192299f@hassard.net> package main import ( "context" "fmt" ap "github.com/gopasspw/gopass/pkg/action" "github.com/gopasspw/gopass/pkg/action/binary" "github.com/gopasspw/gopass/pkg/action/create" "github.com/gopasspw/gopass/pkg/action/xc" "github.com/gopasspw/gopass/pkg/agent" "github.com/gopasspw/gopass/pkg/agent/client" "github.com/gopasspw/gopass/pkg/config" "github.com/gopasspw/gopass/pkg/ctxutil" "github.com/urfave/cli" ) func getCommands(ctx context.Context, action *ap.Action, app *cli.App) []cli.Command { return []cli.Command{ { Name: "agent", Usage: "Start gopass-agent", Description: "" + "This command starts the gopass agent that will cache passphrases " + "so they don't have to be entered repeatedly.", Action: func(c *cli.Context) error { ec := make(chan error) go func() { ec <- agent.New(config.Directory()).ListenAndServe(ctx) }() select { case <-ctx.Done(): return fmt.Errorf("aborted") case e := <-ec: return e } }, Subcommands: []cli.Command{ { Name: "client", Usage: "Start a simple agent test client", Hidden: true, Action: func(c *cli.Context) error { pw, err := client.New(config.Directory()).Passphrase(ctx, "test", "test") if err != nil { return err } fmt.Println("Passphrase:" + pw) return nil }, }, }, }, { Name: "audit", Usage: "Scan for weak passwords", Description: "" + "This command decrypts all secrets and checks for common flaws and (optionally) " + "against a list of previously leaked passwords.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Audit(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.IntFlag{ Name: "jobs, j", Usage: "The number of jobs to run concurrently when auditing", Value: 1, }, }, Subcommands: []cli.Command{ { Name: "hibp", Usage: "Detect leaked passwords", Description: "" + "This command will decrypt all secrets and check the passwords against the public " + "havibeenpwned.com v2 API or dumps. " + "To use the dumps you need to download the dumps from https://haveibeenpwned.com/passwords first. Be sure to grab the one that says '(ordered by hash)'. " + "This is a very expensive operation, for advanced users. " + "Most users should probably use the API. " + "If you want to use the dumps you need to use 7z to extract the dump: 7z x pwned-passwords-ordered-2.0.txt.7z.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.HIBP(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, cli.BoolFlag{ Name: "api, a", Usage: "Use HIBP API", }, cli.StringSliceFlag{ Name: "dumps", Usage: "One or more HIBP v1/v2 dumps", }, }, }, }, }, { Name: "binary", Usage: "Assist with Binary/Base64 content", Description: "" + "These commands directly convert binary files from/to base64 encoding.", Aliases: []string{"bin"}, Subcommands: []cli.Command{ { Name: "cat", Usage: "Print content of a secret to stdout, or insert from stdin", Description: "" + "This command is similar to the way cat works on the command line. " + "It can either be used to retrieve the decoded content of a secret " + "similar to 'cat file' or vice versa to encode the content from STDIN " + "to a secret.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return binary.Cat(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, }, { Name: "sum", Usage: "Compute the SHA256 checksum", Description: "" + "This command decodes an Base64 encoded secret and computes the SHA256 checksum " + "over the decoded data. This is useful to verify the integrity of an " + "inserted secret.", Aliases: []string{"sha", "sha256"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return binary.Sum(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, }, { Name: "copy", Usage: "Copy files from or to the password store", Description: "" + "This command either reads a file from the filesystem and writes the " + "encoded and encrypted version in the store or it decrypts and decodes " + "a secret and writes the result to a file. Either source or destination " + "must be a file and the other one a secret. If you want the source to " + "be securely removed after copying, use 'gopass binary move'", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Aliases: []string{"cp"}, Action: func(c *cli.Context) error { return binary.Copy(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, { Name: "move", Usage: "Move files from or to the password store", Description: "" + "This command either reads a file from the filesystem and writes the " + "encoded and encrypted version in the store or it decrypts and decodes " + "a secret and writes the result to a file. Either source or destination " + "must be a file and the other one a secret. The source will be wiped " + "from disk or from the store after it has been copied successfully " + "and validated. If you don't want the source to be removed use " + "'gopass binary copy'", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Aliases: []string{"mv"}, Action: func(c *cli.Context) error { return binary.Move(withGlobalFlags(ctx, c), c, action.Store) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, }, }, { Name: "clone", Usage: "Clone a store from git", Description: "" + "This command clones an existing password store from a git remote to " + "a local password store. Can be either used to initialize a new root store " + "or to add a new mounted sub-store." + "" + "Needs at least one argument (git URL) to clone from. " + "Accepts a second argument (mount location) to clone and mount a sub-store, e.g. " + "'gopass clone git@example.com/store.git foo/bar'", Action: func(c *cli.Context) error { return action.Clone(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "path", Usage: "Path to clone the repo to", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "sync", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "completion", Usage: "Bash and ZSH completion", Description: "" + "Source the output of this command with bash or zsh to get auto completion", Subcommands: []cli.Command{{ Name: "bash", Usage: "Source for auto completion in bash", Action: action.CompletionBash, }, { Name: "zsh", Usage: "Source for auto completion in zsh", Action: func(c *cli.Context) error { return action.CompletionZSH(c, app) }, }, { Name: "fish", Usage: "Source for auto completion in fish", Action: func(c *cli.Context) error { return action.CompletionFish(c, app) }, }, { Name: "openbsdksh", Usage: "Source for auto completion in OpenBSD's ksh", Action: func(c *cli.Context) error { return action.CompletionOpenBSDKsh(c, app) }, }}, }, { Name: "config", Usage: "Edit configuration", Description: "" + "This command allows for easy printing and editing of the configuration. " + "Without argument, the entire config is printed. " + "With a single argument, a single key can be printed. " + "With two arguments a setting specified by key can be set to value.", Action: func(c *cli.Context) error { return action.Config(withGlobalFlags(ctx, c), c) }, BashComplete: action.ConfigComplete, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Set value to substore config", }, }, }, { Name: "copy", Aliases: []string{"cp"}, Usage: "Copy secrets from one location to another", Description: "" + "This command copies an existing secret in the store to another location. " + "This also works across different sub-stores. If the source is a directory it will " + "automatically copy recursively. In that case, the source directory is re-created " + "at the destination if no trailing slash is found, otherwise the contents are " + "flattened (similar to rsync).", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Copy(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to copy the secret and overwrite existing one", }, }, }, { Name: "create", Aliases: []string{"new"}, Usage: "Easy creation of new secrets", Description: "" + "This command starts a wizard to aid in creation of new secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return create.Create(withGlobalFlags(ctx, c), c, action.Store) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store, s", Usage: "Which store to use", }, }, }, { Name: "delete", Usage: "Remove secrets", Description: "" + "This command removes secrets. It can work recursively on folders. " + "Recursing across stores is purposefully not supported.", Aliases: []string{"remove", "rm"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Delete(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "recursive, r", Usage: "Recursive delete files and folders", }, cli.BoolFlag{ Name: "force, f", Usage: "Force to delete the secret", }, }, }, { Name: "edit", Usage: "Edit new or existing secrets", Description: "" + "Use this command to insert a new secret or edit an existing one using " + "your $EDITOR. It will attempt to create a secure temporary directory " + "for storing your secret while the editor is accessing it. Please make " + "sure your editor doesn't leak sensitive data to other locations while " + "editing.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Edit(withGlobalFlags(ctx, c), c) }, Aliases: []string{"set"}, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "editor, e", Usage: "Use this editor binary", }, cli.BoolFlag{ Name: "create, c", Usage: "Create a new secret if none found", }, }, }, { Name: "find", Usage: "Search for secrets", Description: "" + "This command will first attempt a simple pattern match on the name of the " + "secret. If that yields no results, it will trigger a fuzzy search. " + "If there is an exact match it will be shown directly; if there are " + "multiple matches, a selection will be shown.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Find(withGlobalFlags(ctxutil.WithFuzzySearch(ctx, false), c), c) }, Aliases: []string{"search"}, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the password into the clipboard", }, }, }, { Name: "fsck", Usage: "Check store integrity", Description: "" + "Check the integrity of the given sub-store or all stores if none are specified. " + "Will automatically fix all issues found.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Fsck(withGlobalFlags(ctx, c), c) }, BashComplete: action.MountsComplete, }, { Name: "generate", Usage: "Generate a new password", Description: "" + "Generate a new password of the specified length, optionally with no symbols. " + "Alternatively, a xkcd style password can be generated (https://xkcd.com/936/). " + "Optionally put it on the clipboard and clear clipboard after 45 seconds. " + "Prompt before overwriting existing password unless forced. " + "It will replace only the first line of an existing file with a new password.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Generate(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.CompleteGenerate(ctx, c) }, Flags: []cli.Flag{ cli.BoolTFlag{ Name: "clip, c", Usage: "Copy the generated password to the clipboard", }, cli.BoolFlag{ Name: "print, p", Usage: "Print the generated password to the terminal", }, cli.BoolFlag{ Name: "force, f", Usage: "Force to overwrite existing password", }, cli.BoolFlag{ Name: "edit, e", Usage: "Open secret for editing after generating a password", }, cli.BoolFlag{ Name: "symbols, s", Usage: "Use symbols in the password", }, cli.BoolFlag{ Name: "xkcd, x", Usage: "Use multiple random english words combined to a password. By default, space is used as separator and all words are lowercase", }, cli.StringFlag{ Name: "xkcdsep, xs", Usage: "Word separator for generated xkcd style password. If no separator is specified, the words are combined without spaces/separator and the first character of words is capitalised. This flag implies -xkcd", Value: "", }, cli.StringFlag{ Name: "xkcdlang, xl", Usage: "Language to generate password from, currently de (german) and en (english, default) are supported", Value: "en", }, }, }, { Name: "git-credential", Usage: `Use "!gopass git-credential $@" as git's credential.helper`, Description: "" + "This command allows you to cache your git-credentials with gopass." + "Activate by using `git config --global credential.helper \"!gopass git-credential $@\"`", Subcommands: []cli.Command{ { Name: "get", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialGet(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "store", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialStore(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "erase", Hidden: true, Action: func(c *cli.Context) error { return action.GitCredentialErase(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.GitCredentialBefore(ctxutil.WithInteractive(withGlobalFlags(ctx, c), false), c) }, }, { Name: "configure", Description: "This command configures gopass as git's credential.helper", Action: func(c *cli.Context) error { return action.GitCredentialConfigure(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "global", Usage: "Install for current user", }, cli.BoolFlag{ Name: "local", Usage: "Install for current repository only", }, cli.BoolFlag{ Name: "system", Usage: "Install for all users, requires superuser rights", }, }, }, }, }, { Name: "jsonapi", Usage: "Run and configure gopass as jsonapi e.g. for browser plugins", Description: "Setup and run gopass as native messaging hosts, e.g. for browser plugins.", Hidden: false, Subcommands: []cli.Command{ { Name: "listen", Usage: "Listen and respond to messages via stdin/stdout", Description: "Gopass is started in listen mode from browser plugins using a wrapper specified in native messaging host manifests", Action: func(c *cli.Context) error { return action.JSONAPI(withGlobalFlags(ctx, c), c) }, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, }, { Name: "configure", Usage: "Setup gopass native messaging manifest for selected browser", Description: "To access gopass from browser plugins, a native app manifest must be installed at the correct location", Action: func(c *cli.Context) error { return action.SetupNativeMessaging(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "browser", Usage: "One of 'chrome' and 'firefox'", }, cli.StringFlag{ Name: "path", Usage: "Path to install 'gopass_wrapper.sh' to", }, cli.StringFlag{ Name: "manifest-path", Usage: "Path to install 'com.justwatch.gopass.json' to", }, cli.BoolFlag{ Name: "global", Usage: "Install for all users, requires superuser rights", }, cli.StringFlag{ Name: "libpath", Usage: "Library path for global installation on linux. Default is /usr/lib", }, cli.StringFlag{ Name: "gopass-path", Usage: "Path to gopass binary. Default is auto detected", }, cli.BoolTFlag{ Name: "print", Usage: "Print installation summary before creating any files", }, }, }, }, }, { Name: "otp", Usage: "Generate time- or hmac-based tokens", Aliases: []string{"totp", "hotp"}, Description: "" + "Tries to parse an OTP URL (otpauth://). URL can be TOTP or HOTP. " + "The URL can be provided on its own line or on a key value line with a key named 'totp'.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.OTP(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the time-based token into the clipboard", }, cli.StringFlag{ Name: "qr, q", Usage: "Write QR code to FILE", }, cli.BoolFlag{ Name: "password, o", Usage: "Only display the token", }, }, }, { Name: "git", Usage: "Run a git command inside a password store (init, remote, push, pull)", Description: "" + "If the password store is a git repository, execute a git command " + "specified by git-command-args.", Subcommands: []cli.Command{ { Name: "init", Usage: "Init git repo", Description: "Create and initialize a new git repo in the store", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitInit(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.StringFlag{ Name: "sign-key", Usage: "GPG Key to sign commits", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "remote", Usage: "Manage git remotes", Description: "These subcommands can be used to manage git remotes", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Usage: "Add git remote", Description: "Add a new git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitAddRemote(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, { Name: "remove", Usage: "Remove git remote", Description: "Remove a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitRemoveRemote(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, }, }, { Name: "push", Usage: "Push to remote", Description: "Push to a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitPush(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, { Name: "pull", Usage: "Pull from remote", Description: "Pull from a git remote", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.GitPull(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, }, }, }, }, { Name: "grep", Usage: "Search for secrets files containing search-string when decrypted.", Description: "" + "This command decrypts all secrets and performs a pattern matching on the " + "content.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Grep(withGlobalFlags(ctx, c), c) }, }, { Name: "history", Usage: "Show password history", Aliases: []string{"hist"}, Description: "" + "Display the change history for a secret", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.History(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "password, p", Usage: "Include passwords in output", }, }, }, { Name: "init", Usage: "Initialize new password store.", Description: "" + "Initialize new password storage and use gpg-id for encryption.", Action: func(c *cli.Context) error { return action.Init(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "path, p", Usage: "Set the sub-store path to operate on", }, cli.StringFlag{ Name: "store, s", Usage: "Set the name of the sub-store", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, cli.BoolFlag{ Name: "nogit", Usage: "(DEPRECATED): Select noop RCS backend. Use '--rcs noop' instead", Hidden: true, }, }, }, { Name: "insert", Usage: "Insert a new secret", Description: "" + "Insert a new secret. Optionally, echo the secret back to the console during entry. " + "Or, optionally, the entry may be multiline. " + "Prompt before overwriting existing secret unless forced.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Insert(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "echo, e", Usage: "Display secret while typing", }, cli.BoolFlag{ Name: "multiline, m", Usage: "Insert using $EDITOR", }, cli.BoolFlag{ Name: "force, f", Usage: "Overwrite any existing secret and do not prompt to confirm recipients", }, cli.BoolFlag{ Name: "append, a", Usage: "Append to any existing data", }, }, }, { Name: "list", Usage: "List existing secrets", Description: "" + "This command will list all existing secrets. Provide a folder prefix to list " + "only certain subfolders of the store.", Aliases: []string{"ls"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.List(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.IntFlag{ Name: "limit, l", Usage: "Max tree depth", }, cli.BoolFlag{ Name: "flat, f", Usage: "Print flat list", }, cli.BoolFlag{ Name: "folders, fo", Usage: "Print flat list of folders", }, cli.BoolFlag{ Name: "strip-prefix, s", Usage: "Strip prefix from filtered entries", }, }, }, { Name: "move", Aliases: []string{"mv"}, Usage: "Move secrets from one location to another", Description: "" + "This command moves a secret from one path to another. This also works " + "across different sub-stores. If the source is a directory, the source directory " + "is re-created at the destination if no trailing slash is found, otherwise the " + "contents are flattened (similar to rsync).", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Move(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "force, f", Usage: "Force to move the secret and overwrite existing one", }, }, }, { Name: "mounts", Usage: "Edit mounted stores", Description: "" + "This command displays all mounted password stores. It offers several " + "subcommands to create or remove mounts.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountsPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Aliases: []string{"mount"}, Usage: "Mount a password store", Description: "" + "This command allows for mounting an existing or new password store " + "at any path in an existing root store.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountAdd(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "init, i", Usage: "Init the store with the given recipient key", }, }, }, { Name: "remove", Aliases: []string{"rm", "unmount", "umount"}, Usage: "Umount an mounted password store", Description: "" + "This command allows to unmount an mounted password store. This will " + "only updated the configuration and not delete the password store.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.MountRemove(withGlobalFlags(ctx, c), c) }, BashComplete: action.MountsComplete, }, }, }, { Name: "recipients", Usage: "Edit recipient permissions", Description: "" + "This command displays all existing recipients for all mounted stores. " + "The subcommands allow adding or removing recipients.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "add", Aliases: []string{"authorize"}, Usage: "Add any number of Recipients to any store", Description: "" + "This command adds any number of recipients to any existing store. " + "If none are given it will display a list of usable public keys. " + "After adding the recipient to the list it will re-encrypt the whole " + "affected store to make sure the recipient has access to all existing " + "secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsAdd(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.BoolFlag{ Name: "force", Usage: "Force adding non-existing keys", }, }, }, { Name: "remove", Aliases: []string{"rm", "deauthorize"}, Usage: "Remove any number of Recipients from any store", Description: "" + "This command removes any number of recipients from any existing store. " + "If no recipients are provided, it will show a list of existing recipients " + "to choose from. It will refuse to remove the current user's key from the " + "store to avoid losing access. After removing the keys it will re-encrypt " + "all existing secrets. Please note that the removed recipients will still " + "be able to decrypt old revisions of the password store and any local " + "copies they might have. The only way to reliably remove a recipient is to " + "rotate all existing secrets.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsRemove(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.RecipientsComplete(ctx, c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store", Usage: "Store to operate on", }, cli.BoolFlag{ Name: "force", Usage: "Force adding non-existing keys", }, }, }, { Name: "update", Usage: "Recompute the saved recipient list checksums", Description: "" + "This command will recompute the saved recipient checksum" + "and save them to the config.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.RecipientsUpdate(withGlobalFlags(ctx, c), c) }, }, }, }, { Name: "setup", Usage: "Initialize a new password store", Description: "" + "This command is automatically invoked if gopass is started without any " + "existing password store. This command exists so users can be provided with " + "simple one-command setup instructions.", Hidden: true, Action: func(c *cli.Context) error { return action.InitOnboarding(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "remote", Usage: "URL to a git remote, will attempt to join this team", }, cli.StringFlag{ Name: "alias", Usage: "Local mount point for the given remote", }, cli.BoolFlag{ Name: "create", Usage: "Create a new team (default: false, i.e. join an existing team)", }, cli.StringFlag{ Name: "name", Usage: "Firstname and Lastname for unattended GPG key generation", }, cli.StringFlag{ Name: "email", Usage: "EMail for unattended GPG key generation", }, cli.StringFlag{ Name: "crypto", Usage: "Select crypto backend (gpg, gpgcli, plain, xc)", }, cli.StringFlag{ Name: "rcs", Usage: "Select sync backend (git, gitcli, gogit, noop)", }, }, }, { Name: "show", Usage: "Display a secret", Description: "" + "Show an existing secret and optionally put its first line on the clipboard. " + "If put on the clipboard, it will be cleared after 45 seconds.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Show(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.Complete(ctx, c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "clip, c", Usage: "Copy the first line of the secret into the clipboard", }, cli.BoolFlag{ Name: "qr", Usage: "Print the first line of the secret as QR Code", }, cli.BoolFlag{ Name: "force, f", Usage: "Display the password even if safecontent is enabled", }, cli.BoolFlag{ Name: "password, o", Usage: "Display only the password", }, cli.BoolFlag{ Name: "sync, s", Usage: "Sync before attempting to display the secret", }, cli.StringFlag{ Name: "revision", Usage: "Show a past revision", }, }, }, { Name: "sync", Usage: "Sync all local stores with their remotes", Description: "" + "Sync all local stores with their git remotes, if any, and check " + "any possibly affected gpg keys.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.Sync(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "store, s", Usage: "Select the store to sync", }, }, }, { Name: "templates", Usage: "Edit templates", Description: "" + "List existing templates in the password store and allow for editing " + "and creating them.", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplatesPrint(withGlobalFlags(ctx, c), c) }, Subcommands: []cli.Command{ { Name: "show", Usage: "Show a secret template.", Description: "Display an existing template", Aliases: []string{"cat"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplatePrint(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, { Name: "edit", Usage: "Edit secret templates.", Description: "Edit an existing or new template", Aliases: []string{"create", "new"}, Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplateEdit(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, { Name: "remove", Aliases: []string{"rm"}, Usage: "Remove secret templates.", Description: "Remove an existing template", Before: func(c *cli.Context) error { return action.Initialized(withGlobalFlags(ctx, c), c) }, Action: func(c *cli.Context) error { return action.TemplateRemove(withGlobalFlags(ctx, c), c) }, BashComplete: func(c *cli.Context) { action.TemplatesComplete(ctx, c) }, }, }, }, { Name: "unclip", Usage: "Internal command to clear clipboard", Description: "Clear the clipboard if the content matches the checksum.", Action: func(c *cli.Context) error { return action.Unclip(withGlobalFlags(ctx, c), c) }, Hidden: true, Flags: []cli.Flag{ cli.IntFlag{ Name: "timeout", Usage: "Time to wait", }, cli.BoolFlag{ Name: "force", Usage: "Clear clipboard even if checksum mismatches", }, }, }, { Name: "update", Usage: "Check for updates", Description: "" + "This command checks for gopass updates at GitHub and automatically " + "downloads and installs any missing update.", Action: func(c *cli.Context) error { return action.Update(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "pre", Usage: "Update to prereleases", }, }, }, { Name: "version", Usage: "Display version", Description: "" + "This command displays version and build time information " + "along with version information of important external commands. " + "Please provide the output when reporting issues.", Action: func(c *cli.Context) error { return action.Version(withGlobalFlags(ctx, c), c) }, }, { Name: "xc", Usage: "Experimental Crypto", Description: "" + "These subcommands are used to control and test the experimental crypto" + "implementation.", Subcommands: []cli.Command{ { Name: "list-private-keys", Action: func(c *cli.Context) error { return xc.ListPrivateKeys(withGlobalFlags(ctx, c), c) }, }, { Name: "list-public-keys", Action: func(c *cli.Context) error { return xc.ListPublicKeys(withGlobalFlags(ctx, c), c) }, }, { Name: "generate", Action: func(c *cli.Context) error { return xc.GenerateKeypair(withGlobalFlags(ctx, c), c) }, }, { Name: "export", Action: func(c *cli.Context) error { return xc.ExportPublicKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "import", Action: func(c *cli.Context) error { return xc.ImportPublicKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "export-private-key", Action: func(c *cli.Context) error { return xc.ExportPrivateKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "import-private-key", Action: func(c *cli.Context) error { return xc.ImportPrivateKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, cli.StringFlag{ Name: "file", }, }, }, { Name: "remove", Action: func(c *cli.Context) error { return xc.RemoveKey(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "id", }, }, }, { Name: "encrypt", Action: func(c *cli.Context) error { return xc.EncryptFile(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "file", }, cli.StringSliceFlag{ Name: "recipients", }, cli.BoolFlag{ Name: "stream", }, }, }, { Name: "decrypt", Action: func(c *cli.Context) error { return xc.DecryptFile(withGlobalFlags(ctx, c), c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "file", }, cli.BoolFlag{ Name: "stream", }, }, }, }, }, } }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" "github.com/codegangsta/cli" "github.com/mackerelio/gomkr/utils" mkr "github.com/mackerelio/mackerel-client-go" ) var Commands = []cli.Command{ commandStatus, commandHosts, commandCreate, commandUpdate, commandThrow, commandFetch, commandRetire, } var commandStatus = cli.Command{ Name: "status", Usage: "Show host status", Description: ` `, Action: doStatus, Flags: []cli.Flag{ cli.BoolFlag{Name: "verbose, v", Usage: "Verbose output mode"}, }, } var commandHosts = cli.Command{ Name: "hosts", Usage: "List hosts", Description: ` `, Action: doHosts, Flags: []cli.Flag{ cli.StringFlag{Name: "name, n", Value: "", Usage: "Show hosts only matched with <name>"}, cli.StringFlag{Name: "service, s", Value: "", Usage: "Show hosts only belongs to <service>"}, cli.StringSliceFlag{ Name: "role, r", Value: &cli.StringSlice{}, Usage: "Show hosts only belongs to <role>. Multiple choice allow. Required --service", }, cli.StringSliceFlag{ Name: "status, st", Value: &cli.StringSlice{}, Usage: "Show hosts only matched <status>. Multiple choice allow.", }, cli.BoolFlag{Name: "verbose, v", Usage: "Verbose output mode"}, }, } var commandCreate = cli.Command{ Name: "create", Usage: "Create a new host", Description: ` `, Action: doCreate, Flags: []cli.Flag{ cli.StringFlag{Name: "status, st", Value: "", Usage: "Host status ('working', 'standby', 'meintenance')"}, cli.StringSliceFlag{ Name: "roleFullname, R", Value: &cli.StringSlice{}, Usage: "Multiple choice allow. ex. My-Service:proxy, My-Service:db-master", }, }, } var commandUpdate = cli.Command{ Name: "update", Usage: "Update host information like hostname, status and role", Description: ` `, Action: doUpdate, Flags: []cli.Flag{ cli.StringFlag{Name: "name, n", Value: "", Usage: "Update <hostId> hostname to <name>."}, cli.StringFlag{Name: "status, st", Value: "", Usage: "Update <hostId> status to <status>."}, cli.StringSliceFlag{ Name: "roleFullname, R", Value: &cli.StringSlice{}, Usage: "Update <hostId> rolefullname to <roleFullname>.", }, }, } var commandThrow = cli.Command{ Name: "throw", Usage: "Post metric values", Description: ` `, Action: doThrow, Flags: []cli.Flag{ cli.StringFlag{Name: "host, H", Value: "", Usage: "Post host metric values to <hostId>."}, cli.StringFlag{Name: "service, s", Value: "", Usage: "Post service metric values to <service>."}, }, } var commandFetch = cli.Command{ Name: "fetch", Usage: "Fetch metric values", Description: ` `, Action: doFetch, Flags: []cli.Flag{ cli.StringSliceFlag{ Name: "name, n", Value: &cli.StringSlice{}, Usage: "Fetch metric values identified with <name>. Required. Multiple choise allow. ", }, }, } var commandRetire = cli.Command{ Name: "retire", Usage: "Retire host", Description: ` Retire host identified by <hostId>. Be careful because this is a irreversible operation. `, Action: doRetire, } func debug(v ...interface{}) { if os.Getenv("DEBUG") != "" { log.Println(v...) } } func assert(err error) { if err != nil { log.Fatal(err) } } func newMackerel() *mkr.Client { apiKey := os.Getenv("MACKEREL_APIKEY") if apiKey == "" { utils.Log("error", ` Not set MACKEREL_APIKEY environment variable. (Try "export MACKEREL_APIKEY='<Your apikey>'") `) os.Exit(1) } if os.Getenv("DEBUG") != "" { mackerel, err := mkr.NewClientForTest(apiKey, "https://mackerel.io/api/v0", true) utils.DieIf(err) return mackerel } else { return mkr.NewClient(apiKey) } } func doStatus(c *cli.Context) { argHostId := c.Args().Get(0) isVerbose := c.Bool("verbose") if argHostId == "" { cli.ShowCommandHelp(c, "status") os.Exit(1) } host, err := newMackerel().FindHost(argHostId) utils.DieIf(err) if isVerbose { PrettyPrintJson(host) } else { format := &HostFormat{ Id: host.Id, Name: host.Name, Status: host.Status, RoleFullnames: host.GetRoleFullnames(), IsRetired: host.IsRetired, CreatedAt: host.DateStringFromCreatedAt(), IpAddresses: host.IpAddresses(), } PrettyPrintJson(format) } } func doHosts(c *cli.Context) { isVerbose := c.Bool("verbose") argName := c.String("name") argService := c.String("service") argRoles := c.StringSlice("role") argStatuses := c.StringSlice("status") hosts, err := newMackerel().FindHosts(&mkr.FindHostsParam{ Name: argName, Service: argService, Roles: argRoles, Statuses: argStatuses, }) utils.DieIf(err) if isVerbose { PrettyPrintJson(hosts) } else { var hostsFormat []*HostFormat for _, host := range hosts { format := &HostFormat{ Id: host.Id, Name: host.Name, Status: host.Status, RoleFullnames: host.GetRoleFullnames(), IsRetired: host.IsRetired, CreatedAt: host.DateStringFromCreatedAt(), IpAddresses: host.IpAddresses(), } hostsFormat = append(hostsFormat, format) } PrettyPrintJson(hostsFormat) } } func doCreate(c *cli.Context) { argHostName := c.Args().Get(0) argRoleFullnames := c.StringSlice("roleFullname") argStatus := c.String("status") if argHostName == "" { cli.ShowCommandHelp(c, "create") os.Exit(1) } hostId, err := newMackerel().CreateHost(&mkr.CreateHostParam{ Name: argHostName, RoleFullnames: argRoleFullnames, }) utils.DieIf(err) if argStatus != "" { err := newMackerel().UpdateHostStatus(hostId, argStatus) utils.DieIf(err) } } func doUpdate(c *cli.Context) { argHostId := c.Args().Get(0) name := c.String("name") status := c.String("status") RoleFullnames := c.StringSlice("roleFullname") if argHostId == "" { cli.ShowCommandHelp(c, "update") os.Exit(1) } isUpdated := false if status != "" { err := newMackerel().UpdateHostStatus(argHostId, status) utils.DieIf(err) isUpdated = true } if name != "" || len(RoleFullnames) > 0 { _, err := newMackerel().UpdateHost(argHostId, &mkr.UpdateHostParam{ Name: name, RoleFullnames: RoleFullnames, }) utils.DieIf(err) isUpdated = true } if !isUpdated { cli.ShowCommandHelp(c, "update") os.Exit(1) } } func doThrow(c *cli.Context) { argHostId := c.String("host") argService := c.String("service") var metricValues []*(mkr.MetricValue) scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // name, value, timestamp // ex.) tcp.CLOSING 0 1397031808 items := strings.Fields(line) fmt.Printf("%v+", items) if len(items) != 3 { continue } value, err := strconv.ParseFloat(items[1], 64) if err != nil { utils.Log("warning", fmt.Sprintf("Failed to parse values: %s", err)) continue } time, err := strconv.ParseInt(items[2], 10, 64) if err != nil { utils.Log("warning", fmt.Sprintf("Failed to parse values: %s", err)) continue } metricValue := &mkr.MetricValue{ Name: items[0], Value: value, Time: time, } metricValues = append(metricValues, metricValue) } utils.ErrorIf(scanner.Err()) if argHostId != "" { err := newMackerel().PostHostMetricValuesByHostId(argHostId, metricValues) utils.DieIf(err) } else if argService != "" { err := newMackerel().PostServiceMetricValues(argService, metricValues) utils.DieIf(err) } else { cli.ShowCommandHelp(c, "throw") os.Exit(1) } } func doFetch(c *cli.Context) { argHostIds := c.Args() argMetricNames := c.StringSlice("name") if len(argHostIds) < 1 || len(argMetricNames) < 1 { cli.ShowCommandHelp(c, "fetch") os.Exit(1) } metricValues, err := newMackerel().FetchLatestMetricValues(argHostIds, argMetricNames) utils.DieIf(err) PrettyPrintJson(metricValues) } func doRetire(c *cli.Context) { argHostId := c.Args().Get(0) if argHostId == "" { cli.ShowCommandHelp(c, "retire") os.Exit(1) } err := newMackerel().RetireHost(argHostId) utils.DieIf(err) } Delete redundant code package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" "github.com/codegangsta/cli" "github.com/mackerelio/gomkr/utils" mkr "github.com/mackerelio/mackerel-client-go" ) var Commands = []cli.Command{ commandStatus, commandHosts, commandCreate, commandUpdate, commandThrow, commandFetch, commandRetire, } var commandStatus = cli.Command{ Name: "status", Usage: "Show host status", Description: ` `, Action: doStatus, Flags: []cli.Flag{ cli.BoolFlag{Name: "verbose, v", Usage: "Verbose output mode"}, }, } var commandHosts = cli.Command{ Name: "hosts", Usage: "List hosts", Description: ` `, Action: doHosts, Flags: []cli.Flag{ cli.StringFlag{Name: "name, n", Value: "", Usage: "Show hosts only matched with <name>"}, cli.StringFlag{Name: "service, s", Value: "", Usage: "Show hosts only belongs to <service>"}, cli.StringSliceFlag{ Name: "role, r", Value: &cli.StringSlice{}, Usage: "Show hosts only belongs to <role>. Multiple choice allow. Required --service", }, cli.StringSliceFlag{ Name: "status, st", Value: &cli.StringSlice{}, Usage: "Show hosts only matched <status>. Multiple choice allow.", }, cli.BoolFlag{Name: "verbose, v", Usage: "Verbose output mode"}, }, } var commandCreate = cli.Command{ Name: "create", Usage: "Create a new host", Description: ` `, Action: doCreate, Flags: []cli.Flag{ cli.StringFlag{Name: "status, st", Value: "", Usage: "Host status ('working', 'standby', 'meintenance')"}, cli.StringSliceFlag{ Name: "roleFullname, R", Value: &cli.StringSlice{}, Usage: "Multiple choice allow. ex. My-Service:proxy, My-Service:db-master", }, }, } var commandUpdate = cli.Command{ Name: "update", Usage: "Update host information like hostname, status and role", Description: ` `, Action: doUpdate, Flags: []cli.Flag{ cli.StringFlag{Name: "name, n", Value: "", Usage: "Update <hostId> hostname to <name>."}, cli.StringFlag{Name: "status, st", Value: "", Usage: "Update <hostId> status to <status>."}, cli.StringSliceFlag{ Name: "roleFullname, R", Value: &cli.StringSlice{}, Usage: "Update <hostId> rolefullname to <roleFullname>.", }, }, } var commandThrow = cli.Command{ Name: "throw", Usage: "Post metric values", Description: ` `, Action: doThrow, Flags: []cli.Flag{ cli.StringFlag{Name: "host, H", Value: "", Usage: "Post host metric values to <hostId>."}, cli.StringFlag{Name: "service, s", Value: "", Usage: "Post service metric values to <service>."}, }, } var commandFetch = cli.Command{ Name: "fetch", Usage: "Fetch metric values", Description: ` `, Action: doFetch, Flags: []cli.Flag{ cli.StringSliceFlag{ Name: "name, n", Value: &cli.StringSlice{}, Usage: "Fetch metric values identified with <name>. Required. Multiple choise allow. ", }, }, } var commandRetire = cli.Command{ Name: "retire", Usage: "Retire host", Description: ` Retire host identified by <hostId>. Be careful because this is a irreversible operation. `, Action: doRetire, } func debug(v ...interface{}) { if os.Getenv("DEBUG") != "" { log.Println(v...) } } func assert(err error) { if err != nil { log.Fatal(err) } } func newMackerel() *mkr.Client { apiKey := os.Getenv("MACKEREL_APIKEY") if apiKey == "" { utils.Log("error", ` Not set MACKEREL_APIKEY environment variable. (Try "export MACKEREL_APIKEY='<Your apikey>'") `) os.Exit(1) } if os.Getenv("DEBUG") != "" { mackerel, err := mkr.NewClientForTest(apiKey, "https://mackerel.io/api/v0", true) utils.DieIf(err) return mackerel } else { return mkr.NewClient(apiKey) } } func doStatus(c *cli.Context) { argHostId := c.Args().Get(0) isVerbose := c.Bool("verbose") if argHostId == "" { cli.ShowCommandHelp(c, "status") os.Exit(1) } host, err := newMackerel().FindHost(argHostId) utils.DieIf(err) if isVerbose { PrettyPrintJson(host) } else { format := &HostFormat{ Id: host.Id, Name: host.Name, Status: host.Status, RoleFullnames: host.GetRoleFullnames(), IsRetired: host.IsRetired, CreatedAt: host.DateStringFromCreatedAt(), IpAddresses: host.IpAddresses(), } PrettyPrintJson(format) } } func doHosts(c *cli.Context) { isVerbose := c.Bool("verbose") hosts, err := newMackerel().FindHosts(&mkr.FindHostsParam{ Name: c.String("name"), Service: c.String("service"), Roles: c.StringSlice("role"), Statuses: c.StringSlice("status"), }) utils.DieIf(err) if isVerbose { PrettyPrintJson(hosts) } else { var hostsFormat []*HostFormat for _, host := range hosts { format := &HostFormat{ Id: host.Id, Name: host.Name, Status: host.Status, RoleFullnames: host.GetRoleFullnames(), IsRetired: host.IsRetired, CreatedAt: host.DateStringFromCreatedAt(), IpAddresses: host.IpAddresses(), } hostsFormat = append(hostsFormat, format) } PrettyPrintJson(hostsFormat) } } func doCreate(c *cli.Context) { argHostName := c.Args().Get(0) argRoleFullnames := c.StringSlice("roleFullname") argStatus := c.String("status") if argHostName == "" { cli.ShowCommandHelp(c, "create") os.Exit(1) } hostId, err := newMackerel().CreateHost(&mkr.CreateHostParam{ Name: argHostName, RoleFullnames: argRoleFullnames, }) utils.DieIf(err) if argStatus != "" { err := newMackerel().UpdateHostStatus(hostId, argStatus) utils.DieIf(err) } } func doUpdate(c *cli.Context) { argHostId := c.Args().Get(0) name := c.String("name") status := c.String("status") RoleFullnames := c.StringSlice("roleFullname") if argHostId == "" { cli.ShowCommandHelp(c, "update") os.Exit(1) } isUpdated := false if status != "" { err := newMackerel().UpdateHostStatus(argHostId, status) utils.DieIf(err) isUpdated = true } if name != "" || len(RoleFullnames) > 0 { _, err := newMackerel().UpdateHost(argHostId, &mkr.UpdateHostParam{ Name: name, RoleFullnames: RoleFullnames, }) utils.DieIf(err) isUpdated = true } if !isUpdated { cli.ShowCommandHelp(c, "update") os.Exit(1) } } func doThrow(c *cli.Context) { argHostId := c.String("host") argService := c.String("service") var metricValues []*(mkr.MetricValue) scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // name, value, timestamp // ex.) tcp.CLOSING 0 1397031808 items := strings.Fields(line) fmt.Printf("%v+", items) if len(items) != 3 { continue } value, err := strconv.ParseFloat(items[1], 64) if err != nil { utils.Log("warning", fmt.Sprintf("Failed to parse values: %s", err)) continue } time, err := strconv.ParseInt(items[2], 10, 64) if err != nil { utils.Log("warning", fmt.Sprintf("Failed to parse values: %s", err)) continue } metricValue := &mkr.MetricValue{ Name: items[0], Value: value, Time: time, } metricValues = append(metricValues, metricValue) } utils.ErrorIf(scanner.Err()) if argHostId != "" { err := newMackerel().PostHostMetricValuesByHostId(argHostId, metricValues) utils.DieIf(err) } else if argService != "" { err := newMackerel().PostServiceMetricValues(argService, metricValues) utils.DieIf(err) } else { cli.ShowCommandHelp(c, "throw") os.Exit(1) } } func doFetch(c *cli.Context) { argHostIds := c.Args() argMetricNames := c.StringSlice("name") if len(argHostIds) < 1 || len(argMetricNames) < 1 { cli.ShowCommandHelp(c, "fetch") os.Exit(1) } metricValues, err := newMackerel().FetchLatestMetricValues(argHostIds, argMetricNames) utils.DieIf(err) PrettyPrintJson(metricValues) } func doRetire(c *cli.Context) { argHostId := c.Args().Get(0) if argHostId == "" { cli.ShowCommandHelp(c, "retire") os.Exit(1) } err := newMackerel().RetireHost(argHostId) utils.DieIf(err) }
package main import ( "flag" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "strconv" "strings" "sync" "syscall" "unicode/utf8" ) func Execute(outw, errw io.Writer, in io.Reader, stop <-chan struct{}, jq string, s *JQStack) (int64, int64, error) { if jq == "" { jq = "jq" } outcounter := &writeCounter{0, outw} errcounter := &writeCounter{0, errw} cmd := exec.Command(jq, "-C", JoinFilter(s)) // TODO test if stdout is a terminal cmd.Stdin = in cmd.Stdout = outcounter cmd.Stderr = errcounter done := make(chan error, 1) err := cmd.Start() if err != nil { return 0, 0, err } go func() { done <- cmd.Wait() close(done) }() select { case <-stop: err := cmd.Process.Kill() if err != nil { log.Println("unable to kill process %d", cmd.Process.Pid) } case err = <-done: break } nout := outcounter.n nerr := errcounter.n return nout, nerr, err } type Lib struct { mut sync.Mutex topics map[string]string cmds map[string]JQShellCommand } func Library() *Lib { lib := new(Lib) lib.topics = make(map[string]string) lib.cmds = make(map[string]JQShellCommand) return lib } func (lib *Lib) help(jq *JQShell, args []string) { flags := Flags("help", args) flags.Parse(nil) if len(args) == 0 { fmt.Println("available commands:") for name := range lib.cmds { fmt.Println("\t" + name) } fmt.Println("\thelp") fmt.Println("pass -h to a command for usage details") if len(lib.topics) > 0 { fmt.Println("additional help topics:") for name := range lib.topics { fmt.Println("\t" + name) } fmt.Println("for information on a topic run `help <topic>`") } } } func (lib *Lib) Register(name string, cmd JQShellCommand) { lib.mut.Lock() defer lib.mut.Unlock() _, ok := lib.cmds[name] if ok { panic("already registered") } lib.cmds[name] = cmd } func (lib *Lib) Execute(jq *JQShell, name string, args []string) error { lib.mut.Lock() defer lib.mut.Unlock() if name == "help" { lib.help(jq, args) return nil } cmd, ok := lib.cmds[name] if !ok { return fmt.Errorf("%v: unknown command", name) } err := cmd.ExecuteShellCommand(jq, args) if err != nil { return ExecError{append([]string{name}, args...), err} } return nil } var ShellExit = fmt.Errorf("exit") type JQShellCommand interface { ExecuteShellCommand(*JQShell, []string) error } type JQShellCommandFunc func(*JQShell, []string) error func (fn JQShellCommandFunc) ExecuteShellCommand(jq *JQShell, args []string) error { return fn(jq, args) } func cmdQuit(jq *JQShell, args []string) error { return ShellExit } func cmdScript(jq *JQShell, args []string) error { flags := Flags("script", args) flags.Bool("oneline", false, "do not print a hash-bang (#!) line") flags.String("f", "", "specify the file argument to jq") flags.Bool("F", false, "use the current file as the argument to jq") flags.String("o", "", "path to write executable script") flags.Parse(nil) var script []string script = append(script, "#!/usr/bin/env sh") script = append(script, "") f := JoinFilter(jq.Stack) fesc := shellEscape(f, "'", "\\'") bin := "jq" cmd := []string{bin} cmd = append(cmd, fesc) cmd = append(cmd, `"${@}"`) script = append(script, strings.Join(cmd, " ")) fmt.Println(strings.Join(script, "\n")) return nil } func shellEscape(s, q, qesc string) string { return q + strings.Replace(s, q, qesc, -1) + q } func cmdFilter(jq *JQShell, args []string) error { flags := Flags("filter", args) jqsyntax := flags.Bool("jq", false, "print the filter with jq syntax") qchars := flags.String("quote", "", "quote and escaped quote runes the -jq filter string (e.g. \"'\\'\")") err := flags.Parse(nil) if err != nil { return err } if *jqsyntax { var quote, qesc string if *qchars != "" { qrune, n := utf8.DecodeRuneInString(*qchars) if qrune == utf8.RuneError && n == 1 { return fmt.Errorf("invalid quote runes %q: %v", *qchars, err) } quote = string([]rune{qrune}) qesc = (*qchars)[n:] if qesc == "" { return fmt.Errorf("missing escape for quote character '%c'", qrune) } } filter := JoinFilter(jq.Stack) filter = shellEscape(filter, quote, qesc) fmt.Println(filter) return nil } filters := jq.Stack.JQFilter() if len(filters) == 0 { fmt.Fprintln(os.Stderr, "no filter") return nil } for i, piece := range filters { fmt.Printf("[%02d] %v\n", i, piece) } return nil } func cmdPush(jq *JQShell, args []string) error { for _, arg := range args { if arg == "" { continue } jq.Stack.Push(JQFilterString(arg)) } return nil } func cmdPop(jq *JQShell, args []string) error { var n int if len(args) > 1 { return fmt.Errorf("too many arguments given") } if len(args) == 0 { n = 1 } else { var err error n, err = strconv.Atoi(args[0]) if err != nil { return fmt.Errorf("argument must me an integer") } } if n < 0 { return fmt.Errorf("argument must be positive") } for i := 0; i < n; i++ { jq.Stack.Pop() } return nil } func cmdLoad(jq *JQShell, args []string) error { if len(args) != 1 { return fmt.Errorf("expects one filename") } f, err := os.Open(args[0]) if err != nil { return err } err = f.Close() if err != nil { return fmt.Errorf("error closing file") } jq.filename = args[0] jq.istmp = false return nil } func cmdWrite(jq *JQShell, args []string) error { if len(args) == 0 { r, err := jq.Input() if err != nil { return err } defer r.Close() w, errch := Page(nil) select { case err := <-errch: return err default: break } pageerr := make(chan error, 1) stop := make(chan struct{}) go func() { err := <-errch close(stop) if err != nil { pageerr <- err } close(pageerr) }() _, _, err = Execute(w, os.Stderr, r, stop, "", jq.Stack) w.Close() if err != nil { return ExecError{[]string{"jq"}, err} } pageErr := <-pageerr if pageErr != nil { jq.log("pager: ", pageErr) } return nil } return fmt.Errorf("file output not allowed") } func cmdRaw(jq *JQShell, args []string) error { if len(args) == 0 { r, err := jq.Input() if err != nil { return err } defer r.Close() w, errch := Page(nil) select { case err := <-errch: return err default: break } pageerr := make(chan error, 1) stop := make(chan struct{}) go func() { err := <-errch close(stop) if err != nil { pageerr <- err } close(pageerr) }() _, err = io.Copy(w, r) w.Close() if perr, ok := err.(*os.PathError); ok { if perr.Err == syscall.EPIPE { //jq.Log.Printf("DEBUG broken pipe") } } else if err != nil { return fmt.Errorf("copying file: %#v", err) } pageErr := <-pageerr if pageErr != nil { jq.log("pager: ", pageErr) } return nil } return fmt.Errorf("file output not allowed") } func cmdExec(jq *JQShell, args []string) error { flags := Flags("exec", args) ignore := flags.Bool("ignore", false, "ignore process exit status") filename := flags.String("o", "", "a json file produced by the command") pfilename := flags.String("O", "", "like -O but the file will not be deleted by jqsh") nocache := flags.Bool("c", false, "disable caching of results (no effect with -o)") err := flags.Parse(nil) if err != nil { return err } args = flags.Args() var out io.Writer var path string var istmp bool if *filename != "" && *pfilename != "" { return fmt.Errorf("both -o and -O given") } if *filename != "" { path = *filename istmp = true } else if *pfilename != "" { path = *pfilename } if *nocache { jq.SetInput(_cmdExecInput(jq, args[0], args[1:]...)) return nil } if path == "" { tmpfile, err := ioutil.TempFile("", "jqsh-exec-") if err != nil { return fmt.Errorf("creating temp file: %v", err) } path = tmpfile.Name() istmp = true out = tmpfile defer tmpfile.Close() } else { out = os.Stdout } if err != nil { return err } if len(args) == 0 { return fmt.Errorf("missing command") } stdout, err := _cmdExecInput(jq, args[0], args[1:]...)() if err != nil && !*ignore { os.Remove(path) return err } _, err = io.Copy(out, stdout) if err != nil { os.Remove(path) return err } jq.SetInputFile(path, istmp) return nil } func _cmdExecInput(jq *JQShell, name string, args ...string) func() (io.ReadCloser, error) { return func() (io.ReadCloser, error) { cmd := exec.Command(name, args...) //cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } err = cmd.Start() if err != nil { stdout.Close() return nil, err } go func() { err := cmd.Wait() if err != nil { jq.Log.Printf("%v: %v", name, err) } else { jq.Log.Printf("%v: exit status 0", name) } }() return stdout, nil } } type CmdFlags struct { *flag.FlagSet name string args []string } func Flags(name string, args []string) *CmdFlags { set := flag.NewFlagSet(name, flag.PanicOnError) return &CmdFlags{set, name, args} } func (f *CmdFlags) Parse(args *[]string) (err error) { defer func() { if e := recover(); e != nil { var iserr bool err, iserr = e.(error) if iserr { return } err = fmt.Errorf("%v", e) } }() if args == nil { args = &f.args } f.FlagSet.Parse(*args) return nil } change JQShellCommand interface so all commands use *CmdFlags package main import ( "flag" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "strconv" "strings" "sync" "syscall" "unicode/utf8" ) func Execute(outw, errw io.Writer, in io.Reader, stop <-chan struct{}, jq string, s *JQStack) (int64, int64, error) { if jq == "" { jq = "jq" } outcounter := &writeCounter{0, outw} errcounter := &writeCounter{0, errw} cmd := exec.Command(jq, "-C", JoinFilter(s)) // TODO test if stdout is a terminal cmd.Stdin = in cmd.Stdout = outcounter cmd.Stderr = errcounter done := make(chan error, 1) err := cmd.Start() if err != nil { return 0, 0, err } go func() { done <- cmd.Wait() close(done) }() select { case <-stop: err := cmd.Process.Kill() if err != nil { log.Println("unable to kill process %d", cmd.Process.Pid) } case err = <-done: break } nout := outcounter.n nerr := errcounter.n return nout, nerr, err } type Lib struct { mut sync.Mutex topics map[string]string cmds map[string]JQShellCommand } func Library() *Lib { lib := new(Lib) lib.topics = make(map[string]string) lib.cmds = make(map[string]JQShellCommand) return lib } func (lib *Lib) help(jq *JQShell, args []string) { flags := Flags("help", args) flags.Parse(nil) if len(args) == 0 { fmt.Println("available commands:") for name := range lib.cmds { fmt.Println("\t" + name) } fmt.Println("\thelp") fmt.Println("pass -h to a command for usage details") if len(lib.topics) > 0 { fmt.Println("additional help topics:") for name := range lib.topics { fmt.Println("\t" + name) } fmt.Println("for information on a topic run `help <topic>`") } } } func (lib *Lib) Register(name string, cmd JQShellCommand) { lib.mut.Lock() defer lib.mut.Unlock() _, ok := lib.cmds[name] if ok { panic("already registered") } lib.cmds[name] = cmd } func (lib *Lib) Execute(jq *JQShell, name string, args []string) error { lib.mut.Lock() defer lib.mut.Unlock() if name == "help" { lib.help(jq, args) return nil } cmd, ok := lib.cmds[name] if !ok { return fmt.Errorf("%v: unknown command", name) } err := cmd.ExecuteShellCommand(jq, Flags(name, args)) if err != nil { return ExecError{append([]string{name}, args...), err} } return nil } var ShellExit = fmt.Errorf("exit") type JQShellCommand interface { ExecuteShellCommand(*JQShell, *CmdFlags) error } type JQShellCommandFunc func(*JQShell, *CmdFlags) error func (fn JQShellCommandFunc) ExecuteShellCommand(jq *JQShell, flags *CmdFlags) error { return fn(jq, flags) } func cmdQuit(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } return ShellExit } func cmdScript(jq *JQShell, flags *CmdFlags) error { flags.Bool("oneline", false, "do not print a hash-bang (#!) line") flags.String("f", "", "specify the file argument to jq") flags.Bool("F", false, "use the current file as the argument to jq") flags.String("o", "", "path to write executable script") flags.Parse(nil) var script []string script = append(script, "#!/usr/bin/env sh") script = append(script, "") f := JoinFilter(jq.Stack) fesc := shellEscape(f, "'", "\\'") bin := "jq" cmd := []string{bin} cmd = append(cmd, fesc) cmd = append(cmd, `"${@}"`) script = append(script, strings.Join(cmd, " ")) fmt.Println(strings.Join(script, "\n")) return nil } func shellEscape(s, q, qesc string) string { return q + strings.Replace(s, q, qesc, -1) + q } func cmdFilter(jq *JQShell, flags *CmdFlags) error { jqsyntax := flags.Bool("jq", false, "print the filter with jq syntax") qchars := flags.String("quote", "", "quote and escaped quote runes the -jq filter string (e.g. \"'\\'\")") err := flags.Parse(nil) if err != nil { return err } if *jqsyntax { var quote, qesc string if *qchars != "" { qrune, n := utf8.DecodeRuneInString(*qchars) if qrune == utf8.RuneError && n == 1 { return fmt.Errorf("invalid quote runes %q: %v", *qchars, err) } quote = string([]rune{qrune}) qesc = (*qchars)[n:] if qesc == "" { return fmt.Errorf("missing escape for quote character '%c'", qrune) } } filter := JoinFilter(jq.Stack) filter = shellEscape(filter, quote, qesc) fmt.Println(filter) return nil } filters := jq.Stack.JQFilter() if len(filters) == 0 { fmt.Fprintln(os.Stderr, "no filter") return nil } for i, piece := range filters { fmt.Printf("[%02d] %v\n", i, piece) } return nil } func cmdPush(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } args := flags.Args() for _, arg := range args { if arg == "" { continue } jq.Stack.Push(JQFilterString(arg)) } return nil } func cmdPop(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } args := flags.Args() var n int if len(args) > 1 { return fmt.Errorf("too many arguments given") } if len(args) == 0 { n = 1 } else { var err error n, err = strconv.Atoi(args[0]) if err != nil { return fmt.Errorf("argument must me an integer") } } if n < 0 { return fmt.Errorf("argument must be positive") } for i := 0; i < n; i++ { jq.Stack.Pop() } return nil } func cmdLoad(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } args := flags.Args() if len(args) != 1 { return fmt.Errorf("expects one filename") } f, err := os.Open(args[0]) if err != nil { return err } err = f.Close() if err != nil { return fmt.Errorf("error closing file") } jq.filename = args[0] jq.istmp = false return nil } func cmdWrite(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } args := flags.Args() if len(args) == 0 { r, err := jq.Input() if err != nil { return err } defer r.Close() w, errch := Page(nil) select { case err := <-errch: return err default: break } pageerr := make(chan error, 1) stop := make(chan struct{}) go func() { err := <-errch close(stop) if err != nil { pageerr <- err } close(pageerr) }() _, _, err = Execute(w, os.Stderr, r, stop, "", jq.Stack) w.Close() if err != nil { return ExecError{[]string{"jq"}, err} } pageErr := <-pageerr if pageErr != nil { jq.log("pager: ", pageErr) } return nil } return fmt.Errorf("file output not allowed") } func cmdRaw(jq *JQShell, flags *CmdFlags) error { err := flags.Parse(nil) if err != nil { return err } args := flags.Args() if len(args) == 0 { r, err := jq.Input() if err != nil { return err } defer r.Close() w, errch := Page(nil) select { case err := <-errch: return err default: break } pageerr := make(chan error, 1) stop := make(chan struct{}) go func() { err := <-errch close(stop) if err != nil { pageerr <- err } close(pageerr) }() _, err = io.Copy(w, r) w.Close() if perr, ok := err.(*os.PathError); ok { if perr.Err == syscall.EPIPE { //jq.Log.Printf("DEBUG broken pipe") } } else if err != nil { return fmt.Errorf("copying file: %#v", err) } pageErr := <-pageerr if pageErr != nil { jq.log("pager: ", pageErr) } return nil } return fmt.Errorf("file output not allowed") } func cmdExec(jq *JQShell, flags *CmdFlags) error { ignore := flags.Bool("ignore", false, "ignore process exit status") filename := flags.String("o", "", "a json file produced by the command") pfilename := flags.String("O", "", "like -O but the file will not be deleted by jqsh") nocache := flags.Bool("c", false, "disable caching of results (no effect with -o)") err := flags.Parse(nil) if err != nil { return err } args := flags.Args() var out io.Writer var path string var istmp bool if *filename != "" && *pfilename != "" { return fmt.Errorf("both -o and -O given") } if *filename != "" { path = *filename istmp = true } else if *pfilename != "" { path = *pfilename } if *nocache { jq.SetInput(_cmdExecInput(jq, args[0], args[1:]...)) return nil } if path == "" { tmpfile, err := ioutil.TempFile("", "jqsh-exec-") if err != nil { return fmt.Errorf("creating temp file: %v", err) } path = tmpfile.Name() istmp = true out = tmpfile defer tmpfile.Close() } else { out = os.Stdout } if err != nil { return err } if len(args) == 0 { return fmt.Errorf("missing command") } stdout, err := _cmdExecInput(jq, args[0], args[1:]...)() if err != nil && !*ignore { os.Remove(path) return err } _, err = io.Copy(out, stdout) if err != nil { os.Remove(path) return err } jq.SetInputFile(path, istmp) return nil } func _cmdExecInput(jq *JQShell, name string, args ...string) func() (io.ReadCloser, error) { return func() (io.ReadCloser, error) { cmd := exec.Command(name, args...) //cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } err = cmd.Start() if err != nil { stdout.Close() return nil, err } go func() { err := cmd.Wait() if err != nil { jq.Log.Printf("%v: %v", name, err) } else { jq.Log.Printf("%v: exit status 0", name) } }() return stdout, nil } } type CmdFlags struct { *flag.FlagSet name string args []string } func Flags(name string, args []string) *CmdFlags { set := flag.NewFlagSet(name, flag.PanicOnError) return &CmdFlags{set, name, args} } func (f *CmdFlags) Parse(args *[]string) (err error) { defer func() { if e := recover(); e != nil { var iserr bool err, iserr = e.(error) if iserr { return } err = fmt.Errorf("%v", e) } }() if args == nil { args = &f.args } f.FlagSet.Parse(*args) return nil }
package main import ( //"errors" "fmt" "github.com/simulatedsimian/emu6502/core6502" "reflect" "strconv" "strings" ) /* var test interface{} test = ctx logDisp.WriteLine(fmt.Sprint(reflect.TypeOf(test))) t := reflect.TypeOf(testFunc) for n := 0; n < t.NumIn(); n++ { logDisp.WriteLine(fmt.Sprint(t.In(n))) } testFuncVal := reflect.ValueOf(testFunc) args := []reflect.Value{reflect.ValueOf("str"), reflect.ValueOf(uint8(22)), reflect.ValueOf(uint16(7625))} testFuncVal.Call(args) logDisp.WriteLine(fmt.Sprint(t)) // i, err := strconv.ParseInt(inp, 16, 16) // logDisp.WriteLine(fmt.Sprint(i, err)) */ type commandInfo struct { name, help string handler interface{} } var commands = []commandInfo{ {"sm", "Set Memory: sm <address> <value>", setMemory}, {"sb", "Set Block: smb <address> <count> <value>", setMemory}, {"sr", "Set Register: sr <reg> <value>", setReg}, } func processArgs(handler reflect.Value, ctx core6502.CPUContext, parts []string) ([]reflect.Value, error) { args := []reflect.Value{reflect.ValueOf(ctx)} handler_t := reflect.TypeOf(handler) for n := 0; n < handler_t.NumIn(); n++ { switch handler_t.In(n) { case reflect.TypeOf(uint8(0)): i, err := strconv.ParseInt(parts[n], 16, 8) if err != nil { return nil, err } args = append(args, reflect.ValueOf(uint8(i))) case reflect.TypeOf(uint16(0)): i, err := strconv.ParseInt(parts[n], 16, 16) if err != nil { return nil, err } args = append(args, reflect.ValueOf(uint16(i))) case reflect.TypeOf(""): args = append(args, reflect.ValueOf(parts[n])) } } return nil } func DispatchCommand(ctx core6502.CPUContext, cmd string) (bool, error) { if cmd == "q" { return true, nil } parts := strings.Split(cmd, " ") if len(parts) > 0 { for n := 0; n < len(commands); n++ { if commands[n].name == parts[0] } } return false, nil } func setMemory(ctx core6502.CPUContext, addr uint16, val uint8) error { ctx.Poke(addr, val) return nil } func setMemoryBlock(ctx core6502.CPUContext, addr uint16, count uint16, val uint8) error { for count != 0 { ctx.Poke(addr, val) addr++ count-- } return nil } func setReg(ctx core6502.CPUContext, reg string, val uint8) error { switch reg { case "a": ctx.SetRegA(val) case "x": ctx.SetRegX(val) case "y": ctx.SetRegY(val) default: return fmt.Errorf("Invalid Register: %s", reg) } return nil } implementing command parser package main import ( //"errors" "fmt" "github.com/simulatedsimian/emu6502/core6502" "reflect" "strconv" "strings" ) /* var test interface{} test = ctx logDisp.WriteLine(fmt.Sprint(reflect.TypeOf(test))) t := reflect.TypeOf(testFunc) for n := 0; n < t.NumIn(); n++ { logDisp.WriteLine(fmt.Sprint(t.In(n))) } testFuncVal := reflect.ValueOf(testFunc) args := []reflect.Value{reflect.ValueOf("str"), reflect.ValueOf(uint8(22)), reflect.ValueOf(uint16(7625))} testFuncVal.Call(args) logDisp.WriteLine(fmt.Sprint(t)) // i, err := strconv.ParseInt(inp, 16, 16) // logDisp.WriteLine(fmt.Sprint(i, err)) */ type commandInfo struct { name, help string handler reflect.Value } var commands = []commandInfo{ {"sm", "Set Memory: sm <address> <value>", reflect.ValueOf(setMemory)}, {"sb", "Set Block: smb <address> <count> <value>", reflect.ValueOf(setMemoryBlock)}, {"sr", "Set Register: sr <reg> <value>", reflect.ValueOf(setReg)}, } func processArgs(handler reflect.Value, ctx core6502.CPUContext, parts []string) ([]reflect.Value, error) { args := []reflect.Value{} args = append(args, reflect.ValueOf(ctx)) handler_t := handler.Type() //panic(fmt.Sprint(handler_t.In(1), reflect.TypeOf(uint8(0)))) for n := 0; n < handler_t.NumIn(); n++ { switch handler_t.In(n) { case reflect.TypeOf(uint8(0)): i, err := strconv.ParseUint(parts[0], 16, 8) if err != nil { return nil, err } args = append(args, reflect.ValueOf(uint8(i))) parts = parts[1:] case reflect.TypeOf(uint16(0)): i, err := strconv.ParseUint(parts[0], 16, 16) if err != nil { return nil, err } args = append(args, reflect.ValueOf(uint16(i))) parts = parts[1:] case reflect.TypeOf(""): args = append(args, reflect.ValueOf(parts[0])) parts = parts[1:] } } // todo verify arg count return args, nil } func DispatchCommand(ctx core6502.CPUContext, cmd string) (bool, error) { if cmd == "q" { return true, nil } parts := strings.Split(cmd, " ") if len(parts) > 0 { for n := 0; n < len(commands); n++ { if commands[n].name == parts[0] { args, err := processArgs(commands[n].handler, ctx, parts[1:]) if err != nil { return false, err } commands[n].handler.Call(args) return false, nil } } return false, fmt.Errorf("Unknown Command: %s", parts[0]) } return false, nil } func setMemory(ctx core6502.CPUContext, addr uint16, val uint8) error { ctx.Poke(addr, val) return nil } func setMemoryBlock(ctx core6502.CPUContext, addr uint16, count uint16, val uint8) error { for count != 0 { ctx.Poke(addr, val) addr++ count-- } return nil } func setReg(ctx core6502.CPUContext, reg string, val uint8) error { switch reg { case "a": ctx.SetRegA(val) case "x": ctx.SetRegX(val) case "y": ctx.SetRegY(val) default: return fmt.Errorf("Invalid Register: %s", reg) } return nil }
package main import ( "os" "os/signal" "github.com/hashicorp/terraform/command" "github.com/mitchellh/cli" ) // Commands is the mapping of all the available Terraform commands. var Commands map[string]cli.CommandFactory // Ui is the cli.Ui used for communicating to the outside world. var Ui cli.Ui const ErrorPrefix = "e:" const OutputPrefix = "o:" func init() { Ui = &cli.PrefixedUi{ AskPrefix: OutputPrefix, OutputPrefix: OutputPrefix, InfoPrefix: OutputPrefix, ErrorPrefix: ErrorPrefix, Ui: &cli.BasicUi{Writer: os.Stdout}, } meta := command.Meta{ Color: true, ContextOpts: &ContextOpts, Ui: Ui, } Commands = map[string]cli.CommandFactory{ "apply": func() (cli.Command, error) { return &command.ApplyCommand{ Meta: meta, ShutdownCh: makeShutdownCh(), }, nil }, "get": func() (cli.Command, error) { return &command.GetCommand{ Meta: meta, }, nil }, "graph": func() (cli.Command, error) { return &command.GraphCommand{ Meta: meta, }, nil }, "init": func() (cli.Command, error) { return &command.InitCommand{ Meta: meta, }, nil }, "output": func() (cli.Command, error) { return &command.OutputCommand{ Meta: meta, }, nil }, "plan": func() (cli.Command, error) { return &command.PlanCommand{ Meta: meta, }, nil }, "refresh": func() (cli.Command, error) { return &command.RefreshCommand{ Meta: meta, }, nil }, "show": func() (cli.Command, error) { return &command.ShowCommand{ Meta: meta, }, nil }, "version": func() (cli.Command, error) { return &command.VersionCommand{ Meta: meta, Revision: GitCommit, Version: Version, VersionPrerelease: VersionPrerelease, }, nil }, } } // makeShutdownCh creates an interrupt listener and returns a channel. // A message will be sent on the channel for every interrupt received. func makeShutdownCh() <-chan struct{} { resultCh := make(chan struct{}) signalCh := make(chan os.Signal, 4) signal.Notify(signalCh, os.Interrupt) go func() { for { <-signalCh resultCh <- struct{}{} } }() return resultCh } main: add Destroy package main import ( "os" "os/signal" "github.com/hashicorp/terraform/command" "github.com/mitchellh/cli" ) // Commands is the mapping of all the available Terraform commands. var Commands map[string]cli.CommandFactory // Ui is the cli.Ui used for communicating to the outside world. var Ui cli.Ui const ErrorPrefix = "e:" const OutputPrefix = "o:" func init() { Ui = &cli.PrefixedUi{ AskPrefix: OutputPrefix, OutputPrefix: OutputPrefix, InfoPrefix: OutputPrefix, ErrorPrefix: ErrorPrefix, Ui: &cli.BasicUi{Writer: os.Stdout}, } meta := command.Meta{ Color: true, ContextOpts: &ContextOpts, Ui: Ui, } Commands = map[string]cli.CommandFactory{ "apply": func() (cli.Command, error) { return &command.ApplyCommand{ Meta: meta, ShutdownCh: makeShutdownCh(), }, nil }, "destroy": func() (cli.Command, error) { return &command.ApplyCommand{ Meta: meta, Destroy: true, ShutdownCh: makeShutdownCh(), }, nil }, "get": func() (cli.Command, error) { return &command.GetCommand{ Meta: meta, }, nil }, "graph": func() (cli.Command, error) { return &command.GraphCommand{ Meta: meta, }, nil }, "init": func() (cli.Command, error) { return &command.InitCommand{ Meta: meta, }, nil }, "output": func() (cli.Command, error) { return &command.OutputCommand{ Meta: meta, }, nil }, "plan": func() (cli.Command, error) { return &command.PlanCommand{ Meta: meta, }, nil }, "refresh": func() (cli.Command, error) { return &command.RefreshCommand{ Meta: meta, }, nil }, "show": func() (cli.Command, error) { return &command.ShowCommand{ Meta: meta, }, nil }, "version": func() (cli.Command, error) { return &command.VersionCommand{ Meta: meta, Revision: GitCommit, Version: Version, VersionPrerelease: VersionPrerelease, }, nil }, } } // makeShutdownCh creates an interrupt listener and returns a channel. // A message will be sent on the channel for every interrupt received. func makeShutdownCh() <-chan struct{} { resultCh := make(chan struct{}) signalCh := make(chan os.Signal, 4) signal.Notify(signalCh, os.Interrupt) go func() { for { <-signalCh resultCh <- struct{}{} } }() return resultCh }
package main import ( "log" "github.com/Tomohiro/air/media" "github.com/codegangsta/cli" "github.com/gongo/go-airplay" ) func newApp() *cli.App { app := cli.NewApp() app.Name = "air" app.Version = Version app.Usage = "Command-line AirPlay client for Apple TV" app.Author = "Tomohiro TAIRA" app.Email = "tomohiro.t@gmail.com" app.Action = play return app } func play(c *cli.Context) { path := c.Args().First() mediaType, err := media.ClassifyType(path) if err != nil { log.Fatal(err) } var m media.Media switch mediaType { case media.IsFile: m = media.NewFile(path) } client, err := airplay.FirstClient() if err != nil { log.Fatal(err) } ch := client.Play(m.URL()) <-ch } Remove media package package main import ( "log" "github.com/codegangsta/cli" "github.com/gongo/go-airplay" ) func newApp() *cli.App { app := cli.NewApp() app.Name = "air" app.Version = Version app.Usage = "Command-line AirPlay client for Apple TV" app.Author = "Tomohiro TAIRA" app.Email = "tomohiro.t@gmail.com" app.Action = play return app } func play(c *cli.Context) { path := c.Args().First() mediaType, err := classifyType(path) if err != nil { log.Fatal(err) } var m media switch mediaType { case isFile: m = newFile(path) } client, err := airplay.FirstClient() if err != nil { log.Fatal(err) } ch := client.Play(m.URL()) <-ch }
package main import ( "bytes" "errors" "os" "os/exec" "path/filepath" "strings" "github.com/codegangsta/cli" ) const ( GOPKG = repoType(iota) HTTP HTTPS GIT SSH ) type repoType int var ( getCommandDesc = `Clones a package into your GOPATH using the go tool chain, creates a link between it and your workspace, and if possible updates the repos remote origin to use SSH.` getCommand = cli.Command{ Name: "get", Usage: "'go get' a repo, and link it to your workspace", Description: getCommandDesc, Action: func(c *cli.Context) { err := getCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing code"}, cli.BoolFlag{"force, f", "Force updating and linking (Irreverseible)"}, cli.BoolFlag{"no-ssh", "Do not update the remote origin to use SSH"}, cli.StringFlag{"ssh-user", "git", "Set the user for the SSH url (Default: git)"}, }, } cloneCommand = cli.Command{ Name: "clone", Usage: "Clone the repo into your GOPATH", Action: func(c *cli.Context) { err := cloneCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing code"}, }, } linkCommand = cli.Command{ Name: "link", Usage: "Create a link from the GOPATH/project to WORKSPACE/project", Action: func(c *cli.Context) { err := linkCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing link"}, cli.BoolFlag{"force, f", "Force updating and linking (Irreverseible)"}, }, } updateRemoteCommand = cli.Command{ Name: "update-remote", Usage: "Updates the git remote origin url to use SSH", Action: func(c *cli.Context) { err := updateRemoteCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.StringFlag{"ssh-user", "git", "Set the user for the SSH url (Default: git)"}, }, } ) func getCommandAction(c *cli.Context) error { err := cloneCommandAction(c) if err != nil { return err } err = linkCommandAction(c) if err != nil { return err } if !c.Bool("no-ssh") { err = updateRemoteCommandAction(c) if err != nil { return err } } return nil } func cloneCommandAction(c *cli.Context) error { pkgpath := projectFromURL(c.Args().First()) log.Info("Getting package: %v", pkgpath) var err error if c.Bool("update") { log.Debug(" ----> running %v", concat("go", " ", "get", " -u ", pkgpath)) err = pipeFromExec(os.Stdout, "go", "get", "-u", pkgpath) } else { log.Debug(" ----> running %v", concat("go", " ", "get", " ", pkgpath)) err = pipeFromExec(os.Stdout, "go", "get", pkgpath) } if err != nil { log.Error("Couldn't get package: %v", err) return err } return nil } func linkCommandAction(c *cli.Context) error { pkgpath := projectFromURL(c.Args().First()) pkg := pkgFromPath(pkgpath) workspacepath := concat(WORKSPACE, "/", pkg) log.Info("Linking package %v to %v", pkgpath, workspacepath) fullpkgpath := getAbsPath(concat(GOPATH, "/src/", pkgpath)) fullworkspacepath := getAbsPath(workspacepath) // check if anything exists here if _, err := os.Stat(fullworkspacepath); !os.IsNotExist(err) { info, _ := os.Lstat(fullworkspacepath) if info.Mode()&os.ModeSymlink != 0 { if c.Bool("update") || c.Bool("force") { os.Remove(fullworkspacepath) } else { log.Warning("[WARNING]: Link already exists!") symlink, _ := filepath.EvalSymlinks(fullworkspacepath) log.Warning(" ----> %v -> %v", workspacepath, symlink) return errors.New("Link already exists") } } else if c.Bool("force") { log.Warning(" ----> removing %v", workspacepath) os.Remove(fullworkspacepath) } else { log.Error(" ----> [ERROR]: File/Folder already exists at %v, if you wish to proceed use -f", workspacepath) return errors.New("File/Folder already exists") } } cmd := exec.Command("ln", "-s", fullpkgpath, fullworkspacepath) log.Debug(" ----> running: %v", concat("ln", " -s", concat(" $GOPATH/src/", pkgpath), concat(" ", WORKSPACE, "/", pkg))) err := cmd.Run() if err != nil { log.Error("Failed to create link: %v", err) return err } log.Debug(" ----> Successfully linked!") return nil } func updateRemoteCommandAction(c *cli.Context) error { path := c.Args().First() pkgpath := projectFromURL(path) fullpkgpath := getAbsPath(concat(GOPATH, "/src/", pkgpath)) log.Info("Update remote origin URL for repo: %v", pkgpath) os.Chdir(fullpkgpath) cmd := exec.Command("git", "remote", "-v") log.Debug(" ----> running: git remote -v") var buf bytes.Buffer cmd.Stdout = &buf err := cmd.Run() if err != nil { log.Error("Couldn't update remote url: %v", err) return err } endpoints := strings.Split(buf.String(), "\n") var repo string for _, line := range endpoints { url, err := parseGitOriginURL(line) if err == nil { repo = url } } if repo == "" { log.Error("Couldn't parse git remote origin url") return errors.New("Couldn't parse git remote origin url") } user := c.String("ssh-user") newRepoURL := getSSHPath(repo, user) os.Chdir(fullpkgpath) cmd = exec.Command("git", "remote", "set-url", "origin", newRepoURL) log.Debug(" ----> running: git remote set-url origin %v", newRepoURL) err = cmd.Run() if err != nil { log.Error("Failed to update remote origin: %v", err) return err } log.Debug(" ----> Successfully updated remote origin") return nil } Added -d (download only) flag option to 'get' and 'clone' package main import ( "bytes" "errors" "os" "os/exec" "path/filepath" "strings" "github.com/codegangsta/cli" ) const ( GOPKG = repoType(iota) HTTP HTTPS GIT SSH ) type repoType int var ( getCommandDesc = `Clones a package into your GOPATH using the go tool chain, creates a link between it and your workspace, and if possible updates the repos remote origin to use SSH.` getCommand = cli.Command{ Name: "get", Usage: "'go get' a repo, and link it to your workspace", Description: getCommandDesc, Action: func(c *cli.Context) { err := getCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing code"}, cli.BoolFlag{"download-only, d", "Only download the code, don't install with the go toolchain (go build, go install)"}, cli.BoolFlag{"force, f", "Force updating and linking (Irreverseible)"}, cli.BoolFlag{"no-ssh", "Do not update the remote origin to use SSH"}, cli.StringFlag{"ssh-user", "<user>", "Set the user for the SSH url (Default: git)"}, }, } cloneCommand = cli.Command{ Name: "clone", Usage: "Clone the repo into your GOPATH", Action: func(c *cli.Context) { err := cloneCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing code"}, cli.BoolFlag{"download-only, d", "Only download the code, don't install with the go toolchain (go build, go install)"}, }, } linkCommand = cli.Command{ Name: "link", Usage: "Create a link from the GOPATH/project to WORKSPACE/project", Action: func(c *cli.Context) { err := linkCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.BoolFlag{"update, u", "Update existing link"}, cli.BoolFlag{"force, f", "Force updating and linking (Irreverseible)"}, }, } updateRemoteCommand = cli.Command{ Name: "update-remote", Usage: "Updates the git remote origin url to use SSH", Action: func(c *cli.Context) { err := updateRemoteCommandAction(c) if err != nil { exitStatus = FAIL return } }, Flags: []cli.Flag{ cli.StringFlag{"ssh-user", "git", "Set the user for the SSH url (Default: git)"}, }, } ) func getCommandAction(c *cli.Context) error { err := cloneCommandAction(c) if err != nil { return err } err = linkCommandAction(c) if err != nil { return err } if !c.Bool("no-ssh") { err = updateRemoteCommandAction(c) if err != nil { return err } } return nil } func cloneCommandAction(c *cli.Context) error { pkgpath := projectFromURL(c.Args().First()) log.Info("Getting package: %v", pkgpath) args := []string{"get"} if c.Bool("update") { args = append(args, "-u") //log.Debug(" ----> running %v", concat("go", " ", "get", " -u ", pkgpath)) //err = pipeFromExec(os.Stdout, "go", "get", "-u", pkgpath) } if c.Bool("download-only") { args = append(args, "-d") //log.Debug(" ----> running %v", concat("go", " ", "get", " ", pkgpath)) //err = pipeFromExec(os.Stdout, "go", "get", pkgpath) } args = append(args, pkgpath) log.Debug(" ----> running go %v", concatWithSpace(args...)) err := pipeFromExec(os.Stdout, "go", args...) if err != nil { log.Error("Couldn't get package: %v", err) return err } log.Debug(" ----> Successfully got package!") return nil } func linkCommandAction(c *cli.Context) error { pkgpath := projectFromURL(c.Args().First()) pkg := pkgFromPath(pkgpath) workspacepath := concat(WORKSPACE, "/", pkg) log.Info("Linking package %v to %v", pkgpath, workspacepath) fullpkgpath := getAbsPath(concat(GOPATH, "/src/", pkgpath)) fullworkspacepath := getAbsPath(workspacepath) // check if anything exists here if _, err := os.Stat(fullworkspacepath); !os.IsNotExist(err) { info, _ := os.Lstat(fullworkspacepath) if info.Mode()&os.ModeSymlink != 0 { if c.Bool("update") || c.Bool("force") { os.Remove(fullworkspacepath) } else { log.Warning("[WARNING]: Link already exists!") symlink, _ := filepath.EvalSymlinks(fullworkspacepath) log.Warning(" ----> %v -> %v", workspacepath, symlink) return errors.New("Link already exists") } } else if c.Bool("force") { log.Warning(" ----> removing %v", workspacepath) os.Remove(fullworkspacepath) } else { log.Error(" ----> [ERROR]: File/Folder already exists at %v, if you wish to proceed use -f", workspacepath) return errors.New("File/Folder already exists") } } cmd := exec.Command("ln", "-s", fullpkgpath, fullworkspacepath) log.Debug(" ----> running: %v", concat("ln", " -s", concat(" $GOPATH/src/", pkgpath), concat(" ", WORKSPACE, "/", pkg))) err := cmd.Run() if err != nil { log.Error("Failed to create link: %v", err) return err } log.Debug(" ----> Successfully linked!") return nil } func updateRemoteCommandAction(c *cli.Context) error { path := c.Args().First() pkgpath := projectFromURL(path) fullpkgpath := getAbsPath(concat(GOPATH, "/src/", pkgpath)) log.Info("Update remote origin URL for repo: %v", pkgpath) os.Chdir(fullpkgpath) cmd := exec.Command("git", "remote", "-v") log.Debug(" ----> running: git remote -v") var buf bytes.Buffer cmd.Stdout = &buf err := cmd.Run() if err != nil { log.Error("Couldn't update remote url: %v", err) return err } endpoints := strings.Split(buf.String(), "\n") var repo string for _, line := range endpoints { url, err := parseGitOriginURL(line) if err == nil { repo = url } } if repo == "" { log.Error("Couldn't parse git remote origin url") return errors.New("Couldn't parse git remote origin url") } user := c.String("ssh-user") newRepoURL := getSSHPath(repo, user) os.Chdir(fullpkgpath) cmd = exec.Command("git", "remote", "set-url", "origin", newRepoURL) log.Debug(" ----> running: git remote set-url origin %v", newRepoURL) err = cmd.Run() if err != nil { log.Error("Failed to update remote origin: %v", err) return err } log.Debug(" ----> Successfully updated remote origin") return nil }
package server import "github.com/labstack/echo" func RegisterController(name string, e *echo.Echo, m []echo.Middleware, config Config) { rc := ResourceController{name} rcBase := e.Group("/" + name) rcBase.Get("", rc.IndexHandler) rcBase.Post("", rc.CreateHandler) rcItem := rcBase.Group("/:id") rcItem.Get("", rc.ShowHandler) rcItem.Put("", rc.UpdateHandler) rcItem.Delete("", rc.DeleteHandler) if config.UseSmartAuth { m = append(m, SmartAuthHandler(name)) } if len(m) > 0 { rcBase.Use(m...) } } func RegisterRoutes(e *echo.Echo, config map[string][]echo.Middleware, serverConfig Config) { // Batch Support e.Post("/", BatchHandler) // Resource, useSmartAuths RegisterController("Appointment", e, config["Appointment"], serverConfig) RegisterController("ReferralRequest", e, config["ReferralRequest"], serverConfig) RegisterController("Account", e, config["Account"], serverConfig) RegisterController("Provenance", e, config["Provenance"], serverConfig) RegisterController("Questionnaire", e, config["Questionnaire"], serverConfig) RegisterController("ExplanationOfBenefit", e, config["ExplanationOfBenefit"], serverConfig) RegisterController("DocumentManifest", e, config["DocumentManifest"], serverConfig) RegisterController("Specimen", e, config["Specimen"], serverConfig) RegisterController("AllergyIntolerance", e, config["AllergyIntolerance"], serverConfig) RegisterController("CarePlan", e, config["CarePlan"], serverConfig) RegisterController("Goal", e, config["Goal"], serverConfig) RegisterController("StructureDefinition", e, config["StructureDefinition"], serverConfig) RegisterController("EnrollmentRequest", e, config["EnrollmentRequest"], serverConfig) RegisterController("EpisodeOfCare", e, config["EpisodeOfCare"], serverConfig) RegisterController("OperationOutcome", e, config["OperationOutcome"], serverConfig) RegisterController("Medication", e, config["Medication"], serverConfig) RegisterController("Procedure", e, config["Procedure"], serverConfig) RegisterController("List", e, config["List"], serverConfig) RegisterController("ConceptMap", e, config["ConceptMap"], serverConfig) RegisterController("Subscription", e, config["Subscription"], serverConfig) RegisterController("ValueSet", e, config["ValueSet"], serverConfig) RegisterController("OperationDefinition", e, config["OperationDefinition"], serverConfig) RegisterController("DocumentReference", e, config["DocumentReference"], serverConfig) RegisterController("Order", e, config["Order"], serverConfig) RegisterController("Immunization", e, config["Immunization"], serverConfig) RegisterController("Device", e, config["Device"], serverConfig) RegisterController("VisionPrescription", e, config["VisionPrescription"], serverConfig) RegisterController("Media", e, config["Media"], serverConfig) RegisterController("Conformance", e, config["Conformance"], serverConfig) RegisterController("ProcedureRequest", e, config["ProcedureRequest"], serverConfig) RegisterController("EligibilityResponse", e, config["EligibilityResponse"], serverConfig) RegisterController("DeviceUseRequest", e, config["DeviceUseRequest"], serverConfig) RegisterController("DeviceMetric", e, config["DeviceMetric"], serverConfig) RegisterController("Flag", e, config["Flag"], serverConfig) RegisterController("RelatedPerson", e, config["RelatedPerson"], serverConfig) RegisterController("SupplyRequest", e, config["SupplyRequest"], serverConfig) RegisterController("Practitioner", e, config["Practitioner"], serverConfig) RegisterController("AppointmentResponse", e, config["AppointmentResponse"], serverConfig) RegisterController("Observation", e, config["Observation"], serverConfig) RegisterController("MedicationAdministration", e, config["MedicationAdministration"], serverConfig) RegisterController("Slot", e, config["Slot"], serverConfig) RegisterController("EnrollmentResponse", e, config["EnrollmentResponse"], serverConfig) RegisterController("Binary", e, config["Binary"], serverConfig) RegisterController("MedicationStatement", e, config["MedicationStatement"], serverConfig) RegisterController("Person", e, config["Person"], serverConfig) RegisterController("Contract", e, config["Contract"], serverConfig) RegisterController("CommunicationRequest", e, config["CommunicationRequest"], serverConfig) RegisterController("RiskAssessment", e, config["RiskAssessment"], serverConfig) RegisterController("TestScript", e, config["TestScript"], serverConfig) RegisterController("Basic", e, config["Basic"], serverConfig) RegisterController("Group", e, config["Group"], serverConfig) RegisterController("PaymentNotice", e, config["PaymentNotice"], serverConfig) RegisterController("Organization", e, config["Organization"], serverConfig) RegisterController("ImplementationGuide", e, config["ImplementationGuide"], serverConfig) RegisterController("ClaimResponse", e, config["ClaimResponse"], serverConfig) RegisterController("EligibilityRequest", e, config["EligibilityRequest"], serverConfig) RegisterController("ProcessRequest", e, config["ProcessRequest"], serverConfig) RegisterController("MedicationDispense", e, config["MedicationDispense"], serverConfig) RegisterController("DiagnosticReport", e, config["DiagnosticReport"], serverConfig) RegisterController("ImagingStudy", e, config["ImagingStudy"], serverConfig) RegisterController("ImagingObjectSelection", e, config["ImagingObjectSelection"], serverConfig) RegisterController("HealthcareService", e, config["HealthcareService"], serverConfig) RegisterController("DataElement", e, config["DataElement"], serverConfig) RegisterController("DeviceComponent", e, config["DeviceComponent"], serverConfig) RegisterController("FamilyMemberHistory", e, config["FamilyMemberHistory"], serverConfig) RegisterController("NutritionOrder", e, config["NutritionOrder"], serverConfig) RegisterController("Encounter", e, config["Encounter"], serverConfig) RegisterController("Substance", e, config["Substance"], serverConfig) RegisterController("AuditEvent", e, config["AuditEvent"], serverConfig) RegisterController("MedicationOrder", e, config["MedicationOrder"], serverConfig) RegisterController("SearchParameter", e, config["SearchParameter"], serverConfig) RegisterController("PaymentReconciliation", e, config["PaymentReconciliation"], serverConfig) RegisterController("Communication", e, config["Communication"], serverConfig) RegisterController("Condition", e, config["Condition"], serverConfig) RegisterController("Composition", e, config["Composition"], serverConfig) RegisterController("DetectedIssue", e, config["DetectedIssue"], serverConfig) RegisterController("Bundle", e, config["Bundle"], serverConfig) RegisterController("DiagnosticOrder", e, config["DiagnosticOrder"], serverConfig) RegisterController("Patient", e, config["Patient"], serverConfig) RegisterController("OrderResponse", e, config["OrderResponse"], serverConfig) RegisterController("Coverage", e, config["Coverage"], serverConfig) RegisterController("QuestionnaireResponse", e, config["QuestionnaireResponse"], serverConfig) RegisterController("DeviceUseStatement", e, config["DeviceUseStatement"], serverConfig) RegisterController("ProcessResponse", e, config["ProcessResponse"], serverConfig) RegisterController("NamingSystem", e, config["NamingSystem"], serverConfig) RegisterController("Schedule", e, config["Schedule"], serverConfig) RegisterController("SupplyDelivery", e, config["SupplyDelivery"], serverConfig) RegisterController("ClinicalImpression", e, config["ClinicalImpression"], serverConfig) RegisterController("MessageHeader", e, config["MessageHeader"], serverConfig) RegisterController("Claim", e, config["Claim"], serverConfig) RegisterController("ImmunizationRecommendation", e, config["ImmunizationRecommendation"], serverConfig) RegisterController("Location", e, config["Location"], serverConfig) RegisterController("BodySite", e, config["BodySite"], serverConfig) } Fixing addition of SMART Auth Middleware No longer manipulating the middleware parameter that is passed in. Adding it after registered middleware so it will get invoked before them. package server import "github.com/labstack/echo" func RegisterController(name string, e *echo.Echo, m []echo.Middleware, config Config) { rc := ResourceController{name} rcBase := e.Group("/" + name) rcBase.Get("", rc.IndexHandler) rcBase.Post("", rc.CreateHandler) rcItem := rcBase.Group("/:id") rcItem.Get("", rc.ShowHandler) rcItem.Put("", rc.UpdateHandler) rcItem.Delete("", rc.DeleteHandler) if len(m) > 0 { rcBase.Use(m...) } if config.UseSmartAuth { rcBase.Use(SmartAuthHandler(name)) } } func RegisterRoutes(e *echo.Echo, config map[string][]echo.Middleware, serverConfig Config) { // Batch Support e.Post("/", BatchHandler) // Resource, useSmartAuths RegisterController("Appointment", e, config["Appointment"], serverConfig) RegisterController("ReferralRequest", e, config["ReferralRequest"], serverConfig) RegisterController("Account", e, config["Account"], serverConfig) RegisterController("Provenance", e, config["Provenance"], serverConfig) RegisterController("Questionnaire", e, config["Questionnaire"], serverConfig) RegisterController("ExplanationOfBenefit", e, config["ExplanationOfBenefit"], serverConfig) RegisterController("DocumentManifest", e, config["DocumentManifest"], serverConfig) RegisterController("Specimen", e, config["Specimen"], serverConfig) RegisterController("AllergyIntolerance", e, config["AllergyIntolerance"], serverConfig) RegisterController("CarePlan", e, config["CarePlan"], serverConfig) RegisterController("Goal", e, config["Goal"], serverConfig) RegisterController("StructureDefinition", e, config["StructureDefinition"], serverConfig) RegisterController("EnrollmentRequest", e, config["EnrollmentRequest"], serverConfig) RegisterController("EpisodeOfCare", e, config["EpisodeOfCare"], serverConfig) RegisterController("OperationOutcome", e, config["OperationOutcome"], serverConfig) RegisterController("Medication", e, config["Medication"], serverConfig) RegisterController("Procedure", e, config["Procedure"], serverConfig) RegisterController("List", e, config["List"], serverConfig) RegisterController("ConceptMap", e, config["ConceptMap"], serverConfig) RegisterController("Subscription", e, config["Subscription"], serverConfig) RegisterController("ValueSet", e, config["ValueSet"], serverConfig) RegisterController("OperationDefinition", e, config["OperationDefinition"], serverConfig) RegisterController("DocumentReference", e, config["DocumentReference"], serverConfig) RegisterController("Order", e, config["Order"], serverConfig) RegisterController("Immunization", e, config["Immunization"], serverConfig) RegisterController("Device", e, config["Device"], serverConfig) RegisterController("VisionPrescription", e, config["VisionPrescription"], serverConfig) RegisterController("Media", e, config["Media"], serverConfig) RegisterController("Conformance", e, config["Conformance"], serverConfig) RegisterController("ProcedureRequest", e, config["ProcedureRequest"], serverConfig) RegisterController("EligibilityResponse", e, config["EligibilityResponse"], serverConfig) RegisterController("DeviceUseRequest", e, config["DeviceUseRequest"], serverConfig) RegisterController("DeviceMetric", e, config["DeviceMetric"], serverConfig) RegisterController("Flag", e, config["Flag"], serverConfig) RegisterController("RelatedPerson", e, config["RelatedPerson"], serverConfig) RegisterController("SupplyRequest", e, config["SupplyRequest"], serverConfig) RegisterController("Practitioner", e, config["Practitioner"], serverConfig) RegisterController("AppointmentResponse", e, config["AppointmentResponse"], serverConfig) RegisterController("Observation", e, config["Observation"], serverConfig) RegisterController("MedicationAdministration", e, config["MedicationAdministration"], serverConfig) RegisterController("Slot", e, config["Slot"], serverConfig) RegisterController("EnrollmentResponse", e, config["EnrollmentResponse"], serverConfig) RegisterController("Binary", e, config["Binary"], serverConfig) RegisterController("MedicationStatement", e, config["MedicationStatement"], serverConfig) RegisterController("Person", e, config["Person"], serverConfig) RegisterController("Contract", e, config["Contract"], serverConfig) RegisterController("CommunicationRequest", e, config["CommunicationRequest"], serverConfig) RegisterController("RiskAssessment", e, config["RiskAssessment"], serverConfig) RegisterController("TestScript", e, config["TestScript"], serverConfig) RegisterController("Basic", e, config["Basic"], serverConfig) RegisterController("Group", e, config["Group"], serverConfig) RegisterController("PaymentNotice", e, config["PaymentNotice"], serverConfig) RegisterController("Organization", e, config["Organization"], serverConfig) RegisterController("ImplementationGuide", e, config["ImplementationGuide"], serverConfig) RegisterController("ClaimResponse", e, config["ClaimResponse"], serverConfig) RegisterController("EligibilityRequest", e, config["EligibilityRequest"], serverConfig) RegisterController("ProcessRequest", e, config["ProcessRequest"], serverConfig) RegisterController("MedicationDispense", e, config["MedicationDispense"], serverConfig) RegisterController("DiagnosticReport", e, config["DiagnosticReport"], serverConfig) RegisterController("ImagingStudy", e, config["ImagingStudy"], serverConfig) RegisterController("ImagingObjectSelection", e, config["ImagingObjectSelection"], serverConfig) RegisterController("HealthcareService", e, config["HealthcareService"], serverConfig) RegisterController("DataElement", e, config["DataElement"], serverConfig) RegisterController("DeviceComponent", e, config["DeviceComponent"], serverConfig) RegisterController("FamilyMemberHistory", e, config["FamilyMemberHistory"], serverConfig) RegisterController("NutritionOrder", e, config["NutritionOrder"], serverConfig) RegisterController("Encounter", e, config["Encounter"], serverConfig) RegisterController("Substance", e, config["Substance"], serverConfig) RegisterController("AuditEvent", e, config["AuditEvent"], serverConfig) RegisterController("MedicationOrder", e, config["MedicationOrder"], serverConfig) RegisterController("SearchParameter", e, config["SearchParameter"], serverConfig) RegisterController("PaymentReconciliation", e, config["PaymentReconciliation"], serverConfig) RegisterController("Communication", e, config["Communication"], serverConfig) RegisterController("Condition", e, config["Condition"], serverConfig) RegisterController("Composition", e, config["Composition"], serverConfig) RegisterController("DetectedIssue", e, config["DetectedIssue"], serverConfig) RegisterController("Bundle", e, config["Bundle"], serverConfig) RegisterController("DiagnosticOrder", e, config["DiagnosticOrder"], serverConfig) RegisterController("Patient", e, config["Patient"], serverConfig) RegisterController("OrderResponse", e, config["OrderResponse"], serverConfig) RegisterController("Coverage", e, config["Coverage"], serverConfig) RegisterController("QuestionnaireResponse", e, config["QuestionnaireResponse"], serverConfig) RegisterController("DeviceUseStatement", e, config["DeviceUseStatement"], serverConfig) RegisterController("ProcessResponse", e, config["ProcessResponse"], serverConfig) RegisterController("NamingSystem", e, config["NamingSystem"], serverConfig) RegisterController("Schedule", e, config["Schedule"], serverConfig) RegisterController("SupplyDelivery", e, config["SupplyDelivery"], serverConfig) RegisterController("ClinicalImpression", e, config["ClinicalImpression"], serverConfig) RegisterController("MessageHeader", e, config["MessageHeader"], serverConfig) RegisterController("Claim", e, config["Claim"], serverConfig) RegisterController("ImmunizationRecommendation", e, config["ImmunizationRecommendation"], serverConfig) RegisterController("Location", e, config["Location"], serverConfig) RegisterController("BodySite", e, config["BodySite"], serverConfig) }
package server import ( "fmt" "os" "path/filepath" pb "github.com/kubernetes/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "github.com/opencontainers/ocitools/generate" "golang.org/x/net/context" ) // Version returns the runtime name, runtime version and runtime API version func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { version, err := getGPRCVersion() if err != nil { return nil, err } runtimeVersion, err := s.runtime.Version() if err != nil { return nil, err } // taking const address rav := runtimeAPIVersion runtimeName := s.runtime.Name() return &pb.VersionResponse{ Version: &version, RuntimeName: &runtimeName, RuntimeVersion: &runtimeVersion, RuntimeApiVersion: &rav, }, nil } // CreatePodSandbox creates a pod-level sandbox. // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 func (s *Server) CreatePodSandbox(ctx context.Context, req *pb.CreatePodSandboxRequest) (*pb.CreatePodSandboxResponse, error) { var err error if err := os.MkdirAll(s.runtime.SandboxDir(), 0755); err != nil { return nil, err } // process req.Name name := req.GetConfig().GetName() if name == "" { return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty") } podSandboxDir := filepath.Join(s.runtime.SandboxDir(), name) if _, err := os.Stat(podSandboxDir); err == nil { return nil, fmt.Errorf("pod sandbox (%s) already exists", podSandboxDir) } if err := os.MkdirAll(podSandboxDir, 0755); err != nil { return nil, err } // creates a spec Generator with the default spec. g := generate.New() // process req.Hostname hostname := req.GetConfig().GetHostname() if hostname != "" { g.SetHostname(hostname) } // process req.LogDirectory logDir := req.GetConfig().GetLogDirectory() if logDir == "" { logDir = fmt.Sprintf("/var/log/ocid/pods/%s", name) } dnsServers := req.GetConfig().GetDnsOptions().GetServers() dnsSearches := req.GetConfig().GetDnsOptions().GetSearches() resolvPath := fmt.Sprintf("%s/resolv.conf", podSandboxDir) if err := parseDNSOptions(dnsServers, dnsSearches, resolvPath); err != nil { if err1 := removeFile(resolvPath); err1 != nil { return nil, fmt.Errorf("%v; failed to remove %s: %v", err, resolvPath, err1) } return nil, err } if err := g.AddBindMount(fmt.Sprintf("%s:/etc/resolv.conf", resolvPath)); err != nil { return nil, err } labels := req.GetConfig().GetLabels() s.sandboxes = append(s.sandboxes, &sandbox{ name: name, logDir: logDir, labels: labels, }) annotations := req.GetConfig().GetAnnotations() for k, v := range annotations { err := g.AddAnnotation(fmt.Sprintf("%s=%s", k, v)) if err != nil { return nil, err } } // TODO: double check cgroupParent. cgroupParent := req.GetConfig().GetLinux().GetCgroupParent() if cgroupParent != "" { g.SetLinuxCgroupsPath(cgroupParent) } // set up namespaces if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostNetwork() == false { err := g.AddOrReplaceLinuxNamespace("network", "") if err != nil { return nil, err } } if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostPid() == false { err := g.AddOrReplaceLinuxNamespace("pid", "") if err != nil { return nil, err } } if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostIpc() == false { err := g.AddOrReplaceLinuxNamespace("ipc", "") if err != nil { return nil, err } } err = g.SaveToFile(filepath.Join(podSandboxDir, "config.json")) if err != nil { return nil, err } return &pb.CreatePodSandboxResponse{PodSandboxId: &name}, nil } // StopPodSandbox stops the sandbox. If there are any running containers in the // sandbox, they should be force terminated. func (s *Server) StopPodSandbox(context.Context, *pb.StopPodSandboxRequest) (*pb.StopPodSandboxResponse, error) { return nil, nil } // DeletePodSandbox deletes the sandbox. If there are any running containers in the // sandbox, they should be force deleted. func (s *Server) DeletePodSandbox(context.Context, *pb.DeletePodSandboxRequest) (*pb.DeletePodSandboxResponse, error) { return nil, nil } // PodSandboxStatus returns the Status of the PodSandbox. func (s *Server) PodSandboxStatus(context.Context, *pb.PodSandboxStatusRequest) (*pb.PodSandboxStatusResponse, error) { return nil, nil } // ListPodSandbox returns a list of SandBox. func (s *Server) ListPodSandbox(context.Context, *pb.ListPodSandboxRequest) (*pb.ListPodSandboxResponse, error) { return nil, nil } // CreateContainer creates a new container in specified PodSandbox func (s *Server) CreateContainer(context.Context, *pb.CreateContainerRequest) (*pb.CreateContainerResponse, error) { return nil, nil } // StartContainer starts the container. func (s *Server) StartContainer(context.Context, *pb.StartContainerRequest) (*pb.StartContainerResponse, error) { return nil, nil } // StopContainer stops a running container with a grace period (i.e., timeout). func (s *Server) StopContainer(context.Context, *pb.StopContainerRequest) (*pb.StopContainerResponse, error) { return nil, nil } // RemoveContainer removes the container. If the container is running, the container // should be force removed. func (s *Server) RemoveContainer(context.Context, *pb.RemoveContainerRequest) (*pb.RemoveContainerResponse, error) { return nil, nil } // ListContainers lists all containers by filters. func (s *Server) ListContainers(context.Context, *pb.ListContainersRequest) (*pb.ListContainersResponse, error) { return nil, nil } // ContainerStatus returns status of the container. func (s *Server) ContainerStatus(context.Context, *pb.ContainerStatusRequest) (*pb.ContainerStatusResponse, error) { return nil, nil } // Exec executes the command in the container. func (s *Server) Exec(pb.RuntimeService_ExecServer) error { return nil } update generate functions Signed-off-by: Haiyan Meng <5733cbebbd61c8a953fb75d723ab54f442928cf2@redhat.com> package server import ( "fmt" "os" "path/filepath" pb "github.com/kubernetes/kubernetes/pkg/kubelet/api/v1alpha1/runtime" "github.com/opencontainers/ocitools/generate" "golang.org/x/net/context" ) // Version returns the runtime name, runtime version and runtime API version func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) { version, err := getGPRCVersion() if err != nil { return nil, err } runtimeVersion, err := s.runtime.Version() if err != nil { return nil, err } // taking const address rav := runtimeAPIVersion runtimeName := s.runtime.Name() return &pb.VersionResponse{ Version: &version, RuntimeName: &runtimeName, RuntimeVersion: &runtimeVersion, RuntimeApiVersion: &rav, }, nil } // CreatePodSandbox creates a pod-level sandbox. // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 func (s *Server) CreatePodSandbox(ctx context.Context, req *pb.CreatePodSandboxRequest) (*pb.CreatePodSandboxResponse, error) { var err error if err := os.MkdirAll(s.runtime.SandboxDir(), 0755); err != nil { return nil, err } // process req.Name name := req.GetConfig().GetName() if name == "" { return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty") } podSandboxDir := filepath.Join(s.runtime.SandboxDir(), name) if _, err := os.Stat(podSandboxDir); err == nil { return nil, fmt.Errorf("pod sandbox (%s) already exists", podSandboxDir) } if err := os.MkdirAll(podSandboxDir, 0755); err != nil { return nil, err } // creates a spec Generator with the default spec. g := generate.New() // process req.Hostname hostname := req.GetConfig().GetHostname() if hostname != "" { g.SetHostname(hostname) } // process req.LogDirectory logDir := req.GetConfig().GetLogDirectory() if logDir == "" { logDir = fmt.Sprintf("/var/log/ocid/pods/%s", name) } dnsServers := req.GetConfig().GetDnsOptions().GetServers() dnsSearches := req.GetConfig().GetDnsOptions().GetSearches() resolvPath := fmt.Sprintf("%s/resolv.conf", podSandboxDir) if err := parseDNSOptions(dnsServers, dnsSearches, resolvPath); err != nil { if err1 := removeFile(resolvPath); err1 != nil { return nil, fmt.Errorf("%v; failed to remove %s: %v", err, resolvPath, err1) } return nil, err } g.AddBindMount(resolvPath, "/etc/resolv.conf", "ro") labels := req.GetConfig().GetLabels() s.sandboxes = append(s.sandboxes, &sandbox{ name: name, logDir: logDir, labels: labels, }) annotations := req.GetConfig().GetAnnotations() for k, v := range annotations { g.AddAnnotation(k, v) } // TODO: double check cgroupParent. cgroupParent := req.GetConfig().GetLinux().GetCgroupParent() if cgroupParent != "" { g.SetLinuxCgroupsPath(cgroupParent) } // set up namespaces if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostNetwork() == false { err := g.AddOrReplaceLinuxNamespace("network", "") if err != nil { return nil, err } } if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostPid() == false { err := g.AddOrReplaceLinuxNamespace("pid", "") if err != nil { return nil, err } } if req.GetConfig().GetLinux().GetNamespaceOptions().GetHostIpc() == false { err := g.AddOrReplaceLinuxNamespace("ipc", "") if err != nil { return nil, err } } err = g.SaveToFile(filepath.Join(podSandboxDir, "config.json")) if err != nil { return nil, err } return &pb.CreatePodSandboxResponse{PodSandboxId: &name}, nil } // StopPodSandbox stops the sandbox. If there are any running containers in the // sandbox, they should be force terminated. func (s *Server) StopPodSandbox(context.Context, *pb.StopPodSandboxRequest) (*pb.StopPodSandboxResponse, error) { return nil, nil } // DeletePodSandbox deletes the sandbox. If there are any running containers in the // sandbox, they should be force deleted. func (s *Server) DeletePodSandbox(context.Context, *pb.DeletePodSandboxRequest) (*pb.DeletePodSandboxResponse, error) { return nil, nil } // PodSandboxStatus returns the Status of the PodSandbox. func (s *Server) PodSandboxStatus(context.Context, *pb.PodSandboxStatusRequest) (*pb.PodSandboxStatusResponse, error) { return nil, nil } // ListPodSandbox returns a list of SandBox. func (s *Server) ListPodSandbox(context.Context, *pb.ListPodSandboxRequest) (*pb.ListPodSandboxResponse, error) { return nil, nil } // CreateContainer creates a new container in specified PodSandbox func (s *Server) CreateContainer(context.Context, *pb.CreateContainerRequest) (*pb.CreateContainerResponse, error) { return nil, nil } // StartContainer starts the container. func (s *Server) StartContainer(context.Context, *pb.StartContainerRequest) (*pb.StartContainerResponse, error) { return nil, nil } // StopContainer stops a running container with a grace period (i.e., timeout). func (s *Server) StopContainer(context.Context, *pb.StopContainerRequest) (*pb.StopContainerResponse, error) { return nil, nil } // RemoveContainer removes the container. If the container is running, the container // should be force removed. func (s *Server) RemoveContainer(context.Context, *pb.RemoveContainerRequest) (*pb.RemoveContainerResponse, error) { return nil, nil } // ListContainers lists all containers by filters. func (s *Server) ListContainers(context.Context, *pb.ListContainersRequest) (*pb.ListContainersResponse, error) { return nil, nil } // ContainerStatus returns status of the container. func (s *Server) ContainerStatus(context.Context, *pb.ContainerStatusRequest) (*pb.ContainerStatusResponse, error) { return nil, nil } // Exec executes the command in the container. func (s *Server) Exec(pb.RuntimeService_ExecServer) error { return nil }
// Copyright 2011 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. // Reverse proxy tests. package httputil import ( "bufio" "bytes" "io" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "reflect" "strconv" "strings" "sync" "testing" "time" ) const fakeHopHeader = "X-Fake-Hop-Header-For-Test" func init() { hopHeaders = append(hopHeaders, fakeHopHeader) } func TestReverseProxy(t *testing.T) { const backendResponse = "I am the backend" const backendStatus = 404 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if len(r.TransferEncoding) > 0 { t.Errorf("backend got unexpected TransferEncoding: %v", r.TransferEncoding) } if r.Header.Get("X-Forwarded-For") == "" { t.Errorf("didn't get X-Forwarded-For header") } if c := r.Header.Get("Connection"); c != "" { t.Errorf("handler got Connection header value %q", c) } if c := r.Header.Get("Upgrade"); c != "" { t.Errorf("handler got Upgrade header value %q", c) } if c := r.Header.Get("Proxy-Connection"); c != "" { t.Errorf("handler got Proxy-Connection header value %q", c) } if g, e := r.Host, "some-name"; g != e { t.Errorf("backend got Host header %q, want %q", g, e) } w.Header().Set("Trailers", "not a special header field name") w.Header().Set("Trailer", "X-Trailer") w.Header().Set("X-Foo", "bar") w.Header().Set("Upgrade", "foo") w.Header().Set(fakeHopHeader, "foo") w.Header().Add("X-Multi-Value", "foo") w.Header().Add("X-Multi-Value", "bar") http.SetCookie(w, &http.Cookie{Name: "flavor", Value: "chocolateChip"}) w.WriteHeader(backendStatus) w.Write([]byte(backendResponse)) w.Header().Set("X-Trailer", "trailer_value") })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) getReq.Host = "some-name" getReq.Header.Set("Connection", "close") getReq.Header.Set("Proxy-Connection", "should be deleted") getReq.Header.Set("Upgrade", "foo") getReq.Close = true res, err := http.DefaultClient.Do(getReq) if err != nil { t.Fatalf("Get: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } if g, e := res.Header.Get("X-Foo"), "bar"; g != e { t.Errorf("got X-Foo %q; expected %q", g, e) } if c := res.Header.Get(fakeHopHeader); c != "" { t.Errorf("got %s header value %q", fakeHopHeader, c) } if g, e := res.Header.Get("Trailers"), "not a special header field name"; g != e { t.Errorf("header Trailers = %q; want %q", g, e) } if g, e := len(res.Header["X-Multi-Value"]), 2; g != e { t.Errorf("got %d X-Multi-Value header values; expected %d", g, e) } if g, e := len(res.Header["Set-Cookie"]), 1; g != e { t.Fatalf("got %d SetCookies, want %d", g, e) } if g, e := res.Trailer, (http.Header{"X-Trailer": nil}); !reflect.DeepEqual(g, e) { t.Errorf("before reading body, Trailer = %#v; want %#v", g, e) } if cookie := res.Cookies()[0]; cookie.Name != "flavor" { t.Errorf("unexpected cookie %q", cookie.Name) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } if g, e := res.Trailer.Get("X-Trailer"), "trailer_value"; g != e { t.Errorf("Trailer(X-Trailer) = %q ; want %q", g, e) } } func TestXForwardedFor(t *testing.T) { const prevForwardedFor = "client ip" const backendResponse = "I am the backend" const backendStatus = 404 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Forwarded-For") == "" { t.Errorf("didn't get X-Forwarded-For header") } if !strings.Contains(r.Header.Get("X-Forwarded-For"), prevForwardedFor) { t.Errorf("X-Forwarded-For didn't contain prior data") } w.WriteHeader(backendStatus) w.Write([]byte(backendResponse)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) getReq.Host = "some-name" getReq.Header.Set("Connection", "close") getReq.Header.Set("X-Forwarded-For", prevForwardedFor) getReq.Close = true res, err := http.DefaultClient.Do(getReq) if err != nil { t.Fatalf("Get: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } } var proxyQueryTests = []struct { baseSuffix string // suffix to add to backend URL reqSuffix string // suffix to add to frontend's request URL want string // what backend should see for final request URL (without ?) }{ {"", "", ""}, {"?sta=tic", "?us=er", "sta=tic&us=er"}, {"", "?us=er", "us=er"}, {"?sta=tic", "", "sta=tic"}, } func TestReverseProxyQuery(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Got-Query", r.URL.RawQuery) w.Write([]byte("hi")) })) defer backend.Close() for i, tt := range proxyQueryTests { backendURL, err := url.Parse(backend.URL + tt.baseSuffix) if err != nil { t.Fatal(err) } frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL)) req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("%d. Get: %v", i, err) } if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e { t.Errorf("%d. got query %q; expected %q", i, g, e) } res.Body.Close() frontend.Close() } } func TestReverseProxyFlushInterval(t *testing.T) { const expected = "hi" backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(expected)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) proxyHandler.FlushInterval = time.Microsecond done := make(chan bool) onExitFlushLoop = func() { done <- true } defer func() { onExitFlushLoop = nil }() frontend := httptest.NewServer(proxyHandler) defer frontend.Close() req, _ := http.NewRequest("GET", frontend.URL, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("Get: %v", err) } defer res.Body.Close() if bodyBytes, _ := ioutil.ReadAll(res.Body); string(bodyBytes) != expected { t.Errorf("got body %q; expected %q", bodyBytes, expected) } select { case <-done: // OK case <-time.After(5 * time.Second): t.Error("maxLatencyWriter flushLoop() never exited") } } func TestReverseProxyCancelation(t *testing.T) { const backendResponse = "I am the backend" reqInFlight := make(chan struct{}) backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(reqInFlight) select { case <-time.After(10 * time.Second): // Note: this should only happen in broken implementations, and the // closenotify case should be instantaneous. t.Log("Failed to close backend connection") t.Fail() case <-w.(http.CloseNotifier).CloseNotify(): } w.WriteHeader(http.StatusOK) w.Write([]byte(backendResponse)) })) defer backend.Close() backend.Config.ErrorLog = log.New(ioutil.Discard, "", 0) backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) // Discards errors of the form: // http: proxy error: read tcp 127.0.0.1:44643: use of closed network connection proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) go func() { <-reqInFlight http.DefaultTransport.(*http.Transport).CancelRequest(getReq) }() res, err := http.DefaultClient.Do(getReq) if res != nil { t.Fatal("Non-nil response") } if err == nil { // This should be an error like: // Get http://127.0.0.1:58079: read tcp 127.0.0.1:58079: // use of closed network connection t.Fatal("DefaultClient.Do() returned nil error") } } func req(t *testing.T, v string) *http.Request { req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(v))) if err != nil { t.Fatal(err) } return req } // Issue 12344 func TestNilBody(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) })) defer backend.Close() frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { backURL, _ := url.Parse(backend.URL) rp := NewSingleHostReverseProxy(backURL) r := req(t, "GET / HTTP/1.0\r\n\r\n") r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working rp.ServeHTTP(w, r) })) defer frontend.Close() res, err := http.Get(frontend.URL) if err != nil { t.Fatal(err) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if string(slurp) != "hi" { t.Errorf("Got %q; want %q", slurp, "hi") } } type bufferPool struct { get func() []byte put func([]byte) } func (bp bufferPool) Get() []byte { return bp.get() } func (bp bufferPool) Put(v []byte) { bp.put(v) } func TestReverseProxyGetPutBuffer(t *testing.T) { const msg = "hi" backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } var ( mu sync.Mutex log []string ) addLog := func(event string) { mu.Lock() defer mu.Unlock() log = append(log, event) } rp := NewSingleHostReverseProxy(backendURL) const size = 1234 rp.BufferPool = bufferPool{ get: func() []byte { addLog("getBuf") return make([]byte, size) }, put: func(p []byte) { addLog("putBuf-" + strconv.Itoa(len(p))) }, } frontend := httptest.NewServer(rp) defer frontend.Close() req, _ := http.NewRequest("GET", frontend.URL, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("Get: %v", err) } slurp, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatalf("reading body: %v", err) } if string(slurp) != msg { t.Errorf("msg = %q; want %q", slurp, msg) } wantLog := []string{"getBuf", "putBuf-" + strconv.Itoa(size)} mu.Lock() defer mu.Unlock() if !reflect.DeepEqual(log, wantLog) { t.Errorf("Log events = %q; want %q", log, wantLog) } } func TestReverseProxy_Post(t *testing.T) { const backendResponse = "I am the backend" const backendStatus = 200 var requestBody = bytes.Repeat([]byte("a"), 1<<20) backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { slurp, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Backend body read = %v", err) } if len(slurp) != len(requestBody) { t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody)) } if !bytes.Equal(slurp, requestBody) { t.Error("Backend read wrong request body.") // 1MB; omitting details } w.Write([]byte(backendResponse)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() postReq, _ := http.NewRequest("POST", frontend.URL, bytes.NewReader(requestBody)) res, err := http.DefaultClient.Do(postReq) if err != nil { t.Fatalf("Do: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } } func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy { targetQuery := target.RawQuery director := func(res http.ResponseWriter, req *http.Request) error { req.URL.Scheme = target.Scheme req.URL.Host = target.Host req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path) if targetQuery == "" || req.URL.RawQuery == "" { req.URL.RawQuery = targetQuery + req.URL.RawQuery } else { req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery } return nil } return &ReverseProxy{Proxy: director} } httputil: drop unsupported nil body test // Copyright 2011 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. // Reverse proxy tests. package httputil import ( "bufio" "bytes" "io" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "reflect" "strconv" "strings" "sync" "testing" "time" ) const fakeHopHeader = "X-Fake-Hop-Header-For-Test" func init() { hopHeaders = append(hopHeaders, fakeHopHeader) } func TestReverseProxy(t *testing.T) { const backendResponse = "I am the backend" const backendStatus = 404 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if len(r.TransferEncoding) > 0 { t.Errorf("backend got unexpected TransferEncoding: %v", r.TransferEncoding) } if r.Header.Get("X-Forwarded-For") == "" { t.Errorf("didn't get X-Forwarded-For header") } if c := r.Header.Get("Connection"); c != "" { t.Errorf("handler got Connection header value %q", c) } if c := r.Header.Get("Upgrade"); c != "" { t.Errorf("handler got Upgrade header value %q", c) } if c := r.Header.Get("Proxy-Connection"); c != "" { t.Errorf("handler got Proxy-Connection header value %q", c) } if g, e := r.Host, "some-name"; g != e { t.Errorf("backend got Host header %q, want %q", g, e) } w.Header().Set("Trailers", "not a special header field name") w.Header().Set("Trailer", "X-Trailer") w.Header().Set("X-Foo", "bar") w.Header().Set("Upgrade", "foo") w.Header().Set(fakeHopHeader, "foo") w.Header().Add("X-Multi-Value", "foo") w.Header().Add("X-Multi-Value", "bar") http.SetCookie(w, &http.Cookie{Name: "flavor", Value: "chocolateChip"}) w.WriteHeader(backendStatus) w.Write([]byte(backendResponse)) w.Header().Set("X-Trailer", "trailer_value") })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) getReq.Host = "some-name" getReq.Header.Set("Connection", "close") getReq.Header.Set("Proxy-Connection", "should be deleted") getReq.Header.Set("Upgrade", "foo") getReq.Close = true res, err := http.DefaultClient.Do(getReq) if err != nil { t.Fatalf("Get: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } if g, e := res.Header.Get("X-Foo"), "bar"; g != e { t.Errorf("got X-Foo %q; expected %q", g, e) } if c := res.Header.Get(fakeHopHeader); c != "" { t.Errorf("got %s header value %q", fakeHopHeader, c) } if g, e := res.Header.Get("Trailers"), "not a special header field name"; g != e { t.Errorf("header Trailers = %q; want %q", g, e) } if g, e := len(res.Header["X-Multi-Value"]), 2; g != e { t.Errorf("got %d X-Multi-Value header values; expected %d", g, e) } if g, e := len(res.Header["Set-Cookie"]), 1; g != e { t.Fatalf("got %d SetCookies, want %d", g, e) } if g, e := res.Trailer, (http.Header{"X-Trailer": nil}); !reflect.DeepEqual(g, e) { t.Errorf("before reading body, Trailer = %#v; want %#v", g, e) } if cookie := res.Cookies()[0]; cookie.Name != "flavor" { t.Errorf("unexpected cookie %q", cookie.Name) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } if g, e := res.Trailer.Get("X-Trailer"), "trailer_value"; g != e { t.Errorf("Trailer(X-Trailer) = %q ; want %q", g, e) } } func TestXForwardedFor(t *testing.T) { const prevForwardedFor = "client ip" const backendResponse = "I am the backend" const backendStatus = 404 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Forwarded-For") == "" { t.Errorf("didn't get X-Forwarded-For header") } if !strings.Contains(r.Header.Get("X-Forwarded-For"), prevForwardedFor) { t.Errorf("X-Forwarded-For didn't contain prior data") } w.WriteHeader(backendStatus) w.Write([]byte(backendResponse)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) getReq.Host = "some-name" getReq.Header.Set("Connection", "close") getReq.Header.Set("X-Forwarded-For", prevForwardedFor) getReq.Close = true res, err := http.DefaultClient.Do(getReq) if err != nil { t.Fatalf("Get: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } } var proxyQueryTests = []struct { baseSuffix string // suffix to add to backend URL reqSuffix string // suffix to add to frontend's request URL want string // what backend should see for final request URL (without ?) }{ {"", "", ""}, {"?sta=tic", "?us=er", "sta=tic&us=er"}, {"", "?us=er", "us=er"}, {"?sta=tic", "", "sta=tic"}, } func TestReverseProxyQuery(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Got-Query", r.URL.RawQuery) w.Write([]byte("hi")) })) defer backend.Close() for i, tt := range proxyQueryTests { backendURL, err := url.Parse(backend.URL + tt.baseSuffix) if err != nil { t.Fatal(err) } frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL)) req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("%d. Get: %v", i, err) } if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e { t.Errorf("%d. got query %q; expected %q", i, g, e) } res.Body.Close() frontend.Close() } } func TestReverseProxyFlushInterval(t *testing.T) { const expected = "hi" backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(expected)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) proxyHandler.FlushInterval = time.Microsecond done := make(chan bool) onExitFlushLoop = func() { done <- true } defer func() { onExitFlushLoop = nil }() frontend := httptest.NewServer(proxyHandler) defer frontend.Close() req, _ := http.NewRequest("GET", frontend.URL, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("Get: %v", err) } defer res.Body.Close() if bodyBytes, _ := ioutil.ReadAll(res.Body); string(bodyBytes) != expected { t.Errorf("got body %q; expected %q", bodyBytes, expected) } select { case <-done: // OK case <-time.After(5 * time.Second): t.Error("maxLatencyWriter flushLoop() never exited") } } func TestReverseProxyCancelation(t *testing.T) { const backendResponse = "I am the backend" reqInFlight := make(chan struct{}) backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(reqInFlight) select { case <-time.After(10 * time.Second): // Note: this should only happen in broken implementations, and the // closenotify case should be instantaneous. t.Log("Failed to close backend connection") t.Fail() case <-w.(http.CloseNotifier).CloseNotify(): } w.WriteHeader(http.StatusOK) w.Write([]byte(backendResponse)) })) defer backend.Close() backend.Config.ErrorLog = log.New(ioutil.Discard, "", 0) backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) // Discards errors of the form: // http: proxy error: read tcp 127.0.0.1:44643: use of closed network connection proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) go func() { <-reqInFlight http.DefaultTransport.(*http.Transport).CancelRequest(getReq) }() res, err := http.DefaultClient.Do(getReq) if res != nil { t.Fatal("Non-nil response") } if err == nil { // This should be an error like: // Get http://127.0.0.1:58079: read tcp 127.0.0.1:58079: // use of closed network connection t.Fatal("DefaultClient.Do() returned nil error") } } func req(t *testing.T, v string) *http.Request { req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(v))) if err != nil { t.Fatal(err) } return req } type bufferPool struct { get func() []byte put func([]byte) } func (bp bufferPool) Get() []byte { return bp.get() } func (bp bufferPool) Put(v []byte) { bp.put(v) } func TestReverseProxyGetPutBuffer(t *testing.T) { const msg = "hi" backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } var ( mu sync.Mutex log []string ) addLog := func(event string) { mu.Lock() defer mu.Unlock() log = append(log, event) } rp := NewSingleHostReverseProxy(backendURL) const size = 1234 rp.BufferPool = bufferPool{ get: func() []byte { addLog("getBuf") return make([]byte, size) }, put: func(p []byte) { addLog("putBuf-" + strconv.Itoa(len(p))) }, } frontend := httptest.NewServer(rp) defer frontend.Close() req, _ := http.NewRequest("GET", frontend.URL, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("Get: %v", err) } slurp, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatalf("reading body: %v", err) } if string(slurp) != msg { t.Errorf("msg = %q; want %q", slurp, msg) } wantLog := []string{"getBuf", "putBuf-" + strconv.Itoa(size)} mu.Lock() defer mu.Unlock() if !reflect.DeepEqual(log, wantLog) { t.Errorf("Log events = %q; want %q", log, wantLog) } } func TestReverseProxy_Post(t *testing.T) { const backendResponse = "I am the backend" const backendStatus = 200 var requestBody = bytes.Repeat([]byte("a"), 1<<20) backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { slurp, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Backend body read = %v", err) } if len(slurp) != len(requestBody) { t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody)) } if !bytes.Equal(slurp, requestBody) { t.Error("Backend read wrong request body.") // 1MB; omitting details } w.Write([]byte(backendResponse)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) if err != nil { t.Fatal(err) } proxyHandler := NewSingleHostReverseProxy(backendURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() postReq, _ := http.NewRequest("POST", frontend.URL, bytes.NewReader(requestBody)) res, err := http.DefaultClient.Do(postReq) if err != nil { t.Fatalf("Do: %v", err) } if g, e := res.StatusCode, backendStatus; g != e { t.Errorf("got res.StatusCode %d; expected %d", g, e) } bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendResponse; g != e { t.Errorf("got body %q; expected %q", g, e) } } func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy { targetQuery := target.RawQuery director := func(res http.ResponseWriter, req *http.Request) error { req.URL.Scheme = target.Scheme req.URL.Host = target.Host req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path) if targetQuery == "" || req.URL.RawQuery == "" { req.URL.RawQuery = targetQuery + req.URL.RawQuery } else { req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery } return nil } return &ReverseProxy{Proxy: director} }
package jsonHttp import "net/http" import "encoding/json" // ResponseJSON write marshalled obj to http.ResponseWriter with correct header func ResponseJSON(w http.ResponseWriter, obj interface{}) { objJSON, err := json.Marshal(obj) if err == nil { w.Header().Set(`Content-Type`, `application/json`) w.Header().Set(`Cache-Control`, `no-cache`) w.Header().Set(`Access-Control-Allow-Origin`, `*`) w.Write(objJSON) } else { http.Error(w, `Error while marshalling JSON response`, 500) } } Update json.go package jsonHttp import "net/http" import "encoding/json" // ResponseJSON write marshalled obj to http.ResponseWriter with correct header func ResponseJSON(w http.ResponseWriter, obj interface{}) { objJSON, err := json.Marshal(obj) if err == nil { w.Header().Set(`Content-Type`, `application/json`) w.Header().Set(`Cache-Control`, `no-cache`) w.Header().Set(`Access-Control-Allow-Origin`, `*`) w.Write(objJSON) } else { http.Error(w, `Error while marshalling JSON response`, http.StatusInternalServerError) } }
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. /* Package jsonpb provides marshalling/unmarshalling functionality between protocol buffer and JSON objects. Compared to encoding/json, this library: - encodes int64, uint64 as strings - optionally encodes enums as strings */ package jsonpb import ( "bytes" "encoding/json" "fmt" "io" "reflect" "sort" "strconv" "strings" "github.com/golang/protobuf/proto" ) var ( byteArrayType = reflect.TypeOf([]byte{}) ) // Marshaller is a configurable object for converting between // protocol buffer objects and a JSON representation for them type Marshaller struct { // Use string values for enums (as opposed to integer values) EnumsAsString bool // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to be appear between fields and array // elements. Indent string } // Marshal marshals a protocol buffer into JSON. func (m *Marshaller) Marshal(out io.Writer, pb proto.Message) error { writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "") } // MarshalToString converts a protocol buffer object to JSON string. func (m *Marshaller) MarshalToString(pb proto.Message) (string, error) { var buf bytes.Buffer if err := m.Marshal(&buf, pb); err != nil { return "", err } return buf.String(), nil } // marshalObject writes a struct to the Writer. func (m *Marshaller) marshalObject(out *errWriter, v proto.Message, indent string) error { out.write("{") if m.Indent != "" { out.write("\n") } s := reflect.ValueOf(v).Elem() writeBeforeField := "" for i := 0; i < s.NumField(); i++ { value := s.Field(i) valueField := s.Type().Field(i) fieldName, omitFieldIfNil := parseFieldOptions(valueField) // Fields which should not be serialized will specify a json tag with '-' // TODO: proto3 objects should have default values omitted. if fieldName == "-" { continue } else if omitFieldIfNil { // IsNil will panic on most value kinds. skip := false switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: skip = value.IsNil() } if skip { continue } } out.write(writeBeforeField) if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"`) out.write(fieldName) out.write(`":`) if m.Indent != "" { out.write(" ") } if err := m.marshalValue(out, value, valueField, indent); err != nil { return err } if m.Indent != "" { writeBeforeField = ",\n" } else { writeBeforeField = "," } } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } // marshalValue writes the value to the Writer. func (m *Marshaller) marshalValue(out *errWriter, v reflect.Value, structField reflect.StructField, indent string) error { var err error v = reflect.Indirect(v) // Handle repeated elements. if v.Type() != byteArrayType && v.Kind() == reflect.Slice { out.write("[") comma := "" for i := 0; i < v.Len(); i++ { sliceVal := v.Index(i) out.write(comma) if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } m.marshalValue(out, sliceVal, structField, indent+m.Indent) comma = "," } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write("]") return out.err } // Handle enumerations. protoInfo := structField.Tag.Get("protobuf") if m.EnumsAsString && strings.Contains(protoInfo, ",enum=") { // Unknown enum values will are stringified by the proto library as their // value. Such values should _not_ be quoted or they will be intrepreted // as an enum string instead of their value. enumStr := v.Interface().(fmt.Stringer).String() var valStr string if v.Kind() == reflect.Ptr { valStr = strconv.Itoa(int(v.Elem().Int())) } else { valStr = strconv.Itoa(int(v.Int())) } isKnownEnum := enumStr != valStr if isKnownEnum { out.write(`"`) } out.write(enumStr) if isKnownEnum { out.write(`"`) } return out.err } // Handle nested messages. if v.Kind() == reflect.Struct { return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent) } // Handle maps. // Since Go randomizes map iteration, we sort keys for stable output. if v.Kind() == reflect.Map { out.write(`{`) keys := v.MapKeys() sort.Sort(mapKeys(keys)) for i, k := range keys { if i > 0 { out.write(`,`) } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } b, err := json.Marshal(k.Interface()) if err != nil { return err } s := string(b) // If the JSON is not a string value, encode it again to make it one. if !strings.HasPrefix(s, `"`) { b, err := json.Marshal(s) if err != nil { return err } s = string(b) } out.write(s) out.write(`:`) if m.Indent != "" { out.write(` `) } if err := m.marshalValue(out, v.MapIndex(k), structField, indent+m.Indent); err != nil { return err } } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write(`}`) return out.err } // Default handling defers to the encoding/json library. b, err := json.Marshal(v.Interface()) if err != nil { return err } needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) if needToQuote { out.write(`"`) } out.write(string(b)) if needToQuote { out.write(`"`) } return out.err } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaller. func Unmarshal(r io.Reader, pb proto.Message) error { inputValue := json.RawMessage{} if err := json.NewDecoder(r).Decode(&inputValue); err != nil { return err } return unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue) } // UnmarshalString will populate the fields of a protocol buffer based // on a JSON string. This function is lenient and will decode any options // permutations of the related Marshaller. func UnmarshalString(str string, pb proto.Message) error { return Unmarshal(bytes.NewReader([]byte(str)), pb) } // unmarshalValue converts/copies a value into the target. func unmarshalValue(target reflect.Value, inputValue json.RawMessage) error { targetType := target.Type() // Allocate memory for pointer fields. if targetType.Kind() == reflect.Ptr { target.Set(reflect.New(targetType.Elem())) return unmarshalValue(target.Elem(), inputValue) } // Handle nested messages. if targetType.Kind() == reflect.Struct { var jsonFields map[string]json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } for i := 0; i < target.NumField(); i++ { fieldName, _ := parseFieldOptions(target.Type().Field(i)) // Fields which should not be serialized will specify a json tag with '-' if fieldName == "-" { continue } if valueForField, ok := jsonFields[fieldName]; ok { if err := unmarshalValue(target.Field(i), valueForField); err != nil { return err } delete(jsonFields, fieldName) } } if len(jsonFields) > 0 { // Pick any field to be the scapegoat. var f string for fname := range jsonFields { f = fname break } return fmt.Errorf("unknown field %q in %v", f, targetType) } return nil } // Handle arrays (which aren't encoded bytes) if targetType != byteArrayType && targetType.Kind() == reflect.Slice { var slc []json.RawMessage if err := json.Unmarshal(inputValue, &slc); err != nil { return err } len := len(slc) target.Set(reflect.MakeSlice(targetType, len, len)) for i := 0; i < len; i++ { if err := unmarshalValue(target.Index(i), slc[i]); err != nil { return err } } return nil } // Handle maps (whose keys are always strings) if targetType.Kind() == reflect.Map { var mp map[string]json.RawMessage if err := json.Unmarshal(inputValue, &mp); err != nil { return err } target.Set(reflect.MakeMap(targetType)) for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. var k reflect.Value if targetType.Key().Kind() == reflect.String { k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() if err := unmarshalValue(k, json.RawMessage(ks)); err != nil { return err } } // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() if err := unmarshalValue(v, raw); err != nil { return err } target.SetMapIndex(k, v) } return nil } // 64-bit integers can be encoded as strings. In this case we drop // the quotes and proceed as normal. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 if isNum && strings.HasPrefix(string(inputValue), `"`) { inputValue = inputValue[1 : len(inputValue)-1] } // Use the encoding/json for parsing other value types. return json.Unmarshal(inputValue, target.Addr().Interface()) } // hasUnmarshalJSON is a interface implemented by protocol buffer enums. type hasUnmarshalJSON interface { UnmarshalJSON(data []byte) error } // parseFieldOptions returns the field name and if it should be omited. func parseFieldOptions(f reflect.StructField) (string, bool) { // TODO: Do this without using the "json" field tag. name := f.Name omitEmpty := false tag := f.Tag.Get("json") tagParts := strings.Split(tag, ",") for i := range tagParts { if tagParts[i] == "omitempty" || tagParts[i] == "" { omitEmpty = true } else { name = tagParts[i] } } return name, omitEmpty } // Writer wrapper inspired by https://blog.golang.org/errors-are-values type errWriter struct { writer io.Writer err error } func (w *errWriter) write(str string) { if w.err != nil { return } _, w.err = w.writer.Write([]byte(str)) } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. type mapKeys []reflect.Value func (s mapKeys) Len() int { return len(s) } func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s mapKeys) Less(i, j int) bool { return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) } jsonpb: Simplify JSON field name selection. Remove dependence on the "json" field tag. // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. /* Package jsonpb provides marshalling/unmarshalling functionality between protocol buffer and JSON objects. Compared to encoding/json, this library: - encodes int64, uint64 as strings - optionally encodes enums as strings */ package jsonpb import ( "bytes" "encoding/json" "fmt" "io" "reflect" "sort" "strconv" "strings" "github.com/golang/protobuf/proto" ) var ( byteArrayType = reflect.TypeOf([]byte{}) ) // Marshaller is a configurable object for converting between // protocol buffer objects and a JSON representation for them type Marshaller struct { // Use string values for enums (as opposed to integer values) EnumsAsString bool // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to be appear between fields and array // elements. Indent string } // Marshal marshals a protocol buffer into JSON. func (m *Marshaller) Marshal(out io.Writer, pb proto.Message) error { writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "") } // MarshalToString converts a protocol buffer object to JSON string. func (m *Marshaller) MarshalToString(pb proto.Message) (string, error) { var buf bytes.Buffer if err := m.Marshal(&buf, pb); err != nil { return "", err } return buf.String(), nil } // marshalObject writes a struct to the Writer. func (m *Marshaller) marshalObject(out *errWriter, v proto.Message, indent string) error { out.write("{") if m.Indent != "" { out.write("\n") } s := reflect.ValueOf(v).Elem() writeBeforeField := "" for i := 0; i < s.NumField(); i++ { value := s.Field(i) valueField := s.Type().Field(i) if strings.HasPrefix(valueField.Name, "XXX_") { continue } fieldName := jsonFieldName(valueField) // TODO: proto3 objects should have default values omitted. // IsNil will panic on most value kinds. switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: if value.IsNil() { continue } } out.write(writeBeforeField) if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"`) out.write(fieldName) out.write(`":`) if m.Indent != "" { out.write(" ") } if err := m.marshalValue(out, value, valueField, indent); err != nil { return err } if m.Indent != "" { writeBeforeField = ",\n" } else { writeBeforeField = "," } } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } // marshalValue writes the value to the Writer. func (m *Marshaller) marshalValue(out *errWriter, v reflect.Value, structField reflect.StructField, indent string) error { var err error v = reflect.Indirect(v) // Handle repeated elements. if v.Type() != byteArrayType && v.Kind() == reflect.Slice { out.write("[") comma := "" for i := 0; i < v.Len(); i++ { sliceVal := v.Index(i) out.write(comma) if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } m.marshalValue(out, sliceVal, structField, indent+m.Indent) comma = "," } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write("]") return out.err } // Handle enumerations. protoInfo := structField.Tag.Get("protobuf") if m.EnumsAsString && strings.Contains(protoInfo, ",enum=") { // Unknown enum values will are stringified by the proto library as their // value. Such values should _not_ be quoted or they will be intrepreted // as an enum string instead of their value. enumStr := v.Interface().(fmt.Stringer).String() var valStr string if v.Kind() == reflect.Ptr { valStr = strconv.Itoa(int(v.Elem().Int())) } else { valStr = strconv.Itoa(int(v.Int())) } isKnownEnum := enumStr != valStr if isKnownEnum { out.write(`"`) } out.write(enumStr) if isKnownEnum { out.write(`"`) } return out.err } // Handle nested messages. if v.Kind() == reflect.Struct { return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent) } // Handle maps. // Since Go randomizes map iteration, we sort keys for stable output. if v.Kind() == reflect.Map { out.write(`{`) keys := v.MapKeys() sort.Sort(mapKeys(keys)) for i, k := range keys { if i > 0 { out.write(`,`) } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } b, err := json.Marshal(k.Interface()) if err != nil { return err } s := string(b) // If the JSON is not a string value, encode it again to make it one. if !strings.HasPrefix(s, `"`) { b, err := json.Marshal(s) if err != nil { return err } s = string(b) } out.write(s) out.write(`:`) if m.Indent != "" { out.write(` `) } if err := m.marshalValue(out, v.MapIndex(k), structField, indent+m.Indent); err != nil { return err } } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write(`}`) return out.err } // Default handling defers to the encoding/json library. b, err := json.Marshal(v.Interface()) if err != nil { return err } needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) if needToQuote { out.write(`"`) } out.write(string(b)) if needToQuote { out.write(`"`) } return out.err } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaller. func Unmarshal(r io.Reader, pb proto.Message) error { inputValue := json.RawMessage{} if err := json.NewDecoder(r).Decode(&inputValue); err != nil { return err } return unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue) } // UnmarshalString will populate the fields of a protocol buffer based // on a JSON string. This function is lenient and will decode any options // permutations of the related Marshaller. func UnmarshalString(str string, pb proto.Message) error { return Unmarshal(bytes.NewReader([]byte(str)), pb) } // unmarshalValue converts/copies a value into the target. func unmarshalValue(target reflect.Value, inputValue json.RawMessage) error { targetType := target.Type() // Allocate memory for pointer fields. if targetType.Kind() == reflect.Ptr { target.Set(reflect.New(targetType.Elem())) return unmarshalValue(target.Elem(), inputValue) } // Handle nested messages. if targetType.Kind() == reflect.Struct { var jsonFields map[string]json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } for i := 0; i < target.NumField(); i++ { ft := target.Type().Field(i) if strings.HasPrefix(ft.Name, "XXX_") { continue } fieldName := jsonFieldName(ft) if valueForField, ok := jsonFields[fieldName]; ok { if err := unmarshalValue(target.Field(i), valueForField); err != nil { return err } delete(jsonFields, fieldName) } } if len(jsonFields) > 0 { // Pick any field to be the scapegoat. var f string for fname := range jsonFields { f = fname break } return fmt.Errorf("unknown field %q in %v", f, targetType) } return nil } // Handle arrays (which aren't encoded bytes) if targetType != byteArrayType && targetType.Kind() == reflect.Slice { var slc []json.RawMessage if err := json.Unmarshal(inputValue, &slc); err != nil { return err } len := len(slc) target.Set(reflect.MakeSlice(targetType, len, len)) for i := 0; i < len; i++ { if err := unmarshalValue(target.Index(i), slc[i]); err != nil { return err } } return nil } // Handle maps (whose keys are always strings) if targetType.Kind() == reflect.Map { var mp map[string]json.RawMessage if err := json.Unmarshal(inputValue, &mp); err != nil { return err } target.Set(reflect.MakeMap(targetType)) for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. var k reflect.Value if targetType.Key().Kind() == reflect.String { k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() if err := unmarshalValue(k, json.RawMessage(ks)); err != nil { return err } } // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() if err := unmarshalValue(v, raw); err != nil { return err } target.SetMapIndex(k, v) } return nil } // 64-bit integers can be encoded as strings. In this case we drop // the quotes and proceed as normal. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 if isNum && strings.HasPrefix(string(inputValue), `"`) { inputValue = inputValue[1 : len(inputValue)-1] } // Use the encoding/json for parsing other value types. return json.Unmarshal(inputValue, target.Addr().Interface()) } // hasUnmarshalJSON is a interface implemented by protocol buffer enums. type hasUnmarshalJSON interface { UnmarshalJSON(data []byte) error } // jsonFieldName returns the field name to use. func jsonFieldName(f reflect.StructField) string { var prop proto.Properties prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) return prop.OrigName } // Writer wrapper inspired by https://blog.golang.org/errors-are-values type errWriter struct { writer io.Writer err error } func (w *errWriter) write(str string) { if w.err != nil { return } _, w.err = w.writer.Write([]byte(str)) } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. type mapKeys []reflect.Value func (s mapKeys) Len() int { return len(s) } func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s mapKeys) Less(i, j int) bool { return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) }
// Copyright 2009 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 testing import ( "flag" "fmt" "os" "runtime" "sync" "sync/atomic" "time" ) var matchBenchmarks = flag.String("test.bench", "", "regular expression to select benchmarks to run") var benchTime = flag.Duration("test.benchtime", 1*time.Second, "approximate run time for each benchmark") var benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks") // Global lock to ensure only one benchmark runs at a time. var benchmarkLock sync.Mutex // Used for every benchmark for measuring memory. var memStats runtime.MemStats // An internal type but exported because it is cross-package; part of the implementation // of the "go test" command. type InternalBenchmark struct { Name string F func(b *B) } // B is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. // // A benchmark ends when its Benchmark function returns or calls any of the methods // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called // only from the goroutine running the Benchmark function. // The other reporting methods, such as the variations of Log and Error, // may be called simultaneously from multiple goroutines. // // Like in tests, benchmark logs are accumulated during execution // and dumped to standard error when done. Unlike in tests, benchmark logs // are always printed, so as not to hide output whose existence may be // affecting benchmark results. type B struct { common context *benchContext N int previousN int // number of iterations in the previous run previousDuration time.Duration // total duration of the previous run benchFunc func(b *B) benchTime time.Duration bytes int64 missingBytes bool // one of the subbenchmarks does not have bytes set. timerOn bool showAllocResult bool hasSub bool result BenchmarkResult parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines // The initial states of memStats.Mallocs and memStats.TotalAlloc. startAllocs uint64 startBytes uint64 // The net total of this test after being run. netAllocs uint64 netBytes uint64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also used to resume timing after // a call to StopTimer. func (b *B) StartTimer() { if !b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() b.timerOn = true } } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't // want to measure. func (b *B) StopTimer() { if b.timerOn { b.duration += time.Now().Sub(b.start) runtime.ReadMemStats(&memStats) b.netAllocs += memStats.Mallocs - b.startAllocs b.netBytes += memStats.TotalAlloc - b.startBytes b.timerOn = false } } // ResetTimer zeros the elapsed benchmark time and memory allocation counters. // It does not affect whether the timer is running. func (b *B) ResetTimer() { if b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() } b.duration = 0 b.netAllocs = 0 b.netBytes = 0 } // SetBytes records the number of bytes processed in a single operation. // If this is called, the benchmark will report ns/op and MB/s. func (b *B) SetBytes(n int64) { b.bytes = n } // ReportAllocs enables malloc statistics for this benchmark. // It is equivalent to setting -test.benchmem, but it only affects the // benchmark function that calls ReportAllocs. func (b *B) ReportAllocs() { b.showAllocResult = true } func (b *B) nsPerOp() int64 { if b.N <= 0 { return 0 } return b.duration.Nanoseconds() / int64(b.N) } // runN runs a single benchmark for the specified number of iterations. func (b *B) runN(n int) { benchmarkLock.Lock() defer benchmarkLock.Unlock() // Try to get a comparable environment for each run // by clearing garbage from previous runs. runtime.GC() b.N = n b.parallelism = 1 b.ResetTimer() b.StartTimer() b.benchFunc(b) b.StopTimer() b.previousN = n b.previousDuration = b.duration } func min(x, y int) int { if x > y { return y } return x } func max(x, y int) int { if x < y { return y } return x } // roundDown10 rounds a number down to the nearest power of 10. func roundDown10(n int) int { var tens = 0 // tens = floor(log_10(n)) for n >= 10 { n = n / 10 tens++ } // result = 10^tens result := 1 for i := 0; i < tens; i++ { result *= 10 } return result } // roundUp rounds x up to a number of the form [1eX, 2eX, 3eX, 5eX]. func roundUp(n int) int { base := roundDown10(n) switch { case n <= base: return base case n <= (2 * base): return 2 * base case n <= (3 * base): return 3 * base case n <= (5 * base): return 5 * base default: return 10 * base } } // probe runs benchFunc to examine if it has any subbenchmarks. func (b *B) probe() { if ctx := b.context; ctx != nil { // Extend maxLen, if needed. if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen { ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size. } } go func() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() benchmarkLock.Lock() defer benchmarkLock.Unlock() b.N = 0 b.benchFunc(b) }() <-b.signal } // run executes the benchmark in a separate goroutine, including all of its // subbenchmarks. func (b *B) run() BenchmarkResult { if b.context != nil { // Running go test --test.bench b.context.processBench(b) // Must call doBench. } else { // Running func Benchmark. b.doBench() } return b.result } func (b *B) doBench() BenchmarkResult { go b.launch() <-b.signal return b.result } // launch launches the benchmark function. It gradually increases the number // of benchmark iterations until the benchmark runs for the requested benchtime. // launch is run by the doBench function as a separate goroutine. func (b *B) launch() { // Run the benchmark for a single iteration in case it's expensive. n := 1 // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() b.runN(n) // Run the benchmark for at least the specified amount of time. d := b.benchTime for !b.failed && b.duration < d && n < 1e9 { last := n // Predict required iterations. if b.nsPerOp() == 0 { n = 1e9 } else { n = int(d.Nanoseconds() / b.nsPerOp()) } // Run more iterations than we think we'll need (1.2x). // Don't grow too fast in case we had timing errors previously. // Be sure to run at least one more than last time. n = max(min(n+n/5, 100*last), last+1) // Round up to something easy to read. n = roundUp(n) b.runN(n) } b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes} } // The results of a benchmark run. type BenchmarkResult struct { N int // The number of iterations. T time.Duration // The total time taken. Bytes int64 // Bytes processed in one iteration. MemAllocs uint64 // The total number of memory allocations. MemBytes uint64 // The total number of bytes allocated. } func (r BenchmarkResult) NsPerOp() int64 { if r.N <= 0 { return 0 } return r.T.Nanoseconds() / int64(r.N) } func (r BenchmarkResult) mbPerSec() float64 { if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { return 0 } return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() } func (r BenchmarkResult) AllocsPerOp() int64 { if r.N <= 0 { return 0 } return int64(r.MemAllocs) / int64(r.N) } func (r BenchmarkResult) AllocedBytesPerOp() int64 { if r.N <= 0 { return 0 } return int64(r.MemBytes) / int64(r.N) } func (r BenchmarkResult) String() string { mbs := r.mbPerSec() mb := "" if mbs != 0 { mb = fmt.Sprintf("\t%7.2f MB/s", mbs) } nsop := r.NsPerOp() ns := fmt.Sprintf("%10d ns/op", nsop) if r.N > 0 && nsop < 100 { // The format specifiers here make sure that // the ones digits line up for all three possible formats. if nsop < 10 { ns = fmt.Sprintf("%13.2f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) } else { ns = fmt.Sprintf("%12.1f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) } } return fmt.Sprintf("%8d\t%s%s", r.N, ns, mb) } func (r BenchmarkResult) MemString() string { return fmt.Sprintf("%8d B/op\t%8d allocs/op", r.AllocedBytesPerOp(), r.AllocsPerOp()) } // benchmarkName returns full name of benchmark including procs suffix. func benchmarkName(name string, n int) string { if n != 1 { return fmt.Sprintf("%s-%d", name, n) } return name } type benchContext struct { maxLen int // The largest recorded benchmark name. extLen int // Maximum extension length. } // An internal function but exported because it is cross-package; part of the implementation // of the "go test" command. func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { runBenchmarksInternal(matchString, benchmarks) } func runBenchmarksInternal(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool { // If no flag was specified, don't run benchmarks. if len(*matchBenchmarks) == 0 { return true } // Collect matching benchmarks and determine longest name. maxprocs := 1 for _, procs := range cpuList { if procs > maxprocs { maxprocs = procs } } ctx := &benchContext{ extLen: len(benchmarkName("", maxprocs)), } var bs []InternalBenchmark for _, Benchmark := range benchmarks { matched, err := matchString(*matchBenchmarks, Benchmark.Name) if err != nil { fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.bench: %s\n", err) os.Exit(1) } if matched { bs = append(bs, Benchmark) benchName := benchmarkName(Benchmark.Name, maxprocs) if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen { ctx.maxLen = l } } } main := &B{ common: common{name: "Main"}, benchFunc: func(b *B) { for _, Benchmark := range bs { b.runBench(Benchmark.Name, Benchmark.F) } }, benchTime: *benchTime, context: ctx, } main.runN(1) return !main.failed } // processBench runs bench b for the configured CPU counts and prints the results. func (ctx *benchContext) processBench(b *B) { for _, procs := range cpuList { runtime.GOMAXPROCS(procs) benchName := benchmarkName(b.name, procs) b := &B{ common: common{ signal: make(chan bool), name: benchName, }, benchFunc: b.benchFunc, benchTime: b.benchTime, } fmt.Printf("%-*s\t", ctx.maxLen, benchName) r := b.doBench() if b.failed { // The output could be very long here, but probably isn't. // We print it all, regardless, because we don't want to trim the reason // the benchmark failed. fmt.Printf("--- FAIL: %s\n%s", benchName, b.output) continue } results := r.String() if *benchmarkMemory || b.showAllocResult { results += "\t" + r.MemString() } fmt.Println(results) // Unlike with tests, we ignore the -chatty flag and always print output for // benchmarks since the output generation time will skew the results. if len(b.output) > 0 { b.trimOutput() fmt.Printf("--- BENCH: %s\n%s", benchName, b.output) } if p := runtime.GOMAXPROCS(-1); p != procs { fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) } } } // runBench benchmarks f as a subbenchmark with the given name. It reports // whether there were any failures. // // A subbenchmark is like any other benchmark. A benchmark that calls Run at // least once will not be measured itself. func (b *B) runBench(name string, f func(b *B)) bool { // Since b has subbenchmarks, we will no longer run it as a benchmark itself. // Release the lock and acquire it on exit to ensure locks stay paired. b.hasSub = true benchmarkLock.Unlock() defer benchmarkLock.Lock() if b.level > 0 { name = b.name + "/" + name } sub := &B{ common: common{ signal: make(chan bool), name: name, parent: &b.common, level: b.level + 1, }, benchFunc: f, benchTime: b.benchTime, context: b.context, } if sub.probe(); !sub.hasSub { b.add(sub.run()) } return !sub.failed } // add simulates running benchmarks in sequence in a single iteration. It is // used to give some meaningful results in case func Benchmark is used in // combination with Run. func (b *B) add(other BenchmarkResult) { r := &b.result // The aggregated BenchmarkResults resemble running all subbenchmarks as // in sequence in a single benchmark. r.N = 1 r.T += time.Duration(other.NsPerOp()) if other.Bytes == 0 { // Summing Bytes is meaningless in aggregate if not all subbenchmarks // set it. b.missingBytes = true r.Bytes = 0 } if !b.missingBytes { r.Bytes += other.Bytes } r.MemAllocs += uint64(other.AllocsPerOp()) r.MemBytes += uint64(other.AllocedBytesPerOp()) } // trimOutput shortens the output from a benchmark, which can be very long. func (b *B) trimOutput() { // The output is likely to appear multiple times because the benchmark // is run multiple times, but at least it will be seen. This is not a big deal // because benchmarks rarely print, but just in case, we trim it if it's too long. const maxNewlines = 10 for nlCount, j := 0, 0; j < len(b.output); j++ { if b.output[j] == '\n' { nlCount++ if nlCount >= maxNewlines { b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) break } } } } // A PB is used by RunParallel for running parallel benchmarks. type PB struct { globalN *uint64 // shared between all worker goroutines iteration counter grain uint64 // acquire that many iterations from globalN at once cache uint64 // local cache of acquired iterations bN uint64 // total number of iterations to execute (b.N) } // Next reports whether there are more iterations to execute. func (pb *PB) Next() bool { if pb.cache == 0 { n := atomic.AddUint64(pb.globalN, pb.grain) if n <= pb.bN { pb.cache = pb.grain } else if n < pb.bN+pb.grain { pb.cache = pb.bN + pb.grain - n } else { return false } } pb.cache-- return true } // RunParallel runs a benchmark in parallel. // It creates multiple goroutines and distributes b.N iterations among them. // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for // non-CPU-bound benchmarks, call SetParallelism before RunParallel. // RunParallel is usually used with the go test -cpu flag. // // The body function will be run in each goroutine. It should set up any // goroutine-local state and then iterate until pb.Next returns false. // It should not use the StartTimer, StopTimer, or ResetTimer functions, // because they have global effect. func (b *B) RunParallel(body func(*PB)) { // Calculate grain size as number of iterations that take ~100µs. // 100µs is enough to amortize the overhead and provide sufficient // dynamic load balancing. grain := uint64(0) if b.previousN > 0 && b.previousDuration > 0 { grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration) } if grain < 1 { grain = 1 } // We expect the inner loop and function call to take at least 10ns, // so do not do more than 100µs/10ns=1e4 iterations. if grain > 1e4 { grain = 1e4 } n := uint64(0) numProcs := b.parallelism * runtime.GOMAXPROCS(0) var wg sync.WaitGroup wg.Add(numProcs) for p := 0; p < numProcs; p++ { go func() { defer wg.Done() pb := &PB{ globalN: &n, grain: grain, bN: uint64(b.N), } body(pb) }() } wg.Wait() if n <= uint64(b.N) && !b.Failed() { b.Fatal("RunParallel: body exited without pb.Next() == false") } } // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. // There is usually no need to call SetParallelism for CPU-bound benchmarks. // If p is less than 1, this call will have no effect. func (b *B) SetParallelism(p int) { if p >= 1 { b.parallelism = p } } // Benchmark benchmarks a single function. Useful for creating // custom benchmarks that do not use the "go test" command. func Benchmark(f func(b *B)) BenchmarkResult { b := &B{ common: common{ signal: make(chan bool), }, benchFunc: f, benchTime: *benchTime, } return b.run() } testing: always ignore RunParallel in probe phase Change-Id: If45410a2d7e48d1c9e6800cd98f81dd89024832c Reviewed-on: https://go-review.googlesource.com/20852 Reviewed-by: Russ Cox <5ad239cb8a44f659eaaee0aa1ea5b94947abe557@golang.org> // Copyright 2009 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 testing import ( "flag" "fmt" "os" "runtime" "sync" "sync/atomic" "time" ) var matchBenchmarks = flag.String("test.bench", "", "regular expression to select benchmarks to run") var benchTime = flag.Duration("test.benchtime", 1*time.Second, "approximate run time for each benchmark") var benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks") // Global lock to ensure only one benchmark runs at a time. var benchmarkLock sync.Mutex // Used for every benchmark for measuring memory. var memStats runtime.MemStats // An internal type but exported because it is cross-package; part of the implementation // of the "go test" command. type InternalBenchmark struct { Name string F func(b *B) } // B is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. // // A benchmark ends when its Benchmark function returns or calls any of the methods // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called // only from the goroutine running the Benchmark function. // The other reporting methods, such as the variations of Log and Error, // may be called simultaneously from multiple goroutines. // // Like in tests, benchmark logs are accumulated during execution // and dumped to standard error when done. Unlike in tests, benchmark logs // are always printed, so as not to hide output whose existence may be // affecting benchmark results. type B struct { common context *benchContext N int previousN int // number of iterations in the previous run previousDuration time.Duration // total duration of the previous run benchFunc func(b *B) benchTime time.Duration bytes int64 missingBytes bool // one of the subbenchmarks does not have bytes set. timerOn bool showAllocResult bool hasSub bool result BenchmarkResult parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines // The initial states of memStats.Mallocs and memStats.TotalAlloc. startAllocs uint64 startBytes uint64 // The net total of this test after being run. netAllocs uint64 netBytes uint64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also used to resume timing after // a call to StopTimer. func (b *B) StartTimer() { if !b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() b.timerOn = true } } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't // want to measure. func (b *B) StopTimer() { if b.timerOn { b.duration += time.Now().Sub(b.start) runtime.ReadMemStats(&memStats) b.netAllocs += memStats.Mallocs - b.startAllocs b.netBytes += memStats.TotalAlloc - b.startBytes b.timerOn = false } } // ResetTimer zeros the elapsed benchmark time and memory allocation counters. // It does not affect whether the timer is running. func (b *B) ResetTimer() { if b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() } b.duration = 0 b.netAllocs = 0 b.netBytes = 0 } // SetBytes records the number of bytes processed in a single operation. // If this is called, the benchmark will report ns/op and MB/s. func (b *B) SetBytes(n int64) { b.bytes = n } // ReportAllocs enables malloc statistics for this benchmark. // It is equivalent to setting -test.benchmem, but it only affects the // benchmark function that calls ReportAllocs. func (b *B) ReportAllocs() { b.showAllocResult = true } func (b *B) nsPerOp() int64 { if b.N <= 0 { return 0 } return b.duration.Nanoseconds() / int64(b.N) } // runN runs a single benchmark for the specified number of iterations. func (b *B) runN(n int) { benchmarkLock.Lock() defer benchmarkLock.Unlock() // Try to get a comparable environment for each run // by clearing garbage from previous runs. runtime.GC() b.N = n b.parallelism = 1 b.ResetTimer() b.StartTimer() b.benchFunc(b) b.StopTimer() b.previousN = n b.previousDuration = b.duration } func min(x, y int) int { if x > y { return y } return x } func max(x, y int) int { if x < y { return y } return x } // roundDown10 rounds a number down to the nearest power of 10. func roundDown10(n int) int { var tens = 0 // tens = floor(log_10(n)) for n >= 10 { n = n / 10 tens++ } // result = 10^tens result := 1 for i := 0; i < tens; i++ { result *= 10 } return result } // roundUp rounds x up to a number of the form [1eX, 2eX, 3eX, 5eX]. func roundUp(n int) int { base := roundDown10(n) switch { case n <= base: return base case n <= (2 * base): return 2 * base case n <= (3 * base): return 3 * base case n <= (5 * base): return 5 * base default: return 10 * base } } // probe runs benchFunc to examine if it has any subbenchmarks. func (b *B) probe() { if ctx := b.context; ctx != nil { // Extend maxLen, if needed. if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen { ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size. } } go func() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() benchmarkLock.Lock() defer benchmarkLock.Unlock() b.N = 0 b.benchFunc(b) }() <-b.signal } // run executes the benchmark in a separate goroutine, including all of its // subbenchmarks. func (b *B) run() BenchmarkResult { if b.context != nil { // Running go test --test.bench b.context.processBench(b) // Must call doBench. } else { // Running func Benchmark. b.doBench() } return b.result } func (b *B) doBench() BenchmarkResult { go b.launch() <-b.signal return b.result } // launch launches the benchmark function. It gradually increases the number // of benchmark iterations until the benchmark runs for the requested benchtime. // launch is run by the doBench function as a separate goroutine. func (b *B) launch() { // Run the benchmark for a single iteration in case it's expensive. n := 1 // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() b.runN(n) // Run the benchmark for at least the specified amount of time. d := b.benchTime for !b.failed && b.duration < d && n < 1e9 { last := n // Predict required iterations. if b.nsPerOp() == 0 { n = 1e9 } else { n = int(d.Nanoseconds() / b.nsPerOp()) } // Run more iterations than we think we'll need (1.2x). // Don't grow too fast in case we had timing errors previously. // Be sure to run at least one more than last time. n = max(min(n+n/5, 100*last), last+1) // Round up to something easy to read. n = roundUp(n) b.runN(n) } b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes} } // The results of a benchmark run. type BenchmarkResult struct { N int // The number of iterations. T time.Duration // The total time taken. Bytes int64 // Bytes processed in one iteration. MemAllocs uint64 // The total number of memory allocations. MemBytes uint64 // The total number of bytes allocated. } func (r BenchmarkResult) NsPerOp() int64 { if r.N <= 0 { return 0 } return r.T.Nanoseconds() / int64(r.N) } func (r BenchmarkResult) mbPerSec() float64 { if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { return 0 } return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() } func (r BenchmarkResult) AllocsPerOp() int64 { if r.N <= 0 { return 0 } return int64(r.MemAllocs) / int64(r.N) } func (r BenchmarkResult) AllocedBytesPerOp() int64 { if r.N <= 0 { return 0 } return int64(r.MemBytes) / int64(r.N) } func (r BenchmarkResult) String() string { mbs := r.mbPerSec() mb := "" if mbs != 0 { mb = fmt.Sprintf("\t%7.2f MB/s", mbs) } nsop := r.NsPerOp() ns := fmt.Sprintf("%10d ns/op", nsop) if r.N > 0 && nsop < 100 { // The format specifiers here make sure that // the ones digits line up for all three possible formats. if nsop < 10 { ns = fmt.Sprintf("%13.2f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) } else { ns = fmt.Sprintf("%12.1f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) } } return fmt.Sprintf("%8d\t%s%s", r.N, ns, mb) } func (r BenchmarkResult) MemString() string { return fmt.Sprintf("%8d B/op\t%8d allocs/op", r.AllocedBytesPerOp(), r.AllocsPerOp()) } // benchmarkName returns full name of benchmark including procs suffix. func benchmarkName(name string, n int) string { if n != 1 { return fmt.Sprintf("%s-%d", name, n) } return name } type benchContext struct { maxLen int // The largest recorded benchmark name. extLen int // Maximum extension length. } // An internal function but exported because it is cross-package; part of the implementation // of the "go test" command. func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { runBenchmarksInternal(matchString, benchmarks) } func runBenchmarksInternal(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool { // If no flag was specified, don't run benchmarks. if len(*matchBenchmarks) == 0 { return true } // Collect matching benchmarks and determine longest name. maxprocs := 1 for _, procs := range cpuList { if procs > maxprocs { maxprocs = procs } } ctx := &benchContext{ extLen: len(benchmarkName("", maxprocs)), } var bs []InternalBenchmark for _, Benchmark := range benchmarks { matched, err := matchString(*matchBenchmarks, Benchmark.Name) if err != nil { fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.bench: %s\n", err) os.Exit(1) } if matched { bs = append(bs, Benchmark) benchName := benchmarkName(Benchmark.Name, maxprocs) if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen { ctx.maxLen = l } } } main := &B{ common: common{name: "Main"}, benchFunc: func(b *B) { for _, Benchmark := range bs { b.runBench(Benchmark.Name, Benchmark.F) } }, benchTime: *benchTime, context: ctx, } main.runN(1) return !main.failed } // processBench runs bench b for the configured CPU counts and prints the results. func (ctx *benchContext) processBench(b *B) { for _, procs := range cpuList { runtime.GOMAXPROCS(procs) benchName := benchmarkName(b.name, procs) b := &B{ common: common{ signal: make(chan bool), name: benchName, }, benchFunc: b.benchFunc, benchTime: b.benchTime, } fmt.Printf("%-*s\t", ctx.maxLen, benchName) r := b.doBench() if b.failed { // The output could be very long here, but probably isn't. // We print it all, regardless, because we don't want to trim the reason // the benchmark failed. fmt.Printf("--- FAIL: %s\n%s", benchName, b.output) continue } results := r.String() if *benchmarkMemory || b.showAllocResult { results += "\t" + r.MemString() } fmt.Println(results) // Unlike with tests, we ignore the -chatty flag and always print output for // benchmarks since the output generation time will skew the results. if len(b.output) > 0 { b.trimOutput() fmt.Printf("--- BENCH: %s\n%s", benchName, b.output) } if p := runtime.GOMAXPROCS(-1); p != procs { fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) } } } // runBench benchmarks f as a subbenchmark with the given name. It reports // whether there were any failures. // // A subbenchmark is like any other benchmark. A benchmark that calls Run at // least once will not be measured itself. func (b *B) runBench(name string, f func(b *B)) bool { // Since b has subbenchmarks, we will no longer run it as a benchmark itself. // Release the lock and acquire it on exit to ensure locks stay paired. b.hasSub = true benchmarkLock.Unlock() defer benchmarkLock.Lock() if b.level > 0 { name = b.name + "/" + name } sub := &B{ common: common{ signal: make(chan bool), name: name, parent: &b.common, level: b.level + 1, }, benchFunc: f, benchTime: b.benchTime, context: b.context, } if sub.probe(); !sub.hasSub { b.add(sub.run()) } return !sub.failed } // add simulates running benchmarks in sequence in a single iteration. It is // used to give some meaningful results in case func Benchmark is used in // combination with Run. func (b *B) add(other BenchmarkResult) { r := &b.result // The aggregated BenchmarkResults resemble running all subbenchmarks as // in sequence in a single benchmark. r.N = 1 r.T += time.Duration(other.NsPerOp()) if other.Bytes == 0 { // Summing Bytes is meaningless in aggregate if not all subbenchmarks // set it. b.missingBytes = true r.Bytes = 0 } if !b.missingBytes { r.Bytes += other.Bytes } r.MemAllocs += uint64(other.AllocsPerOp()) r.MemBytes += uint64(other.AllocedBytesPerOp()) } // trimOutput shortens the output from a benchmark, which can be very long. func (b *B) trimOutput() { // The output is likely to appear multiple times because the benchmark // is run multiple times, but at least it will be seen. This is not a big deal // because benchmarks rarely print, but just in case, we trim it if it's too long. const maxNewlines = 10 for nlCount, j := 0, 0; j < len(b.output); j++ { if b.output[j] == '\n' { nlCount++ if nlCount >= maxNewlines { b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) break } } } } // A PB is used by RunParallel for running parallel benchmarks. type PB struct { globalN *uint64 // shared between all worker goroutines iteration counter grain uint64 // acquire that many iterations from globalN at once cache uint64 // local cache of acquired iterations bN uint64 // total number of iterations to execute (b.N) } // Next reports whether there are more iterations to execute. func (pb *PB) Next() bool { if pb.cache == 0 { n := atomic.AddUint64(pb.globalN, pb.grain) if n <= pb.bN { pb.cache = pb.grain } else if n < pb.bN+pb.grain { pb.cache = pb.bN + pb.grain - n } else { return false } } pb.cache-- return true } // RunParallel runs a benchmark in parallel. // It creates multiple goroutines and distributes b.N iterations among them. // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for // non-CPU-bound benchmarks, call SetParallelism before RunParallel. // RunParallel is usually used with the go test -cpu flag. // // The body function will be run in each goroutine. It should set up any // goroutine-local state and then iterate until pb.Next returns false. // It should not use the StartTimer, StopTimer, or ResetTimer functions, // because they have global effect. It should also not call Run. func (b *B) RunParallel(body func(*PB)) { if b.N == 0 { return // Nothing to do when probing. } // Calculate grain size as number of iterations that take ~100µs. // 100µs is enough to amortize the overhead and provide sufficient // dynamic load balancing. grain := uint64(0) if b.previousN > 0 && b.previousDuration > 0 { grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration) } if grain < 1 { grain = 1 } // We expect the inner loop and function call to take at least 10ns, // so do not do more than 100µs/10ns=1e4 iterations. if grain > 1e4 { grain = 1e4 } n := uint64(0) numProcs := b.parallelism * runtime.GOMAXPROCS(0) var wg sync.WaitGroup wg.Add(numProcs) for p := 0; p < numProcs; p++ { go func() { defer wg.Done() pb := &PB{ globalN: &n, grain: grain, bN: uint64(b.N), } body(pb) }() } wg.Wait() if n <= uint64(b.N) && !b.Failed() { b.Fatal("RunParallel: body exited without pb.Next() == false") } } // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. // There is usually no need to call SetParallelism for CPU-bound benchmarks. // If p is less than 1, this call will have no effect. func (b *B) SetParallelism(p int) { if p >= 1 { b.parallelism = p } } // Benchmark benchmarks a single function. Useful for creating // custom benchmarks that do not use the "go test" command. func Benchmark(f func(b *B)) BenchmarkResult { b := &B{ common: common{ signal: make(chan bool), }, benchFunc: f, benchTime: *benchTime, } return b.run() }
// Copyright 2009 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 testing import ( "flag" "fmt" "internal/race" "internal/sysinfo" "io" "math" "os" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "unicode" ) func initBenchmarkFlags() { matchBenchmarks = flag.String("test.bench", "", "run only benchmarks matching `regexp`") benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks") flag.Var(&benchTime, "test.benchtime", "run each benchmark for duration `d`") } var ( matchBenchmarks *string benchmarkMemory *bool benchTime = durationOrCountFlag{d: 1 * time.Second} // changed during test of testing package ) type durationOrCountFlag struct { d time.Duration n int allowZero bool } func (f *durationOrCountFlag) String() string { if f.n > 0 { return fmt.Sprintf("%dx", f.n) } return f.d.String() } func (f *durationOrCountFlag) Set(s string) error { if strings.HasSuffix(s, "x") { n, err := strconv.ParseInt(s[:len(s)-1], 10, 0) if err != nil || n < 0 || (!f.allowZero && n == 0) { return fmt.Errorf("invalid count") } *f = durationOrCountFlag{n: int(n)} return nil } d, err := time.ParseDuration(s) if err != nil || d < 0 || (!f.allowZero && d == 0) { return fmt.Errorf("invalid duration") } *f = durationOrCountFlag{d: d} return nil } // Global lock to ensure only one benchmark runs at a time. var benchmarkLock sync.Mutex // Used for every benchmark for measuring memory. var memStats runtime.MemStats // InternalBenchmark is an internal type but exported because it is cross-package; // it is part of the implementation of the "go test" command. type InternalBenchmark struct { Name string F func(b *B) } // B is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. // // A benchmark ends when its Benchmark function returns or calls any of the methods // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called // only from the goroutine running the Benchmark function. // The other reporting methods, such as the variations of Log and Error, // may be called simultaneously from multiple goroutines. // // Like in tests, benchmark logs are accumulated during execution // and dumped to standard output when done. Unlike in tests, benchmark logs // are always printed, so as not to hide output whose existence may be // affecting benchmark results. type B struct { common importPath string // import path of the package containing the benchmark context *benchContext N int previousN int // number of iterations in the previous run previousDuration time.Duration // total duration of the previous run benchFunc func(b *B) benchTime durationOrCountFlag bytes int64 missingBytes bool // one of the subbenchmarks does not have bytes set. timerOn bool showAllocResult bool result BenchmarkResult parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines // The initial states of memStats.Mallocs and memStats.TotalAlloc. startAllocs uint64 startBytes uint64 // The net total of this test after being run. netAllocs uint64 netBytes uint64 // Extra metrics collected by ReportMetric. extra map[string]float64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also be used to resume timing after // a call to StopTimer. func (b *B) StartTimer() { if !b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() b.timerOn = true } } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't // want to measure. func (b *B) StopTimer() { if b.timerOn { b.duration += time.Since(b.start) runtime.ReadMemStats(&memStats) b.netAllocs += memStats.Mallocs - b.startAllocs b.netBytes += memStats.TotalAlloc - b.startBytes b.timerOn = false } } // ResetTimer zeroes the elapsed benchmark time and memory allocation counters // and deletes user-reported metrics. // It does not affect whether the timer is running. func (b *B) ResetTimer() { if b.extra == nil { // Allocate the extra map before reading memory stats. // Pre-size it to make more allocation unlikely. b.extra = make(map[string]float64, 16) } else { for k := range b.extra { delete(b.extra, k) } } if b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() } b.duration = 0 b.netAllocs = 0 b.netBytes = 0 } // SetBytes records the number of bytes processed in a single operation. // If this is called, the benchmark will report ns/op and MB/s. func (b *B) SetBytes(n int64) { b.bytes = n } // ReportAllocs enables malloc statistics for this benchmark. // It is equivalent to setting -test.benchmem, but it only affects the // benchmark function that calls ReportAllocs. func (b *B) ReportAllocs() { b.showAllocResult = true } // runN runs a single benchmark for the specified number of iterations. func (b *B) runN(n int) { benchmarkLock.Lock() defer benchmarkLock.Unlock() defer b.runCleanup(normalPanic) // Try to get a comparable environment for each run // by clearing garbage from previous runs. runtime.GC() b.raceErrors = -race.Errors() b.N = n b.parallelism = 1 b.ResetTimer() b.StartTimer() b.benchFunc(b) b.StopTimer() b.previousN = n b.previousDuration = b.duration b.raceErrors += race.Errors() if b.raceErrors > 0 { b.Errorf("race detected during execution of benchmark") } } func min(x, y int64) int64 { if x > y { return y } return x } func max(x, y int64) int64 { if x < y { return y } return x } // run1 runs the first iteration of benchFunc. It reports whether more // iterations of this benchmarks should be run. func (b *B) run1() bool { if ctx := b.context; ctx != nil { // Extend maxLen, if needed. if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen { ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size. } } go func() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() b.runN(1) }() <-b.signal if b.failed { fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), b.name, b.output) return false } // Only print the output if we know we are not going to proceed. // Otherwise it is printed in processBench. b.mu.RLock() finished := b.finished b.mu.RUnlock() if b.hasSub.Load() || finished { tag := "BENCH" if b.skipped { tag = "SKIP" } if b.chatty != nil && (len(b.output) > 0 || finished) { b.trimOutput() fmt.Fprintf(b.w, "%s--- %s: %s\n%s", b.chatty.prefix(), tag, b.name, b.output) } return false } return true } var labelsOnce sync.Once // run executes the benchmark in a separate goroutine, including all of its // subbenchmarks. b must not have subbenchmarks. func (b *B) run() { labelsOnce.Do(func() { fmt.Fprintf(b.w, "goos: %s\n", runtime.GOOS) fmt.Fprintf(b.w, "goarch: %s\n", runtime.GOARCH) if b.importPath != "" { fmt.Fprintf(b.w, "pkg: %s\n", b.importPath) } if cpu := sysinfo.CPU.Name(); cpu != "" { fmt.Fprintf(b.w, "cpu: %s\n", cpu) } }) if b.context != nil { // Running go test --test.bench b.context.processBench(b) // Must call doBench. } else { // Running func Benchmark. b.doBench() } } func (b *B) doBench() BenchmarkResult { go b.launch() <-b.signal return b.result } // launch launches the benchmark function. It gradually increases the number // of benchmark iterations until the benchmark runs for the requested benchtime. // launch is run by the doBench function as a separate goroutine. // run1 must have been called on b. func (b *B) launch() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() // Run the benchmark for at least the specified amount of time. if b.benchTime.n > 0 { // We already ran a single iteration in run1. // If -benchtime=1x was requested, use that result. // See https://golang.org/issue/32051. if b.benchTime.n > 1 { b.runN(b.benchTime.n) } } else { d := b.benchTime.d for n := int64(1); !b.failed && b.duration < d && n < 1e9; { last := n // Predict required iterations. goalns := d.Nanoseconds() prevIters := int64(b.N) prevns := b.duration.Nanoseconds() if prevns <= 0 { // Round up, to avoid div by zero. prevns = 1 } // Order of operations matters. // For very fast benchmarks, prevIters ~= prevns. // If you divide first, you get 0 or 1, // which can hide an order of magnitude in execution time. // So multiply first, then divide. n = goalns * prevIters / prevns // Run more iterations than we think we'll need (1.2x). n += n / 5 // Don't grow too fast in case we had timing errors previously. n = min(n, 100*last) // Be sure to run at least one more than last time. n = max(n, last+1) // Don't run more than 1e9 times. (This also keeps n in int range on 32 bit platforms.) n = min(n, 1e9) b.runN(int(n)) } } b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra} } // Elapsed returns the measured elapsed time of the benchmark. // The duration reported by Elapsed matches the one measured by // StartTimer, StopTimer, and ResetTimer. func (b *B) Elapsed() time.Duration { d := b.duration if b.timerOn { d += time.Since(b.start) } return d } // ReportMetric adds "n unit" to the reported benchmark results. // If the metric is per-iteration, the caller should divide by b.N, // and by convention units should end in "/op". // ReportMetric overrides any previously reported value for the same unit. // ReportMetric panics if unit is the empty string or if unit contains // any whitespace. // If unit is a unit normally reported by the benchmark framework itself // (such as "allocs/op"), ReportMetric will override that metric. // Setting "ns/op" to 0 will suppress that built-in metric. func (b *B) ReportMetric(n float64, unit string) { if unit == "" { panic("metric unit must not be empty") } if strings.IndexFunc(unit, unicode.IsSpace) >= 0 { panic("metric unit must not contain whitespace") } b.extra[unit] = n } // BenchmarkResult contains the results of a benchmark run. type BenchmarkResult struct { N int // The number of iterations. T time.Duration // The total time taken. Bytes int64 // Bytes processed in one iteration. MemAllocs uint64 // The total number of memory allocations. MemBytes uint64 // The total number of bytes allocated. // Extra records additional metrics reported by ReportMetric. Extra map[string]float64 } // NsPerOp returns the "ns/op" metric. func (r BenchmarkResult) NsPerOp() int64 { if v, ok := r.Extra["ns/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return r.T.Nanoseconds() / int64(r.N) } // mbPerSec returns the "MB/s" metric. func (r BenchmarkResult) mbPerSec() float64 { if v, ok := r.Extra["MB/s"]; ok { return v } if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { return 0 } return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() } // AllocsPerOp returns the "allocs/op" metric, // which is calculated as r.MemAllocs / r.N. func (r BenchmarkResult) AllocsPerOp() int64 { if v, ok := r.Extra["allocs/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return int64(r.MemAllocs) / int64(r.N) } // AllocedBytesPerOp returns the "B/op" metric, // which is calculated as r.MemBytes / r.N. func (r BenchmarkResult) AllocedBytesPerOp() int64 { if v, ok := r.Extra["B/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return int64(r.MemBytes) / int64(r.N) } // String returns a summary of the benchmark results. // It follows the benchmark result line format from // https://golang.org/design/14313-benchmark-format, not including the // benchmark name. // Extra metrics override built-in metrics of the same name. // String does not include allocs/op or B/op, since those are reported // by MemString. func (r BenchmarkResult) String() string { buf := new(strings.Builder) fmt.Fprintf(buf, "%8d", r.N) // Get ns/op as a float. ns, ok := r.Extra["ns/op"] if !ok { ns = float64(r.T.Nanoseconds()) / float64(r.N) } if ns != 0 { buf.WriteByte('\t') prettyPrint(buf, ns, "ns/op") } if mbs := r.mbPerSec(); mbs != 0 { fmt.Fprintf(buf, "\t%7.2f MB/s", mbs) } // Print extra metrics that aren't represented in the standard // metrics. var extraKeys []string for k := range r.Extra { switch k { case "ns/op", "MB/s", "B/op", "allocs/op": // Built-in metrics reported elsewhere. continue } extraKeys = append(extraKeys, k) } sort.Strings(extraKeys) for _, k := range extraKeys { buf.WriteByte('\t') prettyPrint(buf, r.Extra[k], k) } return buf.String() } func prettyPrint(w io.Writer, x float64, unit string) { // Print all numbers with 10 places before the decimal point // and small numbers with four sig figs. Field widths are // chosen to fit the whole part in 10 places while aligning // the decimal point of all fractional formats. var format string switch y := math.Abs(x); { case y == 0 || y >= 999.95: format = "%10.0f %s" case y >= 99.995: format = "%12.1f %s" case y >= 9.9995: format = "%13.2f %s" case y >= 0.99995: format = "%14.3f %s" case y >= 0.099995: format = "%15.4f %s" case y >= 0.0099995: format = "%16.5f %s" case y >= 0.00099995: format = "%17.6f %s" default: format = "%18.7f %s" } fmt.Fprintf(w, format, x, unit) } // MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'. func (r BenchmarkResult) MemString() string { return fmt.Sprintf("%8d B/op\t%8d allocs/op", r.AllocedBytesPerOp(), r.AllocsPerOp()) } // benchmarkName returns full name of benchmark including procs suffix. func benchmarkName(name string, n int) string { if n != 1 { return fmt.Sprintf("%s-%d", name, n) } return name } type benchContext struct { match *matcher maxLen int // The largest recorded benchmark name. extLen int // Maximum extension length. } // RunBenchmarks is an internal function but exported because it is cross-package; // it is part of the implementation of the "go test" command. func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { runBenchmarks("", matchString, benchmarks) } func runBenchmarks(importPath string, matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool { // If no flag was specified, don't run benchmarks. if len(*matchBenchmarks) == 0 { return true } // Collect matching benchmarks and determine longest name. maxprocs := 1 for _, procs := range cpuList { if procs > maxprocs { maxprocs = procs } } ctx := &benchContext{ match: newMatcher(matchString, *matchBenchmarks, "-test.bench", *skip), extLen: len(benchmarkName("", maxprocs)), } var bs []InternalBenchmark for _, Benchmark := range benchmarks { if _, matched, _ := ctx.match.fullName(nil, Benchmark.Name); matched { bs = append(bs, Benchmark) benchName := benchmarkName(Benchmark.Name, maxprocs) if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen { ctx.maxLen = l } } } main := &B{ common: common{ name: "Main", w: os.Stdout, bench: true, }, importPath: importPath, benchFunc: func(b *B) { for _, Benchmark := range bs { b.Run(Benchmark.Name, Benchmark.F) } }, benchTime: benchTime, context: ctx, } if Verbose() { main.chatty = newChattyPrinter(main.w) } main.runN(1) return !main.failed } // processBench runs bench b for the configured CPU counts and prints the results. func (ctx *benchContext) processBench(b *B) { for i, procs := range cpuList { for j := uint(0); j < *count; j++ { runtime.GOMAXPROCS(procs) benchName := benchmarkName(b.name, procs) // If it's chatty, we've already printed this information. if b.chatty == nil { fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName) } // Recompute the running time for all but the first iteration. if i > 0 || j > 0 { b = &B{ common: common{ signal: make(chan bool), name: b.name, w: b.w, chatty: b.chatty, bench: true, }, benchFunc: b.benchFunc, benchTime: b.benchTime, } b.run1() } r := b.doBench() if b.failed { // The output could be very long here, but probably isn't. // We print it all, regardless, because we don't want to trim the reason // the benchmark failed. fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), benchName, b.output) continue } results := r.String() if b.chatty != nil { fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName) } if *benchmarkMemory || b.showAllocResult { results += "\t" + r.MemString() } fmt.Fprintln(b.w, results) // Unlike with tests, we ignore the -chatty flag and always print output for // benchmarks since the output generation time will skew the results. if len(b.output) > 0 { b.trimOutput() fmt.Fprintf(b.w, "%s--- BENCH: %s\n%s", b.chatty.prefix(), benchName, b.output) } if p := runtime.GOMAXPROCS(-1); p != procs { fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) } if b.chatty != nil && b.chatty.json { b.chatty.Updatef("", "=== NAME %s\n", "") } } } } // If hideStdoutForTesting is true, Run does not print the benchName. // This avoids a spurious print during 'go test' on package testing itself, // which invokes b.Run in its own tests (see sub_test.go). var hideStdoutForTesting = false // Run benchmarks f as a subbenchmark with the given name. It reports // whether there were any failures. // // A subbenchmark is like any other benchmark. A benchmark that calls Run at // least once will not be measured itself and will be called once with N=1. func (b *B) Run(name string, f func(b *B)) bool { // Since b has subbenchmarks, we will no longer run it as a benchmark itself. // Release the lock and acquire it on exit to ensure locks stay paired. b.hasSub.Store(true) benchmarkLock.Unlock() defer benchmarkLock.Lock() benchName, ok, partial := b.name, true, false if b.context != nil { benchName, ok, partial = b.context.match.fullName(&b.common, name) } if !ok { return true } var pc [maxStackLen]uintptr n := runtime.Callers(2, pc[:]) sub := &B{ common: common{ signal: make(chan bool), name: benchName, parent: &b.common, level: b.level + 1, creator: pc[:n], w: b.w, chatty: b.chatty, bench: true, }, importPath: b.importPath, benchFunc: f, benchTime: b.benchTime, context: b.context, } if partial { // Partial name match, like -bench=X/Y matching BenchmarkX. // Only process sub-benchmarks, if any. sub.hasSub.Store(true) } if b.chatty != nil { labelsOnce.Do(func() { fmt.Printf("goos: %s\n", runtime.GOOS) fmt.Printf("goarch: %s\n", runtime.GOARCH) if b.importPath != "" { fmt.Printf("pkg: %s\n", b.importPath) } if cpu := sysinfo.CPU.Name(); cpu != "" { fmt.Printf("cpu: %s\n", cpu) } }) if !hideStdoutForTesting { if b.chatty.json { b.chatty.Updatef(benchName, "=== RUN %s\n", benchName) } fmt.Println(benchName) } } if sub.run1() { sub.run() } b.add(sub.result) return !sub.failed } // add simulates running benchmarks in sequence in a single iteration. It is // used to give some meaningful results in case func Benchmark is used in // combination with Run. func (b *B) add(other BenchmarkResult) { r := &b.result // The aggregated BenchmarkResults resemble running all subbenchmarks as // in sequence in a single benchmark. r.N = 1 r.T += time.Duration(other.NsPerOp()) if other.Bytes == 0 { // Summing Bytes is meaningless in aggregate if not all subbenchmarks // set it. b.missingBytes = true r.Bytes = 0 } if !b.missingBytes { r.Bytes += other.Bytes } r.MemAllocs += uint64(other.AllocsPerOp()) r.MemBytes += uint64(other.AllocedBytesPerOp()) } // trimOutput shortens the output from a benchmark, which can be very long. func (b *B) trimOutput() { // The output is likely to appear multiple times because the benchmark // is run multiple times, but at least it will be seen. This is not a big deal // because benchmarks rarely print, but just in case, we trim it if it's too long. const maxNewlines = 10 for nlCount, j := 0, 0; j < len(b.output); j++ { if b.output[j] == '\n' { nlCount++ if nlCount >= maxNewlines { b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) break } } } } // A PB is used by RunParallel for running parallel benchmarks. type PB struct { globalN *uint64 // shared between all worker goroutines iteration counter grain uint64 // acquire that many iterations from globalN at once cache uint64 // local cache of acquired iterations bN uint64 // total number of iterations to execute (b.N) } // Next reports whether there are more iterations to execute. func (pb *PB) Next() bool { if pb.cache == 0 { n := atomic.AddUint64(pb.globalN, pb.grain) if n <= pb.bN { pb.cache = pb.grain } else if n < pb.bN+pb.grain { pb.cache = pb.bN + pb.grain - n } else { return false } } pb.cache-- return true } // RunParallel runs a benchmark in parallel. // It creates multiple goroutines and distributes b.N iterations among them. // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for // non-CPU-bound benchmarks, call SetParallelism before RunParallel. // RunParallel is usually used with the go test -cpu flag. // // The body function will be run in each goroutine. It should set up any // goroutine-local state and then iterate until pb.Next returns false. // It should not use the StartTimer, StopTimer, or ResetTimer functions, // because they have global effect. It should also not call Run. func (b *B) RunParallel(body func(*PB)) { if b.N == 0 { return // Nothing to do when probing. } // Calculate grain size as number of iterations that take ~100µs. // 100µs is enough to amortize the overhead and provide sufficient // dynamic load balancing. grain := uint64(0) if b.previousN > 0 && b.previousDuration > 0 { grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration) } if grain < 1 { grain = 1 } // We expect the inner loop and function call to take at least 10ns, // so do not do more than 100µs/10ns=1e4 iterations. if grain > 1e4 { grain = 1e4 } n := uint64(0) numProcs := b.parallelism * runtime.GOMAXPROCS(0) var wg sync.WaitGroup wg.Add(numProcs) for p := 0; p < numProcs; p++ { go func() { defer wg.Done() pb := &PB{ globalN: &n, grain: grain, bN: uint64(b.N), } body(pb) }() } wg.Wait() if n <= uint64(b.N) && !b.Failed() { b.Fatal("RunParallel: body exited without pb.Next() == false") } } // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. // There is usually no need to call SetParallelism for CPU-bound benchmarks. // If p is less than 1, this call will have no effect. func (b *B) SetParallelism(p int) { if p >= 1 { b.parallelism = p } } // Benchmark benchmarks a single function. It is useful for creating // custom benchmarks that do not use the "go test" command. // // If f depends on testing flags, then Init must be used to register // those flags before calling Benchmark and before calling flag.Parse. // // If f calls Run, the result will be an estimate of running all its // subbenchmarks that don't call Run in sequence in a single benchmark. func Benchmark(f func(b *B)) BenchmarkResult { b := &B{ common: common{ signal: make(chan bool), w: discard{}, }, benchFunc: f, benchTime: benchTime, } if b.run1() { b.run() } return b.result } type discard struct{} func (discard) Write(b []byte) (n int, err error) { return len(b), nil } testing: Document RunParallel ns/op behavior Updates #31884 Change-Id: Ibad3d31038a8426c0bce61c1726392880f934865 Reviewed-on: https://go-review.googlesource.com/c/go/+/447136 Reviewed-by: Bryan Mills <1c8aad60184261ccede67f5c63a0d2a3bf3c9ff4@google.com> Run-TryBot: Bryan Mills <1c8aad60184261ccede67f5c63a0d2a3bf3c9ff4@google.com> Reviewed-by: Benny Siegert <05f4aee36fd25d0de2a07789fd6e73398db492cc@gmail.com> Auto-Submit: Bryan Mills <1c8aad60184261ccede67f5c63a0d2a3bf3c9ff4@google.com> TryBot-Result: Gopher Robot <66cb808b70d30c07676d5e946fee83fd561249e5@golang.org> // Copyright 2009 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 testing import ( "flag" "fmt" "internal/race" "internal/sysinfo" "io" "math" "os" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "unicode" ) func initBenchmarkFlags() { matchBenchmarks = flag.String("test.bench", "", "run only benchmarks matching `regexp`") benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks") flag.Var(&benchTime, "test.benchtime", "run each benchmark for duration `d`") } var ( matchBenchmarks *string benchmarkMemory *bool benchTime = durationOrCountFlag{d: 1 * time.Second} // changed during test of testing package ) type durationOrCountFlag struct { d time.Duration n int allowZero bool } func (f *durationOrCountFlag) String() string { if f.n > 0 { return fmt.Sprintf("%dx", f.n) } return f.d.String() } func (f *durationOrCountFlag) Set(s string) error { if strings.HasSuffix(s, "x") { n, err := strconv.ParseInt(s[:len(s)-1], 10, 0) if err != nil || n < 0 || (!f.allowZero && n == 0) { return fmt.Errorf("invalid count") } *f = durationOrCountFlag{n: int(n)} return nil } d, err := time.ParseDuration(s) if err != nil || d < 0 || (!f.allowZero && d == 0) { return fmt.Errorf("invalid duration") } *f = durationOrCountFlag{d: d} return nil } // Global lock to ensure only one benchmark runs at a time. var benchmarkLock sync.Mutex // Used for every benchmark for measuring memory. var memStats runtime.MemStats // InternalBenchmark is an internal type but exported because it is cross-package; // it is part of the implementation of the "go test" command. type InternalBenchmark struct { Name string F func(b *B) } // B is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. // // A benchmark ends when its Benchmark function returns or calls any of the methods // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called // only from the goroutine running the Benchmark function. // The other reporting methods, such as the variations of Log and Error, // may be called simultaneously from multiple goroutines. // // Like in tests, benchmark logs are accumulated during execution // and dumped to standard output when done. Unlike in tests, benchmark logs // are always printed, so as not to hide output whose existence may be // affecting benchmark results. type B struct { common importPath string // import path of the package containing the benchmark context *benchContext N int previousN int // number of iterations in the previous run previousDuration time.Duration // total duration of the previous run benchFunc func(b *B) benchTime durationOrCountFlag bytes int64 missingBytes bool // one of the subbenchmarks does not have bytes set. timerOn bool showAllocResult bool result BenchmarkResult parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines // The initial states of memStats.Mallocs and memStats.TotalAlloc. startAllocs uint64 startBytes uint64 // The net total of this test after being run. netAllocs uint64 netBytes uint64 // Extra metrics collected by ReportMetric. extra map[string]float64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also be used to resume timing after // a call to StopTimer. func (b *B) StartTimer() { if !b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() b.timerOn = true } } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't // want to measure. func (b *B) StopTimer() { if b.timerOn { b.duration += time.Since(b.start) runtime.ReadMemStats(&memStats) b.netAllocs += memStats.Mallocs - b.startAllocs b.netBytes += memStats.TotalAlloc - b.startBytes b.timerOn = false } } // ResetTimer zeroes the elapsed benchmark time and memory allocation counters // and deletes user-reported metrics. // It does not affect whether the timer is running. func (b *B) ResetTimer() { if b.extra == nil { // Allocate the extra map before reading memory stats. // Pre-size it to make more allocation unlikely. b.extra = make(map[string]float64, 16) } else { for k := range b.extra { delete(b.extra, k) } } if b.timerOn { runtime.ReadMemStats(&memStats) b.startAllocs = memStats.Mallocs b.startBytes = memStats.TotalAlloc b.start = time.Now() } b.duration = 0 b.netAllocs = 0 b.netBytes = 0 } // SetBytes records the number of bytes processed in a single operation. // If this is called, the benchmark will report ns/op and MB/s. func (b *B) SetBytes(n int64) { b.bytes = n } // ReportAllocs enables malloc statistics for this benchmark. // It is equivalent to setting -test.benchmem, but it only affects the // benchmark function that calls ReportAllocs. func (b *B) ReportAllocs() { b.showAllocResult = true } // runN runs a single benchmark for the specified number of iterations. func (b *B) runN(n int) { benchmarkLock.Lock() defer benchmarkLock.Unlock() defer b.runCleanup(normalPanic) // Try to get a comparable environment for each run // by clearing garbage from previous runs. runtime.GC() b.raceErrors = -race.Errors() b.N = n b.parallelism = 1 b.ResetTimer() b.StartTimer() b.benchFunc(b) b.StopTimer() b.previousN = n b.previousDuration = b.duration b.raceErrors += race.Errors() if b.raceErrors > 0 { b.Errorf("race detected during execution of benchmark") } } func min(x, y int64) int64 { if x > y { return y } return x } func max(x, y int64) int64 { if x < y { return y } return x } // run1 runs the first iteration of benchFunc. It reports whether more // iterations of this benchmarks should be run. func (b *B) run1() bool { if ctx := b.context; ctx != nil { // Extend maxLen, if needed. if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen { ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size. } } go func() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() b.runN(1) }() <-b.signal if b.failed { fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), b.name, b.output) return false } // Only print the output if we know we are not going to proceed. // Otherwise it is printed in processBench. b.mu.RLock() finished := b.finished b.mu.RUnlock() if b.hasSub.Load() || finished { tag := "BENCH" if b.skipped { tag = "SKIP" } if b.chatty != nil && (len(b.output) > 0 || finished) { b.trimOutput() fmt.Fprintf(b.w, "%s--- %s: %s\n%s", b.chatty.prefix(), tag, b.name, b.output) } return false } return true } var labelsOnce sync.Once // run executes the benchmark in a separate goroutine, including all of its // subbenchmarks. b must not have subbenchmarks. func (b *B) run() { labelsOnce.Do(func() { fmt.Fprintf(b.w, "goos: %s\n", runtime.GOOS) fmt.Fprintf(b.w, "goarch: %s\n", runtime.GOARCH) if b.importPath != "" { fmt.Fprintf(b.w, "pkg: %s\n", b.importPath) } if cpu := sysinfo.CPU.Name(); cpu != "" { fmt.Fprintf(b.w, "cpu: %s\n", cpu) } }) if b.context != nil { // Running go test --test.bench b.context.processBench(b) // Must call doBench. } else { // Running func Benchmark. b.doBench() } } func (b *B) doBench() BenchmarkResult { go b.launch() <-b.signal return b.result } // launch launches the benchmark function. It gradually increases the number // of benchmark iterations until the benchmark runs for the requested benchtime. // launch is run by the doBench function as a separate goroutine. // run1 must have been called on b. func (b *B) launch() { // Signal that we're done whether we return normally // or by FailNow's runtime.Goexit. defer func() { b.signal <- true }() // Run the benchmark for at least the specified amount of time. if b.benchTime.n > 0 { // We already ran a single iteration in run1. // If -benchtime=1x was requested, use that result. // See https://golang.org/issue/32051. if b.benchTime.n > 1 { b.runN(b.benchTime.n) } } else { d := b.benchTime.d for n := int64(1); !b.failed && b.duration < d && n < 1e9; { last := n // Predict required iterations. goalns := d.Nanoseconds() prevIters := int64(b.N) prevns := b.duration.Nanoseconds() if prevns <= 0 { // Round up, to avoid div by zero. prevns = 1 } // Order of operations matters. // For very fast benchmarks, prevIters ~= prevns. // If you divide first, you get 0 or 1, // which can hide an order of magnitude in execution time. // So multiply first, then divide. n = goalns * prevIters / prevns // Run more iterations than we think we'll need (1.2x). n += n / 5 // Don't grow too fast in case we had timing errors previously. n = min(n, 100*last) // Be sure to run at least one more than last time. n = max(n, last+1) // Don't run more than 1e9 times. (This also keeps n in int range on 32 bit platforms.) n = min(n, 1e9) b.runN(int(n)) } } b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra} } // Elapsed returns the measured elapsed time of the benchmark. // The duration reported by Elapsed matches the one measured by // StartTimer, StopTimer, and ResetTimer. func (b *B) Elapsed() time.Duration { d := b.duration if b.timerOn { d += time.Since(b.start) } return d } // ReportMetric adds "n unit" to the reported benchmark results. // If the metric is per-iteration, the caller should divide by b.N, // and by convention units should end in "/op". // ReportMetric overrides any previously reported value for the same unit. // ReportMetric panics if unit is the empty string or if unit contains // any whitespace. // If unit is a unit normally reported by the benchmark framework itself // (such as "allocs/op"), ReportMetric will override that metric. // Setting "ns/op" to 0 will suppress that built-in metric. func (b *B) ReportMetric(n float64, unit string) { if unit == "" { panic("metric unit must not be empty") } if strings.IndexFunc(unit, unicode.IsSpace) >= 0 { panic("metric unit must not contain whitespace") } b.extra[unit] = n } // BenchmarkResult contains the results of a benchmark run. type BenchmarkResult struct { N int // The number of iterations. T time.Duration // The total time taken. Bytes int64 // Bytes processed in one iteration. MemAllocs uint64 // The total number of memory allocations. MemBytes uint64 // The total number of bytes allocated. // Extra records additional metrics reported by ReportMetric. Extra map[string]float64 } // NsPerOp returns the "ns/op" metric. func (r BenchmarkResult) NsPerOp() int64 { if v, ok := r.Extra["ns/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return r.T.Nanoseconds() / int64(r.N) } // mbPerSec returns the "MB/s" metric. func (r BenchmarkResult) mbPerSec() float64 { if v, ok := r.Extra["MB/s"]; ok { return v } if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { return 0 } return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() } // AllocsPerOp returns the "allocs/op" metric, // which is calculated as r.MemAllocs / r.N. func (r BenchmarkResult) AllocsPerOp() int64 { if v, ok := r.Extra["allocs/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return int64(r.MemAllocs) / int64(r.N) } // AllocedBytesPerOp returns the "B/op" metric, // which is calculated as r.MemBytes / r.N. func (r BenchmarkResult) AllocedBytesPerOp() int64 { if v, ok := r.Extra["B/op"]; ok { return int64(v) } if r.N <= 0 { return 0 } return int64(r.MemBytes) / int64(r.N) } // String returns a summary of the benchmark results. // It follows the benchmark result line format from // https://golang.org/design/14313-benchmark-format, not including the // benchmark name. // Extra metrics override built-in metrics of the same name. // String does not include allocs/op or B/op, since those are reported // by MemString. func (r BenchmarkResult) String() string { buf := new(strings.Builder) fmt.Fprintf(buf, "%8d", r.N) // Get ns/op as a float. ns, ok := r.Extra["ns/op"] if !ok { ns = float64(r.T.Nanoseconds()) / float64(r.N) } if ns != 0 { buf.WriteByte('\t') prettyPrint(buf, ns, "ns/op") } if mbs := r.mbPerSec(); mbs != 0 { fmt.Fprintf(buf, "\t%7.2f MB/s", mbs) } // Print extra metrics that aren't represented in the standard // metrics. var extraKeys []string for k := range r.Extra { switch k { case "ns/op", "MB/s", "B/op", "allocs/op": // Built-in metrics reported elsewhere. continue } extraKeys = append(extraKeys, k) } sort.Strings(extraKeys) for _, k := range extraKeys { buf.WriteByte('\t') prettyPrint(buf, r.Extra[k], k) } return buf.String() } func prettyPrint(w io.Writer, x float64, unit string) { // Print all numbers with 10 places before the decimal point // and small numbers with four sig figs. Field widths are // chosen to fit the whole part in 10 places while aligning // the decimal point of all fractional formats. var format string switch y := math.Abs(x); { case y == 0 || y >= 999.95: format = "%10.0f %s" case y >= 99.995: format = "%12.1f %s" case y >= 9.9995: format = "%13.2f %s" case y >= 0.99995: format = "%14.3f %s" case y >= 0.099995: format = "%15.4f %s" case y >= 0.0099995: format = "%16.5f %s" case y >= 0.00099995: format = "%17.6f %s" default: format = "%18.7f %s" } fmt.Fprintf(w, format, x, unit) } // MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'. func (r BenchmarkResult) MemString() string { return fmt.Sprintf("%8d B/op\t%8d allocs/op", r.AllocedBytesPerOp(), r.AllocsPerOp()) } // benchmarkName returns full name of benchmark including procs suffix. func benchmarkName(name string, n int) string { if n != 1 { return fmt.Sprintf("%s-%d", name, n) } return name } type benchContext struct { match *matcher maxLen int // The largest recorded benchmark name. extLen int // Maximum extension length. } // RunBenchmarks is an internal function but exported because it is cross-package; // it is part of the implementation of the "go test" command. func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { runBenchmarks("", matchString, benchmarks) } func runBenchmarks(importPath string, matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool { // If no flag was specified, don't run benchmarks. if len(*matchBenchmarks) == 0 { return true } // Collect matching benchmarks and determine longest name. maxprocs := 1 for _, procs := range cpuList { if procs > maxprocs { maxprocs = procs } } ctx := &benchContext{ match: newMatcher(matchString, *matchBenchmarks, "-test.bench", *skip), extLen: len(benchmarkName("", maxprocs)), } var bs []InternalBenchmark for _, Benchmark := range benchmarks { if _, matched, _ := ctx.match.fullName(nil, Benchmark.Name); matched { bs = append(bs, Benchmark) benchName := benchmarkName(Benchmark.Name, maxprocs) if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen { ctx.maxLen = l } } } main := &B{ common: common{ name: "Main", w: os.Stdout, bench: true, }, importPath: importPath, benchFunc: func(b *B) { for _, Benchmark := range bs { b.Run(Benchmark.Name, Benchmark.F) } }, benchTime: benchTime, context: ctx, } if Verbose() { main.chatty = newChattyPrinter(main.w) } main.runN(1) return !main.failed } // processBench runs bench b for the configured CPU counts and prints the results. func (ctx *benchContext) processBench(b *B) { for i, procs := range cpuList { for j := uint(0); j < *count; j++ { runtime.GOMAXPROCS(procs) benchName := benchmarkName(b.name, procs) // If it's chatty, we've already printed this information. if b.chatty == nil { fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName) } // Recompute the running time for all but the first iteration. if i > 0 || j > 0 { b = &B{ common: common{ signal: make(chan bool), name: b.name, w: b.w, chatty: b.chatty, bench: true, }, benchFunc: b.benchFunc, benchTime: b.benchTime, } b.run1() } r := b.doBench() if b.failed { // The output could be very long here, but probably isn't. // We print it all, regardless, because we don't want to trim the reason // the benchmark failed. fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), benchName, b.output) continue } results := r.String() if b.chatty != nil { fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName) } if *benchmarkMemory || b.showAllocResult { results += "\t" + r.MemString() } fmt.Fprintln(b.w, results) // Unlike with tests, we ignore the -chatty flag and always print output for // benchmarks since the output generation time will skew the results. if len(b.output) > 0 { b.trimOutput() fmt.Fprintf(b.w, "%s--- BENCH: %s\n%s", b.chatty.prefix(), benchName, b.output) } if p := runtime.GOMAXPROCS(-1); p != procs { fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) } if b.chatty != nil && b.chatty.json { b.chatty.Updatef("", "=== NAME %s\n", "") } } } } // If hideStdoutForTesting is true, Run does not print the benchName. // This avoids a spurious print during 'go test' on package testing itself, // which invokes b.Run in its own tests (see sub_test.go). var hideStdoutForTesting = false // Run benchmarks f as a subbenchmark with the given name. It reports // whether there were any failures. // // A subbenchmark is like any other benchmark. A benchmark that calls Run at // least once will not be measured itself and will be called once with N=1. func (b *B) Run(name string, f func(b *B)) bool { // Since b has subbenchmarks, we will no longer run it as a benchmark itself. // Release the lock and acquire it on exit to ensure locks stay paired. b.hasSub.Store(true) benchmarkLock.Unlock() defer benchmarkLock.Lock() benchName, ok, partial := b.name, true, false if b.context != nil { benchName, ok, partial = b.context.match.fullName(&b.common, name) } if !ok { return true } var pc [maxStackLen]uintptr n := runtime.Callers(2, pc[:]) sub := &B{ common: common{ signal: make(chan bool), name: benchName, parent: &b.common, level: b.level + 1, creator: pc[:n], w: b.w, chatty: b.chatty, bench: true, }, importPath: b.importPath, benchFunc: f, benchTime: b.benchTime, context: b.context, } if partial { // Partial name match, like -bench=X/Y matching BenchmarkX. // Only process sub-benchmarks, if any. sub.hasSub.Store(true) } if b.chatty != nil { labelsOnce.Do(func() { fmt.Printf("goos: %s\n", runtime.GOOS) fmt.Printf("goarch: %s\n", runtime.GOARCH) if b.importPath != "" { fmt.Printf("pkg: %s\n", b.importPath) } if cpu := sysinfo.CPU.Name(); cpu != "" { fmt.Printf("cpu: %s\n", cpu) } }) if !hideStdoutForTesting { if b.chatty.json { b.chatty.Updatef(benchName, "=== RUN %s\n", benchName) } fmt.Println(benchName) } } if sub.run1() { sub.run() } b.add(sub.result) return !sub.failed } // add simulates running benchmarks in sequence in a single iteration. It is // used to give some meaningful results in case func Benchmark is used in // combination with Run. func (b *B) add(other BenchmarkResult) { r := &b.result // The aggregated BenchmarkResults resemble running all subbenchmarks as // in sequence in a single benchmark. r.N = 1 r.T += time.Duration(other.NsPerOp()) if other.Bytes == 0 { // Summing Bytes is meaningless in aggregate if not all subbenchmarks // set it. b.missingBytes = true r.Bytes = 0 } if !b.missingBytes { r.Bytes += other.Bytes } r.MemAllocs += uint64(other.AllocsPerOp()) r.MemBytes += uint64(other.AllocedBytesPerOp()) } // trimOutput shortens the output from a benchmark, which can be very long. func (b *B) trimOutput() { // The output is likely to appear multiple times because the benchmark // is run multiple times, but at least it will be seen. This is not a big deal // because benchmarks rarely print, but just in case, we trim it if it's too long. const maxNewlines = 10 for nlCount, j := 0, 0; j < len(b.output); j++ { if b.output[j] == '\n' { nlCount++ if nlCount >= maxNewlines { b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) break } } } } // A PB is used by RunParallel for running parallel benchmarks. type PB struct { globalN *uint64 // shared between all worker goroutines iteration counter grain uint64 // acquire that many iterations from globalN at once cache uint64 // local cache of acquired iterations bN uint64 // total number of iterations to execute (b.N) } // Next reports whether there are more iterations to execute. func (pb *PB) Next() bool { if pb.cache == 0 { n := atomic.AddUint64(pb.globalN, pb.grain) if n <= pb.bN { pb.cache = pb.grain } else if n < pb.bN+pb.grain { pb.cache = pb.bN + pb.grain - n } else { return false } } pb.cache-- return true } // RunParallel runs a benchmark in parallel. // It creates multiple goroutines and distributes b.N iterations among them. // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for // non-CPU-bound benchmarks, call SetParallelism before RunParallel. // RunParallel is usually used with the go test -cpu flag. // // The body function will be run in each goroutine. It should set up any // goroutine-local state and then iterate until pb.Next returns false. // It should not use the StartTimer, StopTimer, or ResetTimer functions, // because they have global effect. It should also not call Run. // // RunParallel reports ns/op values as wall time for the benchmark as a whole, // not the sum of wall time or CPU time over each parallel goroutine. func (b *B) RunParallel(body func(*PB)) { if b.N == 0 { return // Nothing to do when probing. } // Calculate grain size as number of iterations that take ~100µs. // 100µs is enough to amortize the overhead and provide sufficient // dynamic load balancing. grain := uint64(0) if b.previousN > 0 && b.previousDuration > 0 { grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration) } if grain < 1 { grain = 1 } // We expect the inner loop and function call to take at least 10ns, // so do not do more than 100µs/10ns=1e4 iterations. if grain > 1e4 { grain = 1e4 } n := uint64(0) numProcs := b.parallelism * runtime.GOMAXPROCS(0) var wg sync.WaitGroup wg.Add(numProcs) for p := 0; p < numProcs; p++ { go func() { defer wg.Done() pb := &PB{ globalN: &n, grain: grain, bN: uint64(b.N), } body(pb) }() } wg.Wait() if n <= uint64(b.N) && !b.Failed() { b.Fatal("RunParallel: body exited without pb.Next() == false") } } // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. // There is usually no need to call SetParallelism for CPU-bound benchmarks. // If p is less than 1, this call will have no effect. func (b *B) SetParallelism(p int) { if p >= 1 { b.parallelism = p } } // Benchmark benchmarks a single function. It is useful for creating // custom benchmarks that do not use the "go test" command. // // If f depends on testing flags, then Init must be used to register // those flags before calling Benchmark and before calling flag.Parse. // // If f calls Run, the result will be an estimate of running all its // subbenchmarks that don't call Run in sequence in a single benchmark. func Benchmark(f func(b *B)) BenchmarkResult { b := &B{ common: common{ signal: make(chan bool), w: discard{}, }, benchFunc: f, benchTime: benchTime, } if b.run1() { b.run() } return b.result } type discard struct{} func (discard) Write(b []byte) (n int, err error) { return len(b), nil }
// Copyright 2015 The etcd Authors // // 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 wal import ( "bytes" "errors" "fmt" "hash/crc32" "io" "os" "path/filepath" "strings" "sync" "time" "go.etcd.io/etcd/pkg/v3/fileutil" "go.etcd.io/etcd/pkg/v3/pbutil" "go.etcd.io/etcd/raft/v3" "go.etcd.io/etcd/raft/v3/raftpb" "go.etcd.io/etcd/server/v3/wal/walpb" "go.uber.org/zap" ) const ( metadataType int64 = iota + 1 entryType stateType crcType snapshotType // warnSyncDuration is the amount of time allotted to an fsync before // logging a warning warnSyncDuration = time.Second ) var ( // SegmentSizeBytes is the preallocated size of each wal segment file. // The actual size might be larger than this. In general, the default // value should be used, but this is defined as an exported variable // so that tests can set a different segment size. SegmentSizeBytes int64 = 64 * 1000 * 1000 // 64MB ErrMetadataConflict = errors.New("wal: conflicting metadata found") ErrFileNotFound = errors.New("wal: file not found") ErrCRCMismatch = errors.New("wal: crc mismatch") ErrSnapshotMismatch = errors.New("wal: snapshot mismatch") ErrSnapshotNotFound = errors.New("wal: snapshot not found") ErrSliceOutOfRange = errors.New("wal: slice bounds out of range") ErrMaxWALEntrySizeLimitExceeded = errors.New("wal: max entry size limit exceeded") ErrDecoderNotFound = errors.New("wal: decoder not found") crcTable = crc32.MakeTable(crc32.Castagnoli) ) // WAL is a logical representation of the stable storage. // WAL is either in read mode or append mode but not both. // A newly created WAL is in append mode, and ready for appending records. // A just opened WAL is in read mode, and ready for reading records. // The WAL will be ready for appending after reading out all the previous records. type WAL struct { lg *zap.Logger dir string // the living directory of the underlay files // dirFile is a fd for the wal directory for syncing on Rename dirFile *os.File metadata []byte // metadata recorded at the head of each WAL state raftpb.HardState // hardstate recorded at the head of WAL start walpb.Snapshot // snapshot to start reading decoder *decoder // decoder to decode records readClose func() error // closer for decode reader unsafeNoSync bool // if set, do not fsync mu sync.Mutex enti uint64 // index of the last entry saved to the wal encoder *encoder // encoder to encode records locks []*fileutil.LockedFile // the locked files the WAL holds (the name is increasing) fp *filePipeline } // Create creates a WAL ready for appending records. The given metadata is // recorded at the head of each WAL file, and can be retrieved with ReadAll // after the file is Open. func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error) { if Exist(dirpath) { return nil, os.ErrExist } if lg == nil { lg = zap.NewNop() } // keep temporary wal directory so WAL initialization appears atomic tmpdirpath := filepath.Clean(dirpath) + ".tmp" if fileutil.Exist(tmpdirpath) { if err := os.RemoveAll(tmpdirpath); err != nil { return nil, err } } defer os.RemoveAll(tmpdirpath) if err := fileutil.CreateDirAll(tmpdirpath); err != nil { lg.Warn( "failed to create a temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", dirpath), zap.Error(err), ) return nil, err } p := filepath.Join(tmpdirpath, walName(0, 0)) f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode) if err != nil { lg.Warn( "failed to flock an initial WAL file", zap.String("path", p), zap.Error(err), ) return nil, err } if _, err = f.Seek(0, io.SeekEnd); err != nil { lg.Warn( "failed to seek an initial WAL file", zap.String("path", p), zap.Error(err), ) return nil, err } if err = fileutil.Preallocate(f.File, SegmentSizeBytes, true); err != nil { lg.Warn( "failed to preallocate an initial WAL file", zap.String("path", p), zap.Int64("segment-bytes", SegmentSizeBytes), zap.Error(err), ) return nil, err } w := &WAL{ lg: lg, dir: dirpath, metadata: metadata, } w.encoder, err = newFileEncoder(f.File, 0) if err != nil { return nil, err } w.locks = append(w.locks, f) if err = w.saveCrc(0); err != nil { return nil, err } if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil { return nil, err } if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil { return nil, err } logDirPath := w.dir if w, err = w.renameWAL(tmpdirpath); err != nil { lg.Warn( "failed to rename the temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", logDirPath), zap.Error(err), ) return nil, err } var perr error defer func() { if perr != nil { w.cleanupWAL(lg) } }() // directory was renamed; sync parent dir to persist rename pdir, perr := fileutil.OpenDir(filepath.Dir(w.dir)) if perr != nil { lg.Warn( "failed to open the parent data directory", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return nil, perr } dirCloser := func() error { if perr = pdir.Close(); perr != nil { lg.Warn( "failed to close the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return perr } return nil } start := time.Now() if perr = fileutil.Fsync(pdir); perr != nil { dirCloser() lg.Warn( "failed to fsync the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return nil, perr } walFsyncSec.Observe(time.Since(start).Seconds()) if err = dirCloser(); err != nil { return nil, err } return w, nil } func (w *WAL) SetUnsafeNoFsync() { w.unsafeNoSync = true } func (w *WAL) cleanupWAL(lg *zap.Logger) { var err error if err = w.Close(); err != nil { lg.Panic("failed to close WAL during cleanup", zap.Error(err)) } brokenDirName := fmt.Sprintf("%s.broken.%v", w.dir, time.Now().Format("20060102.150405.999999")) if err = os.Rename(w.dir, brokenDirName); err != nil { lg.Panic( "failed to rename WAL during cleanup", zap.Error(err), zap.String("source-path", w.dir), zap.String("rename-path", brokenDirName), ) } } func (w *WAL) renameWAL(tmpdirpath string) (*WAL, error) { if err := os.RemoveAll(w.dir); err != nil { return nil, err } // On non-Windows platforms, hold the lock while renaming. Releasing // the lock and trying to reacquire it quickly can be flaky because // it's possible the process will fork to spawn a process while this is // happening. The fds are set up as close-on-exec by the Go runtime, // but there is a window between the fork and the exec where another // process holds the lock. if err := os.Rename(tmpdirpath, w.dir); err != nil { if _, ok := err.(*os.LinkError); ok { return w.renameWALUnlock(tmpdirpath) } return nil, err } w.fp = newFilePipeline(w.lg, w.dir, SegmentSizeBytes) df, err := fileutil.OpenDir(w.dir) w.dirFile = df return w, err } func (w *WAL) renameWALUnlock(tmpdirpath string) (*WAL, error) { // rename of directory with locked files doesn't work on windows/cifs; // close the WAL to release the locks so the directory can be renamed. w.lg.Info( "closing WAL to release flock and retry directory renaming", zap.String("from", tmpdirpath), zap.String("to", w.dir), ) w.Close() if err := os.Rename(tmpdirpath, w.dir); err != nil { return nil, err } // reopen and relock newWAL, oerr := Open(w.lg, w.dir, walpb.Snapshot{}) if oerr != nil { return nil, oerr } if _, _, _, err := newWAL.ReadAll(); err != nil { newWAL.Close() return nil, err } return newWAL, nil } // Open opens the WAL at the given snap. // The snap SHOULD have been previously saved to the WAL, or the following // ReadAll will fail. // The returned WAL is ready to read and the first record will be the one after // the given snap. The WAL cannot be appended to before reading out all of its // previous records. func Open(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) { w, err := openAtIndex(lg, dirpath, snap, true) if err != nil { return nil, err } if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil { return nil, err } return w, nil } // OpenForRead only opens the wal files for read. // Write on a read only wal panics. func OpenForRead(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) { return openAtIndex(lg, dirpath, snap, false) } func openAtIndex(lg *zap.Logger, dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) { if lg == nil { lg = zap.NewNop() } names, nameIndex, err := selectWALFiles(lg, dirpath, snap) if err != nil { return nil, err } rs, ls, closer, err := openWALFiles(lg, dirpath, names, nameIndex, write) if err != nil { return nil, err } // create a WAL ready for reading w := &WAL{ lg: lg, dir: dirpath, start: snap, decoder: newDecoder(rs...), readClose: closer, locks: ls, } if write { // write reuses the file descriptors from read; don't close so // WAL can append without dropping the file lock w.readClose = nil if _, _, err := parseWALName(filepath.Base(w.tail().Name())); err != nil { closer() return nil, err } w.fp = newFilePipeline(lg, w.dir, SegmentSizeBytes) } return w, nil } func selectWALFiles(lg *zap.Logger, dirpath string, snap walpb.Snapshot) ([]string, int, error) { names, err := readWALNames(lg, dirpath) if err != nil { return nil, -1, err } nameIndex, ok := searchIndex(lg, names, snap.Index) if !ok || !isValidSeq(lg, names[nameIndex:]) { err = ErrFileNotFound return nil, -1, err } return names, nameIndex, nil } func openWALFiles(lg *zap.Logger, dirpath string, names []string, nameIndex int, write bool) ([]io.Reader, []*fileutil.LockedFile, func() error, error) { rcs := make([]io.ReadCloser, 0) rs := make([]io.Reader, 0) ls := make([]*fileutil.LockedFile, 0) for _, name := range names[nameIndex:] { p := filepath.Join(dirpath, name) if write { l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode) if err != nil { closeAll(lg, rcs...) return nil, nil, nil, err } ls = append(ls, l) rcs = append(rcs, l) } else { rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode) if err != nil { closeAll(lg, rcs...) return nil, nil, nil, err } ls = append(ls, nil) rcs = append(rcs, rf) } rs = append(rs, rcs[len(rcs)-1]) } closer := func() error { return closeAll(lg, rcs...) } return rs, ls, closer, nil } // ReadAll reads out records of the current WAL. // If opened in write mode, it must read out all records until EOF. Or an error // will be returned. // If opened in read mode, it will try to read all records if possible. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound. // If loaded snap doesn't match with the expected one, it will return // all the records and error ErrSnapshotMismatch. // TODO: detect not-last-snap error. // TODO: maybe loose the checking of match. // After ReadAll, the WAL will be ready for appending new records. // // ReadAll suppresses WAL entries that got overridden (i.e. a newer entry with the same index // exists in the log). Such a situation can happen in cases described in figure 7. of the // RAFT paper (http://web.stanford.edu/~ouster/cgi-bin/papers/raft-atc14.pdf). // // ReadAll may return uncommitted yet entries, that are subject to be overriden. // Do not apply entries that have index > state.commit, as they are subject to change. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) { w.mu.Lock() defer w.mu.Unlock() rec := &walpb.Record{} if w.decoder == nil { return nil, state, nil, ErrDecoderNotFound } decoder := w.decoder var match bool for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case entryType: e := mustUnmarshalEntry(rec.Data) // 0 <= e.Index-w.start.Index - 1 < len(ents) if e.Index > w.start.Index { // prevent "panic: runtime error: slice bounds out of range [:13038096702221461992] with capacity 0" up := e.Index - w.start.Index - 1 if up > uint64(len(ents)) { // return error before append call causes runtime panic return nil, state, nil, ErrSliceOutOfRange } // The line below is potentially overriding some 'uncommitted' entries. ents = append(ents[:up], e) } w.enti = e.Index case stateType: state = mustUnmarshalState(rec.Data) case metadataType: if metadata != nil && !bytes.Equal(metadata, rec.Data) { state.Reset() return nil, state, nil, ErrMetadataConflict } metadata = rec.Data case crcType: crc := decoder.crc.Sum32() // current crc of decoder must match the crc of the record. // do no need to match 0 crc, since the decoder is a new one at this case. if crc != 0 && rec.Validate(crc) != nil { state.Reset() return nil, state, nil, ErrCRCMismatch } decoder.updateCRC(rec.Crc) case snapshotType: var snap walpb.Snapshot pbutil.MustUnmarshal(&snap, rec.Data) if snap.Index == w.start.Index { if snap.Term != w.start.Term { state.Reset() return nil, state, nil, ErrSnapshotMismatch } match = true } default: state.Reset() return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type) } } switch w.tail() { case nil: // We do not have to read out all entries in read mode. // The last record maybe a partial written one, so // ErrunexpectedEOF might be returned. if err != io.EOF && err != io.ErrUnexpectedEOF { state.Reset() return nil, state, nil, err } default: // We must read all of the entries if WAL is opened in write mode. if err != io.EOF { state.Reset() return nil, state, nil, err } // decodeRecord() will return io.EOF if it detects a zero record, // but this zero record may be followed by non-zero records from // a torn write. Overwriting some of these non-zero records, but // not all, will cause CRC errors on WAL open. Since the records // were never fully synced to disk in the first place, it's safe // to zero them out to avoid any CRC errors from new writes. if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil { return nil, state, nil, err } if err = fileutil.ZeroToEnd(w.tail().File); err != nil { return nil, state, nil, err } } err = nil if !match { err = ErrSnapshotNotFound } // close decoder, disable reading if w.readClose != nil { w.readClose() w.readClose = nil } w.start = walpb.Snapshot{} w.metadata = metadata if w.tail() != nil { // create encoder (chain crc with the decoder), enable appending w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC()) if err != nil { return } } w.decoder = nil return metadata, state, ents, err } // ValidSnapshotEntries returns all the valid snapshot entries in the wal logs in the given directory. // Snapshot entries are valid if their index is less than or equal to the most recent committed hardstate. func ValidSnapshotEntries(lg *zap.Logger, walDir string) ([]walpb.Snapshot, error) { var snaps []walpb.Snapshot var state raftpb.HardState var err error rec := &walpb.Record{} names, err := readWALNames(lg, walDir) if err != nil { return nil, err } // open wal files in read mode, so that there is no conflict // when the same WAL is opened elsewhere in write mode rs, _, closer, err := openWALFiles(lg, walDir, names, 0, false) if err != nil { return nil, err } defer func() { if closer != nil { closer() } }() // create a new decoder from the readers on the WAL files decoder := newDecoder(rs...) for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case snapshotType: var loadedSnap walpb.Snapshot pbutil.MustUnmarshal(&loadedSnap, rec.Data) snaps = append(snaps, loadedSnap) case stateType: state = mustUnmarshalState(rec.Data) case crcType: crc := decoder.crc.Sum32() // current crc of decoder must match the crc of the record. // do no need to match 0 crc, since the decoder is a new one at this case. if crc != 0 && rec.Validate(crc) != nil { return nil, ErrCRCMismatch } decoder.updateCRC(rec.Crc) } } // We do not have to read out all the WAL entries // as the decoder is opened in read mode. if err != io.EOF && err != io.ErrUnexpectedEOF { return nil, err } // filter out any snaps that are newer than the committed hardstate n := 0 for _, s := range snaps { if s.Index <= state.Commit { snaps[n] = s n++ } } snaps = snaps[:n:n] return snaps, nil } // Verify reads through the given WAL and verifies that it is not corrupted. // It creates a new decoder to read through the records of the given WAL. // It does not conflict with any open WAL, but it is recommended not to // call this function after opening the WAL for writing. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound. // If the loaded snap doesn't match with the expected one, it will // return error ErrSnapshotMismatch. func Verify(lg *zap.Logger, walDir string, snap walpb.Snapshot) error { var metadata []byte var err error var match bool rec := &walpb.Record{} if lg == nil { lg = zap.NewNop() } names, nameIndex, err := selectWALFiles(lg, walDir, snap) if err != nil { return err } // open wal files in read mode, so that there is no conflict // when the same WAL is opened elsewhere in write mode rs, _, closer, err := openWALFiles(lg, walDir, names, nameIndex, false) if err != nil { return err } defer func() { if closer != nil { closer() } }() // create a new decoder from the readers on the WAL files decoder := newDecoder(rs...) for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case metadataType: if metadata != nil && !bytes.Equal(metadata, rec.Data) { return ErrMetadataConflict } metadata = rec.Data case crcType: crc := decoder.crc.Sum32() // Current crc of decoder must match the crc of the record. // We need not match 0 crc, since the decoder is a new one at this point. if crc != 0 && rec.Validate(crc) != nil { return ErrCRCMismatch } decoder.updateCRC(rec.Crc) case snapshotType: var loadedSnap walpb.Snapshot pbutil.MustUnmarshal(&loadedSnap, rec.Data) if loadedSnap.Index == snap.Index { if loadedSnap.Term != snap.Term { return ErrSnapshotMismatch } match = true } // We ignore all entry and state type records as these // are not necessary for validating the WAL contents case entryType: case stateType: default: return fmt.Errorf("unexpected block type %d", rec.Type) } } // We do not have to read out all the WAL entries // as the decoder is opened in read mode. if err != io.EOF && err != io.ErrUnexpectedEOF { return err } if !match { return ErrSnapshotNotFound } return nil } // cut closes current file written and creates a new one ready to append. // cut first creates a temp wal file and writes necessary headers into it. // Then cut atomically rename temp wal file to a wal file. func (w *WAL) cut() error { // close old wal file; truncate to avoid wasting space if an early cut off, serr := w.tail().Seek(0, io.SeekCurrent) if serr != nil { return serr } if err := w.tail().Truncate(off); err != nil { return err } if err := w.sync(); err != nil { return err } fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1)) // create a temp wal file with name sequence + 1, or truncate the existing one newTail, err := w.fp.Open() if err != nil { return err } // update writer and save the previous crc w.locks = append(w.locks, newTail) prevCrc := w.encoder.crc.Sum32() w.encoder, err = newFileEncoder(w.tail().File, prevCrc) if err != nil { return err } if err = w.saveCrc(prevCrc); err != nil { return err } if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil { return err } if err = w.saveState(&w.state); err != nil { return err } // atomically move temp wal file to wal file if err = w.sync(); err != nil { return err } off, err = w.tail().Seek(0, io.SeekCurrent) if err != nil { return err } if err = os.Rename(newTail.Name(), fpath); err != nil { return err } start := time.Now() if err = fileutil.Fsync(w.dirFile); err != nil { return err } walFsyncSec.Observe(time.Since(start).Seconds()) // reopen newTail with its new path so calls to Name() match the wal filename format newTail.Close() if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil { return err } if _, err = newTail.Seek(off, io.SeekStart); err != nil { return err } w.locks[len(w.locks)-1] = newTail prevCrc = w.encoder.crc.Sum32() w.encoder, err = newFileEncoder(w.tail().File, prevCrc) if err != nil { return err } w.lg.Info("created a new WAL segment", zap.String("path", fpath)) return nil } func (w *WAL) sync() error { if w.unsafeNoSync { return nil } if w.encoder != nil { if err := w.encoder.flush(); err != nil { return err } } start := time.Now() err := fileutil.Fdatasync(w.tail().File) took := time.Since(start) if took > warnSyncDuration { w.lg.Warn( "slow fdatasync", zap.Duration("took", took), zap.Duration("expected-duration", warnSyncDuration), ) } walFsyncSec.Observe(took.Seconds()) return err } func (w *WAL) Sync() error { return w.sync() } // ReleaseLockTo releases the locks, which has smaller index than the given index // except the largest one among them. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4. func (w *WAL) ReleaseLockTo(index uint64) error { w.mu.Lock() defer w.mu.Unlock() if len(w.locks) == 0 { return nil } var smaller int found := false for i, l := range w.locks { _, lockIndex, err := parseWALName(filepath.Base(l.Name())) if err != nil { return err } if lockIndex >= index { smaller = i - 1 found = true break } } // if no lock index is greater than the release index, we can // release lock up to the last one(excluding). if !found { smaller = len(w.locks) - 1 } if smaller <= 0 { return nil } for i := 0; i < smaller; i++ { if w.locks[i] == nil { continue } w.locks[i].Close() } w.locks = w.locks[smaller:] return nil } // Close closes the current WAL file and directory. func (w *WAL) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.fp != nil { w.fp.Close() w.fp = nil } if w.tail() != nil { if err := w.sync(); err != nil { return err } } for _, l := range w.locks { if l == nil { continue } if err := l.Close(); err != nil { w.lg.Error("failed to close WAL", zap.Error(err)) } } return w.dirFile.Close() } func (w *WAL) saveEntry(e *raftpb.Entry) error { // TODO: add MustMarshalTo to reduce one allocation. b := pbutil.MustMarshal(e) rec := &walpb.Record{Type: entryType, Data: b} if err := w.encoder.encode(rec); err != nil { return err } w.enti = e.Index return nil } func (w *WAL) saveState(s *raftpb.HardState) error { if raft.IsEmptyHardState(*s) { return nil } w.state = *s b := pbutil.MustMarshal(s) rec := &walpb.Record{Type: stateType, Data: b} return w.encoder.encode(rec) } func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error { w.mu.Lock() defer w.mu.Unlock() // short cut, do not call sync if raft.IsEmptyHardState(st) && len(ents) == 0 { return nil } mustSync := raft.MustSync(st, w.state, len(ents)) // TODO(xiangli): no more reference operator for i := range ents { if err := w.saveEntry(&ents[i]); err != nil { return err } } if err := w.saveState(&st); err != nil { return err } curOff, err := w.tail().Seek(0, io.SeekCurrent) if err != nil { return err } if curOff < SegmentSizeBytes { if mustSync { return w.sync() } return nil } return w.cut() } func (w *WAL) SaveSnapshot(e walpb.Snapshot) error { b := pbutil.MustMarshal(&e) w.mu.Lock() defer w.mu.Unlock() rec := &walpb.Record{Type: snapshotType, Data: b} if err := w.encoder.encode(rec); err != nil { return err } // update enti only when snapshot is ahead of last index if w.enti < e.Index { w.enti = e.Index } return w.sync() } func (w *WAL) saveCrc(prevCrc uint32) error { return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc}) } func (w *WAL) tail() *fileutil.LockedFile { if len(w.locks) > 0 { return w.locks[len(w.locks)-1] } return nil } func (w *WAL) seq() uint64 { t := w.tail() if t == nil { return 0 } seq, _, err := parseWALName(filepath.Base(t.Name())) if err != nil { w.lg.Fatal("failed to parse WAL name", zap.String("name", t.Name()), zap.Error(err)) } return seq } func closeAll(lg *zap.Logger, rcs ...io.ReadCloser) error { stringArr := make([]string, 0) for _, f := range rcs { if err := f.Close(); err != nil { lg.Warn("failed to close: ", zap.Error(err)) stringArr = append(stringArr, err.Error()) } } if len(stringArr) == 0 { return nil } return errors.New(strings.Join(stringArr, ", ")) } etcdserver: when using --unsafe-no-fsync write data There are situations where we don't wish to fsync but we do want to write the data. Typically this occurs in clusters where fsync latency (often the result of firmware) transiently spikes. For Kubernetes clusters this causes (many) elections which have knock-on effects such that the API server will transiently fail causing other components fail in turn. By writing the data (buffered and asynchronously flushed, so in most situations the write is fast) and avoiding the fsync we no longer trigger this situation and opportunistically write out the data. Anecdotally: Because the fsync is missing there is the argument that certain types of failure events will cause data corruption or loss, in testing this wasn't seen. If this was to occur the expectation is the member can be readded to a cluster or worst-case restored from a robust persisted snapshot. The etcd members are deployed across isolated racks with different power feeds. An instantaneous failure of all of them simultaneously is unlikely. Testing was usually of the form: * create (Kubernetes) etcd write-churn by creating replicasets of some 1000s of pods * break/fail the leader Failure testing included: * hard node power-off events * disk removal * orderly reboots/shutdown In all cases when the node recovered it was able to rejoin the cluster and synchronize. // Copyright 2015 The etcd Authors // // 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 wal import ( "bytes" "errors" "fmt" "hash/crc32" "io" "os" "path/filepath" "strings" "sync" "time" "go.etcd.io/etcd/pkg/v3/fileutil" "go.etcd.io/etcd/pkg/v3/pbutil" "go.etcd.io/etcd/raft/v3" "go.etcd.io/etcd/raft/v3/raftpb" "go.etcd.io/etcd/server/v3/wal/walpb" "go.uber.org/zap" ) const ( metadataType int64 = iota + 1 entryType stateType crcType snapshotType // warnSyncDuration is the amount of time allotted to an fsync before // logging a warning warnSyncDuration = time.Second ) var ( // SegmentSizeBytes is the preallocated size of each wal segment file. // The actual size might be larger than this. In general, the default // value should be used, but this is defined as an exported variable // so that tests can set a different segment size. SegmentSizeBytes int64 = 64 * 1000 * 1000 // 64MB ErrMetadataConflict = errors.New("wal: conflicting metadata found") ErrFileNotFound = errors.New("wal: file not found") ErrCRCMismatch = errors.New("wal: crc mismatch") ErrSnapshotMismatch = errors.New("wal: snapshot mismatch") ErrSnapshotNotFound = errors.New("wal: snapshot not found") ErrSliceOutOfRange = errors.New("wal: slice bounds out of range") ErrMaxWALEntrySizeLimitExceeded = errors.New("wal: max entry size limit exceeded") ErrDecoderNotFound = errors.New("wal: decoder not found") crcTable = crc32.MakeTable(crc32.Castagnoli) ) // WAL is a logical representation of the stable storage. // WAL is either in read mode or append mode but not both. // A newly created WAL is in append mode, and ready for appending records. // A just opened WAL is in read mode, and ready for reading records. // The WAL will be ready for appending after reading out all the previous records. type WAL struct { lg *zap.Logger dir string // the living directory of the underlay files // dirFile is a fd for the wal directory for syncing on Rename dirFile *os.File metadata []byte // metadata recorded at the head of each WAL state raftpb.HardState // hardstate recorded at the head of WAL start walpb.Snapshot // snapshot to start reading decoder *decoder // decoder to decode records readClose func() error // closer for decode reader unsafeNoSync bool // if set, do not fsync mu sync.Mutex enti uint64 // index of the last entry saved to the wal encoder *encoder // encoder to encode records locks []*fileutil.LockedFile // the locked files the WAL holds (the name is increasing) fp *filePipeline } // Create creates a WAL ready for appending records. The given metadata is // recorded at the head of each WAL file, and can be retrieved with ReadAll // after the file is Open. func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error) { if Exist(dirpath) { return nil, os.ErrExist } if lg == nil { lg = zap.NewNop() } // keep temporary wal directory so WAL initialization appears atomic tmpdirpath := filepath.Clean(dirpath) + ".tmp" if fileutil.Exist(tmpdirpath) { if err := os.RemoveAll(tmpdirpath); err != nil { return nil, err } } defer os.RemoveAll(tmpdirpath) if err := fileutil.CreateDirAll(tmpdirpath); err != nil { lg.Warn( "failed to create a temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", dirpath), zap.Error(err), ) return nil, err } p := filepath.Join(tmpdirpath, walName(0, 0)) f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode) if err != nil { lg.Warn( "failed to flock an initial WAL file", zap.String("path", p), zap.Error(err), ) return nil, err } if _, err = f.Seek(0, io.SeekEnd); err != nil { lg.Warn( "failed to seek an initial WAL file", zap.String("path", p), zap.Error(err), ) return nil, err } if err = fileutil.Preallocate(f.File, SegmentSizeBytes, true); err != nil { lg.Warn( "failed to preallocate an initial WAL file", zap.String("path", p), zap.Int64("segment-bytes", SegmentSizeBytes), zap.Error(err), ) return nil, err } w := &WAL{ lg: lg, dir: dirpath, metadata: metadata, } w.encoder, err = newFileEncoder(f.File, 0) if err != nil { return nil, err } w.locks = append(w.locks, f) if err = w.saveCrc(0); err != nil { return nil, err } if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil { return nil, err } if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil { return nil, err } logDirPath := w.dir if w, err = w.renameWAL(tmpdirpath); err != nil { lg.Warn( "failed to rename the temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", logDirPath), zap.Error(err), ) return nil, err } var perr error defer func() { if perr != nil { w.cleanupWAL(lg) } }() // directory was renamed; sync parent dir to persist rename pdir, perr := fileutil.OpenDir(filepath.Dir(w.dir)) if perr != nil { lg.Warn( "failed to open the parent data directory", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return nil, perr } dirCloser := func() error { if perr = pdir.Close(); perr != nil { lg.Warn( "failed to close the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return perr } return nil } start := time.Now() if perr = fileutil.Fsync(pdir); perr != nil { dirCloser() lg.Warn( "failed to fsync the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) return nil, perr } walFsyncSec.Observe(time.Since(start).Seconds()) if err = dirCloser(); err != nil { return nil, err } return w, nil } func (w *WAL) SetUnsafeNoFsync() { w.unsafeNoSync = true } func (w *WAL) cleanupWAL(lg *zap.Logger) { var err error if err = w.Close(); err != nil { lg.Panic("failed to close WAL during cleanup", zap.Error(err)) } brokenDirName := fmt.Sprintf("%s.broken.%v", w.dir, time.Now().Format("20060102.150405.999999")) if err = os.Rename(w.dir, brokenDirName); err != nil { lg.Panic( "failed to rename WAL during cleanup", zap.Error(err), zap.String("source-path", w.dir), zap.String("rename-path", brokenDirName), ) } } func (w *WAL) renameWAL(tmpdirpath string) (*WAL, error) { if err := os.RemoveAll(w.dir); err != nil { return nil, err } // On non-Windows platforms, hold the lock while renaming. Releasing // the lock and trying to reacquire it quickly can be flaky because // it's possible the process will fork to spawn a process while this is // happening. The fds are set up as close-on-exec by the Go runtime, // but there is a window between the fork and the exec where another // process holds the lock. if err := os.Rename(tmpdirpath, w.dir); err != nil { if _, ok := err.(*os.LinkError); ok { return w.renameWALUnlock(tmpdirpath) } return nil, err } w.fp = newFilePipeline(w.lg, w.dir, SegmentSizeBytes) df, err := fileutil.OpenDir(w.dir) w.dirFile = df return w, err } func (w *WAL) renameWALUnlock(tmpdirpath string) (*WAL, error) { // rename of directory with locked files doesn't work on windows/cifs; // close the WAL to release the locks so the directory can be renamed. w.lg.Info( "closing WAL to release flock and retry directory renaming", zap.String("from", tmpdirpath), zap.String("to", w.dir), ) w.Close() if err := os.Rename(tmpdirpath, w.dir); err != nil { return nil, err } // reopen and relock newWAL, oerr := Open(w.lg, w.dir, walpb.Snapshot{}) if oerr != nil { return nil, oerr } if _, _, _, err := newWAL.ReadAll(); err != nil { newWAL.Close() return nil, err } return newWAL, nil } // Open opens the WAL at the given snap. // The snap SHOULD have been previously saved to the WAL, or the following // ReadAll will fail. // The returned WAL is ready to read and the first record will be the one after // the given snap. The WAL cannot be appended to before reading out all of its // previous records. func Open(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) { w, err := openAtIndex(lg, dirpath, snap, true) if err != nil { return nil, err } if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil { return nil, err } return w, nil } // OpenForRead only opens the wal files for read. // Write on a read only wal panics. func OpenForRead(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) { return openAtIndex(lg, dirpath, snap, false) } func openAtIndex(lg *zap.Logger, dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) { if lg == nil { lg = zap.NewNop() } names, nameIndex, err := selectWALFiles(lg, dirpath, snap) if err != nil { return nil, err } rs, ls, closer, err := openWALFiles(lg, dirpath, names, nameIndex, write) if err != nil { return nil, err } // create a WAL ready for reading w := &WAL{ lg: lg, dir: dirpath, start: snap, decoder: newDecoder(rs...), readClose: closer, locks: ls, } if write { // write reuses the file descriptors from read; don't close so // WAL can append without dropping the file lock w.readClose = nil if _, _, err := parseWALName(filepath.Base(w.tail().Name())); err != nil { closer() return nil, err } w.fp = newFilePipeline(lg, w.dir, SegmentSizeBytes) } return w, nil } func selectWALFiles(lg *zap.Logger, dirpath string, snap walpb.Snapshot) ([]string, int, error) { names, err := readWALNames(lg, dirpath) if err != nil { return nil, -1, err } nameIndex, ok := searchIndex(lg, names, snap.Index) if !ok || !isValidSeq(lg, names[nameIndex:]) { err = ErrFileNotFound return nil, -1, err } return names, nameIndex, nil } func openWALFiles(lg *zap.Logger, dirpath string, names []string, nameIndex int, write bool) ([]io.Reader, []*fileutil.LockedFile, func() error, error) { rcs := make([]io.ReadCloser, 0) rs := make([]io.Reader, 0) ls := make([]*fileutil.LockedFile, 0) for _, name := range names[nameIndex:] { p := filepath.Join(dirpath, name) if write { l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode) if err != nil { closeAll(lg, rcs...) return nil, nil, nil, err } ls = append(ls, l) rcs = append(rcs, l) } else { rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode) if err != nil { closeAll(lg, rcs...) return nil, nil, nil, err } ls = append(ls, nil) rcs = append(rcs, rf) } rs = append(rs, rcs[len(rcs)-1]) } closer := func() error { return closeAll(lg, rcs...) } return rs, ls, closer, nil } // ReadAll reads out records of the current WAL. // If opened in write mode, it must read out all records until EOF. Or an error // will be returned. // If opened in read mode, it will try to read all records if possible. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound. // If loaded snap doesn't match with the expected one, it will return // all the records and error ErrSnapshotMismatch. // TODO: detect not-last-snap error. // TODO: maybe loose the checking of match. // After ReadAll, the WAL will be ready for appending new records. // // ReadAll suppresses WAL entries that got overridden (i.e. a newer entry with the same index // exists in the log). Such a situation can happen in cases described in figure 7. of the // RAFT paper (http://web.stanford.edu/~ouster/cgi-bin/papers/raft-atc14.pdf). // // ReadAll may return uncommitted yet entries, that are subject to be overriden. // Do not apply entries that have index > state.commit, as they are subject to change. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) { w.mu.Lock() defer w.mu.Unlock() rec := &walpb.Record{} if w.decoder == nil { return nil, state, nil, ErrDecoderNotFound } decoder := w.decoder var match bool for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case entryType: e := mustUnmarshalEntry(rec.Data) // 0 <= e.Index-w.start.Index - 1 < len(ents) if e.Index > w.start.Index { // prevent "panic: runtime error: slice bounds out of range [:13038096702221461992] with capacity 0" up := e.Index - w.start.Index - 1 if up > uint64(len(ents)) { // return error before append call causes runtime panic return nil, state, nil, ErrSliceOutOfRange } // The line below is potentially overriding some 'uncommitted' entries. ents = append(ents[:up], e) } w.enti = e.Index case stateType: state = mustUnmarshalState(rec.Data) case metadataType: if metadata != nil && !bytes.Equal(metadata, rec.Data) { state.Reset() return nil, state, nil, ErrMetadataConflict } metadata = rec.Data case crcType: crc := decoder.crc.Sum32() // current crc of decoder must match the crc of the record. // do no need to match 0 crc, since the decoder is a new one at this case. if crc != 0 && rec.Validate(crc) != nil { state.Reset() return nil, state, nil, ErrCRCMismatch } decoder.updateCRC(rec.Crc) case snapshotType: var snap walpb.Snapshot pbutil.MustUnmarshal(&snap, rec.Data) if snap.Index == w.start.Index { if snap.Term != w.start.Term { state.Reset() return nil, state, nil, ErrSnapshotMismatch } match = true } default: state.Reset() return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type) } } switch w.tail() { case nil: // We do not have to read out all entries in read mode. // The last record maybe a partial written one, so // ErrunexpectedEOF might be returned. if err != io.EOF && err != io.ErrUnexpectedEOF { state.Reset() return nil, state, nil, err } default: // We must read all of the entries if WAL is opened in write mode. if err != io.EOF { state.Reset() return nil, state, nil, err } // decodeRecord() will return io.EOF if it detects a zero record, // but this zero record may be followed by non-zero records from // a torn write. Overwriting some of these non-zero records, but // not all, will cause CRC errors on WAL open. Since the records // were never fully synced to disk in the first place, it's safe // to zero them out to avoid any CRC errors from new writes. if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil { return nil, state, nil, err } if err = fileutil.ZeroToEnd(w.tail().File); err != nil { return nil, state, nil, err } } err = nil if !match { err = ErrSnapshotNotFound } // close decoder, disable reading if w.readClose != nil { w.readClose() w.readClose = nil } w.start = walpb.Snapshot{} w.metadata = metadata if w.tail() != nil { // create encoder (chain crc with the decoder), enable appending w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC()) if err != nil { return } } w.decoder = nil return metadata, state, ents, err } // ValidSnapshotEntries returns all the valid snapshot entries in the wal logs in the given directory. // Snapshot entries are valid if their index is less than or equal to the most recent committed hardstate. func ValidSnapshotEntries(lg *zap.Logger, walDir string) ([]walpb.Snapshot, error) { var snaps []walpb.Snapshot var state raftpb.HardState var err error rec := &walpb.Record{} names, err := readWALNames(lg, walDir) if err != nil { return nil, err } // open wal files in read mode, so that there is no conflict // when the same WAL is opened elsewhere in write mode rs, _, closer, err := openWALFiles(lg, walDir, names, 0, false) if err != nil { return nil, err } defer func() { if closer != nil { closer() } }() // create a new decoder from the readers on the WAL files decoder := newDecoder(rs...) for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case snapshotType: var loadedSnap walpb.Snapshot pbutil.MustUnmarshal(&loadedSnap, rec.Data) snaps = append(snaps, loadedSnap) case stateType: state = mustUnmarshalState(rec.Data) case crcType: crc := decoder.crc.Sum32() // current crc of decoder must match the crc of the record. // do no need to match 0 crc, since the decoder is a new one at this case. if crc != 0 && rec.Validate(crc) != nil { return nil, ErrCRCMismatch } decoder.updateCRC(rec.Crc) } } // We do not have to read out all the WAL entries // as the decoder is opened in read mode. if err != io.EOF && err != io.ErrUnexpectedEOF { return nil, err } // filter out any snaps that are newer than the committed hardstate n := 0 for _, s := range snaps { if s.Index <= state.Commit { snaps[n] = s n++ } } snaps = snaps[:n:n] return snaps, nil } // Verify reads through the given WAL and verifies that it is not corrupted. // It creates a new decoder to read through the records of the given WAL. // It does not conflict with any open WAL, but it is recommended not to // call this function after opening the WAL for writing. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound. // If the loaded snap doesn't match with the expected one, it will // return error ErrSnapshotMismatch. func Verify(lg *zap.Logger, walDir string, snap walpb.Snapshot) error { var metadata []byte var err error var match bool rec := &walpb.Record{} if lg == nil { lg = zap.NewNop() } names, nameIndex, err := selectWALFiles(lg, walDir, snap) if err != nil { return err } // open wal files in read mode, so that there is no conflict // when the same WAL is opened elsewhere in write mode rs, _, closer, err := openWALFiles(lg, walDir, names, nameIndex, false) if err != nil { return err } defer func() { if closer != nil { closer() } }() // create a new decoder from the readers on the WAL files decoder := newDecoder(rs...) for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) { switch rec.Type { case metadataType: if metadata != nil && !bytes.Equal(metadata, rec.Data) { return ErrMetadataConflict } metadata = rec.Data case crcType: crc := decoder.crc.Sum32() // Current crc of decoder must match the crc of the record. // We need not match 0 crc, since the decoder is a new one at this point. if crc != 0 && rec.Validate(crc) != nil { return ErrCRCMismatch } decoder.updateCRC(rec.Crc) case snapshotType: var loadedSnap walpb.Snapshot pbutil.MustUnmarshal(&loadedSnap, rec.Data) if loadedSnap.Index == snap.Index { if loadedSnap.Term != snap.Term { return ErrSnapshotMismatch } match = true } // We ignore all entry and state type records as these // are not necessary for validating the WAL contents case entryType: case stateType: default: return fmt.Errorf("unexpected block type %d", rec.Type) } } // We do not have to read out all the WAL entries // as the decoder is opened in read mode. if err != io.EOF && err != io.ErrUnexpectedEOF { return err } if !match { return ErrSnapshotNotFound } return nil } // cut closes current file written and creates a new one ready to append. // cut first creates a temp wal file and writes necessary headers into it. // Then cut atomically rename temp wal file to a wal file. func (w *WAL) cut() error { // close old wal file; truncate to avoid wasting space if an early cut off, serr := w.tail().Seek(0, io.SeekCurrent) if serr != nil { return serr } if err := w.tail().Truncate(off); err != nil { return err } if err := w.sync(); err != nil { return err } fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1)) // create a temp wal file with name sequence + 1, or truncate the existing one newTail, err := w.fp.Open() if err != nil { return err } // update writer and save the previous crc w.locks = append(w.locks, newTail) prevCrc := w.encoder.crc.Sum32() w.encoder, err = newFileEncoder(w.tail().File, prevCrc) if err != nil { return err } if err = w.saveCrc(prevCrc); err != nil { return err } if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil { return err } if err = w.saveState(&w.state); err != nil { return err } // atomically move temp wal file to wal file if err = w.sync(); err != nil { return err } off, err = w.tail().Seek(0, io.SeekCurrent) if err != nil { return err } if err = os.Rename(newTail.Name(), fpath); err != nil { return err } start := time.Now() if err = fileutil.Fsync(w.dirFile); err != nil { return err } walFsyncSec.Observe(time.Since(start).Seconds()) // reopen newTail with its new path so calls to Name() match the wal filename format newTail.Close() if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil { return err } if _, err = newTail.Seek(off, io.SeekStart); err != nil { return err } w.locks[len(w.locks)-1] = newTail prevCrc = w.encoder.crc.Sum32() w.encoder, err = newFileEncoder(w.tail().File, prevCrc) if err != nil { return err } w.lg.Info("created a new WAL segment", zap.String("path", fpath)) return nil } func (w *WAL) sync() error { if w.encoder != nil { if err := w.encoder.flush(); err != nil { return err } } if w.unsafeNoSync { return nil } start := time.Now() err := fileutil.Fdatasync(w.tail().File) took := time.Since(start) if took > warnSyncDuration { w.lg.Warn( "slow fdatasync", zap.Duration("took", took), zap.Duration("expected-duration", warnSyncDuration), ) } walFsyncSec.Observe(took.Seconds()) return err } func (w *WAL) Sync() error { return w.sync() } // ReleaseLockTo releases the locks, which has smaller index than the given index // except the largest one among them. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4. func (w *WAL) ReleaseLockTo(index uint64) error { w.mu.Lock() defer w.mu.Unlock() if len(w.locks) == 0 { return nil } var smaller int found := false for i, l := range w.locks { _, lockIndex, err := parseWALName(filepath.Base(l.Name())) if err != nil { return err } if lockIndex >= index { smaller = i - 1 found = true break } } // if no lock index is greater than the release index, we can // release lock up to the last one(excluding). if !found { smaller = len(w.locks) - 1 } if smaller <= 0 { return nil } for i := 0; i < smaller; i++ { if w.locks[i] == nil { continue } w.locks[i].Close() } w.locks = w.locks[smaller:] return nil } // Close closes the current WAL file and directory. func (w *WAL) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.fp != nil { w.fp.Close() w.fp = nil } if w.tail() != nil { if err := w.sync(); err != nil { return err } } for _, l := range w.locks { if l == nil { continue } if err := l.Close(); err != nil { w.lg.Error("failed to close WAL", zap.Error(err)) } } return w.dirFile.Close() } func (w *WAL) saveEntry(e *raftpb.Entry) error { // TODO: add MustMarshalTo to reduce one allocation. b := pbutil.MustMarshal(e) rec := &walpb.Record{Type: entryType, Data: b} if err := w.encoder.encode(rec); err != nil { return err } w.enti = e.Index return nil } func (w *WAL) saveState(s *raftpb.HardState) error { if raft.IsEmptyHardState(*s) { return nil } w.state = *s b := pbutil.MustMarshal(s) rec := &walpb.Record{Type: stateType, Data: b} return w.encoder.encode(rec) } func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error { w.mu.Lock() defer w.mu.Unlock() // short cut, do not call sync if raft.IsEmptyHardState(st) && len(ents) == 0 { return nil } mustSync := raft.MustSync(st, w.state, len(ents)) // TODO(xiangli): no more reference operator for i := range ents { if err := w.saveEntry(&ents[i]); err != nil { return err } } if err := w.saveState(&st); err != nil { return err } curOff, err := w.tail().Seek(0, io.SeekCurrent) if err != nil { return err } if curOff < SegmentSizeBytes { if mustSync { return w.sync() } return nil } return w.cut() } func (w *WAL) SaveSnapshot(e walpb.Snapshot) error { b := pbutil.MustMarshal(&e) w.mu.Lock() defer w.mu.Unlock() rec := &walpb.Record{Type: snapshotType, Data: b} if err := w.encoder.encode(rec); err != nil { return err } // update enti only when snapshot is ahead of last index if w.enti < e.Index { w.enti = e.Index } return w.sync() } func (w *WAL) saveCrc(prevCrc uint32) error { return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc}) } func (w *WAL) tail() *fileutil.LockedFile { if len(w.locks) > 0 { return w.locks[len(w.locks)-1] } return nil } func (w *WAL) seq() uint64 { t := w.tail() if t == nil { return 0 } seq, _, err := parseWALName(filepath.Base(t.Name())) if err != nil { w.lg.Fatal("failed to parse WAL name", zap.String("name", t.Name()), zap.Error(err)) } return seq } func closeAll(lg *zap.Logger, rcs ...io.ReadCloser) error { stringArr := make([]string, 0) for _, f := range rcs { if err := f.Close(); err != nil { lg.Warn("failed to close: ", zap.Error(err)) stringArr = append(stringArr, err.Error()) } } if len(stringArr) == 0 { return nil } return errors.New(strings.Join(stringArr, ", ")) }
package service import ( "fmt" "net/http" "github.com/gamegos/scotty/storage" "github.com/gorilla/mux" ) func healthCheck(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") } // NewRouter creates and returns the router. func NewRouter(stg storage.Storage) *mux.Router { hnd := new(Handlers) hnd.stg = stg router := mux.NewRouter().StrictSlash(true) router. Methods("GET"). Path("/health"). Name("Health Check"). HandlerFunc(hnd.getHealth) router. Methods("GET"). Path("/apps/{appId}"). Name("Get App"). HandlerFunc(hnd.getApp) router. Methods("POST"). Path("/apps"). Name("Create App"). HandlerFunc(hnd.createApp) router. Methods("PUT"). Path("/apps/{appId}"). Name("Update App"). HandlerFunc(hnd.updateApp) router. Methods("POST"). Path("/apps/{appId}/devices"). Name("Add Device to Subscriber"). HandlerFunc(hnd.addDevice) router. Methods("POST"). Path("/apps/{appId}/channels"). Name("Add Channel to App"). HandlerFunc(hnd.addChannel) router. Methods("DELETE"). Path("/apps/{appId}/channels/{channelId}"). Name("Delete Channel from App"). HandlerFunc(hnd.deleteChannel) router. Methods("POST"). Path("/apps/{appId}/channels/{channelId}/subscribers"). Name("Add Subscriber to Channel"). HandlerFunc(hnd.addSubscriber) router. Methods("POST"). Path("/apps/{appId}/publish"). Name("Publish a message"). HandlerFunc(hnd.publishMessage) return router } Remove unused healthcheck function package service import ( "github.com/gamegos/scotty/storage" "github.com/gorilla/mux" ) // NewRouter creates and returns the router. func NewRouter(stg storage.Storage) *mux.Router { hnd := new(Handlers) hnd.stg = stg router := mux.NewRouter().StrictSlash(true) router. Methods("GET"). Path("/health"). Name("Health Check"). HandlerFunc(hnd.getHealth) router. Methods("GET"). Path("/apps/{appId}"). Name("Get App"). HandlerFunc(hnd.getApp) router. Methods("POST"). Path("/apps"). Name("Create App"). HandlerFunc(hnd.createApp) router. Methods("PUT"). Path("/apps/{appId}"). Name("Update App"). HandlerFunc(hnd.updateApp) router. Methods("POST"). Path("/apps/{appId}/devices"). Name("Add Device to Subscriber"). HandlerFunc(hnd.addDevice) router. Methods("POST"). Path("/apps/{appId}/channels"). Name("Add Channel to App"). HandlerFunc(hnd.addChannel) router. Methods("DELETE"). Path("/apps/{appId}/channels/{channelId}"). Name("Delete Channel from App"). HandlerFunc(hnd.deleteChannel) router. Methods("POST"). Path("/apps/{appId}/channels/{channelId}/subscribers"). Name("Add Subscriber to Channel"). HandlerFunc(hnd.addSubscriber) router. Methods("POST"). Path("/apps/{appId}/publish"). Name("Publish a message"). HandlerFunc(hnd.publishMessage) return router }
// Copyright 2016 CoreOS, 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 backend import ( "context" "encoding/json" "fmt" "net/http" "time" "github.com/coreos/etcd/clientv3" ) // KeyValue defines key-value pair. type KeyValue struct { Key string Value string } // ClientRequest defines client requests. type ClientRequest struct { Action string // 'write', 'stress', 'delete', 'get', 'stop-node', 'restart-node' RangePrefix bool // 'delete', 'get' Endpoints []string KeyValue KeyValue } // ClientResponse translates client's GET response in frontend-friendly format. type ClientResponse struct { ClientRequest ClientRequest Success bool Result string ResultLines []string KeyValues []KeyValue } var ( minScaleToDisplay = time.Millisecond // ErrNoEndpoint is returned when client request has no target endpoint. ErrNoEndpoint = "no endpoint is given" ) // clientRequestHandler handles writes, reads, deletes, kill, restart operations. func clientRequestHandler(ctx context.Context, w http.ResponseWriter, req *http.Request) error { switch req.Method { case "POST": cresp := ClientResponse{Success: true} if rmsg, ok := globalClientRequestLimiter.Check(); !ok { cresp.Success = false cresp.Result = "client request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalClientRequestLimiter.Advance() creq := ClientRequest{} if err := json.NewDecoder(req.Body).Decode(&creq); err != nil { cresp.Success = false cresp.Result = err.Error() cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer req.Body.Close() cresp.ClientRequest = creq if len(creq.Endpoints) == 0 { cresp.Success = false cresp.Result = ErrNoEndpoint cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } idx := globalCluster.FindIndex(creq.Endpoints[0]) if idx == -1 { cresp.Success = false cresp.Result = fmt.Sprintf("wrong endpoints are given (%v)", creq.Endpoints) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cctx, ccancel := context.WithTimeout(ctx, 3*time.Second) defer ccancel() reqStart := time.Now() switch creq.Action { case "write": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'write' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() cresp.KeyValues = []KeyValue{creq.KeyValue} if _, err := cli.Put(cctx, creq.KeyValue.Key, creq.KeyValue.Value); err != nil { cresp.Success = false cresp.Result = err.Error() cresp.ResultLines = []string{cresp.Result} } else { cresp.Success = true cresp.Result = fmt.Sprintf("'write' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, 1) for i := range lines { ks, vs := cresp.KeyValues[i].Key, cresp.KeyValues[i].Value if len(ks) > 7 { ks = ks[:7] + "..." } if len(vs) > 7 { vs = vs[:7] + "..." } lines[i] = fmt.Sprintf("'write' success (key: %s, value: %s)", ks, vs) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "stress": cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() cresp.KeyValues = multiRandKeyValues("foo", "bar", 3, 3) for _, kv := range cresp.KeyValues { if _, err := cli.Put(cctx, kv.Key, kv.Value); err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} break } } if cresp.Success { cresp.Result = fmt.Sprintf("'stress' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, 3) for i := range lines { ks, vs := cresp.KeyValues[i].Key, cresp.KeyValues[i].Value if len(ks) > 7 { ks = ks[:7] + "..." } if len(vs) > 7 { vs = vs[:7] + "..." } lines[i] = fmt.Sprintf("'stress' success (key: %s, value: %s)", ks, vs) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "delete": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'delete' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() var opts []clientv3.OpOption if creq.RangePrefix { opts = append(opts, clientv3.WithPrefix(), clientv3.WithPrevKV()) } dresp, err := cli.Delete(cctx, creq.KeyValue.Key, opts...) if err != nil { cresp.Success = false cresp.Result = err.Error() } kvs := make([]KeyValue, len(dresp.PrevKvs)) for i := range dresp.PrevKvs { kvs[i] = KeyValue{Key: string(dresp.PrevKvs[i].Key), Value: string(dresp.PrevKvs[i].Value)} } cresp.KeyValues = kvs if cresp.Success { cresp.Result = fmt.Sprintf("'delete' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, len(cresp.KeyValues)) for i := range lines { lines[i] = fmt.Sprintf("'delete' success (key: %s, value: %s)", cresp.KeyValues[i].Key, cresp.KeyValues[i].Value) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "get": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'get' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } // TODO: get all keys and by prefix cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() var opts []clientv3.OpOption if creq.RangePrefix { opts = append(opts, clientv3.WithPrefix(), clientv3.WithPrevKV()) } gresp, err := cli.Get(cctx, creq.KeyValue.Key, opts...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} } kvs := make([]KeyValue, len(gresp.Kvs)) for i := range gresp.Kvs { kvs[i] = KeyValue{Key: string(gresp.Kvs[i].Key), Value: string(gresp.Kvs[i].Value)} } cresp.KeyValues = kvs if err == nil { cresp.Result = fmt.Sprintf("'get' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, len(cresp.KeyValues)) for i := range lines { lines[i] = fmt.Sprintf("'get' success (key: %s, value: %s)", cresp.KeyValues[i].Key, cresp.KeyValues[i].Value) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "stop-node": if rmsg, ok := globalStopRestartLimiter.Check(); !ok { cresp.Success = false cresp.Result = "'stop-node' request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalStopRestartLimiter.Advance() if globalCluster.IsStopped(idx) { cresp.Success = false cresp.Result = fmt.Sprintf("%s is already stopped (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalCluster.Stop(idx) cresp.Result = fmt.Sprintf("stopped %s (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "restart-node": if rmsg, ok := globalStopRestartLimiter.Check(); !ok { cresp.Success = false cresp.Result = "'restart-node' request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalStopRestartLimiter.Advance() if !globalCluster.IsStopped(idx) { cresp.Success = false cresp.Result = fmt.Sprintf("%s is already started (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } if rerr := globalCluster.Restart(idx); rerr != nil { cresp.Success = false cresp.Result = rerr.Error() } else { cresp.Success = true cresp.Result = fmt.Sprintf("restarted %s (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) } cresp.ResultLines = []string{cresp.Result} if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } default: return fmt.Errorf("unknown action %q", creq.Action) } default: http.Error(w, "Method Not Allowed", 405) } return nil } backend: log when 'get' returns 0 key-value pair // Copyright 2016 CoreOS, 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 backend import ( "context" "encoding/json" "fmt" "net/http" "time" "github.com/coreos/etcd/clientv3" ) // KeyValue defines key-value pair. type KeyValue struct { Key string Value string } // ClientRequest defines client requests. type ClientRequest struct { Action string // 'write', 'stress', 'delete', 'get', 'stop-node', 'restart-node' RangePrefix bool // 'delete', 'get' Endpoints []string KeyValue KeyValue } // ClientResponse translates client's GET response in frontend-friendly format. type ClientResponse struct { ClientRequest ClientRequest Success bool Result string ResultLines []string KeyValues []KeyValue } var ( minScaleToDisplay = time.Millisecond // ErrNoEndpoint is returned when client request has no target endpoint. ErrNoEndpoint = "no endpoint is given" ) // clientRequestHandler handles writes, reads, deletes, kill, restart operations. func clientRequestHandler(ctx context.Context, w http.ResponseWriter, req *http.Request) error { switch req.Method { case "POST": cresp := ClientResponse{Success: true} if rmsg, ok := globalClientRequestLimiter.Check(); !ok { cresp.Success = false cresp.Result = "client request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalClientRequestLimiter.Advance() creq := ClientRequest{} if err := json.NewDecoder(req.Body).Decode(&creq); err != nil { cresp.Success = false cresp.Result = err.Error() cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer req.Body.Close() cresp.ClientRequest = creq if len(creq.Endpoints) == 0 { cresp.Success = false cresp.Result = ErrNoEndpoint cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } idx := globalCluster.FindIndex(creq.Endpoints[0]) if idx == -1 { cresp.Success = false cresp.Result = fmt.Sprintf("wrong endpoints are given (%v)", creq.Endpoints) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cctx, ccancel := context.WithTimeout(ctx, 3*time.Second) defer ccancel() reqStart := time.Now() switch creq.Action { case "write": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'write' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() cresp.KeyValues = []KeyValue{creq.KeyValue} if _, err := cli.Put(cctx, creq.KeyValue.Key, creq.KeyValue.Value); err != nil { cresp.Success = false cresp.Result = err.Error() cresp.ResultLines = []string{cresp.Result} } else { cresp.Success = true cresp.Result = fmt.Sprintf("'write' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, 1) for i := range lines { ks, vs := cresp.KeyValues[i].Key, cresp.KeyValues[i].Value if len(ks) > 7 { ks = ks[:7] + "..." } if len(vs) > 7 { vs = vs[:7] + "..." } lines[i] = fmt.Sprintf("'write' success (key: %s, value: %s)", ks, vs) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "stress": cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() cresp.KeyValues = multiRandKeyValues("foo", "bar", 3, 3) for _, kv := range cresp.KeyValues { if _, err := cli.Put(cctx, kv.Key, kv.Value); err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} break } } if cresp.Success { cresp.Result = fmt.Sprintf("'stress' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, 3) for i := range lines { ks, vs := cresp.KeyValues[i].Key, cresp.KeyValues[i].Value if len(ks) > 7 { ks = ks[:7] + "..." } if len(vs) > 7 { vs = vs[:7] + "..." } lines[i] = fmt.Sprintf("'stress' success (key: %s, value: %s)", ks, vs) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "delete": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'delete' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() var opts []clientv3.OpOption if creq.RangePrefix { opts = append(opts, clientv3.WithPrefix(), clientv3.WithPrevKV()) } dresp, err := cli.Delete(cctx, creq.KeyValue.Key, opts...) if err != nil { cresp.Success = false cresp.Result = err.Error() } kvs := make([]KeyValue, len(dresp.PrevKvs)) for i := range dresp.PrevKvs { kvs[i] = KeyValue{Key: string(dresp.PrevKvs[i].Key), Value: string(dresp.PrevKvs[i].Value)} } cresp.KeyValues = kvs if cresp.Success { cresp.Result = fmt.Sprintf("'delete' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, len(cresp.KeyValues)) for i := range lines { lines[i] = fmt.Sprintf("'delete' success (key: %s, value: %s)", cresp.KeyValues[i].Key, cresp.KeyValues[i].Value) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "get": if creq.KeyValue.Key == "" { cresp.Success = false cresp.Result = fmt.Sprint("'get' request got empty key") cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } // TODO: get all keys and by prefix cli, _, err := globalCluster.Client(creq.Endpoints...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } defer cli.Close() var opts []clientv3.OpOption if creq.RangePrefix { opts = append(opts, clientv3.WithPrefix(), clientv3.WithPrevKV()) } gresp, err := cli.Get(cctx, creq.KeyValue.Key, opts...) if err != nil { cresp.Success = false cresp.Result = fmt.Sprintf("client error %v (took %v)", err, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} } kvs := make([]KeyValue, len(gresp.Kvs)) for i := range gresp.Kvs { kvs[i] = KeyValue{Key: string(gresp.Kvs[i].Key), Value: string(gresp.Kvs[i].Value)} } cresp.KeyValues = kvs if err == nil { cresp.Result = fmt.Sprintf("'get' success (took %v)", roundDownDuration(time.Since(reqStart), minScaleToDisplay)) lines := make([]string, len(cresp.KeyValues)) for i := range lines { lines[i] = fmt.Sprintf("'get' success (key: %s, value: %s)", cresp.KeyValues[i].Key, cresp.KeyValues[i].Value) } if len(lines) == 0 { lines = append(lines, fmt.Sprintf("key %q does not exist", creq.KeyValue.Key)) } cresp.ResultLines = lines } if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "stop-node": if rmsg, ok := globalStopRestartLimiter.Check(); !ok { cresp.Success = false cresp.Result = "'stop-node' request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalStopRestartLimiter.Advance() if globalCluster.IsStopped(idx) { cresp.Success = false cresp.Result = fmt.Sprintf("%s is already stopped (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalCluster.Stop(idx) cresp.Result = fmt.Sprintf("stopped %s (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } case "restart-node": if rmsg, ok := globalStopRestartLimiter.Check(); !ok { cresp.Success = false cresp.Result = "'restart-node' request " + rmsg cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } globalStopRestartLimiter.Advance() if !globalCluster.IsStopped(idx) { cresp.Success = false cresp.Result = fmt.Sprintf("%s is already started (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) cresp.ResultLines = []string{cresp.Result} return json.NewEncoder(w).Encode(cresp) } if rerr := globalCluster.Restart(idx); rerr != nil { cresp.Success = false cresp.Result = rerr.Error() } else { cresp.Success = true cresp.Result = fmt.Sprintf("restarted %s (took %v)", globalCluster.NodeStatus(idx).Name, roundDownDuration(time.Since(reqStart), minScaleToDisplay)) } cresp.ResultLines = []string{cresp.Result} if err := json.NewEncoder(w).Encode(cresp); err != nil { return err } default: return fmt.Errorf("unknown action %q", creq.Action) } default: http.Error(w, "Method Not Allowed", 405) } return nil }
// Copyright The OpenTelemetry Authors // // 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 service // import "go.opentelemetry.io/collector/service" import ( "net/http" "path" "sort" otelzpages "go.opentelemetry.io/contrib/zpages" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/internal/version" "go.opentelemetry.io/collector/service/internal/zpages" ) const ( tracezPath = "tracez" servicezPath = "servicez" pipelinezPath = "pipelinez" extensionzPath = "extensionz" zPipelineName = "zpipelinename" zComponentName = "zcomponentname" zComponentKind = "zcomponentkind" zExtensionName = "zextensionname" ) func (srv *service) RegisterZPages(mux *http.ServeMux, pathPrefix string) { mux.Handle(path.Join(pathPrefix, tracezPath), otelzpages.NewTracezHandler(srv.zPagesSpanProcessor)) mux.HandleFunc(path.Join(pathPrefix, servicezPath), srv.handleServicezRequest) mux.HandleFunc(path.Join(pathPrefix, pipelinezPath), srv.handlePipelinezRequest) mux.HandleFunc(path.Join(pathPrefix, extensionzPath), func(w http.ResponseWriter, r *http.Request) { handleExtensionzRequest(srv, w, r) }) } func (srv *service) handleServicezRequest(w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck w.Header().Set("Content-Type", "text/html; charset=utf-8") zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "service"}) zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: "Pipelines", ComponentEndpoint: pipelinezPath, Link: true, }) zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: "Extensions", ComponentEndpoint: extensionzPath, Link: true, }) zpages.WriteHTMLPropertiesTable(w, zpages.PropertiesTableData{Name: "Build And Runtime", Properties: version.RuntimeVar()}) zpages.WriteHTMLFooter(w) } func (srv *service) handlePipelinezRequest(w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck w.Header().Set("Content-Type", "text/html; charset=utf-8") pipelineName := r.Form.Get(zPipelineName) componentName := r.Form.Get(zComponentName) componentKind := r.Form.Get(zComponentKind) zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "Pipelines"}) zpages.WriteHTMLPipelinesSummaryTable(w, srv.getPipelinesSummaryTableData()) if pipelineName != "" && componentName != "" && componentKind != "" { fullName := componentName if componentKind == "processor" { fullName = pipelineName + "/" + componentName } zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: componentKind + ": " + fullName, }) // TODO: Add config + status info. } zpages.WriteHTMLFooter(w) } func (srv *service) getPipelinesSummaryTableData() zpages.SummaryPipelinesTableData { data := zpages.SummaryPipelinesTableData{ ComponentEndpoint: pipelinezPath, } data.Rows = make([]zpages.SummaryPipelinesTableRowData, 0, len(srv.builtPipelines)) for c, p := range srv.builtPipelines { // TODO: Change the template to use ID. var recvs []string for _, recvID := range p.Config.Receivers { recvs = append(recvs, recvID.String()) } var procs []string for _, procID := range p.Config.Processors { procs = append(procs, procID.String()) } var exps []string for _, expID := range p.Config.Exporters { exps = append(exps, expID.String()) } row := zpages.SummaryPipelinesTableRowData{ FullName: c.String(), InputType: string(c.Type()), MutatesData: p.MutatesData, Receivers: recvs, Processors: procs, Exporters: exps, } data.Rows = append(data.Rows, row) } sort.Slice(data.Rows, func(i, j int) bool { return data.Rows[i].FullName < data.Rows[j].FullName }) return data } func handleExtensionzRequest(host component.Host, w http.ResponseWriter, r *http.Request) { r.ParseForm() // nolint:errcheck w.Header().Set("Content-Type", "text/html; charset=utf-8") extensionName := r.Form.Get(zExtensionName) zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "Extensions"}) zpages.WriteHTMLExtensionsSummaryTable(w, getExtensionsSummaryTableData(host)) if extensionName != "" { zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: extensionName, }) // TODO: Add config + status info. } zpages.WriteHTMLFooter(w) } func getExtensionsSummaryTableData(host component.Host) zpages.SummaryExtensionsTableData { data := zpages.SummaryExtensionsTableData{ ComponentEndpoint: extensionzPath, } extensions := host.GetExtensions() data.Rows = make([]zpages.SummaryExtensionsTableRowData, 0, len(extensions)) for c := range extensions { row := zpages.SummaryExtensionsTableRowData{FullName: c.Name()} data.Rows = append(data.Rows, row) } sort.Slice(data.Rows, func(i, j int) bool { return data.Rows[i].FullName < data.Rows[j].FullName }) return data } Remove usage of request Form, we always send params in URL query (#4357) Signed-off-by: Bogdan Drutu <3f8e17047c2434e5c82a61403e56b9ef3e226d99@gmail.com> // Copyright The OpenTelemetry Authors // // 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 service // import "go.opentelemetry.io/collector/service" import ( "net/http" "path" "sort" otelzpages "go.opentelemetry.io/contrib/zpages" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/internal/version" "go.opentelemetry.io/collector/service/internal/zpages" ) const ( tracezPath = "tracez" servicezPath = "servicez" pipelinezPath = "pipelinez" extensionzPath = "extensionz" zPipelineName = "zpipelinename" zComponentName = "zcomponentname" zComponentKind = "zcomponentkind" zExtensionName = "zextensionname" ) func (srv *service) RegisterZPages(mux *http.ServeMux, pathPrefix string) { mux.Handle(path.Join(pathPrefix, tracezPath), otelzpages.NewTracezHandler(srv.zPagesSpanProcessor)) mux.HandleFunc(path.Join(pathPrefix, servicezPath), srv.handleServicezRequest) mux.HandleFunc(path.Join(pathPrefix, pipelinezPath), srv.handlePipelinezRequest) mux.HandleFunc(path.Join(pathPrefix, extensionzPath), func(w http.ResponseWriter, r *http.Request) { handleExtensionzRequest(srv, w, r) }) } func (srv *service) handleServicezRequest(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "service"}) zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: "Pipelines", ComponentEndpoint: pipelinezPath, Link: true, }) zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: "Extensions", ComponentEndpoint: extensionzPath, Link: true, }) zpages.WriteHTMLPropertiesTable(w, zpages.PropertiesTableData{Name: "Build And Runtime", Properties: version.RuntimeVar()}) zpages.WriteHTMLFooter(w) } func (srv *service) handlePipelinezRequest(w http.ResponseWriter, r *http.Request) { qValues := r.URL.Query() pipelineName := qValues.Get(zPipelineName) componentName := qValues.Get(zComponentName) componentKind := qValues.Get(zComponentKind) w.Header().Set("Content-Type", "text/html; charset=utf-8") zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "Pipelines"}) zpages.WriteHTMLPipelinesSummaryTable(w, srv.getPipelinesSummaryTableData()) if pipelineName != "" && componentName != "" && componentKind != "" { fullName := componentName if componentKind == "processor" { fullName = pipelineName + "/" + componentName } zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: componentKind + ": " + fullName, }) // TODO: Add config + status info. } zpages.WriteHTMLFooter(w) } func (srv *service) getPipelinesSummaryTableData() zpages.SummaryPipelinesTableData { data := zpages.SummaryPipelinesTableData{ ComponentEndpoint: pipelinezPath, } data.Rows = make([]zpages.SummaryPipelinesTableRowData, 0, len(srv.builtPipelines)) for c, p := range srv.builtPipelines { // TODO: Change the template to use ID. var recvs []string for _, recvID := range p.Config.Receivers { recvs = append(recvs, recvID.String()) } var procs []string for _, procID := range p.Config.Processors { procs = append(procs, procID.String()) } var exps []string for _, expID := range p.Config.Exporters { exps = append(exps, expID.String()) } row := zpages.SummaryPipelinesTableRowData{ FullName: c.String(), InputType: string(c.Type()), MutatesData: p.MutatesData, Receivers: recvs, Processors: procs, Exporters: exps, } data.Rows = append(data.Rows, row) } sort.Slice(data.Rows, func(i, j int) bool { return data.Rows[i].FullName < data.Rows[j].FullName }) return data } func handleExtensionzRequest(host component.Host, w http.ResponseWriter, r *http.Request) { extensionName := r.URL.Query().Get(zExtensionName) w.Header().Set("Content-Type", "text/html; charset=utf-8") zpages.WriteHTMLHeader(w, zpages.HeaderData{Title: "Extensions"}) zpages.WriteHTMLExtensionsSummaryTable(w, getExtensionsSummaryTableData(host)) if extensionName != "" { zpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{ Name: extensionName, }) // TODO: Add config + status info. } zpages.WriteHTMLFooter(w) } func getExtensionsSummaryTableData(host component.Host) zpages.SummaryExtensionsTableData { data := zpages.SummaryExtensionsTableData{ ComponentEndpoint: extensionzPath, } extensions := host.GetExtensions() data.Rows = make([]zpages.SummaryExtensionsTableRowData, 0, len(extensions)) for c := range extensions { row := zpages.SummaryExtensionsTableRowData{FullName: c.Name()} data.Rows = append(data.Rows, row) } sort.Slice(data.Rows, func(i, j int) bool { return data.Rows[i].FullName < data.Rows[j].FullName }) return data }
// package peer implements an object used to represent peers in the ipfs network. package peer import ( "encoding/hex" "encoding/json" "fmt" b58 "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-base58" ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash" ic "github.com/jbenet/go-ipfs/p2p/crypto" u "github.com/jbenet/go-ipfs/util" ) var log = u.Logger("peer") // ID represents the identity of a peer. type ID string // Pretty returns a b58-encoded string of the ID func (id ID) Pretty() string { return IDB58Encode(id) } func (id ID) Loggable() map[string]interface{} { return map[string]interface{}{ "peerID": id.Pretty(), } } // String prints out the peer. // // TODO(brian): ensure correctness at ID generation and // enforce this by only exposing functions that generate // IDs safely. Then any peer.ID type found in the // codebase is known to be correct. func (id ID) String() string { pid := id.Pretty() maxRunes := 6 skip := 2 //Added to skip past Qm which is identical for all SHA256 nodes if len(pid) < maxRunes + skip { maxRunes = len(pid) - skip } return fmt.Sprintf("<peer.ID %s>", pid[skip:maxRunes + skip]) } // MatchesPrivateKey tests whether this ID was derived from sk func (id ID) MatchesPrivateKey(sk ic.PrivKey) bool { return id.MatchesPublicKey(sk.GetPublic()) } // MatchesPublicKey tests whether this ID was derived from pk func (id ID) MatchesPublicKey(pk ic.PubKey) bool { oid, err := IDFromPublicKey(pk) if err != nil { return false } return oid == id } // IDFromString cast a string to ID type, and validate // the id to make sure it is a multihash. func IDFromString(s string) (ID, error) { if _, err := mh.Cast([]byte(s)); err != nil { return ID(""), err } return ID(s), nil } // IDFromBytes cast a string to ID type, and validate // the id to make sure it is a multihash. func IDFromBytes(b []byte) (ID, error) { if _, err := mh.Cast(b); err != nil { return ID(""), err } return ID(b), nil } // IDB58Decode returns a b58-decoded Peer func IDB58Decode(s string) (ID, error) { m, err := mh.FromB58String(s) if err != nil { return "", err } return ID(m), err } // IDB58Encode returns b58-encoded string func IDB58Encode(id ID) string { return b58.Encode([]byte(id)) } // IDHexDecode returns a b58-decoded Peer func IDHexDecode(s string) (ID, error) { m, err := mh.FromHexString(s) if err != nil { return "", err } return ID(m), err } // IDHexEncode returns b58-encoded string func IDHexEncode(id ID) string { return hex.EncodeToString([]byte(id)) } // IDFromPublicKey returns the Peer ID corresponding to pk func IDFromPublicKey(pk ic.PubKey) (ID, error) { b, err := pk.Bytes() if err != nil { return "", err } hash := u.Hash(b) return ID(hash), nil } // IDFromPrivateKey returns the Peer ID corresponding to sk func IDFromPrivateKey(sk ic.PrivKey) (ID, error) { return IDFromPublicKey(sk.GetPublic()) } // Map maps a Peer ID to a struct. type Set map[ID]struct{} // PeerInfo is a small struct used to pass around a peer with // a set of addresses (and later, keys?). This is not meant to be // a complete view of the system, but rather to model updates to // the peerstore. It is used by things like the routing system. type PeerInfo struct { ID ID Addrs []ma.Multiaddr } func (pi *PeerInfo) MarshalJSON() ([]byte, error) { out := make(map[string]interface{}) out["ID"] = IDB58Encode(pi.ID) var addrs []string for _, a := range pi.Addrs { addrs = append(addrs, a.String()) } out["Addrs"] = addrs return json.Marshal(out) } func (pi *PeerInfo) UnmarshalJSON(b []byte) error { var data map[string]interface{} err := json.Unmarshal(b, &data) if err != nil { return err } pid, err := IDB58Decode(data["ID"].(string)) if err != nil { return err } pi.ID = pid addrs, ok := data["Addrs"].([]interface{}) if ok { for _, a := range addrs { pi.Addrs = append(pi.Addrs, ma.StringCast(a.(string))) } } return nil } // IDSlice for sorting peers type IDSlice []ID func (es IDSlice) Len() int { return len(es) } func (es IDSlice) Swap(i, j int) { es[i], es[j] = es[j], es[i] } func (es IDSlice) Less(i, j int) bool { return string(es[i]) < string(es[j]) } Implemented @jbenet's suggestion to avoid panics if peerID is of length 0. // package peer implements an object used to represent peers in the ipfs network. package peer import ( "encoding/hex" "encoding/json" "fmt" "strings" b58 "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-base58" ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash" ic "github.com/jbenet/go-ipfs/p2p/crypto" u "github.com/jbenet/go-ipfs/util" ) var log = u.Logger("peer") // ID represents the identity of a peer. type ID string // Pretty returns a b58-encoded string of the ID func (id ID) Pretty() string { return IDB58Encode(id) } func (id ID) Loggable() map[string]interface{} { return map[string]interface{}{ "peerID": id.Pretty(), } } // String prints out the peer. // // TODO(brian): ensure correctness at ID generation and // enforce this by only exposing functions that generate // IDs safely. Then any peer.ID type found in the // codebase is known to be correct. func (id ID) String() string { pid := id.Pretty() //All sha256 nodes start with Qm //We can skip the Qm to make the peer.ID more useful if strings.HasPrefix(pid, "Qm") { pid = pid[2:] } maxRunes := 6 if len(pid) < maxRunes { maxRunes = len(pid) } return fmt.Sprintf("<peer.ID %s>", pid[:maxRunes]) } // MatchesPrivateKey tests whether this ID was derived from sk func (id ID) MatchesPrivateKey(sk ic.PrivKey) bool { return id.MatchesPublicKey(sk.GetPublic()) } // MatchesPublicKey tests whether this ID was derived from pk func (id ID) MatchesPublicKey(pk ic.PubKey) bool { oid, err := IDFromPublicKey(pk) if err != nil { return false } return oid == id } // IDFromString cast a string to ID type, and validate // the id to make sure it is a multihash. func IDFromString(s string) (ID, error) { if _, err := mh.Cast([]byte(s)); err != nil { return ID(""), err } return ID(s), nil } // IDFromBytes cast a string to ID type, and validate // the id to make sure it is a multihash. func IDFromBytes(b []byte) (ID, error) { if _, err := mh.Cast(b); err != nil { return ID(""), err } return ID(b), nil } // IDB58Decode returns a b58-decoded Peer func IDB58Decode(s string) (ID, error) { m, err := mh.FromB58String(s) if err != nil { return "", err } return ID(m), err } // IDB58Encode returns b58-encoded string func IDB58Encode(id ID) string { return b58.Encode([]byte(id)) } // IDHexDecode returns a b58-decoded Peer func IDHexDecode(s string) (ID, error) { m, err := mh.FromHexString(s) if err != nil { return "", err } return ID(m), err } // IDHexEncode returns b58-encoded string func IDHexEncode(id ID) string { return hex.EncodeToString([]byte(id)) } // IDFromPublicKey returns the Peer ID corresponding to pk func IDFromPublicKey(pk ic.PubKey) (ID, error) { b, err := pk.Bytes() if err != nil { return "", err } hash := u.Hash(b) return ID(hash), nil } // IDFromPrivateKey returns the Peer ID corresponding to sk func IDFromPrivateKey(sk ic.PrivKey) (ID, error) { return IDFromPublicKey(sk.GetPublic()) } // Map maps a Peer ID to a struct. type Set map[ID]struct{} // PeerInfo is a small struct used to pass around a peer with // a set of addresses (and later, keys?). This is not meant to be // a complete view of the system, but rather to model updates to // the peerstore. It is used by things like the routing system. type PeerInfo struct { ID ID Addrs []ma.Multiaddr } func (pi *PeerInfo) MarshalJSON() ([]byte, error) { out := make(map[string]interface{}) out["ID"] = IDB58Encode(pi.ID) var addrs []string for _, a := range pi.Addrs { addrs = append(addrs, a.String()) } out["Addrs"] = addrs return json.Marshal(out) } func (pi *PeerInfo) UnmarshalJSON(b []byte) error { var data map[string]interface{} err := json.Unmarshal(b, &data) if err != nil { return err } pid, err := IDB58Decode(data["ID"].(string)) if err != nil { return err } pi.ID = pid addrs, ok := data["Addrs"].([]interface{}) if ok { for _, a := range addrs { pi.Addrs = append(pi.Addrs, ma.StringCast(a.(string))) } } return nil } // IDSlice for sorting peers type IDSlice []ID func (es IDSlice) Len() int { return len(es) } func (es IDSlice) Swap(i, j int) { es[i], es[j] = es[j], es[i] } func (es IDSlice) Less(i, j int) bool { return string(es[i]) < string(es[j]) }
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 stats import ( "context" "errors" "fmt" "time" "github.com/aws/amazon-ecs-agent/agent/config" "github.com/aws/amazon-ecs-agent/agent/dockerclient" "github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi" "github.com/aws/amazon-ecs-agent/agent/stats/resolver" "github.com/aws/amazon-ecs-agent/agent/utils/retry" "github.com/cihub/seelog" ) func newStatsContainer(dockerID string, client dockerapi.DockerClient, resolver resolver.ContainerMetadataResolver, cfg *config.Config) (*StatsContainer, error) { dockerContainer, err := resolver.ResolveContainer(dockerID) if err != nil { return nil, err } ctx, cancel := context.WithCancel(context.Background()) return &StatsContainer{ containerMetadata: &ContainerMetadata{ DockerID: dockerID, Name: dockerContainer.Container.Name, NetworkMode: dockerContainer.Container.GetNetworkMode(), }, ctx: ctx, cancel: cancel, client: client, resolver: resolver, config: cfg, }, nil } func (container *StatsContainer) StartStatsCollection() { // queue will be sized to hold enough stats for 4 publishing intervals. var queueSize int if container.config != nil && container.config.PollMetrics.Enabled() { pollingInterval := container.config.PollingMetricsWaitDuration.Seconds() queueSize = int(config.DefaultContainerMetricsPublishInterval.Seconds() / pollingInterval * 4) } else { // for streaming stats we assume 1 stat every second queueSize = int(config.DefaultContainerMetricsPublishInterval.Seconds() * 4) } container.statsQueue = NewQueue(queueSize) go container.collect() } func (container *StatsContainer) StopStatsCollection() { container.cancel() } func (container *StatsContainer) collect() { dockerID := container.containerMetadata.DockerID backoff := retry.NewExponentialBackoff(time.Second*1, time.Second*10, 0.5, 2) for { err := container.processStatsStream() select { case <-container.ctx.Done(): seelog.Infof("Container [%s]: Stopping stats collection", dockerID) return default: if err != nil { d := backoff.Duration() seelog.Debugf("Container [%s]: Error processing stats stream of container, backing off %s before reopening", dockerID, d) time.Sleep(d) } // We were disconnected from the stats stream. // Check if the container is terminal. If it is, stop collecting metrics. // We might sometimes miss events from docker task engine and this helps // in reconciling the state. terminal, err := container.terminal() if err != nil { // Error determining if the container is terminal. This means that the container // id could not be resolved to a container that is being tracked by the // docker task engine. If the docker task engine has already removed // the container from its state, there's no point in stats engine tracking the // container. So, clean-up anyway. seelog.Warnf("Container [%s]: Error determining if the container is terminal, stopping stats collection: %v", dockerID, err) container.StopStatsCollection() return } else if terminal { seelog.Infof("Container [%s]: container is terminal, stopping stats collection", dockerID) container.StopStatsCollection() return } } } } func (container *StatsContainer) processStatsStream() error { dockerID := container.containerMetadata.DockerID seelog.Debugf("Collecting stats for container %s", dockerID) if container.client == nil { return errors.New("container processStatsStream: Client is not set.") } dockerStats, errC := container.client.Stats(container.ctx, dockerID, dockerclient.StatsInactivityTimeout) returnError := false for { select { case <-container.ctx.Done(): return nil case err := <-errC: seelog.Warnf("Error encountered processing metrics stream from docker, this may affect cloudwatch metric accuracy: %s", err) returnError = true case rawStat, ok := <-dockerStats: if !ok { if returnError { return fmt.Errorf("error encountered processing metrics stream from docker") } return nil } err := validateDockerStats(rawStat) if err != nil { return err } if err := container.statsQueue.Add(rawStat); err != nil { seelog.Warnf("Container [%s]: error converting stats for container: %v", dockerID, err) } } } } func (container *StatsContainer) terminal() (bool, error) { dockerContainer, err := container.resolver.ResolveContainer(container.containerMetadata.DockerID) if err != nil { return false, err } return dockerContainer.Container.KnownTerminal(), nil } container stats: ignore context.Canceled errors we often receive context.Canceled errors when a container exits during docker stats collection. there is a benign race condition where if we process the error first before processing that the context is "Done", then we will log this canceled error as a warning message here: https://github.com/aws/amazon-ecs-agent/blob/5be7aa08bed215a557f48c16d8201ad3db59a9be/agent/stats/container.go#L118-L122 this change ignores these context.Canceled errors so that we don't log them. This will eliminate log messages that look like this when a container exits: level=warn time=2020-12-25T07:51:33Z msg="Error encountered processing metrics stream from docker, this may affect cloudwatch metric accuracy: DockerGoClient: Unable to decode stats for container REDACTED: context canceled" module=container.go // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 stats import ( "context" "errors" "fmt" "time" "github.com/aws/amazon-ecs-agent/agent/config" "github.com/aws/amazon-ecs-agent/agent/dockerclient" "github.com/aws/amazon-ecs-agent/agent/dockerclient/dockerapi" "github.com/aws/amazon-ecs-agent/agent/stats/resolver" "github.com/aws/amazon-ecs-agent/agent/utils/retry" "github.com/cihub/seelog" ) func newStatsContainer(dockerID string, client dockerapi.DockerClient, resolver resolver.ContainerMetadataResolver, cfg *config.Config) (*StatsContainer, error) { dockerContainer, err := resolver.ResolveContainer(dockerID) if err != nil { return nil, err } ctx, cancel := context.WithCancel(context.Background()) return &StatsContainer{ containerMetadata: &ContainerMetadata{ DockerID: dockerID, Name: dockerContainer.Container.Name, NetworkMode: dockerContainer.Container.GetNetworkMode(), }, ctx: ctx, cancel: cancel, client: client, resolver: resolver, config: cfg, }, nil } func (container *StatsContainer) StartStatsCollection() { // queue will be sized to hold enough stats for 4 publishing intervals. var queueSize int if container.config != nil && container.config.PollMetrics.Enabled() { pollingInterval := container.config.PollingMetricsWaitDuration.Seconds() queueSize = int(config.DefaultContainerMetricsPublishInterval.Seconds() / pollingInterval * 4) } else { // for streaming stats we assume 1 stat every second queueSize = int(config.DefaultContainerMetricsPublishInterval.Seconds() * 4) } container.statsQueue = NewQueue(queueSize) go container.collect() } func (container *StatsContainer) StopStatsCollection() { container.cancel() } func (container *StatsContainer) collect() { dockerID := container.containerMetadata.DockerID backoff := retry.NewExponentialBackoff(time.Second*1, time.Second*10, 0.5, 2) for { err := container.processStatsStream() select { case <-container.ctx.Done(): seelog.Infof("Container [%s]: Stopping stats collection", dockerID) return default: if err != nil { d := backoff.Duration() seelog.Debugf("Container [%s]: Error processing stats stream of container, backing off %s before reopening", dockerID, d) time.Sleep(d) } // We were disconnected from the stats stream. // Check if the container is terminal. If it is, stop collecting metrics. // We might sometimes miss events from docker task engine and this helps // in reconciling the state. terminal, err := container.terminal() if err != nil { // Error determining if the container is terminal. This means that the container // id could not be resolved to a container that is being tracked by the // docker task engine. If the docker task engine has already removed // the container from its state, there's no point in stats engine tracking the // container. So, clean-up anyway. seelog.Warnf("Container [%s]: Error determining if the container is terminal, stopping stats collection: %v", dockerID, err) container.StopStatsCollection() return } else if terminal { seelog.Infof("Container [%s]: container is terminal, stopping stats collection", dockerID) container.StopStatsCollection() return } } } } func (container *StatsContainer) processStatsStream() error { dockerID := container.containerMetadata.DockerID seelog.Debugf("Collecting stats for container %s", dockerID) if container.client == nil { return errors.New("container processStatsStream: Client is not set.") } dockerStats, errC := container.client.Stats(container.ctx, dockerID, dockerclient.StatsInactivityTimeout) returnError := false for { select { case <-container.ctx.Done(): return nil case err := <-errC: select { case <-container.ctx.Done(): // ignore error when container.ctx.Done() default: seelog.Warnf("Error encountered processing metrics stream from docker, this may affect cloudwatch metric accuracy: %s", err) returnError = true } case rawStat, ok := <-dockerStats: if !ok { if returnError { return fmt.Errorf("error encountered processing metrics stream from docker") } return nil } err := validateDockerStats(rawStat) if err != nil { return err } if err := container.statsQueue.Add(rawStat); err != nil { seelog.Warnf("Container [%s]: error converting stats for container: %v", dockerID, err) } } } } func (container *StatsContainer) terminal() (bool, error) { dockerContainer, err := container.resolver.ResolveContainer(container.containerMetadata.DockerID) if err != nil { return false, err } return dockerContainer.Container.KnownTerminal(), nil }
// Application that runs the specified benchmark over CT's webpage archives. package main import ( "flag" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "strconv" "time" "github.com/skia-dev/glog" "strings" "skia.googlesource.com/buildbot.git/ct/go/adb" "skia.googlesource.com/buildbot.git/ct/go/util" "skia.googlesource.com/buildbot.git/go/common" ) var ( workerNum = flag.Int("worker_num", 1, "The number of this CT worker. It will be in the {1..100} range.") pagesetType = flag.String("pageset_type", util.PAGESET_TYPE_MOBILE_10k, "The type of pagesets to create from the Alexa CSV list. Eg: 10k, Mobile10k, All.") chromiumBuild = flag.String("chromium_build", "", "The chromium build that was used to create the SKPs we would like to run lua scripts against.") runID = flag.String("run_id", "", "The unique run id (typically requester + timestamp).") benchmarkName = flag.String("benchmark_name", "", "The telemetry benchmark to run on this worker.") benchmarkExtraArgs = flag.String("benchmark_extra_args", "", "The extra arguments that are passed to the specified benchmark.") browserExtraArgs = flag.String("browser_extra_args", "", "The extra arguments that are passed to the browser while running the benchmark.") repeatBenchmark = flag.Int("repeat_benchmark", 1, "The number of times the benchmark should be repeated. For skpicture_printer benchmark this value is always 1.") targetPlatform = flag.String("target_platform", util.PLATFORM_ANDROID, "The platform the benchmark will run on (Android / Linux).") ) func main() { common.Init() defer util.TimeTrack(time.Now(), "Running Benchmark") defer glog.Flush() // Validate required arguments. if *chromiumBuild == "" { glog.Error("Must specify --chromium_build") return } if *runID == "" { glog.Error("Must specify --run_id") return } if *benchmarkName == "" { glog.Error("Must specify --benchmark_name") return } benchmarkArgs := *benchmarkExtraArgs browserArgs := *browserExtraArgs repeats := *repeatBenchmark // Sync the local chromium checkout. if err := util.SyncDir(util.ChromiumSrcDir); err != nil { glog.Errorf("Could not gclient sync %s: %s", util.ChromiumSrcDir, err) return } // Create the task file so that the master knows this worker is still busy. util.CreateTaskFile(util.ACTIVITY_RUNNING_BENCHMARKS) defer util.DeleteTaskFile(util.ACTIVITY_RUNNING_BENCHMARKS) if *targetPlatform == util.PLATFORM_ANDROID { if err := adb.VerifyLocalDevice(); err != nil { // Android device missing or offline. glog.Errorf("Could not find Android device: %s", err) return } // Make sure adb shell is running as root. util.ExecuteCmd(util.BINARY_ADB, []string{"root"}, []string{}, 5*time.Minute, nil, nil) } // Instantiate GsUtil object. gs, err := util.NewGsUtil(nil) if err != nil { glog.Error(err) return } // Download the specified chromium build. if err := gs.DownloadChromiumBuild(*chromiumBuild); err != nil { glog.Error(err) return } // Delete the chromium build to save space when we are done. defer os.RemoveAll(filepath.Join(util.ChromiumBuildsDir, *chromiumBuild)) chromiumBinary := filepath.Join(util.ChromiumBuildsDir, *chromiumBuild, util.BINARY_CHROME) if *targetPlatform == util.PLATFORM_ANDROID { // Install the APK on the Android device. chromiumApk := filepath.Join(util.ChromiumBuildsDir, *chromiumBuild, util.ApkPath) if err := util.ExecuteCmd(util.BINARY_ADB, []string{"install", "-r", chromiumApk}, []string{}, 5*time.Minute, nil, nil); err != nil { glog.Errorf("Could not install the chromium APK: %s", err) return } } // Download pagesets if they do not exist locally. if err := gs.DownloadWorkerArtifacts(util.PAGESETS_DIR_NAME, *pagesetType, *workerNum); err != nil { glog.Error(err) return } pathToPagesets := filepath.Join(util.PagesetsDir, *pagesetType) // Download archives if they do not exist locally. if err := gs.DownloadWorkerArtifacts(util.WEB_ARCHIVES_DIR_NAME, *pagesetType, *workerNum); err != nil { glog.Error(err) return } // Special handling for the "skpicture_printer" benchmark. Need to create the // dir that SKPs will be stored in. pathToSkps := filepath.Join(util.SkpsDir, *pagesetType, *chromiumBuild) if *benchmarkName == util.BENCHMARK_SKPICTURE_PRINTER { // Delete and remake the local SKPs directory. os.RemoveAll(pathToSkps) os.MkdirAll(pathToSkps, 0700) // Tell skpicture_printer where to output SKPs. // Do not allow unneeded whitespace for benchmarkArgs since they are // directly passed to run_benchmarks. if benchmarkArgs != "" { benchmarkArgs += " " } benchmarkArgs += "--skp-outdir=" + pathToSkps // Only do one run for SKPs. repeats = 1 } // Special handling for the "smoothness" benchmark. if *benchmarkName == util.BENCHMARK_SMOOTHNESS { // A synthetic scroll needs to be able to output at least two frames. Make // the viewport size smaller than the page size. // TODO(rmistry): I dont think smoothness honors the below flag, fix this // in telemetry code. browserArgs += " --window-size=1280,512" } // Establish output paths. localOutputDir := filepath.Join(util.StorageDir, util.BenchmarkRunsDir, *runID) os.RemoveAll(localOutputDir) os.MkdirAll(localOutputDir, 0700) defer os.RemoveAll(localOutputDir) remoteDir := filepath.Join(util.BenchmarkRunsDir, *runID) // Construct path to the ct_run_benchmark python script. _, currentFile, _, _ := runtime.Caller(0) pathToPyFiles := filepath.Join( filepath.Dir((filepath.Dir(filepath.Dir(filepath.Dir(currentFile))))), "py") // Loop through all pagesets. timeoutSecs := util.PagesetTypeToInfo[*pagesetType].RunBenchmarksTimeoutSecs fileInfos, err := ioutil.ReadDir(pathToPagesets) if err != nil { glog.Errorf("Unable to read the pagesets dir %s: %s", pathToPagesets, err) return } for _, fileInfo := range fileInfos { pagesetBaseName := filepath.Base(fileInfo.Name()) if pagesetBaseName == util.TIMESTAMP_FILE_NAME || filepath.Ext(pagesetBaseName) == ".pyc" { // Ignore timestamp files and .pyc files. continue } // Convert the filename into a format consumable by the run_benchmarks // binary. pagesetName := strings.TrimSuffix(pagesetBaseName, filepath.Ext(pagesetBaseName)) pagesetPath := filepath.Join(pathToPagesets, fileInfo.Name()) glog.Infof("===== Processing %s =====", pagesetPath) // Repeat runs the specified number of times. for repeatNum := 1; repeatNum <= repeats; repeatNum++ { os.Chdir(pathToPyFiles) args := []string{ util.BINARY_RUN_BENCHMARK, *benchmarkName, "--page-set-name=" + pagesetName, "--page-set-base-dir=" + pathToPagesets, "--also-run-disabled-tests", } // Need to capture output for all benchmarks except skpicture_printer. if *benchmarkName != util.BENCHMARK_SKPICTURE_PRINTER { outputDirArgValue := filepath.Join(localOutputDir, pagesetName, strconv.Itoa(repeatNum)) args = append(args, "--output-dir="+outputDirArgValue) } // Figure out which browser should be used. if *targetPlatform == util.PLATFORM_ANDROID { args = append(args, "--browser=android-chrome-shell") } else { args = append(args, "--browser=exact", "--browser-executable="+chromiumBinary) } // Split benchmark args if not empty and append to args. if benchmarkArgs != "" { for _, benchmarkArg := range strings.Split(benchmarkArgs, " ") { args = append(args, benchmarkArg) } } // Add browserArgs if not empty to args. if browserArgs != "" { args = append(args, "--extra-browser-args="+browserArgs) } // Set the PYTHONPATH to the pagesets and the telemetry dirs. env := []string{ fmt.Sprintf("PYTHONPATH=%s:%s:%s:$PYTHONPATH", pathToPagesets, util.TelemetryBinariesDir, util.TelemetrySrcDir), "DISPLAY=:0", } util.ExecuteCmd("python", args, env, time.Duration(timeoutSecs)*time.Second, nil, nil) } } // If "--output-format=csv" was specified then merge all CSV files and upload. if strings.Contains(benchmarkArgs, "--output-format=csv") { // Move all results into a single directory. for repeatNum := 1; repeatNum <= repeats; repeatNum++ { fileInfos, err := ioutil.ReadDir(localOutputDir) if err != nil { glog.Errorf("Unable to read %s: %s", localOutputDir, err) return } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { continue } outputFile := filepath.Join(localOutputDir, fileInfo.Name(), strconv.Itoa(repeatNum), "results.csv") newFile := filepath.Join(localOutputDir, fmt.Sprintf("%s-%s.csv", fileInfo.Name(), strconv.Itoa(repeatNum))) os.Rename(outputFile, newFile) } } // Call csv_merger.py to merge all results into a single results CSV. pathToCsvMerger := filepath.Join(pathToPyFiles, "csv_merger.py") outputFileName := *runID + ".output" args := []string{ pathToCsvMerger, "--csv_dir=" + localOutputDir, "--output_csv_name=" + filepath.Join(localOutputDir, outputFileName), } if err := util.ExecuteCmd("python", args, []string{}, 10*time.Minute, nil, nil); err != nil { glog.Errorf("Error running csv_merger.py: %s", err) return } // Copy the output file to Google Storage. remoteOutputDir := filepath.Join(remoteDir, fmt.Sprintf("slave%d", *workerNum), "outputs") if err := gs.UploadFile(outputFileName, localOutputDir, remoteOutputDir); err != nil { glog.Errorf("Unable to upload %s to %s: %s", outputFileName, remoteOutputDir, err) return } } // Move, validate and upload all SKP files if skpicture_printer was used. if *benchmarkName == util.BENCHMARK_SKPICTURE_PRINTER { // List all directories in pathToSkps and copy out the skps. fileInfos, err := ioutil.ReadDir(pathToSkps) if err != nil { glog.Errorf("Unable to read %s: %s", pathToSkps, err) return } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { // We are only interested in directories. continue } skpName := fileInfo.Name() // Find the largest layer in this directory. layerInfos, err := ioutil.ReadDir(filepath.Join(pathToSkps, skpName)) if err != nil { glog.Errorf("Unable to read %s: %s", filepath.Join(pathToSkps, skpName), err) } if len(layerInfos) > 0 { largestLayerInfo := layerInfos[0] for _, layerInfo := range layerInfos { fmt.Println(layerInfo.Size()) if layerInfo.Size() > largestLayerInfo.Size() { largestLayerInfo = layerInfo } } // Only save SKPs greater than 6000 bytes. Less than that are probably // malformed. if largestLayerInfo.Size() > 6000 { layerPath := filepath.Join(pathToSkps, skpName, largestLayerInfo.Name()) os.Rename(layerPath, filepath.Join(pathToSkps, skpName+".skp")) } else { glog.Warningf("Skipping %s because size was less than 5000 bytes", skpName) } } // We extracted what we needed from the directory, now delete it. os.RemoveAll(filepath.Join(pathToSkps, skpName)) } glog.Info("Calling remove_invalid_skps.py") // Sync Skia tree. util.SyncDir(util.SkiaTreeDir) // Build tools. util.BuildSkiaTools() // Run remove_invalid_skps.py pathToRemoveSKPs := filepath.Join(pathToPyFiles, "remove_invalid_skps.py") pathToSKPInfo := filepath.Join(util.SkiaTreeDir, "out", "Release", "skpinfo") args := []string{ pathToRemoveSKPs, "--skp_dir=" + pathToSkps, "--path_to_skpinfo=" + pathToSKPInfo, } util.ExecuteCmd("python", args, []string{}, 10*time.Minute, nil, nil) // Write timestamp to the SKPs dir. util.CreateTimestampFile(pathToSkps) // Upload SKPs dir to Google Storage. if err := gs.UploadWorkerArtifacts(util.SKPS_DIR_NAME, filepath.Join(*pagesetType, *chromiumBuild), *workerNum); err != nil { glog.Error(err) return } // Delete all tmp files from the slaves because telemetry tends to // generate a lot of temporary artifacts there and they take up root disk // space. files, _ := ioutil.ReadDir(os.TempDir()) for _, f := range files { os.RemoveAll(filepath.Join(os.TempDir(), f.Name())) } } } Clean tmp dir for all benchmark runs // Application that runs the specified benchmark over CT's webpage archives. package main import ( "flag" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "strconv" "time" "github.com/skia-dev/glog" "strings" "skia.googlesource.com/buildbot.git/ct/go/adb" "skia.googlesource.com/buildbot.git/ct/go/util" "skia.googlesource.com/buildbot.git/go/common" ) var ( workerNum = flag.Int("worker_num", 1, "The number of this CT worker. It will be in the {1..100} range.") pagesetType = flag.String("pageset_type", util.PAGESET_TYPE_MOBILE_10k, "The type of pagesets to create from the Alexa CSV list. Eg: 10k, Mobile10k, All.") chromiumBuild = flag.String("chromium_build", "", "The chromium build that was used to create the SKPs we would like to run lua scripts against.") runID = flag.String("run_id", "", "The unique run id (typically requester + timestamp).") benchmarkName = flag.String("benchmark_name", "", "The telemetry benchmark to run on this worker.") benchmarkExtraArgs = flag.String("benchmark_extra_args", "", "The extra arguments that are passed to the specified benchmark.") browserExtraArgs = flag.String("browser_extra_args", "", "The extra arguments that are passed to the browser while running the benchmark.") repeatBenchmark = flag.Int("repeat_benchmark", 1, "The number of times the benchmark should be repeated. For skpicture_printer benchmark this value is always 1.") targetPlatform = flag.String("target_platform", util.PLATFORM_ANDROID, "The platform the benchmark will run on (Android / Linux).") ) func main() { common.Init() defer util.TimeTrack(time.Now(), "Running Benchmark") defer glog.Flush() // Validate required arguments. if *chromiumBuild == "" { glog.Error("Must specify --chromium_build") return } if *runID == "" { glog.Error("Must specify --run_id") return } if *benchmarkName == "" { glog.Error("Must specify --benchmark_name") return } benchmarkArgs := *benchmarkExtraArgs browserArgs := *browserExtraArgs repeats := *repeatBenchmark // Sync the local chromium checkout. if err := util.SyncDir(util.ChromiumSrcDir); err != nil { glog.Errorf("Could not gclient sync %s: %s", util.ChromiumSrcDir, err) return } // Create the task file so that the master knows this worker is still busy. util.CreateTaskFile(util.ACTIVITY_RUNNING_BENCHMARKS) defer util.DeleteTaskFile(util.ACTIVITY_RUNNING_BENCHMARKS) if *targetPlatform == util.PLATFORM_ANDROID { if err := adb.VerifyLocalDevice(); err != nil { // Android device missing or offline. glog.Errorf("Could not find Android device: %s", err) return } // Make sure adb shell is running as root. util.ExecuteCmd(util.BINARY_ADB, []string{"root"}, []string{}, 5*time.Minute, nil, nil) } // Instantiate GsUtil object. gs, err := util.NewGsUtil(nil) if err != nil { glog.Error(err) return } // Download the specified chromium build. if err := gs.DownloadChromiumBuild(*chromiumBuild); err != nil { glog.Error(err) return } // Delete the chromium build to save space when we are done. defer os.RemoveAll(filepath.Join(util.ChromiumBuildsDir, *chromiumBuild)) chromiumBinary := filepath.Join(util.ChromiumBuildsDir, *chromiumBuild, util.BINARY_CHROME) if *targetPlatform == util.PLATFORM_ANDROID { // Install the APK on the Android device. chromiumApk := filepath.Join(util.ChromiumBuildsDir, *chromiumBuild, util.ApkPath) if err := util.ExecuteCmd(util.BINARY_ADB, []string{"install", "-r", chromiumApk}, []string{}, 5*time.Minute, nil, nil); err != nil { glog.Errorf("Could not install the chromium APK: %s", err) return } } // Download pagesets if they do not exist locally. if err := gs.DownloadWorkerArtifacts(util.PAGESETS_DIR_NAME, *pagesetType, *workerNum); err != nil { glog.Error(err) return } pathToPagesets := filepath.Join(util.PagesetsDir, *pagesetType) // Download archives if they do not exist locally. if err := gs.DownloadWorkerArtifacts(util.WEB_ARCHIVES_DIR_NAME, *pagesetType, *workerNum); err != nil { glog.Error(err) return } // Special handling for the "skpicture_printer" benchmark. Need to create the // dir that SKPs will be stored in. pathToSkps := filepath.Join(util.SkpsDir, *pagesetType, *chromiumBuild) if *benchmarkName == util.BENCHMARK_SKPICTURE_PRINTER { // Delete and remake the local SKPs directory. os.RemoveAll(pathToSkps) os.MkdirAll(pathToSkps, 0700) // Tell skpicture_printer where to output SKPs. // Do not allow unneeded whitespace for benchmarkArgs since they are // directly passed to run_benchmarks. if benchmarkArgs != "" { benchmarkArgs += " " } benchmarkArgs += "--skp-outdir=" + pathToSkps // Only do one run for SKPs. repeats = 1 } // Special handling for the "smoothness" benchmark. if *benchmarkName == util.BENCHMARK_SMOOTHNESS { // A synthetic scroll needs to be able to output at least two frames. Make // the viewport size smaller than the page size. // TODO(rmistry): I dont think smoothness honors the below flag, fix this // in telemetry code. browserArgs += " --window-size=1280,512" } // Establish output paths. localOutputDir := filepath.Join(util.StorageDir, util.BenchmarkRunsDir, *runID) os.RemoveAll(localOutputDir) os.MkdirAll(localOutputDir, 0700) defer os.RemoveAll(localOutputDir) remoteDir := filepath.Join(util.BenchmarkRunsDir, *runID) // Construct path to the ct_run_benchmark python script. _, currentFile, _, _ := runtime.Caller(0) pathToPyFiles := filepath.Join( filepath.Dir((filepath.Dir(filepath.Dir(filepath.Dir(currentFile))))), "py") // Loop through all pagesets. timeoutSecs := util.PagesetTypeToInfo[*pagesetType].RunBenchmarksTimeoutSecs fileInfos, err := ioutil.ReadDir(pathToPagesets) if err != nil { glog.Errorf("Unable to read the pagesets dir %s: %s", pathToPagesets, err) return } for _, fileInfo := range fileInfos { pagesetBaseName := filepath.Base(fileInfo.Name()) if pagesetBaseName == util.TIMESTAMP_FILE_NAME || filepath.Ext(pagesetBaseName) == ".pyc" { // Ignore timestamp files and .pyc files. continue } // Convert the filename into a format consumable by the run_benchmarks // binary. pagesetName := strings.TrimSuffix(pagesetBaseName, filepath.Ext(pagesetBaseName)) pagesetPath := filepath.Join(pathToPagesets, fileInfo.Name()) glog.Infof("===== Processing %s =====", pagesetPath) // Repeat runs the specified number of times. for repeatNum := 1; repeatNum <= repeats; repeatNum++ { os.Chdir(pathToPyFiles) args := []string{ util.BINARY_RUN_BENCHMARK, *benchmarkName, "--page-set-name=" + pagesetName, "--page-set-base-dir=" + pathToPagesets, "--also-run-disabled-tests", } // Need to capture output for all benchmarks except skpicture_printer. if *benchmarkName != util.BENCHMARK_SKPICTURE_PRINTER { outputDirArgValue := filepath.Join(localOutputDir, pagesetName, strconv.Itoa(repeatNum)) args = append(args, "--output-dir="+outputDirArgValue) } // Figure out which browser should be used. if *targetPlatform == util.PLATFORM_ANDROID { args = append(args, "--browser=android-chrome-shell") } else { args = append(args, "--browser=exact", "--browser-executable="+chromiumBinary) } // Split benchmark args if not empty and append to args. if benchmarkArgs != "" { for _, benchmarkArg := range strings.Split(benchmarkArgs, " ") { args = append(args, benchmarkArg) } } // Add browserArgs if not empty to args. if browserArgs != "" { args = append(args, "--extra-browser-args="+browserArgs) } // Set the PYTHONPATH to the pagesets and the telemetry dirs. env := []string{ fmt.Sprintf("PYTHONPATH=%s:%s:%s:$PYTHONPATH", pathToPagesets, util.TelemetryBinariesDir, util.TelemetrySrcDir), "DISPLAY=:0", } util.ExecuteCmd("python", args, env, time.Duration(timeoutSecs)*time.Second, nil, nil) } } // If "--output-format=csv" was specified then merge all CSV files and upload. if strings.Contains(benchmarkArgs, "--output-format=csv") { // Move all results into a single directory. for repeatNum := 1; repeatNum <= repeats; repeatNum++ { fileInfos, err := ioutil.ReadDir(localOutputDir) if err != nil { glog.Errorf("Unable to read %s: %s", localOutputDir, err) return } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { continue } outputFile := filepath.Join(localOutputDir, fileInfo.Name(), strconv.Itoa(repeatNum), "results.csv") newFile := filepath.Join(localOutputDir, fmt.Sprintf("%s-%s.csv", fileInfo.Name(), strconv.Itoa(repeatNum))) os.Rename(outputFile, newFile) } } // Call csv_merger.py to merge all results into a single results CSV. pathToCsvMerger := filepath.Join(pathToPyFiles, "csv_merger.py") outputFileName := *runID + ".output" args := []string{ pathToCsvMerger, "--csv_dir=" + localOutputDir, "--output_csv_name=" + filepath.Join(localOutputDir, outputFileName), } if err := util.ExecuteCmd("python", args, []string{}, 10*time.Minute, nil, nil); err != nil { glog.Errorf("Error running csv_merger.py: %s", err) return } // Copy the output file to Google Storage. remoteOutputDir := filepath.Join(remoteDir, fmt.Sprintf("slave%d", *workerNum), "outputs") if err := gs.UploadFile(outputFileName, localOutputDir, remoteOutputDir); err != nil { glog.Errorf("Unable to upload %s to %s: %s", outputFileName, remoteOutputDir, err) return } } // Move, validate and upload all SKP files if skpicture_printer was used. if *benchmarkName == util.BENCHMARK_SKPICTURE_PRINTER { // List all directories in pathToSkps and copy out the skps. fileInfos, err := ioutil.ReadDir(pathToSkps) if err != nil { glog.Errorf("Unable to read %s: %s", pathToSkps, err) return } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { // We are only interested in directories. continue } skpName := fileInfo.Name() // Find the largest layer in this directory. layerInfos, err := ioutil.ReadDir(filepath.Join(pathToSkps, skpName)) if err != nil { glog.Errorf("Unable to read %s: %s", filepath.Join(pathToSkps, skpName), err) } if len(layerInfos) > 0 { largestLayerInfo := layerInfos[0] for _, layerInfo := range layerInfos { fmt.Println(layerInfo.Size()) if layerInfo.Size() > largestLayerInfo.Size() { largestLayerInfo = layerInfo } } // Only save SKPs greater than 6000 bytes. Less than that are probably // malformed. if largestLayerInfo.Size() > 6000 { layerPath := filepath.Join(pathToSkps, skpName, largestLayerInfo.Name()) os.Rename(layerPath, filepath.Join(pathToSkps, skpName+".skp")) } else { glog.Warningf("Skipping %s because size was less than 5000 bytes", skpName) } } // We extracted what we needed from the directory, now delete it. os.RemoveAll(filepath.Join(pathToSkps, skpName)) } glog.Info("Calling remove_invalid_skps.py") // Sync Skia tree. util.SyncDir(util.SkiaTreeDir) // Build tools. util.BuildSkiaTools() // Run remove_invalid_skps.py pathToRemoveSKPs := filepath.Join(pathToPyFiles, "remove_invalid_skps.py") pathToSKPInfo := filepath.Join(util.SkiaTreeDir, "out", "Release", "skpinfo") args := []string{ pathToRemoveSKPs, "--skp_dir=" + pathToSkps, "--path_to_skpinfo=" + pathToSKPInfo, } util.ExecuteCmd("python", args, []string{}, 10*time.Minute, nil, nil) // Write timestamp to the SKPs dir. util.CreateTimestampFile(pathToSkps) // Upload SKPs dir to Google Storage. if err := gs.UploadWorkerArtifacts(util.SKPS_DIR_NAME, filepath.Join(*pagesetType, *chromiumBuild), *workerNum); err != nil { glog.Error(err) return } } // Delete all tmp files from the slaves because telemetry tends to // generate a lot of temporary artifacts there and they take up root disk // space. files, _ := ioutil.ReadDir(os.TempDir()) for _, f := range files { os.RemoveAll(filepath.Join(os.TempDir(), f.Name())) } }
// Copyright 2017 Istio Authors // // 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 crd provides an implementation of the config store and cache // using Kubernetes Custom Resources and the informer framework from Kubernetes package crd import ( "fmt" "time" "github.com/golang/glog" multierror "github.com/hashicorp/go-multierror" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/util/wait" // import GKE cluster authentication plugin _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // import OIDC cluster authentication plugin, e.g. for Tectonic _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "istio.io/pilot/model" "istio.io/pilot/platform/kube" ) // IstioObject is a k8s wrapper interface for config objects type IstioObject interface { runtime.Object GetSpec() map[string]interface{} SetSpec(map[string]interface{}) GetObjectMeta() meta_v1.ObjectMeta SetObjectMeta(meta_v1.ObjectMeta) } // IstioObjectList is a k8s wrapper interface for config lists type IstioObjectList interface { runtime.Object GetItems() []IstioObject } // Client is a basic REST client for CRDs implementing config store type Client struct { descriptor model.ConfigDescriptor // restconfig for REST type descriptors restconfig *rest.Config // dynamic REST client for accessing config CRDs dynamic *rest.RESTClient // domainSuffix for the config metadata domainSuffix string } // CreateRESTConfig for cluster API server, pass empty config file for in-cluster func CreateRESTConfig(kubeconfig string) (config *rest.Config, err error) { if kubeconfig == "" { config, err = rest.InClusterConfig() } else { config, err = clientcmd.BuildConfigFromFlags("", kubeconfig) } if err != nil { return } version := schema.GroupVersion{ Group: model.IstioAPIGroup, Version: model.IstioAPIVersion, } config.GroupVersion = &version config.APIPath = "/apis" config.ContentType = runtime.ContentTypeJSON types := runtime.NewScheme() schemeBuilder := runtime.NewSchemeBuilder( func(scheme *runtime.Scheme) error { for _, kind := range knownTypes { scheme.AddKnownTypes(version, kind.object, kind.collection) } meta_v1.AddToGroupVersion(scheme, version) return nil }) err = schemeBuilder.AddToScheme(types) config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(types)} return } // NewClient creates a client to Kubernetes API using a kubeconfig file. // Use an empty value for `kubeconfig` to use the in-cluster config. // If the kubeconfig file is empty, defaults to in-cluster config as well. func NewClient(config string, descriptor model.ConfigDescriptor, domainSuffix string) (*Client, error) { for _, typ := range descriptor { if _, exists := knownTypes[typ.Type]; !exists { return nil, fmt.Errorf("missing known type for %q", typ.Type) } } kubeconfig, err := kube.ResolveConfig(config) if err != nil { return nil, err } restconfig, err := CreateRESTConfig(kubeconfig) if err != nil { return nil, err } dynamic, err := rest.RESTClientFor(restconfig) if err != nil { return nil, err } out := &Client{ descriptor: descriptor, restconfig: restconfig, dynamic: dynamic, domainSuffix: domainSuffix, } return out, nil } // RegisterResources sends a request to create CRDs and waits for them to initialize func (cl *Client) RegisterResources() error { clientset, err := apiextensionsclient.NewForConfig(cl.restconfig) if err != nil { return err } for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup crd := &apiextensionsv1beta1.CustomResourceDefinition{ ObjectMeta: meta_v1.ObjectMeta{ Name: name, }, Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{ Group: model.IstioAPIGroup, Version: model.IstioAPIVersion, Scope: apiextensionsv1beta1.NamespaceScoped, Names: apiextensionsv1beta1.CustomResourceDefinitionNames{ Plural: ResourceName(schema.Plural), Kind: kabobCaseToCamelCase(schema.Type), }, }, } glog.V(2).Infof("registering CRD %q", name) _, err = clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd) if err != nil && !apierrors.IsAlreadyExists(err) { return err } } // wait for CRD being established errPoll := wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) { descriptor: for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup crd, errGet := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(name, meta_v1.GetOptions{}) if errGet != nil { return false, errGet } for _, cond := range crd.Status.Conditions { switch cond.Type { case apiextensionsv1beta1.Established: if cond.Status == apiextensionsv1beta1.ConditionTrue { glog.V(2).Infof("established CRD %q", name) continue descriptor } case apiextensionsv1beta1.NamesAccepted: if cond.Status == apiextensionsv1beta1.ConditionFalse { glog.Warningf("name conflict: %v", cond.Reason) } } } glog.V(2).Infof("missing status condition for %q", name) return false, err } return true, nil }) if errPoll != nil { deleteErr := cl.DeregisterResources() if deleteErr != nil { return multierror.Append(err, deleteErr) } return err } return nil } // DeregisterResources removes third party resources func (cl *Client) DeregisterResources() error { clientset, err := apiextensionsclient.NewForConfig(cl.restconfig) if err != nil { return err } var errs error for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(name, nil) errs = multierror.Append(errs, err) } return errs } // ConfigDescriptor for the store func (cl *Client) ConfigDescriptor() model.ConfigDescriptor { return cl.descriptor } // Get implements store interface func (cl *Client) Get(typ, name, namespace string) (*model.Config, bool) { schema, exists := cl.descriptor.GetByType(typ) if !exists { return nil, false } config := knownTypes[typ].object.DeepCopyObject().(IstioObject) err := cl.dynamic.Get(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Name(name). Do().Into(config) if err != nil { glog.Warning(err) return nil, false } out, err := ConvertObject(schema, config, cl.domainSuffix) if err != nil { glog.Warning(err) return nil, false } return out, true } // Create implements store interface func (cl *Client) Create(config model.Config) (string, error) { schema, exists := cl.descriptor.GetByType(config.Type) if !exists { return "", fmt.Errorf("unrecognized type %q", config.Type) } if err := schema.Validate(config.Spec); err != nil { return "", multierror.Prefix(err, "validation error:") } out, err := ConvertConfig(schema, config) if err != nil { return "", err } obj := knownTypes[schema.Type].object.DeepCopyObject().(IstioObject) err = cl.dynamic.Post(). Namespace(out.GetObjectMeta().Namespace). Resource(ResourceName(schema.Plural)). Body(out). Do().Into(obj) if err != nil { return "", err } return obj.GetObjectMeta().ResourceVersion, nil } // Update implements store interface func (cl *Client) Update(config model.Config) (string, error) { schema, exists := cl.descriptor.GetByType(config.Type) if !exists { return "", fmt.Errorf("unrecognized type %q", config.Type) } if err := schema.Validate(config.Spec); err != nil { return "", multierror.Prefix(err, "validation error:") } if config.ResourceVersion == "" { return "", fmt.Errorf("revision is required") } out, err := ConvertConfig(schema, config) if err != nil { return "", err } obj := knownTypes[schema.Type].object.DeepCopyObject().(IstioObject) err = cl.dynamic.Put(). Namespace(out.GetObjectMeta().Namespace). Resource(ResourceName(schema.Plural)). Name(out.GetObjectMeta().Name). Body(out). Do().Into(obj) if err != nil { return "", err } return obj.GetObjectMeta().ResourceVersion, nil } // Delete implements store interface func (cl *Client) Delete(typ, name, namespace string) error { schema, exists := cl.descriptor.GetByType(typ) if !exists { return fmt.Errorf("missing type %q", typ) } return cl.dynamic.Delete(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Name(name). Do().Error() } // List implements store interface func (cl *Client) List(typ, namespace string) ([]model.Config, error) { schema, exists := cl.descriptor.GetByType(typ) if !exists { return nil, fmt.Errorf("missing type %q", typ) } list := knownTypes[schema.Type].collection.DeepCopyObject().(IstioObjectList) errs := cl.dynamic.Get(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Do().Into(list) out := make([]model.Config, 0) for _, item := range list.GetItems() { obj, err := ConvertObject(schema, item, cl.domainSuffix) if err != nil { errs = multierror.Append(errs, err) } else { out = append(out, *obj) } } return out, errs } fix for error message (#1231) // Copyright 2017 Istio Authors // // 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 crd provides an implementation of the config store and cache // using Kubernetes Custom Resources and the informer framework from Kubernetes package crd import ( "fmt" "time" "github.com/golang/glog" multierror "github.com/hashicorp/go-multierror" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/util/wait" // import GKE cluster authentication plugin _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // import OIDC cluster authentication plugin, e.g. for Tectonic _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "istio.io/pilot/model" "istio.io/pilot/platform/kube" ) // IstioObject is a k8s wrapper interface for config objects type IstioObject interface { runtime.Object GetSpec() map[string]interface{} SetSpec(map[string]interface{}) GetObjectMeta() meta_v1.ObjectMeta SetObjectMeta(meta_v1.ObjectMeta) } // IstioObjectList is a k8s wrapper interface for config lists type IstioObjectList interface { runtime.Object GetItems() []IstioObject } // Client is a basic REST client for CRDs implementing config store type Client struct { descriptor model.ConfigDescriptor // restconfig for REST type descriptors restconfig *rest.Config // dynamic REST client for accessing config CRDs dynamic *rest.RESTClient // domainSuffix for the config metadata domainSuffix string } // CreateRESTConfig for cluster API server, pass empty config file for in-cluster func CreateRESTConfig(kubeconfig string) (config *rest.Config, err error) { if kubeconfig == "" { config, err = rest.InClusterConfig() } else { config, err = clientcmd.BuildConfigFromFlags("", kubeconfig) } if err != nil { return } version := schema.GroupVersion{ Group: model.IstioAPIGroup, Version: model.IstioAPIVersion, } config.GroupVersion = &version config.APIPath = "/apis" config.ContentType = runtime.ContentTypeJSON types := runtime.NewScheme() schemeBuilder := runtime.NewSchemeBuilder( func(scheme *runtime.Scheme) error { for _, kind := range knownTypes { scheme.AddKnownTypes(version, kind.object, kind.collection) } meta_v1.AddToGroupVersion(scheme, version) return nil }) err = schemeBuilder.AddToScheme(types) config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(types)} return } // NewClient creates a client to Kubernetes API using a kubeconfig file. // Use an empty value for `kubeconfig` to use the in-cluster config. // If the kubeconfig file is empty, defaults to in-cluster config as well. func NewClient(config string, descriptor model.ConfigDescriptor, domainSuffix string) (*Client, error) { for _, typ := range descriptor { if _, exists := knownTypes[typ.Type]; !exists { return nil, fmt.Errorf("missing known type for %q", typ.Type) } } kubeconfig, err := kube.ResolveConfig(config) if err != nil { return nil, err } restconfig, err := CreateRESTConfig(kubeconfig) if err != nil { return nil, err } dynamic, err := rest.RESTClientFor(restconfig) if err != nil { return nil, err } out := &Client{ descriptor: descriptor, restconfig: restconfig, dynamic: dynamic, domainSuffix: domainSuffix, } return out, nil } // RegisterResources sends a request to create CRDs and waits for them to initialize func (cl *Client) RegisterResources() error { clientset, err := apiextensionsclient.NewForConfig(cl.restconfig) if err != nil { return err } for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup crd := &apiextensionsv1beta1.CustomResourceDefinition{ ObjectMeta: meta_v1.ObjectMeta{ Name: name, }, Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{ Group: model.IstioAPIGroup, Version: model.IstioAPIVersion, Scope: apiextensionsv1beta1.NamespaceScoped, Names: apiextensionsv1beta1.CustomResourceDefinitionNames{ Plural: ResourceName(schema.Plural), Kind: kabobCaseToCamelCase(schema.Type), }, }, } glog.V(2).Infof("registering CRD %q", name) _, err = clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd) if err != nil && !apierrors.IsAlreadyExists(err) { return err } } // wait for CRD being established errPoll := wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) { descriptor: for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup crd, errGet := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(name, meta_v1.GetOptions{}) if errGet != nil { return false, errGet } for _, cond := range crd.Status.Conditions { switch cond.Type { case apiextensionsv1beta1.Established: if cond.Status == apiextensionsv1beta1.ConditionTrue { glog.V(2).Infof("established CRD %q", name) continue descriptor } case apiextensionsv1beta1.NamesAccepted: if cond.Status == apiextensionsv1beta1.ConditionFalse { glog.Warningf("name conflict: %v", cond.Reason) } } } glog.V(2).Infof("missing status condition for %q", name) return false, nil } return true, nil }) if errPoll != nil { deleteErr := cl.DeregisterResources() if deleteErr != nil { return multierror.Append(errPoll, deleteErr) } return errPoll } return nil } // DeregisterResources removes third party resources func (cl *Client) DeregisterResources() error { clientset, err := apiextensionsclient.NewForConfig(cl.restconfig) if err != nil { return err } var errs error for _, schema := range cl.descriptor { name := ResourceName(schema.Plural) + "." + model.IstioAPIGroup err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(name, nil) errs = multierror.Append(errs, err) } return errs } // ConfigDescriptor for the store func (cl *Client) ConfigDescriptor() model.ConfigDescriptor { return cl.descriptor } // Get implements store interface func (cl *Client) Get(typ, name, namespace string) (*model.Config, bool) { schema, exists := cl.descriptor.GetByType(typ) if !exists { return nil, false } config := knownTypes[typ].object.DeepCopyObject().(IstioObject) err := cl.dynamic.Get(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Name(name). Do().Into(config) if err != nil { glog.Warning(err) return nil, false } out, err := ConvertObject(schema, config, cl.domainSuffix) if err != nil { glog.Warning(err) return nil, false } return out, true } // Create implements store interface func (cl *Client) Create(config model.Config) (string, error) { schema, exists := cl.descriptor.GetByType(config.Type) if !exists { return "", fmt.Errorf("unrecognized type %q", config.Type) } if err := schema.Validate(config.Spec); err != nil { return "", multierror.Prefix(err, "validation error:") } out, err := ConvertConfig(schema, config) if err != nil { return "", err } obj := knownTypes[schema.Type].object.DeepCopyObject().(IstioObject) err = cl.dynamic.Post(). Namespace(out.GetObjectMeta().Namespace). Resource(ResourceName(schema.Plural)). Body(out). Do().Into(obj) if err != nil { return "", err } return obj.GetObjectMeta().ResourceVersion, nil } // Update implements store interface func (cl *Client) Update(config model.Config) (string, error) { schema, exists := cl.descriptor.GetByType(config.Type) if !exists { return "", fmt.Errorf("unrecognized type %q", config.Type) } if err := schema.Validate(config.Spec); err != nil { return "", multierror.Prefix(err, "validation error:") } if config.ResourceVersion == "" { return "", fmt.Errorf("revision is required") } out, err := ConvertConfig(schema, config) if err != nil { return "", err } obj := knownTypes[schema.Type].object.DeepCopyObject().(IstioObject) err = cl.dynamic.Put(). Namespace(out.GetObjectMeta().Namespace). Resource(ResourceName(schema.Plural)). Name(out.GetObjectMeta().Name). Body(out). Do().Into(obj) if err != nil { return "", err } return obj.GetObjectMeta().ResourceVersion, nil } // Delete implements store interface func (cl *Client) Delete(typ, name, namespace string) error { schema, exists := cl.descriptor.GetByType(typ) if !exists { return fmt.Errorf("missing type %q", typ) } return cl.dynamic.Delete(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Name(name). Do().Error() } // List implements store interface func (cl *Client) List(typ, namespace string) ([]model.Config, error) { schema, exists := cl.descriptor.GetByType(typ) if !exists { return nil, fmt.Errorf("missing type %q", typ) } list := knownTypes[schema.Type].collection.DeepCopyObject().(IstioObjectList) errs := cl.dynamic.Get(). Namespace(namespace). Resource(ResourceName(schema.Plural)). Do().Into(list) out := make([]model.Config, 0) for _, item := range list.GetItems() { obj, err := ConvertObject(schema, item, cl.domainSuffix) if err != nil { errs = multierror.Append(errs, err) } else { out = append(out, *obj) } } return out, errs }
package physical import ( "fmt" "io/ioutil" "log" "net" "net/url" "strconv" "strings" "sync" "sync/atomic" "time" "crypto/tls" "crypto/x509" "github.com/armon/go-metrics" "github.com/hashicorp/consul/api" "github.com/hashicorp/consul/lib" "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" ) const ( // checkJitterFactor specifies the jitter factor used to stagger checks checkJitterFactor = 16 // checkMinBuffer specifies provides a guarantee that a check will not // be executed too close to the TTL check timeout checkMinBuffer = 100 * time.Millisecond // defaultCheckTimeout changes the timeout of TTL checks defaultCheckTimeout = 5 * time.Second // defaultCheckInterval specifies the default interval used to send // checks defaultCheckInterval = 4 * time.Second // defaultServiceName is the default Consul service name used when // advertising a Vault instance. defaultServiceName = "vault" // registrationRetryInterval specifies the retry duration to use when // a registration to the Consul agent fails. registrationRetryInterval = 1 * time.Second ) // ConsulBackend is a physical backend that stores data at specific // prefix within Consul. It is used for most production situations as // it allows Vault to run on multiple machines in a highly-available manner. type ConsulBackend struct { path string logger *log.Logger client *api.Client kv *api.KV permitPool *PermitPool serviceLock sync.RWMutex service *api.AgentServiceRegistration sealedCheck *api.AgentCheckRegistration registrationLock int64 advertiseHost string advertisePort int64 consulClientConf *api.Config serviceName string running bool active bool unsealed bool disableRegistration bool checkTimeout time.Duration checkTimer *time.Timer } // newConsulBackend constructs a Consul backend using the given API client // and the prefix in the KV store. func newConsulBackend(conf map[string]string, logger *log.Logger) (Backend, error) { // Get the path in Consul path, ok := conf["path"] if !ok { path = "vault/" } // Ensure path is suffixed but not prefixed if !strings.HasSuffix(path, "/") { logger.Printf("[WARN]: consul: appending trailing forward slash to path") path += "/" } if strings.HasPrefix(path, "/") { logger.Printf("[WARN]: consul: trimming path of its forward slash") path = strings.TrimPrefix(path, "/") } // Allow admins to disable consul integration disableReg, ok := conf["disable_registration"] var disableRegistration bool if ok && disableReg != "" { b, err := strconv.ParseBool(disableReg) if err != nil { return nil, errwrap.Wrapf("failed parsing disable_registration parameter: {{err}}", err) } disableRegistration = b } // Get the service name to advertise in Consul service, ok := conf["service"] if !ok { service = defaultServiceName } checkTimeout := defaultCheckTimeout checkTimeoutStr, ok := conf["check_timeout"] if ok { d, err := time.ParseDuration(checkTimeoutStr) if err != nil { return nil, err } min, _ := lib.DurationMinusBufferDomain(d, checkMinBuffer, checkJitterFactor) if min < checkMinBuffer { return nil, fmt.Errorf("Consul check_timeout must be greater than %v", min) } checkTimeout = d } // Configure the client consulConf := api.DefaultConfig() if addr, ok := conf["address"]; ok { consulConf.Address = addr } if scheme, ok := conf["scheme"]; ok { consulConf.Scheme = scheme } if token, ok := conf["token"]; ok { consulConf.Token = token } if consulConf.Scheme == "https" { tlsClientConfig, err := setupTLSConfig(conf) if err != nil { return nil, err } transport := cleanhttp.DefaultPooledTransport() transport.MaxIdleConnsPerHost = 4 transport.TLSClientConfig = tlsClientConfig consulConf.HttpClient.Transport = transport } client, err := api.NewClient(consulConf) if err != nil { return nil, errwrap.Wrapf("client setup failed: {{err}}", err) } maxParStr, ok := conf["max_parallel"] var maxParInt int if ok { maxParInt, err = strconv.Atoi(maxParStr) if err != nil { return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) } logger.Printf("[DEBUG]: consul: max_parallel set to %d", maxParInt) } // Setup the backend c := &ConsulBackend{ path: path, logger: logger, client: client, kv: client.KV(), permitPool: NewPermitPool(maxParInt), consulClientConf: consulConf, serviceName: service, checkTimeout: checkTimeout, checkTimer: time.NewTimer(checkTimeout), disableRegistration: disableRegistration, } return c, nil } // serviceTags returns all of the relevant tags for Consul. func serviceTags(active bool) []string { activeTag := "standby" if active { activeTag = "active" } return []string{activeTag} } func (c *ConsulBackend) AdvertiseActive(active bool) error { c.serviceLock.Lock() defer c.serviceLock.Unlock() // Vault is still bootstrapping if c.service == nil { return nil } // Save a cached copy of the active state: no way to query Core c.active = active // Ensure serial registration to the Consul agent. Allow for // concurrent calls to update active status while a single task // attempts, until successful, to update the Consul Agent. if !c.disableRegistration && atomic.CompareAndSwapInt64(&c.registrationLock, 0, 1) { defer atomic.CompareAndSwapInt64(&c.registrationLock, 1, 0) // Retry agent registration until successful for { c.service.Tags = serviceTags(c.active) agent := c.client.Agent() err := agent.ServiceRegister(c.service) if err == nil { // Success return nil } c.logger.Printf("[WARN] consul: service registration failed: %v", err) c.serviceLock.Unlock() time.Sleep(registrationRetryInterval) c.serviceLock.Lock() if !c.running { // Shutting down return err } } } // Successful concurrent update to active state return nil } func (c *ConsulBackend) AdvertiseSealed(sealed bool) error { c.serviceLock.Lock() defer c.serviceLock.Unlock() c.unsealed = !sealed // Vault is still bootstrapping if c.service == nil { return nil } if !c.disableRegistration { // Push a TTL check immediately to update the state c.runCheck() } return nil } func (c *ConsulBackend) RunServiceDiscovery(shutdownCh ShutdownChannel, advertiseAddr string) (err error) { c.serviceLock.Lock() defer c.serviceLock.Unlock() if c.disableRegistration { return nil } if err := c.setAdvertiseAddr(advertiseAddr); err != nil { return err } serviceID := c.serviceID() c.service = &api.AgentServiceRegistration{ ID: serviceID, Name: c.serviceName, Tags: serviceTags(c.active), Port: int(c.advertisePort), Address: c.advertiseHost, EnableTagOverride: false, } checkStatus := api.HealthCritical if c.unsealed { checkStatus = api.HealthPassing } c.sealedCheck = &api.AgentCheckRegistration{ ID: c.checkID(), Name: "Vault Sealed Status", Notes: "Vault service is healthy when Vault is in an unsealed status and can become an active Vault server", ServiceID: serviceID, AgentServiceCheck: api.AgentServiceCheck{ TTL: c.checkTimeout.String(), Status: checkStatus, }, } agent := c.client.Agent() if err := agent.ServiceRegister(c.service); err != nil { return errwrap.Wrapf("service registration failed: {{err}}", err) } if err := agent.CheckRegister(c.sealedCheck); err != nil { return errwrap.Wrapf("service registration check registration failed: {{err}}", err) } go c.checkRunner(shutdownCh) c.running = true // Deregister upon shutdown go func() { shutdown: for { select { case <-shutdownCh: c.logger.Printf("[INFO]: consul: Shutting down consul backend") break shutdown } } if err := agent.ServiceDeregister(serviceID); err != nil { c.logger.Printf("[WARN]: consul: service deregistration failed: {{err}}", err) } c.running = false }() return nil } // checkRunner periodically runs TTL checks func (c *ConsulBackend) checkRunner(shutdownCh ShutdownChannel) { defer c.checkTimer.Stop() for { select { case <-c.checkTimer.C: go func() { c.serviceLock.Lock() defer c.serviceLock.Unlock() c.runCheck() }() case <-shutdownCh: return } } } // runCheck immediately pushes a TTL check. Assumes c.serviceLock is held // exclusively. func (c *ConsulBackend) runCheck() { // Reset timer before calling run check in order to not slide the // window of the next check. c.checkTimer.Reset(lib.DurationMinusBuffer(c.checkTimeout, checkMinBuffer, checkJitterFactor)) // Run a TTL check agent := c.client.Agent() if c.unsealed { agent.PassTTL(c.checkID(), "Vault Unsealed") } else { agent.FailTTL(c.checkID(), "Vault Sealed") } } // checkID returns the ID used for a Consul Check. Assume at least a read // lock is held. func (c *ConsulBackend) checkID() string { return "vault-sealed-check" } // serviceID returns the Vault ServiceID for use in Consul. Assume at least // a read lock is held. func (c *ConsulBackend) serviceID() string { return fmt.Sprintf("%s:%s:%d", c.serviceName, c.advertiseHost, c.advertisePort) } func (c *ConsulBackend) setAdvertiseAddr(addr string) (err error) { if addr == "" { return fmt.Errorf("advertise address must not be empty") } url, err := url.Parse(addr) if err != nil { return errwrap.Wrapf(fmt.Sprintf(`failed to parse advertise URL "%v": {{err}}`, addr), err) } var portStr string c.advertiseHost, portStr, err = net.SplitHostPort(url.Host) if err != nil { if url.Scheme == "http" { portStr = "80" } else if url.Scheme == "https" { portStr = "443" } else if url.Scheme == "unix" { portStr = "-1" c.advertiseHost = url.Path } else { return errwrap.Wrapf(fmt.Sprintf(`failed to find a host:port in advertise address "%v": {{err}}`, url.Host), err) } } c.advertisePort, err = strconv.ParseInt(portStr, 10, 0) if err != nil || c.advertisePort < -1 || c.advertisePort > 65535 { return errwrap.Wrapf(fmt.Sprintf(`failed to parse valid port "%v": {{err}}`, portStr), err) } return nil } func setupTLSConfig(conf map[string]string) (*tls.Config, error) { serverName := strings.Split(conf["address"], ":") insecureSkipVerify := false if _, ok := conf["tls_skip_verify"]; ok { insecureSkipVerify = true } tlsClientConfig := &tls.Config{ InsecureSkipVerify: insecureSkipVerify, ServerName: serverName[0], } _, okCert := conf["tls_cert_file"] _, okKey := conf["tls_key_file"] if okCert && okKey { tlsCert, err := tls.LoadX509KeyPair(conf["tls_cert_file"], conf["tls_key_file"]) if err != nil { return nil, fmt.Errorf("client tls setup failed: %v", err) } tlsClientConfig.Certificates = []tls.Certificate{tlsCert} } if tlsCaFile, ok := conf["tls_ca_file"]; ok { caPool := x509.NewCertPool() data, err := ioutil.ReadFile(tlsCaFile) if err != nil { return nil, fmt.Errorf("failed to read CA file: %v", err) } if !caPool.AppendCertsFromPEM(data) { return nil, fmt.Errorf("failed to parse CA certificate") } tlsClientConfig.RootCAs = caPool } return tlsClientConfig, nil } // Put is used to insert or update an entry func (c *ConsulBackend) Put(entry *Entry) error { defer metrics.MeasureSince([]string{"consul", "put"}, time.Now()) pair := &api.KVPair{ Key: c.path + entry.Key, Value: entry.Value, } c.permitPool.Acquire() defer c.permitPool.Release() _, err := c.kv.Put(pair, nil) return err } // Get is used to fetch an entry func (c *ConsulBackend) Get(key string) (*Entry, error) { defer metrics.MeasureSince([]string{"consul", "get"}, time.Now()) c.permitPool.Acquire() defer c.permitPool.Release() pair, _, err := c.kv.Get(c.path+key, nil) if err != nil { return nil, err } if pair == nil { return nil, nil } ent := &Entry{ Key: key, Value: pair.Value, } return ent, nil } // Delete is used to permanently delete an entry func (c *ConsulBackend) Delete(key string) error { defer metrics.MeasureSince([]string{"consul", "delete"}, time.Now()) c.permitPool.Acquire() defer c.permitPool.Release() _, err := c.kv.Delete(c.path+key, nil) return err } // List is used to list all the keys under a given // prefix, up to the next prefix. func (c *ConsulBackend) List(prefix string) ([]string, error) { defer metrics.MeasureSince([]string{"consul", "list"}, time.Now()) scan := c.path + prefix // The TrimPrefix call below will not work correctly if we have "//" at the // end. This can happen in cases where you are e.g. listing the root of a // prefix in a logical backend via "/" instead of "" if strings.HasSuffix(scan, "//") { scan = scan[:len(scan)-1] } c.permitPool.Acquire() defer c.permitPool.Release() out, _, err := c.kv.Keys(scan, "/", nil) for idx, val := range out { out[idx] = strings.TrimPrefix(val, scan) } return out, err } // Lock is used for mutual exclusion based on the given key. func (c *ConsulBackend) LockWith(key, value string) (Lock, error) { // Create the lock opts := &api.LockOptions{ Key: c.path + key, Value: []byte(value), SessionName: "Vault Lock", MonitorRetries: 5, } lock, err := c.client.LockOpts(opts) if err != nil { return nil, fmt.Errorf("failed to create lock: %v", err) } cl := &ConsulLock{ client: c.client, key: c.path + key, lock: lock, } return cl, nil } // DetectHostAddr is used to detect the host address by asking the Consul agent func (c *ConsulBackend) DetectHostAddr() (string, error) { agent := c.client.Agent() self, err := agent.Self() if err != nil { return "", err } addr, ok := self["Member"]["Addr"].(string) if !ok { return "", fmt.Errorf("Unable to convert an address to string") } return addr, nil } // ConsulLock is used to provide the Lock interface backed by Consul type ConsulLock struct { client *api.Client key string lock *api.Lock } func (c *ConsulLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { return c.lock.Lock(stopCh) } func (c *ConsulLock) Unlock() error { return c.lock.Unlock() } func (c *ConsulLock) Value() (bool, string, error) { kv := c.client.KV() pair, _, err := kv.Get(c.key, nil) if err != nil { return false, "", err } if pair == nil { return false, "", nil } held := pair.Session != "" value := string(pair.Value) return held, value, nil } Fix logger output Pointed out by: ryanuber package physical import ( "fmt" "io/ioutil" "log" "net" "net/url" "strconv" "strings" "sync" "sync/atomic" "time" "crypto/tls" "crypto/x509" "github.com/armon/go-metrics" "github.com/hashicorp/consul/api" "github.com/hashicorp/consul/lib" "github.com/hashicorp/errwrap" "github.com/hashicorp/go-cleanhttp" ) const ( // checkJitterFactor specifies the jitter factor used to stagger checks checkJitterFactor = 16 // checkMinBuffer specifies provides a guarantee that a check will not // be executed too close to the TTL check timeout checkMinBuffer = 100 * time.Millisecond // defaultCheckTimeout changes the timeout of TTL checks defaultCheckTimeout = 5 * time.Second // defaultCheckInterval specifies the default interval used to send // checks defaultCheckInterval = 4 * time.Second // defaultServiceName is the default Consul service name used when // advertising a Vault instance. defaultServiceName = "vault" // registrationRetryInterval specifies the retry duration to use when // a registration to the Consul agent fails. registrationRetryInterval = 1 * time.Second ) // ConsulBackend is a physical backend that stores data at specific // prefix within Consul. It is used for most production situations as // it allows Vault to run on multiple machines in a highly-available manner. type ConsulBackend struct { path string logger *log.Logger client *api.Client kv *api.KV permitPool *PermitPool serviceLock sync.RWMutex service *api.AgentServiceRegistration sealedCheck *api.AgentCheckRegistration registrationLock int64 advertiseHost string advertisePort int64 consulClientConf *api.Config serviceName string running bool active bool unsealed bool disableRegistration bool checkTimeout time.Duration checkTimer *time.Timer } // newConsulBackend constructs a Consul backend using the given API client // and the prefix in the KV store. func newConsulBackend(conf map[string]string, logger *log.Logger) (Backend, error) { // Get the path in Consul path, ok := conf["path"] if !ok { path = "vault/" } // Ensure path is suffixed but not prefixed if !strings.HasSuffix(path, "/") { logger.Printf("[WARN]: consul: appending trailing forward slash to path") path += "/" } if strings.HasPrefix(path, "/") { logger.Printf("[WARN]: consul: trimming path of its forward slash") path = strings.TrimPrefix(path, "/") } // Allow admins to disable consul integration disableReg, ok := conf["disable_registration"] var disableRegistration bool if ok && disableReg != "" { b, err := strconv.ParseBool(disableReg) if err != nil { return nil, errwrap.Wrapf("failed parsing disable_registration parameter: {{err}}", err) } disableRegistration = b } // Get the service name to advertise in Consul service, ok := conf["service"] if !ok { service = defaultServiceName } checkTimeout := defaultCheckTimeout checkTimeoutStr, ok := conf["check_timeout"] if ok { d, err := time.ParseDuration(checkTimeoutStr) if err != nil { return nil, err } min, _ := lib.DurationMinusBufferDomain(d, checkMinBuffer, checkJitterFactor) if min < checkMinBuffer { return nil, fmt.Errorf("Consul check_timeout must be greater than %v", min) } checkTimeout = d } // Configure the client consulConf := api.DefaultConfig() if addr, ok := conf["address"]; ok { consulConf.Address = addr } if scheme, ok := conf["scheme"]; ok { consulConf.Scheme = scheme } if token, ok := conf["token"]; ok { consulConf.Token = token } if consulConf.Scheme == "https" { tlsClientConfig, err := setupTLSConfig(conf) if err != nil { return nil, err } transport := cleanhttp.DefaultPooledTransport() transport.MaxIdleConnsPerHost = 4 transport.TLSClientConfig = tlsClientConfig consulConf.HttpClient.Transport = transport } client, err := api.NewClient(consulConf) if err != nil { return nil, errwrap.Wrapf("client setup failed: {{err}}", err) } maxParStr, ok := conf["max_parallel"] var maxParInt int if ok { maxParInt, err = strconv.Atoi(maxParStr) if err != nil { return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) } logger.Printf("[DEBUG]: consul: max_parallel set to %d", maxParInt) } // Setup the backend c := &ConsulBackend{ path: path, logger: logger, client: client, kv: client.KV(), permitPool: NewPermitPool(maxParInt), consulClientConf: consulConf, serviceName: service, checkTimeout: checkTimeout, checkTimer: time.NewTimer(checkTimeout), disableRegistration: disableRegistration, } return c, nil } // serviceTags returns all of the relevant tags for Consul. func serviceTags(active bool) []string { activeTag := "standby" if active { activeTag = "active" } return []string{activeTag} } func (c *ConsulBackend) AdvertiseActive(active bool) error { c.serviceLock.Lock() defer c.serviceLock.Unlock() // Vault is still bootstrapping if c.service == nil { return nil } // Save a cached copy of the active state: no way to query Core c.active = active // Ensure serial registration to the Consul agent. Allow for // concurrent calls to update active status while a single task // attempts, until successful, to update the Consul Agent. if !c.disableRegistration && atomic.CompareAndSwapInt64(&c.registrationLock, 0, 1) { defer atomic.CompareAndSwapInt64(&c.registrationLock, 1, 0) // Retry agent registration until successful for { c.service.Tags = serviceTags(c.active) agent := c.client.Agent() err := agent.ServiceRegister(c.service) if err == nil { // Success return nil } c.logger.Printf("[WARN] consul: service registration failed: %v", err) c.serviceLock.Unlock() time.Sleep(registrationRetryInterval) c.serviceLock.Lock() if !c.running { // Shutting down return err } } } // Successful concurrent update to active state return nil } func (c *ConsulBackend) AdvertiseSealed(sealed bool) error { c.serviceLock.Lock() defer c.serviceLock.Unlock() c.unsealed = !sealed // Vault is still bootstrapping if c.service == nil { return nil } if !c.disableRegistration { // Push a TTL check immediately to update the state c.runCheck() } return nil } func (c *ConsulBackend) RunServiceDiscovery(shutdownCh ShutdownChannel, advertiseAddr string) (err error) { c.serviceLock.Lock() defer c.serviceLock.Unlock() if c.disableRegistration { return nil } if err := c.setAdvertiseAddr(advertiseAddr); err != nil { return err } serviceID := c.serviceID() c.service = &api.AgentServiceRegistration{ ID: serviceID, Name: c.serviceName, Tags: serviceTags(c.active), Port: int(c.advertisePort), Address: c.advertiseHost, EnableTagOverride: false, } checkStatus := api.HealthCritical if c.unsealed { checkStatus = api.HealthPassing } c.sealedCheck = &api.AgentCheckRegistration{ ID: c.checkID(), Name: "Vault Sealed Status", Notes: "Vault service is healthy when Vault is in an unsealed status and can become an active Vault server", ServiceID: serviceID, AgentServiceCheck: api.AgentServiceCheck{ TTL: c.checkTimeout.String(), Status: checkStatus, }, } agent := c.client.Agent() if err := agent.ServiceRegister(c.service); err != nil { return errwrap.Wrapf("service registration failed: {{err}}", err) } if err := agent.CheckRegister(c.sealedCheck); err != nil { return errwrap.Wrapf("service registration check registration failed: {{err}}", err) } go c.checkRunner(shutdownCh) c.running = true // Deregister upon shutdown go func() { shutdown: for { select { case <-shutdownCh: c.logger.Printf("[INFO]: consul: Shutting down consul backend") break shutdown } } if err := agent.ServiceDeregister(serviceID); err != nil { c.logger.Printf("[WARN]: consul: service deregistration failed: %v", err) } c.running = false }() return nil } // checkRunner periodically runs TTL checks func (c *ConsulBackend) checkRunner(shutdownCh ShutdownChannel) { defer c.checkTimer.Stop() for { select { case <-c.checkTimer.C: go func() { c.serviceLock.Lock() defer c.serviceLock.Unlock() c.runCheck() }() case <-shutdownCh: return } } } // runCheck immediately pushes a TTL check. Assumes c.serviceLock is held // exclusively. func (c *ConsulBackend) runCheck() { // Reset timer before calling run check in order to not slide the // window of the next check. c.checkTimer.Reset(lib.DurationMinusBuffer(c.checkTimeout, checkMinBuffer, checkJitterFactor)) // Run a TTL check agent := c.client.Agent() if c.unsealed { agent.PassTTL(c.checkID(), "Vault Unsealed") } else { agent.FailTTL(c.checkID(), "Vault Sealed") } } // checkID returns the ID used for a Consul Check. Assume at least a read // lock is held. func (c *ConsulBackend) checkID() string { return "vault-sealed-check" } // serviceID returns the Vault ServiceID for use in Consul. Assume at least // a read lock is held. func (c *ConsulBackend) serviceID() string { return fmt.Sprintf("%s:%s:%d", c.serviceName, c.advertiseHost, c.advertisePort) } func (c *ConsulBackend) setAdvertiseAddr(addr string) (err error) { if addr == "" { return fmt.Errorf("advertise address must not be empty") } url, err := url.Parse(addr) if err != nil { return errwrap.Wrapf(fmt.Sprintf(`failed to parse advertise URL "%v": {{err}}`, addr), err) } var portStr string c.advertiseHost, portStr, err = net.SplitHostPort(url.Host) if err != nil { if url.Scheme == "http" { portStr = "80" } else if url.Scheme == "https" { portStr = "443" } else if url.Scheme == "unix" { portStr = "-1" c.advertiseHost = url.Path } else { return errwrap.Wrapf(fmt.Sprintf(`failed to find a host:port in advertise address "%v": {{err}}`, url.Host), err) } } c.advertisePort, err = strconv.ParseInt(portStr, 10, 0) if err != nil || c.advertisePort < -1 || c.advertisePort > 65535 { return errwrap.Wrapf(fmt.Sprintf(`failed to parse valid port "%v": {{err}}`, portStr), err) } return nil } func setupTLSConfig(conf map[string]string) (*tls.Config, error) { serverName := strings.Split(conf["address"], ":") insecureSkipVerify := false if _, ok := conf["tls_skip_verify"]; ok { insecureSkipVerify = true } tlsClientConfig := &tls.Config{ InsecureSkipVerify: insecureSkipVerify, ServerName: serverName[0], } _, okCert := conf["tls_cert_file"] _, okKey := conf["tls_key_file"] if okCert && okKey { tlsCert, err := tls.LoadX509KeyPair(conf["tls_cert_file"], conf["tls_key_file"]) if err != nil { return nil, fmt.Errorf("client tls setup failed: %v", err) } tlsClientConfig.Certificates = []tls.Certificate{tlsCert} } if tlsCaFile, ok := conf["tls_ca_file"]; ok { caPool := x509.NewCertPool() data, err := ioutil.ReadFile(tlsCaFile) if err != nil { return nil, fmt.Errorf("failed to read CA file: %v", err) } if !caPool.AppendCertsFromPEM(data) { return nil, fmt.Errorf("failed to parse CA certificate") } tlsClientConfig.RootCAs = caPool } return tlsClientConfig, nil } // Put is used to insert or update an entry func (c *ConsulBackend) Put(entry *Entry) error { defer metrics.MeasureSince([]string{"consul", "put"}, time.Now()) pair := &api.KVPair{ Key: c.path + entry.Key, Value: entry.Value, } c.permitPool.Acquire() defer c.permitPool.Release() _, err := c.kv.Put(pair, nil) return err } // Get is used to fetch an entry func (c *ConsulBackend) Get(key string) (*Entry, error) { defer metrics.MeasureSince([]string{"consul", "get"}, time.Now()) c.permitPool.Acquire() defer c.permitPool.Release() pair, _, err := c.kv.Get(c.path+key, nil) if err != nil { return nil, err } if pair == nil { return nil, nil } ent := &Entry{ Key: key, Value: pair.Value, } return ent, nil } // Delete is used to permanently delete an entry func (c *ConsulBackend) Delete(key string) error { defer metrics.MeasureSince([]string{"consul", "delete"}, time.Now()) c.permitPool.Acquire() defer c.permitPool.Release() _, err := c.kv.Delete(c.path+key, nil) return err } // List is used to list all the keys under a given // prefix, up to the next prefix. func (c *ConsulBackend) List(prefix string) ([]string, error) { defer metrics.MeasureSince([]string{"consul", "list"}, time.Now()) scan := c.path + prefix // The TrimPrefix call below will not work correctly if we have "//" at the // end. This can happen in cases where you are e.g. listing the root of a // prefix in a logical backend via "/" instead of "" if strings.HasSuffix(scan, "//") { scan = scan[:len(scan)-1] } c.permitPool.Acquire() defer c.permitPool.Release() out, _, err := c.kv.Keys(scan, "/", nil) for idx, val := range out { out[idx] = strings.TrimPrefix(val, scan) } return out, err } // Lock is used for mutual exclusion based on the given key. func (c *ConsulBackend) LockWith(key, value string) (Lock, error) { // Create the lock opts := &api.LockOptions{ Key: c.path + key, Value: []byte(value), SessionName: "Vault Lock", MonitorRetries: 5, } lock, err := c.client.LockOpts(opts) if err != nil { return nil, fmt.Errorf("failed to create lock: %v", err) } cl := &ConsulLock{ client: c.client, key: c.path + key, lock: lock, } return cl, nil } // DetectHostAddr is used to detect the host address by asking the Consul agent func (c *ConsulBackend) DetectHostAddr() (string, error) { agent := c.client.Agent() self, err := agent.Self() if err != nil { return "", err } addr, ok := self["Member"]["Addr"].(string) if !ok { return "", fmt.Errorf("Unable to convert an address to string") } return addr, nil } // ConsulLock is used to provide the Lock interface backed by Consul type ConsulLock struct { client *api.Client key string lock *api.Lock } func (c *ConsulLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { return c.lock.Lock(stopCh) } func (c *ConsulLock) Unlock() error { return c.lock.Unlock() } func (c *ConsulLock) Value() (bool, string, error) { kv := c.client.KV() pair, _, err := kv.Get(c.key, nil) if err != nil { return false, "", err } if pair == nil { return false, "", nil } held := pair.Session != "" value := string(pair.Value) return held, value, nil }
/* _ _ *__ _____ __ ___ ___ __ _| |_ ___ *\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ * \ V V / __/ (_| |\ V /| | (_| | || __/ * \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| * * Copyright © 2016 - 2019 Weaviate. All rights reserved. * LICENSE: https://github.com/creativesoftwarefdn/weaviate/blob/develop/LICENSE.md * DESIGN & CONCEPT: Bob van Luijt (@bobvanluijt) * CONTACT: hello@creativesoftwarefdn.org */ package janusgraph import ( "context" "fmt" "github.com/creativesoftwarefdn/weaviate/database/connectors/janusgraph/state" "github.com/creativesoftwarefdn/weaviate/database/schema" "github.com/creativesoftwarefdn/weaviate/database/schema/kind" "github.com/creativesoftwarefdn/weaviate/gremlin" "github.com/creativesoftwarefdn/weaviate/gremlin/gremlin_schema_query" "github.com/creativesoftwarefdn/weaviate/models" log "github.com/sirupsen/logrus" ) // Called during initialization of the connector. func (j *Janusgraph) ensureBasicSchema(ctx context.Context) error { // No basic schema has been created yet. if j.state.Version == 0 { query := gremlin_schema_query.New() // Enforce UUID's to be unique across Janus query.MakePropertyKey(PROP_UUID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.AddGraphCompositeIndex(INDEX_BY_UUID, []string{PROP_UUID}, true) // For all classes query.MakePropertyKey(PROP_KIND, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_CLASS_ID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_ID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.AddGraphCompositeIndex(INDEX_BY_KIND_AND_CLASS, []string{PROP_KIND, PROP_CLASS_ID}, false) query.MakePropertyKey(PROP_AT_CONTEXT, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_CREATION_TIME_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_LAST_UPDATE_TIME_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_CREF, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_LOCATION, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_TYPE, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakeVertexLabel(KEY_VERTEX_LABEL) // Keys query.MakeEdgeLabel(KEY_EDGE_LABEL, gremlin_schema_query.MULTIPLICITY_MANY2ONE) query.MakeEdgeLabel(KEY_PARENT_LABEL, gremlin_schema_query.MULTIPLICITY_MANY2ONE) query.MakePropertyKey(PROP_KEY_IS_ROOT, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_DELETE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EXECUTE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_READ, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_WRITE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EMAIL, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_IP_ORIGIN, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EXPIRES_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_TOKEN, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.Commit() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("Could not initialize the basic Janus schema.") } // TODO gh-613: await answer from janus consultants; it's not avaible in our janus setup. //query = gremlin_schema_query.AwaitGraphIndicesAvailable([]string{INDEX_BY_UUID, INDEX_BY_KIND_AND_CLASS}) //_, err = j.client.Execute(query) //if err != nil { // return fmt.Errorf("Could not initialize the basic Janus schema; could not await until the base indices were available.") //} // Set initial version in state. j.state.Version = 1 j.state.LastId = 0 j.state.ClassMap = make(map[schema.ClassName]state.MappedClassName) j.state.PropertyMap = make(map[schema.ClassName]map[schema.PropertyName]state.MappedPropertyName) j.UpdateStateInStateManager(ctx) } return nil } // Add a class to the Thing or Action schema, depending on the kind parameter. func (j *Janusgraph) AddClass(ctx context.Context, kind kind.Kind, class *models.SemanticSchemaClass) error { log.Debugf("Adding class '%v' in JanusGraph", class.Class) // Extra sanity check sanitizedClassName := schema.AssertValidClassName(class.Class) vertexLabel := j.state.AddMappedClassName(sanitizedClassName) query := gremlin_schema_query.New() query.MakeVertexLabel(string(vertexLabel)) for _, prop := range class.Properties { sanitziedPropertyName := schema.AssertValidPropertyName(prop.Name) janusPropertyName := j.state.AddMappedPropertyName(sanitizedClassName, sanitziedPropertyName) // Determine the type of the property propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } if propertyDataType.IsPrimitive() { query.MakePropertyKey(string(janusPropertyName), weaviatePrimitivePropTypeToJanusPropType(schema.DataType(prop.AtDataType[0])), gremlin_schema_query.CARDINALITY_SINGLE) } else { // In principle, we could use a Many2One edge for SingleRefs query.MakeEdgeLabel(string(janusPropertyName), gremlin_schema_query.MULTIPLICITY_MULTI) } } query.Commit() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("could not create vertex/property types in JanusGraph") } // Update mapping j.UpdateStateInStateManager(ctx) return nil } // Drop a class from the schema. func (j *Janusgraph) DropClass(ctx context.Context, kind kind.Kind, name string) error { log.Debugf("Removing class '%v' in JanusGraph", name) sanitizedClassName := schema.AssertValidClassName(name) vertexLabel := j.state.GetMappedClassName(sanitizedClassName) query := gremlin.G.V().HasLabel(string(vertexLabel)).HasString(PROP_CLASS_ID, string(vertexLabel)).Drop() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("could not remove all data of the dropped class in JanusGraph") } // Update mapping j.state.RemoveMappedClassName(sanitizedClassName) j.UpdateStateInStateManager(ctx) return nil } func (j *Janusgraph) UpdateClass(ctx context.Context, kind kind.Kind, className string, newClassName *string, newKeywords *models.SemanticSchemaKeywords) error { if newClassName != nil { oldName := schema.AssertValidClassName(className) newName := schema.AssertValidClassName(*newClassName) j.state.RenameClass(oldName, newName) j.UpdateStateInStateManager(ctx) } return nil } func (j *Janusgraph) AddProperty(ctx context.Context, kind kind.Kind, className string, prop *models.SemanticSchemaClassProperty) error { // Extra sanity check sanitizedClassName := schema.AssertValidClassName(className) query := gremlin_schema_query.New() sanitziedPropertyName := schema.AssertValidPropertyName(prop.Name) janusPropertyName := j.state.AddMappedPropertyName(sanitizedClassName, sanitziedPropertyName) // Determine the type of the property propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } if propertyDataType.IsPrimitive() { query.MakePropertyKey(string(janusPropertyName), weaviatePrimitivePropTypeToJanusPropType(schema.DataType(prop.AtDataType[0])), gremlin_schema_query.CARDINALITY_SINGLE) } else { // In principle, we could use a Many2One edge for SingleRefs query.MakeEdgeLabel(string(janusPropertyName), gremlin_schema_query.MULTIPLICITY_MULTI) } query.Commit() _, err = j.client.Execute(query) if err != nil { return fmt.Errorf("could not create property type in JanusGraph") } // Update mapping j.UpdateStateInStateManager(ctx) return nil } func (j *Janusgraph) UpdateProperty(ctx context.Context, kind kind.Kind, className string, propName string, newName *string, newKeywords *models.SemanticSchemaKeywords) error { if newName != nil { sanitizedClassName := schema.AssertValidClassName(className) oldName := schema.AssertValidPropertyName(propName) newName := schema.AssertValidPropertyName(*newName) j.state.RenameProperty(sanitizedClassName, oldName, newName) j.UpdateStateInStateManager(ctx) } return nil } func (j *Janusgraph) UpdatePropertyAddDataType(ctx context.Context, kind kind.Kind, className string, propName string, newDataType string) error { return nil } func (j *Janusgraph) DropProperty(ctx context.Context, kind kind.Kind, className string, propName string) error { sanitizedClassName := schema.AssertValidClassName(className) sanitizedPropName := schema.AssertValidPropertyName(propName) vertexLabel := j.state.GetMappedClassName(sanitizedClassName) mappedPropertyName := j.state.GetMappedPropertyName(sanitizedClassName, sanitizedPropName) err, prop := j.schema.GetProperty(kind, sanitizedClassName, sanitizedPropName) if err != nil { panic("could not get property") } propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } var query gremlin.Gremlin if propertyDataType.IsPrimitive() { query = gremlin.G.V(). HasLabel(string(vertexLabel)). HasString(PROP_CLASS_ID, string(vertexLabel)). Properties([]string{string(mappedPropertyName)}). Drop() } else { query = gremlin.G.E(). HasLabel(string(mappedPropertyName)). HasString(PROP_REF_ID, string(mappedPropertyName)). Drop() } _, err = j.client.Execute(query) if err != nil { return fmt.Errorf("could not remove all data of the dropped class in JanusGraph") } j.state.RemoveMappedPropertyName(sanitizedClassName, sanitizedPropName) j.UpdateStateInStateManager(ctx) return nil } ///////////////////////////////// // Helper functions //// TODO: add to Gremlin DSL //func graphOpenManagement(s *strings.Builder) { // s.WriteString("mgmt = graph.openManagement()\n") //} // //func graphCommit(s *strings.Builder) { // s.WriteString("mgmt.commit()\n") //} // //func graphAddClass(s *strings.Builder, name MappedClassName) { // s.WriteString(fmt.Sprintf("mgmt.makeVertexLabel(\"%s\").make()\n", name)) //} // //func graphAddProperty(s *strings.Builder, name MappedPropertyName, type_ schema.DataType) { // propDataType := getJanusDataType(type_) // s.WriteString(fmt.Sprintf("mgmt.makePropertyKey(\"%s\").cardinality(Cardinality.SINGLE).dataType(%s.class).make()\n", name, propDataType)) //} // //func graphDropClass(s *strings.Builder, name MappedClassName) { // // Simply all vertices of this class. // //g.V().has("object", "classId", name).drop() //} // //func graphDropProperty(s *strings.Builder, name MappedPropertyName) { // //g.V().has("object", name).properties(name).drop() // //s.WriteString(fmt.Sprintf("mgmt.getPropertyKey(\"%s\").remove()\n", janusPropName)) //} // // Get Janus data type from a weaviate data type. // Panics if passed a wrong type. func weaviatePrimitivePropTypeToJanusPropType(type_ schema.DataType) gremlin_schema_query.DataType { switch type_ { case schema.DataTypeString: return gremlin_schema_query.DATATYPE_STRING case schema.DataTypeText: return gremlin_schema_query.DATATYPE_STRING case schema.DataTypeInt: return gremlin_schema_query.DATATYPE_LONG case schema.DataTypeNumber: return gremlin_schema_query.DATATYPE_DOUBLE case schema.DataTypeBoolean: return gremlin_schema_query.DATATYPE_BOOLEAN case schema.DataTypeDate: return gremlin_schema_query.DATATYPE_STRING default: panic(fmt.Sprintf("unsupported data type '%v'", type_)) } } gh-713: improve error reporting when schema initialization fails /* _ _ *__ _____ __ ___ ___ __ _| |_ ___ *\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ * \ V V / __/ (_| |\ V /| | (_| | || __/ * \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| * * Copyright © 2016 - 2019 Weaviate. All rights reserved. * LICENSE: https://github.com/creativesoftwarefdn/weaviate/blob/develop/LICENSE.md * DESIGN & CONCEPT: Bob van Luijt (@bobvanluijt) * CONTACT: hello@creativesoftwarefdn.org */ package janusgraph import ( "context" "fmt" "github.com/creativesoftwarefdn/weaviate/database/connectors/janusgraph/state" "github.com/creativesoftwarefdn/weaviate/database/schema" "github.com/creativesoftwarefdn/weaviate/database/schema/kind" "github.com/creativesoftwarefdn/weaviate/gremlin" "github.com/creativesoftwarefdn/weaviate/gremlin/gremlin_schema_query" "github.com/creativesoftwarefdn/weaviate/models" "github.com/davecgh/go-spew/spew" log "github.com/sirupsen/logrus" ) // Called during initialization of the connector. func (j *Janusgraph) ensureBasicSchema(ctx context.Context) error { // No basic schema has been created yet. if j.state.Version == 0 { query := gremlin_schema_query.New() // Enforce UUID's to be unique across Janus query.MakePropertyKey(PROP_UUID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.AddGraphCompositeIndex(INDEX_BY_UUID, []string{PROP_UUID}, true) // For all classes query.MakePropertyKey(PROP_KIND, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_CLASS_ID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_ID, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.AddGraphCompositeIndex(INDEX_BY_KIND_AND_CLASS, []string{PROP_KIND, PROP_CLASS_ID}, false) query.MakePropertyKey(PROP_AT_CONTEXT, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_CREATION_TIME_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_LAST_UPDATE_TIME_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_CREF, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_LOCATION, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_REF_EDGE_TYPE, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakeVertexLabel(KEY_VERTEX_LABEL) // Keys query.MakeEdgeLabel(KEY_EDGE_LABEL, gremlin_schema_query.MULTIPLICITY_MANY2ONE) query.MakeEdgeLabel(KEY_PARENT_LABEL, gremlin_schema_query.MULTIPLICITY_MANY2ONE) query.MakePropertyKey(PROP_KEY_IS_ROOT, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_DELETE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EXECUTE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_READ, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_WRITE, gremlin_schema_query.DATATYPE_BOOLEAN, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EMAIL, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_IP_ORIGIN, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_EXPIRES_UNIX, gremlin_schema_query.DATATYPE_LONG, gremlin_schema_query.CARDINALITY_SINGLE) query.MakePropertyKey(PROP_KEY_TOKEN, gremlin_schema_query.DATATYPE_STRING, gremlin_schema_query.CARDINALITY_SINGLE) query.Commit() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("could not initialize the basic Janus schema: %s", spew.Sdump(err)) } // TODO gh-613: await answer from janus consultants; it's not avaible in our janus setup. //query = gremlin_schema_query.AwaitGraphIndicesAvailable([]string{INDEX_BY_UUID, INDEX_BY_KIND_AND_CLASS}) //_, err = j.client.Execute(query) //if err != nil { // return fmt.Errorf("Could not initialize the basic Janus schema; could not await until the base indices were available.") //} // Set initial version in state. j.state.Version = 1 j.state.LastId = 0 j.state.ClassMap = make(map[schema.ClassName]state.MappedClassName) j.state.PropertyMap = make(map[schema.ClassName]map[schema.PropertyName]state.MappedPropertyName) j.UpdateStateInStateManager(ctx) } return nil } // Add a class to the Thing or Action schema, depending on the kind parameter. func (j *Janusgraph) AddClass(ctx context.Context, kind kind.Kind, class *models.SemanticSchemaClass) error { log.Debugf("Adding class '%v' in JanusGraph", class.Class) // Extra sanity check sanitizedClassName := schema.AssertValidClassName(class.Class) vertexLabel := j.state.AddMappedClassName(sanitizedClassName) query := gremlin_schema_query.New() query.MakeVertexLabel(string(vertexLabel)) for _, prop := range class.Properties { sanitziedPropertyName := schema.AssertValidPropertyName(prop.Name) janusPropertyName := j.state.AddMappedPropertyName(sanitizedClassName, sanitziedPropertyName) // Determine the type of the property propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } if propertyDataType.IsPrimitive() { query.MakePropertyKey(string(janusPropertyName), weaviatePrimitivePropTypeToJanusPropType(schema.DataType(prop.AtDataType[0])), gremlin_schema_query.CARDINALITY_SINGLE) } else { // In principle, we could use a Many2One edge for SingleRefs query.MakeEdgeLabel(string(janusPropertyName), gremlin_schema_query.MULTIPLICITY_MULTI) } } query.Commit() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("could not create vertex/property types in JanusGraph") } // Update mapping j.UpdateStateInStateManager(ctx) return nil } // Drop a class from the schema. func (j *Janusgraph) DropClass(ctx context.Context, kind kind.Kind, name string) error { log.Debugf("Removing class '%v' in JanusGraph", name) sanitizedClassName := schema.AssertValidClassName(name) vertexLabel := j.state.GetMappedClassName(sanitizedClassName) query := gremlin.G.V().HasLabel(string(vertexLabel)).HasString(PROP_CLASS_ID, string(vertexLabel)).Drop() _, err := j.client.Execute(query) if err != nil { return fmt.Errorf("could not remove all data of the dropped class in JanusGraph") } // Update mapping j.state.RemoveMappedClassName(sanitizedClassName) j.UpdateStateInStateManager(ctx) return nil } func (j *Janusgraph) UpdateClass(ctx context.Context, kind kind.Kind, className string, newClassName *string, newKeywords *models.SemanticSchemaKeywords) error { if newClassName != nil { oldName := schema.AssertValidClassName(className) newName := schema.AssertValidClassName(*newClassName) j.state.RenameClass(oldName, newName) j.UpdateStateInStateManager(ctx) } return nil } func (j *Janusgraph) AddProperty(ctx context.Context, kind kind.Kind, className string, prop *models.SemanticSchemaClassProperty) error { // Extra sanity check sanitizedClassName := schema.AssertValidClassName(className) query := gremlin_schema_query.New() sanitziedPropertyName := schema.AssertValidPropertyName(prop.Name) janusPropertyName := j.state.AddMappedPropertyName(sanitizedClassName, sanitziedPropertyName) // Determine the type of the property propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } if propertyDataType.IsPrimitive() { query.MakePropertyKey(string(janusPropertyName), weaviatePrimitivePropTypeToJanusPropType(schema.DataType(prop.AtDataType[0])), gremlin_schema_query.CARDINALITY_SINGLE) } else { // In principle, we could use a Many2One edge for SingleRefs query.MakeEdgeLabel(string(janusPropertyName), gremlin_schema_query.MULTIPLICITY_MULTI) } query.Commit() _, err = j.client.Execute(query) if err != nil { return fmt.Errorf("could not create property type in JanusGraph") } // Update mapping j.UpdateStateInStateManager(ctx) return nil } func (j *Janusgraph) UpdateProperty(ctx context.Context, kind kind.Kind, className string, propName string, newName *string, newKeywords *models.SemanticSchemaKeywords) error { if newName != nil { sanitizedClassName := schema.AssertValidClassName(className) oldName := schema.AssertValidPropertyName(propName) newName := schema.AssertValidPropertyName(*newName) j.state.RenameProperty(sanitizedClassName, oldName, newName) j.UpdateStateInStateManager(ctx) } return nil } func (j *Janusgraph) UpdatePropertyAddDataType(ctx context.Context, kind kind.Kind, className string, propName string, newDataType string) error { return nil } func (j *Janusgraph) DropProperty(ctx context.Context, kind kind.Kind, className string, propName string) error { sanitizedClassName := schema.AssertValidClassName(className) sanitizedPropName := schema.AssertValidPropertyName(propName) vertexLabel := j.state.GetMappedClassName(sanitizedClassName) mappedPropertyName := j.state.GetMappedPropertyName(sanitizedClassName, sanitizedPropName) err, prop := j.schema.GetProperty(kind, sanitizedClassName, sanitizedPropName) if err != nil { panic("could not get property") } propertyDataType, err := j.schema.FindPropertyDataType(prop.AtDataType) if err != nil { // This must already be validated. panic(fmt.Sprintf("Data type fo property '%s' is invalid; %v", prop.Name, err)) } var query gremlin.Gremlin if propertyDataType.IsPrimitive() { query = gremlin.G.V(). HasLabel(string(vertexLabel)). HasString(PROP_CLASS_ID, string(vertexLabel)). Properties([]string{string(mappedPropertyName)}). Drop() } else { query = gremlin.G.E(). HasLabel(string(mappedPropertyName)). HasString(PROP_REF_ID, string(mappedPropertyName)). Drop() } _, err = j.client.Execute(query) if err != nil { return fmt.Errorf("could not remove all data of the dropped class in JanusGraph") } j.state.RemoveMappedPropertyName(sanitizedClassName, sanitizedPropName) j.UpdateStateInStateManager(ctx) return nil } ///////////////////////////////// // Helper functions //// TODO: add to Gremlin DSL //func graphOpenManagement(s *strings.Builder) { // s.WriteString("mgmt = graph.openManagement()\n") //} // //func graphCommit(s *strings.Builder) { // s.WriteString("mgmt.commit()\n") //} // //func graphAddClass(s *strings.Builder, name MappedClassName) { // s.WriteString(fmt.Sprintf("mgmt.makeVertexLabel(\"%s\").make()\n", name)) //} // //func graphAddProperty(s *strings.Builder, name MappedPropertyName, type_ schema.DataType) { // propDataType := getJanusDataType(type_) // s.WriteString(fmt.Sprintf("mgmt.makePropertyKey(\"%s\").cardinality(Cardinality.SINGLE).dataType(%s.class).make()\n", name, propDataType)) //} // //func graphDropClass(s *strings.Builder, name MappedClassName) { // // Simply all vertices of this class. // //g.V().has("object", "classId", name).drop() //} // //func graphDropProperty(s *strings.Builder, name MappedPropertyName) { // //g.V().has("object", name).properties(name).drop() // //s.WriteString(fmt.Sprintf("mgmt.getPropertyKey(\"%s\").remove()\n", janusPropName)) //} // // Get Janus data type from a weaviate data type. // Panics if passed a wrong type. func weaviatePrimitivePropTypeToJanusPropType(type_ schema.DataType) gremlin_schema_query.DataType { switch type_ { case schema.DataTypeString: return gremlin_schema_query.DATATYPE_STRING case schema.DataTypeText: return gremlin_schema_query.DATATYPE_STRING case schema.DataTypeInt: return gremlin_schema_query.DATATYPE_LONG case schema.DataTypeNumber: return gremlin_schema_query.DATATYPE_DOUBLE case schema.DataTypeBoolean: return gremlin_schema_query.DATATYPE_BOOLEAN case schema.DataTypeDate: return gremlin_schema_query.DATATYPE_STRING default: panic(fmt.Sprintf("unsupported data type '%v'", type_)) } }
// Package crypt provides wrappers for Fs and Object which implement encryption package crypt import ( "context" "fmt" "io" "path" "strings" "time" "github.com/pkg/errors" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/fs/accounting" "github.com/rclone/rclone/fs/config/configmap" "github.com/rclone/rclone/fs/config/configstruct" "github.com/rclone/rclone/fs/config/obscure" "github.com/rclone/rclone/fs/fspath" "github.com/rclone/rclone/fs/hash" ) // Globals // Register with Fs func init() { fs.Register(&fs.RegInfo{ Name: "crypt", Description: "Encrypt/Decrypt a remote", NewFs: NewFs, CommandHelp: commandHelp, Options: []fs.Option{{ Name: "remote", Help: "Remote to encrypt/decrypt.\nNormally should contain a ':' and a path, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).", Required: true, }, { Name: "filename_encryption", Help: "How to encrypt the filenames.", Default: "standard", Examples: []fs.OptionExample{ { Value: "standard", Help: "Encrypt the filenames see the docs for the details.", }, { Value: "obfuscate", Help: "Very simple filename obfuscation.", }, { Value: "off", Help: "Don't encrypt the file names. Adds a \".bin\" extension only.", }, }, }, { Name: "directory_name_encryption", Help: `Option to either encrypt directory names or leave them intact. NB If filename_encryption is "off" then this option will do nothing.`, Default: true, Examples: []fs.OptionExample{ { Value: "true", Help: "Encrypt directory names.", }, { Value: "false", Help: "Don't encrypt directory names, leave them intact.", }, }, }, { Name: "password", Help: "Password or pass phrase for encryption.", IsPassword: true, Required: true, }, { Name: "password2", Help: "Password or pass phrase for salt. Optional but recommended.\nShould be different to the previous password.", IsPassword: true, }, { Name: "server_side_across_configs", Default: false, Help: `Allow server side operations (eg copy) to work across different crypt configs. Normally this option is not what you want, but if you have two crypts pointing to the same backend you can use it. This can be used, for example, to change file name encryption type without re-uploading all the data. Just make two crypt backends pointing to two different directories with the single changed parameter and use rclone move to move the files between the crypt remotes.`, Advanced: true, }, { Name: "show_mapping", Help: `For all files listed show how the names encrypt. If this flag is set then for each file that the remote is asked to list, it will log (at level INFO) a line stating the decrypted file name and the encrypted file name. This is so you can work out which encrypted names are which decrypted names just in case you need to do something with the encrypted file names, or for debugging purposes.`, Default: false, Hide: fs.OptionHideConfigurator, Advanced: true, }}, }) } // newCipherForConfig constructs a Cipher for the given config name func newCipherForConfig(opt *Options) (*Cipher, error) { mode, err := NewNameEncryptionMode(opt.FilenameEncryption) if err != nil { return nil, err } if opt.Password == "" { return nil, errors.New("password not set in config file") } password, err := obscure.Reveal(opt.Password) if err != nil { return nil, errors.Wrap(err, "failed to decrypt password") } var salt string if opt.Password2 != "" { salt, err = obscure.Reveal(opt.Password2) if err != nil { return nil, errors.Wrap(err, "failed to decrypt password2") } } cipher, err := newCipher(mode, password, salt, opt.DirectoryNameEncryption) if err != nil { return nil, errors.Wrap(err, "failed to make cipher") } return cipher, nil } // NewCipher constructs a Cipher for the given config func NewCipher(m configmap.Mapper) (*Cipher, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } return newCipherForConfig(opt) } // NewFs constructs an Fs from the path, container:path func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } cipher, err := newCipherForConfig(opt) if err != nil { return nil, err } remote := opt.Remote if strings.HasPrefix(remote, name+":") { return nil, errors.New("can't point crypt remote at itself - check the value of the remote setting") } wInfo, wName, wPath, wConfig, err := fs.ConfigFs(remote) if err != nil { return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote) } // Make sure to remove trailing . reffering to the current dir if path.Base(rpath) == "." { rpath = strings.TrimSuffix(rpath, ".") } // Look for a file first remotePath := fspath.JoinRootPath(wPath, cipher.EncryptFileName(rpath)) wrappedFs, err := wInfo.NewFs(wName, remotePath, wConfig) // if that didn't produce a file, look for a directory if err != fs.ErrorIsFile { remotePath = fspath.JoinRootPath(wPath, cipher.EncryptDirName(rpath)) wrappedFs, err = wInfo.NewFs(wName, remotePath, wConfig) } if err != fs.ErrorIsFile && err != nil { return nil, errors.Wrapf(err, "failed to make remote %s:%q to wrap", wName, remotePath) } f := &Fs{ Fs: wrappedFs, name: name, root: rpath, opt: *opt, cipher: cipher, } // the features here are ones we could support, and they are // ANDed with the ones from wrappedFs f.features = (&fs.Features{ CaseInsensitive: cipher.NameEncryptionMode() == NameEncryptionOff, DuplicateFiles: true, ReadMimeType: false, // MimeTypes not supported with crypt WriteMimeType: false, BucketBased: true, CanHaveEmptyDirectories: true, SetTier: true, GetTier: true, ServerSideAcrossConfigs: opt.ServerSideAcrossConfigs, }).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs) return f, err } // Options defines the configuration for this backend type Options struct { Remote string `config:"remote"` FilenameEncryption string `config:"filename_encryption"` DirectoryNameEncryption bool `config:"directory_name_encryption"` Password string `config:"password"` Password2 string `config:"password2"` ServerSideAcrossConfigs bool `config:"server_side_across_configs"` ShowMapping bool `config:"show_mapping"` } // Fs represents a wrapped fs.Fs type Fs struct { fs.Fs wrapper fs.Fs name string root string opt Options features *fs.Features // optional features cipher *Cipher } // Name of the remote (as passed into NewFs) func (f *Fs) Name() string { return f.name } // Root of the remote (as passed into NewFs) func (f *Fs) Root() string { return f.root } // Features returns the optional features of this Fs func (f *Fs) Features() *fs.Features { return f.features } // String returns a description of the FS func (f *Fs) String() string { return fmt.Sprintf("Encrypted drive '%s:%s'", f.name, f.root) } // Encrypt an object file name to entries. func (f *Fs) add(entries *fs.DirEntries, obj fs.Object) { remote := obj.Remote() decryptedRemote, err := f.cipher.DecryptFileName(remote) if err != nil { fs.Debugf(remote, "Skipping undecryptable file name: %v", err) return } if f.opt.ShowMapping { fs.Logf(decryptedRemote, "Encrypts to %q", remote) } *entries = append(*entries, f.newObject(obj)) } // Encrypt a directory file name to entries. func (f *Fs) addDir(ctx context.Context, entries *fs.DirEntries, dir fs.Directory) { remote := dir.Remote() decryptedRemote, err := f.cipher.DecryptDirName(remote) if err != nil { fs.Debugf(remote, "Skipping undecryptable dir name: %v", err) return } if f.opt.ShowMapping { fs.Logf(decryptedRemote, "Encrypts to %q", remote) } *entries = append(*entries, f.newDir(ctx, dir)) } // Encrypt some directory entries. This alters entries returning it as newEntries. func (f *Fs) encryptEntries(ctx context.Context, entries fs.DirEntries) (newEntries fs.DirEntries, err error) { newEntries = entries[:0] // in place filter for _, entry := range entries { switch x := entry.(type) { case fs.Object: f.add(&newEntries, x) case fs.Directory: f.addDir(ctx, &newEntries, x) default: return nil, errors.Errorf("Unknown object type %T", entry) } } return newEntries, nil } // List the objects and directories in dir into entries. The // entries can be returned in any order but should be for a // complete directory. // // dir should be "" to list the root, and should not have // trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) { entries, err = f.Fs.List(ctx, f.cipher.EncryptDirName(dir)) if err != nil { return nil, err } return f.encryptEntries(ctx, entries) } // ListR lists the objects and directories of the Fs starting // from dir recursively into out. // // dir should be "" to start from the root, and should not // have trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. // // It should call callback for each tranche of entries read. // These need not be returned in any particular order. If // callback returns an error then the listing will stop // immediately. // // Don't implement this unless you have a more efficient way // of listing recursively that doing a directory traversal. func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) { return f.Fs.Features().ListR(ctx, f.cipher.EncryptDirName(dir), func(entries fs.DirEntries) error { newEntries, err := f.encryptEntries(ctx, entries) if err != nil { return err } return callback(newEntries) }) } // NewObject finds the Object at remote. func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) { o, err := f.Fs.NewObject(ctx, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(o), nil } type putFn func(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) // put implements Put or PutStream func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options []fs.OpenOption, put putFn) (fs.Object, error) { // Encrypt the data into wrappedIn wrappedIn, encrypter, err := f.cipher.encryptData(in) if err != nil { return nil, err } // Find a hash the destination supports to compute a hash of // the encrypted data ht := f.Fs.Hashes().GetOne() var hasher *hash.MultiHasher if ht != hash.None { hasher, err = hash.NewMultiHasherTypes(hash.NewHashSet(ht)) if err != nil { return nil, err } // unwrap the accounting var wrap accounting.WrapFn wrappedIn, wrap = accounting.UnWrap(wrappedIn) // add the hasher wrappedIn = io.TeeReader(wrappedIn, hasher) // wrap the accounting back on wrappedIn = wrap(wrappedIn) } // Transfer the data o, err := put(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce), options...) if err != nil { return nil, err } // Check the hashes of the encrypted data if we were comparing them if ht != hash.None && hasher != nil { srcHash := hasher.Sums()[ht] var dstHash string dstHash, err = o.Hash(ctx, ht) if err != nil { return nil, errors.Wrap(err, "failed to read destination hash") } if srcHash != "" && dstHash != "" && srcHash != dstHash { // remove object err = o.Remove(ctx) if err != nil { fs.Errorf(o, "Failed to remove corrupted object: %v", err) } return nil, errors.Errorf("corrupted on transfer: %v crypted hash differ %q vs %q", ht, srcHash, dstHash) } } return f.newObject(o), nil } // Put in to the remote path with the modTime given of the given size // // May create the object even if it returns an error - if so // will return the object and the error, otherwise will return // nil and the error func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.put(ctx, in, src, options, f.Fs.Put) } // PutStream uploads to the remote path with the modTime given of indeterminate size func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.put(ctx, in, src, options, f.Fs.Features().PutStream) } // Hashes returns the supported hash sets. func (f *Fs) Hashes() hash.Set { return hash.Set(hash.None) } // Mkdir makes the directory (container, bucket) // // Shouldn't return an error if it already exists func (f *Fs) Mkdir(ctx context.Context, dir string) error { return f.Fs.Mkdir(ctx, f.cipher.EncryptDirName(dir)) } // Rmdir removes the directory (container, bucket) if empty // // Return an error if it doesn't exist or isn't empty func (f *Fs) Rmdir(ctx context.Context, dir string) error { return f.Fs.Rmdir(ctx, f.cipher.EncryptDirName(dir)) } // Purge all files in the directory specified // // Implement this if you have a way of deleting all the files // quicker than just running Remove() on the result of List() // // Return an error if it doesn't exist func (f *Fs) Purge(ctx context.Context, dir string) error { do := f.Fs.Features().Purge if do == nil { return fs.ErrorCantPurge } return do(ctx, dir) } // Copy src to this remote using server side copy operations. // // This is stored with the remote path given // // It returns the destination Object and a possible error // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantCopy func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { do := f.Fs.Features().Copy if do == nil { return nil, fs.ErrorCantCopy } o, ok := src.(*Object) if !ok { return nil, fs.ErrorCantCopy } oResult, err := do(ctx, o.Object, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(oResult), nil } // Move src to this remote using server side move operations. // // This is stored with the remote path given // // It returns the destination Object and a possible error // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantMove func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { do := f.Fs.Features().Move if do == nil { return nil, fs.ErrorCantMove } o, ok := src.(*Object) if !ok { return nil, fs.ErrorCantMove } oResult, err := do(ctx, o.Object, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(oResult), nil } // DirMove moves src, srcRemote to this remote at dstRemote // using server side move operations. // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantDirMove // // If destination exists then return fs.ErrorDirExists func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error { do := f.Fs.Features().DirMove if do == nil { return fs.ErrorCantDirMove } srcFs, ok := src.(*Fs) if !ok { fs.Debugf(srcFs, "Can't move directory - not same remote type") return fs.ErrorCantDirMove } return do(ctx, srcFs.Fs, f.cipher.EncryptDirName(srcRemote), f.cipher.EncryptDirName(dstRemote)) } // PutUnchecked uploads the object // // This will create a duplicate if we upload a new file without // checking to see if there is one already - use Put() for that. func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { do := f.Fs.Features().PutUnchecked if do == nil { return nil, errors.New("can't PutUnchecked") } wrappedIn, encrypter, err := f.cipher.encryptData(in) if err != nil { return nil, err } o, err := do(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce)) if err != nil { return nil, err } return f.newObject(o), nil } // CleanUp the trash in the Fs // // Implement this if you have a way of emptying the trash or // otherwise cleaning up old versions of files. func (f *Fs) CleanUp(ctx context.Context) error { do := f.Fs.Features().CleanUp if do == nil { return errors.New("can't CleanUp") } return do(ctx) } // About gets quota information from the Fs func (f *Fs) About(ctx context.Context) (*fs.Usage, error) { do := f.Fs.Features().About if do == nil { return nil, errors.New("About not supported") } return do(ctx) } // UnWrap returns the Fs that this Fs is wrapping func (f *Fs) UnWrap() fs.Fs { return f.Fs } // WrapFs returns the Fs that is wrapping this Fs func (f *Fs) WrapFs() fs.Fs { return f.wrapper } // SetWrapper sets the Fs that is wrapping this Fs func (f *Fs) SetWrapper(wrapper fs.Fs) { f.wrapper = wrapper } // EncryptFileName returns an encrypted file name func (f *Fs) EncryptFileName(fileName string) string { return f.cipher.EncryptFileName(fileName) } // DecryptFileName returns a decrypted file name func (f *Fs) DecryptFileName(encryptedFileName string) (string, error) { return f.cipher.DecryptFileName(encryptedFileName) } // computeHashWithNonce takes the nonce and encrypts the contents of // src with it, and calculates the hash given by HashType on the fly // // Note that we break lots of encapsulation in this function. func (f *Fs) computeHashWithNonce(ctx context.Context, nonce nonce, src fs.Object, hashType hash.Type) (hashStr string, err error) { // Open the src for input in, err := src.Open(ctx) if err != nil { return "", errors.Wrap(err, "failed to open src") } defer fs.CheckClose(in, &err) // Now encrypt the src with the nonce out, err := f.cipher.newEncrypter(in, &nonce) if err != nil { return "", errors.Wrap(err, "failed to make encrypter") } // pipe into hash m, err := hash.NewMultiHasherTypes(hash.NewHashSet(hashType)) if err != nil { return "", errors.Wrap(err, "failed to make hasher") } _, err = io.Copy(m, out) if err != nil { return "", errors.Wrap(err, "failed to hash data") } return m.Sums()[hashType], nil } // ComputeHash takes the nonce from o, and encrypts the contents of // src with it, and calculates the hash given by HashType on the fly // // Note that we break lots of encapsulation in this function. func (f *Fs) ComputeHash(ctx context.Context, o *Object, src fs.Object, hashType hash.Type) (hashStr string, err error) { // Read the nonce - opening the file is sufficient to read the nonce in // use a limited read so we only read the header in, err := o.Object.Open(ctx, &fs.RangeOption{Start: 0, End: int64(fileHeaderSize) - 1}) if err != nil { return "", errors.Wrap(err, "failed to open object to read nonce") } d, err := f.cipher.newDecrypter(in) if err != nil { _ = in.Close() return "", errors.Wrap(err, "failed to open object to read nonce") } nonce := d.nonce // fs.Debugf(o, "Read nonce % 2x", nonce) // Check nonce isn't all zeros isZero := true for i := range nonce { if nonce[i] != 0 { isZero = false } } if isZero { fs.Errorf(o, "empty nonce read") } // Close d (and hence in) once we have read the nonce err = d.Close() if err != nil { return "", errors.Wrap(err, "failed to close nonce read") } return f.computeHashWithNonce(ctx, nonce, src, hashType) } // MergeDirs merges the contents of all the directories passed // in into the first one and rmdirs the other directories. func (f *Fs) MergeDirs(ctx context.Context, dirs []fs.Directory) error { do := f.Fs.Features().MergeDirs if do == nil { return errors.New("MergeDirs not supported") } out := make([]fs.Directory, len(dirs)) for i, dir := range dirs { out[i] = fs.NewDirCopy(ctx, dir).SetRemote(f.cipher.EncryptDirName(dir.Remote())) } return do(ctx, out) } // DirCacheFlush resets the directory cache - used in testing // as an optional interface func (f *Fs) DirCacheFlush() { do := f.Fs.Features().DirCacheFlush if do != nil { do() } } // PublicLink generates a public link to the remote path (usually readable by anyone) func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) { do := f.Fs.Features().PublicLink if do == nil { return "", errors.New("PublicLink not supported") } o, err := f.NewObject(ctx, remote) if err != nil { // assume it is a directory return do(ctx, f.cipher.EncryptDirName(remote), expire, unlink) } return do(ctx, o.(*Object).Object.Remote(), expire, unlink) } // ChangeNotify calls the passed function with a path // that has had changes. If the implementation // uses polling, it should adhere to the given interval. func (f *Fs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryType), pollIntervalChan <-chan time.Duration) { do := f.Fs.Features().ChangeNotify if do == nil { return } wrappedNotifyFunc := func(path string, entryType fs.EntryType) { // fs.Debugf(f, "ChangeNotify: path %q entryType %d", path, entryType) var ( err error decrypted string ) switch entryType { case fs.EntryDirectory: decrypted, err = f.cipher.DecryptDirName(path) case fs.EntryObject: decrypted, err = f.cipher.DecryptFileName(path) default: fs.Errorf(path, "crypt ChangeNotify: ignoring unknown EntryType %d", entryType) return } if err != nil { fs.Logf(f, "ChangeNotify was unable to decrypt %q: %s", path, err) return } notifyFunc(decrypted, entryType) } do(ctx, wrappedNotifyFunc, pollIntervalChan) } var commandHelp = []fs.CommandHelp{ { Name: "encode", Short: "Encode the given filename(s)", Long: `This encodes the filenames given as arguments returning a list of strings of the encoded results. Usage Example: rclone backend encode crypt: file1 [file2...] rclone rc backend/command command=encode fs=crypt: file1 [file2...] `, }, { Name: "decode", Short: "Decode the given filename(s)", Long: `This decodes the filenames given as arguments returning a list of strings of the decoded results. It will return an error if any of the inputs are invalid. Usage Example: rclone backend decode crypt: encryptedfile1 [encryptedfile2...] rclone rc backend/command command=decode fs=crypt: encryptedfile1 [encryptedfile2...] `, }, } // Command the backend to run a named command // // The command run is name // args may be used to read arguments from // opts may be used to read optional arguments from // // The result should be capable of being JSON encoded // If it is a string or a []string it will be shown to the user // otherwise it will be JSON encoded and shown to the user like that func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (out interface{}, err error) { switch name { case "decode": out := make([]string, 0, len(arg)) for _, encryptedFileName := range arg { fileName, err := f.DecryptFileName(encryptedFileName) if err != nil { return out, errors.Wrap(err, fmt.Sprintf("Failed to decrypt : %s", encryptedFileName)) } out = append(out, fileName) } return out, nil case "encode": out := make([]string, 0, len(arg)) for _, fileName := range arg { encryptedFileName := f.EncryptFileName(fileName) out = append(out, encryptedFileName) } return out, nil default: return nil, fs.ErrorCommandNotFound } } // Object describes a wrapped for being read from the Fs // // This decrypts the remote name and decrypts the data type Object struct { fs.Object f *Fs } func (f *Fs) newObject(o fs.Object) *Object { return &Object{ Object: o, f: f, } } // Fs returns read only access to the Fs that this object is part of func (o *Object) Fs() fs.Info { return o.f } // Return a string version func (o *Object) String() string { if o == nil { return "<nil>" } return o.Remote() } // Remote returns the remote path func (o *Object) Remote() string { remote := o.Object.Remote() decryptedName, err := o.f.cipher.DecryptFileName(remote) if err != nil { fs.Debugf(remote, "Undecryptable file name: %v", err) return remote } return decryptedName } // Size returns the size of the file func (o *Object) Size() int64 { size, err := o.f.cipher.DecryptedSize(o.Object.Size()) if err != nil { fs.Debugf(o, "Bad size for decrypt: %v", err) } return size } // Hash returns the selected checksum of the file // If no checksum is available it returns "" func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) { return "", hash.ErrUnsupported } // UnWrap returns the wrapped Object func (o *Object) UnWrap() fs.Object { return o.Object } // Open opens the file for read. Call Close() on the returned io.ReadCloser func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.ReadCloser, err error) { var openOptions []fs.OpenOption var offset, limit int64 = 0, -1 for _, option := range options { switch x := option.(type) { case *fs.SeekOption: offset = x.Offset case *fs.RangeOption: offset, limit = x.Decode(o.Size()) default: // pass on Options to underlying open if appropriate openOptions = append(openOptions, option) } } rc, err = o.f.cipher.DecryptDataSeek(ctx, func(ctx context.Context, underlyingOffset, underlyingLimit int64) (io.ReadCloser, error) { if underlyingOffset == 0 && underlyingLimit < 0 { // Open with no seek return o.Object.Open(ctx, openOptions...) } // Open stream with a range of underlyingOffset, underlyingLimit end := int64(-1) if underlyingLimit >= 0 { end = underlyingOffset + underlyingLimit - 1 if end >= o.Object.Size() { end = -1 } } newOpenOptions := append(openOptions, &fs.RangeOption{Start: underlyingOffset, End: end}) return o.Object.Open(ctx, newOpenOptions...) }, offset, limit) if err != nil { return nil, err } return rc, nil } // Update in to the object with the modTime given of the given size func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error { update := func(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return o.Object, o.Object.Update(ctx, in, src, options...) } _, err := o.f.put(ctx, in, src, options, update) return err } // newDir returns a dir with the Name decrypted func (f *Fs) newDir(ctx context.Context, dir fs.Directory) fs.Directory { newDir := fs.NewDirCopy(ctx, dir) remote := dir.Remote() decryptedRemote, err := f.cipher.DecryptDirName(remote) if err != nil { fs.Debugf(remote, "Undecryptable dir name: %v", err) } else { newDir.SetRemote(decryptedRemote) } return newDir } // UserInfo returns info about the connected user func (f *Fs) UserInfo(ctx context.Context) (map[string]string, error) { do := f.Fs.Features().UserInfo if do == nil { return nil, fs.ErrorNotImplemented } return do(ctx) } // Disconnect the current user func (f *Fs) Disconnect(ctx context.Context) error { do := f.Fs.Features().Disconnect if do == nil { return fs.ErrorNotImplemented } return do(ctx) } // ObjectInfo describes a wrapped fs.ObjectInfo for being the source // // This encrypts the remote name and adjusts the size type ObjectInfo struct { fs.ObjectInfo f *Fs nonce nonce } func (f *Fs) newObjectInfo(src fs.ObjectInfo, nonce nonce) *ObjectInfo { return &ObjectInfo{ ObjectInfo: src, f: f, nonce: nonce, } } // Fs returns read only access to the Fs that this object is part of func (o *ObjectInfo) Fs() fs.Info { return o.f } // Remote returns the remote path func (o *ObjectInfo) Remote() string { return o.f.cipher.EncryptFileName(o.ObjectInfo.Remote()) } // Size returns the size of the file func (o *ObjectInfo) Size() int64 { size := o.ObjectInfo.Size() if size < 0 { return size } return o.f.cipher.EncryptedSize(size) } // Hash returns the selected checksum of the file // If no checksum is available it returns "" func (o *ObjectInfo) Hash(ctx context.Context, hash hash.Type) (string, error) { var srcObj fs.Object var ok bool // Get the underlying object if there is one if srcObj, ok = o.ObjectInfo.(fs.Object); ok { // Prefer direct interface assertion } else if do, ok := o.ObjectInfo.(fs.ObjectUnWrapper); ok { // Otherwise likely is an operations.OverrideRemote srcObj = do.UnWrap() } else { return "", nil } // if this is wrapping a local object then we work out the hash if srcObj.Fs().Features().IsLocal { // Read the data and encrypt it to calculate the hash fs.Debugf(o, "Computing %v hash of encrypted source", hash) return o.f.computeHashWithNonce(ctx, o.nonce, srcObj, hash) } return "", nil } // ID returns the ID of the Object if known, or "" if not func (o *Object) ID() string { do, ok := o.Object.(fs.IDer) if !ok { return "" } return do.ID() } // SetTier performs changing storage tier of the Object if // multiple storage classes supported func (o *Object) SetTier(tier string) error { do, ok := o.Object.(fs.SetTierer) if !ok { return errors.New("crypt: underlying remote does not support SetTier") } return do.SetTier(tier) } // GetTier returns storage tier or class of the Object func (o *Object) GetTier() string { do, ok := o.Object.(fs.GetTierer) if !ok { return "" } return do.GetTier() } // Check the interfaces are satisfied var ( _ fs.Fs = (*Fs)(nil) _ fs.Purger = (*Fs)(nil) _ fs.Copier = (*Fs)(nil) _ fs.Mover = (*Fs)(nil) _ fs.DirMover = (*Fs)(nil) _ fs.Commander = (*Fs)(nil) _ fs.PutUncheckeder = (*Fs)(nil) _ fs.PutStreamer = (*Fs)(nil) _ fs.CleanUpper = (*Fs)(nil) _ fs.UnWrapper = (*Fs)(nil) _ fs.ListRer = (*Fs)(nil) _ fs.Abouter = (*Fs)(nil) _ fs.Wrapper = (*Fs)(nil) _ fs.MergeDirser = (*Fs)(nil) _ fs.DirCacheFlusher = (*Fs)(nil) _ fs.ChangeNotifier = (*Fs)(nil) _ fs.PublicLinker = (*Fs)(nil) _ fs.UserInfoer = (*Fs)(nil) _ fs.Disconnecter = (*Fs)(nil) _ fs.ObjectInfo = (*ObjectInfo)(nil) _ fs.Object = (*Object)(nil) _ fs.ObjectUnWrapper = (*Object)(nil) _ fs.IDer = (*Object)(nil) _ fs.SetTierer = (*Object)(nil) _ fs.GetTierer = (*Object)(nil) ) crypt: fix purge bug introduced by refactor #1891 In this commit a2afa9aaddbfb2ef fs: Add directory to optional Purge interface We failed to encrypt the directory name so the Purge failed. This was spotted by the integration tests. // Package crypt provides wrappers for Fs and Object which implement encryption package crypt import ( "context" "fmt" "io" "path" "strings" "time" "github.com/pkg/errors" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/fs/accounting" "github.com/rclone/rclone/fs/config/configmap" "github.com/rclone/rclone/fs/config/configstruct" "github.com/rclone/rclone/fs/config/obscure" "github.com/rclone/rclone/fs/fspath" "github.com/rclone/rclone/fs/hash" ) // Globals // Register with Fs func init() { fs.Register(&fs.RegInfo{ Name: "crypt", Description: "Encrypt/Decrypt a remote", NewFs: NewFs, CommandHelp: commandHelp, Options: []fs.Option{{ Name: "remote", Help: "Remote to encrypt/decrypt.\nNormally should contain a ':' and a path, eg \"myremote:path/to/dir\",\n\"myremote:bucket\" or maybe \"myremote:\" (not recommended).", Required: true, }, { Name: "filename_encryption", Help: "How to encrypt the filenames.", Default: "standard", Examples: []fs.OptionExample{ { Value: "standard", Help: "Encrypt the filenames see the docs for the details.", }, { Value: "obfuscate", Help: "Very simple filename obfuscation.", }, { Value: "off", Help: "Don't encrypt the file names. Adds a \".bin\" extension only.", }, }, }, { Name: "directory_name_encryption", Help: `Option to either encrypt directory names or leave them intact. NB If filename_encryption is "off" then this option will do nothing.`, Default: true, Examples: []fs.OptionExample{ { Value: "true", Help: "Encrypt directory names.", }, { Value: "false", Help: "Don't encrypt directory names, leave them intact.", }, }, }, { Name: "password", Help: "Password or pass phrase for encryption.", IsPassword: true, Required: true, }, { Name: "password2", Help: "Password or pass phrase for salt. Optional but recommended.\nShould be different to the previous password.", IsPassword: true, }, { Name: "server_side_across_configs", Default: false, Help: `Allow server side operations (eg copy) to work across different crypt configs. Normally this option is not what you want, but if you have two crypts pointing to the same backend you can use it. This can be used, for example, to change file name encryption type without re-uploading all the data. Just make two crypt backends pointing to two different directories with the single changed parameter and use rclone move to move the files between the crypt remotes.`, Advanced: true, }, { Name: "show_mapping", Help: `For all files listed show how the names encrypt. If this flag is set then for each file that the remote is asked to list, it will log (at level INFO) a line stating the decrypted file name and the encrypted file name. This is so you can work out which encrypted names are which decrypted names just in case you need to do something with the encrypted file names, or for debugging purposes.`, Default: false, Hide: fs.OptionHideConfigurator, Advanced: true, }}, }) } // newCipherForConfig constructs a Cipher for the given config name func newCipherForConfig(opt *Options) (*Cipher, error) { mode, err := NewNameEncryptionMode(opt.FilenameEncryption) if err != nil { return nil, err } if opt.Password == "" { return nil, errors.New("password not set in config file") } password, err := obscure.Reveal(opt.Password) if err != nil { return nil, errors.Wrap(err, "failed to decrypt password") } var salt string if opt.Password2 != "" { salt, err = obscure.Reveal(opt.Password2) if err != nil { return nil, errors.Wrap(err, "failed to decrypt password2") } } cipher, err := newCipher(mode, password, salt, opt.DirectoryNameEncryption) if err != nil { return nil, errors.Wrap(err, "failed to make cipher") } return cipher, nil } // NewCipher constructs a Cipher for the given config func NewCipher(m configmap.Mapper) (*Cipher, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } return newCipherForConfig(opt) } // NewFs constructs an Fs from the path, container:path func NewFs(name, rpath string, m configmap.Mapper) (fs.Fs, error) { // Parse config into Options struct opt := new(Options) err := configstruct.Set(m, opt) if err != nil { return nil, err } cipher, err := newCipherForConfig(opt) if err != nil { return nil, err } remote := opt.Remote if strings.HasPrefix(remote, name+":") { return nil, errors.New("can't point crypt remote at itself - check the value of the remote setting") } wInfo, wName, wPath, wConfig, err := fs.ConfigFs(remote) if err != nil { return nil, errors.Wrapf(err, "failed to parse remote %q to wrap", remote) } // Make sure to remove trailing . reffering to the current dir if path.Base(rpath) == "." { rpath = strings.TrimSuffix(rpath, ".") } // Look for a file first remotePath := fspath.JoinRootPath(wPath, cipher.EncryptFileName(rpath)) wrappedFs, err := wInfo.NewFs(wName, remotePath, wConfig) // if that didn't produce a file, look for a directory if err != fs.ErrorIsFile { remotePath = fspath.JoinRootPath(wPath, cipher.EncryptDirName(rpath)) wrappedFs, err = wInfo.NewFs(wName, remotePath, wConfig) } if err != fs.ErrorIsFile && err != nil { return nil, errors.Wrapf(err, "failed to make remote %s:%q to wrap", wName, remotePath) } f := &Fs{ Fs: wrappedFs, name: name, root: rpath, opt: *opt, cipher: cipher, } // the features here are ones we could support, and they are // ANDed with the ones from wrappedFs f.features = (&fs.Features{ CaseInsensitive: cipher.NameEncryptionMode() == NameEncryptionOff, DuplicateFiles: true, ReadMimeType: false, // MimeTypes not supported with crypt WriteMimeType: false, BucketBased: true, CanHaveEmptyDirectories: true, SetTier: true, GetTier: true, ServerSideAcrossConfigs: opt.ServerSideAcrossConfigs, }).Fill(f).Mask(wrappedFs).WrapsFs(f, wrappedFs) return f, err } // Options defines the configuration for this backend type Options struct { Remote string `config:"remote"` FilenameEncryption string `config:"filename_encryption"` DirectoryNameEncryption bool `config:"directory_name_encryption"` Password string `config:"password"` Password2 string `config:"password2"` ServerSideAcrossConfigs bool `config:"server_side_across_configs"` ShowMapping bool `config:"show_mapping"` } // Fs represents a wrapped fs.Fs type Fs struct { fs.Fs wrapper fs.Fs name string root string opt Options features *fs.Features // optional features cipher *Cipher } // Name of the remote (as passed into NewFs) func (f *Fs) Name() string { return f.name } // Root of the remote (as passed into NewFs) func (f *Fs) Root() string { return f.root } // Features returns the optional features of this Fs func (f *Fs) Features() *fs.Features { return f.features } // String returns a description of the FS func (f *Fs) String() string { return fmt.Sprintf("Encrypted drive '%s:%s'", f.name, f.root) } // Encrypt an object file name to entries. func (f *Fs) add(entries *fs.DirEntries, obj fs.Object) { remote := obj.Remote() decryptedRemote, err := f.cipher.DecryptFileName(remote) if err != nil { fs.Debugf(remote, "Skipping undecryptable file name: %v", err) return } if f.opt.ShowMapping { fs.Logf(decryptedRemote, "Encrypts to %q", remote) } *entries = append(*entries, f.newObject(obj)) } // Encrypt a directory file name to entries. func (f *Fs) addDir(ctx context.Context, entries *fs.DirEntries, dir fs.Directory) { remote := dir.Remote() decryptedRemote, err := f.cipher.DecryptDirName(remote) if err != nil { fs.Debugf(remote, "Skipping undecryptable dir name: %v", err) return } if f.opt.ShowMapping { fs.Logf(decryptedRemote, "Encrypts to %q", remote) } *entries = append(*entries, f.newDir(ctx, dir)) } // Encrypt some directory entries. This alters entries returning it as newEntries. func (f *Fs) encryptEntries(ctx context.Context, entries fs.DirEntries) (newEntries fs.DirEntries, err error) { newEntries = entries[:0] // in place filter for _, entry := range entries { switch x := entry.(type) { case fs.Object: f.add(&newEntries, x) case fs.Directory: f.addDir(ctx, &newEntries, x) default: return nil, errors.Errorf("Unknown object type %T", entry) } } return newEntries, nil } // List the objects and directories in dir into entries. The // entries can be returned in any order but should be for a // complete directory. // // dir should be "" to list the root, and should not have // trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) { entries, err = f.Fs.List(ctx, f.cipher.EncryptDirName(dir)) if err != nil { return nil, err } return f.encryptEntries(ctx, entries) } // ListR lists the objects and directories of the Fs starting // from dir recursively into out. // // dir should be "" to start from the root, and should not // have trailing slashes. // // This should return ErrDirNotFound if the directory isn't // found. // // It should call callback for each tranche of entries read. // These need not be returned in any particular order. If // callback returns an error then the listing will stop // immediately. // // Don't implement this unless you have a more efficient way // of listing recursively that doing a directory traversal. func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) { return f.Fs.Features().ListR(ctx, f.cipher.EncryptDirName(dir), func(entries fs.DirEntries) error { newEntries, err := f.encryptEntries(ctx, entries) if err != nil { return err } return callback(newEntries) }) } // NewObject finds the Object at remote. func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) { o, err := f.Fs.NewObject(ctx, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(o), nil } type putFn func(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) // put implements Put or PutStream func (f *Fs) put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options []fs.OpenOption, put putFn) (fs.Object, error) { // Encrypt the data into wrappedIn wrappedIn, encrypter, err := f.cipher.encryptData(in) if err != nil { return nil, err } // Find a hash the destination supports to compute a hash of // the encrypted data ht := f.Fs.Hashes().GetOne() var hasher *hash.MultiHasher if ht != hash.None { hasher, err = hash.NewMultiHasherTypes(hash.NewHashSet(ht)) if err != nil { return nil, err } // unwrap the accounting var wrap accounting.WrapFn wrappedIn, wrap = accounting.UnWrap(wrappedIn) // add the hasher wrappedIn = io.TeeReader(wrappedIn, hasher) // wrap the accounting back on wrappedIn = wrap(wrappedIn) } // Transfer the data o, err := put(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce), options...) if err != nil { return nil, err } // Check the hashes of the encrypted data if we were comparing them if ht != hash.None && hasher != nil { srcHash := hasher.Sums()[ht] var dstHash string dstHash, err = o.Hash(ctx, ht) if err != nil { return nil, errors.Wrap(err, "failed to read destination hash") } if srcHash != "" && dstHash != "" && srcHash != dstHash { // remove object err = o.Remove(ctx) if err != nil { fs.Errorf(o, "Failed to remove corrupted object: %v", err) } return nil, errors.Errorf("corrupted on transfer: %v crypted hash differ %q vs %q", ht, srcHash, dstHash) } } return f.newObject(o), nil } // Put in to the remote path with the modTime given of the given size // // May create the object even if it returns an error - if so // will return the object and the error, otherwise will return // nil and the error func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.put(ctx, in, src, options, f.Fs.Put) } // PutStream uploads to the remote path with the modTime given of indeterminate size func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return f.put(ctx, in, src, options, f.Fs.Features().PutStream) } // Hashes returns the supported hash sets. func (f *Fs) Hashes() hash.Set { return hash.Set(hash.None) } // Mkdir makes the directory (container, bucket) // // Shouldn't return an error if it already exists func (f *Fs) Mkdir(ctx context.Context, dir string) error { return f.Fs.Mkdir(ctx, f.cipher.EncryptDirName(dir)) } // Rmdir removes the directory (container, bucket) if empty // // Return an error if it doesn't exist or isn't empty func (f *Fs) Rmdir(ctx context.Context, dir string) error { return f.Fs.Rmdir(ctx, f.cipher.EncryptDirName(dir)) } // Purge all files in the directory specified // // Implement this if you have a way of deleting all the files // quicker than just running Remove() on the result of List() // // Return an error if it doesn't exist func (f *Fs) Purge(ctx context.Context, dir string) error { do := f.Fs.Features().Purge if do == nil { return fs.ErrorCantPurge } return do(ctx, f.cipher.EncryptDirName(dir)) } // Copy src to this remote using server side copy operations. // // This is stored with the remote path given // // It returns the destination Object and a possible error // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantCopy func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { do := f.Fs.Features().Copy if do == nil { return nil, fs.ErrorCantCopy } o, ok := src.(*Object) if !ok { return nil, fs.ErrorCantCopy } oResult, err := do(ctx, o.Object, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(oResult), nil } // Move src to this remote using server side move operations. // // This is stored with the remote path given // // It returns the destination Object and a possible error // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantMove func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { do := f.Fs.Features().Move if do == nil { return nil, fs.ErrorCantMove } o, ok := src.(*Object) if !ok { return nil, fs.ErrorCantMove } oResult, err := do(ctx, o.Object, f.cipher.EncryptFileName(remote)) if err != nil { return nil, err } return f.newObject(oResult), nil } // DirMove moves src, srcRemote to this remote at dstRemote // using server side move operations. // // Will only be called if src.Fs().Name() == f.Name() // // If it isn't possible then return fs.ErrorCantDirMove // // If destination exists then return fs.ErrorDirExists func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error { do := f.Fs.Features().DirMove if do == nil { return fs.ErrorCantDirMove } srcFs, ok := src.(*Fs) if !ok { fs.Debugf(srcFs, "Can't move directory - not same remote type") return fs.ErrorCantDirMove } return do(ctx, srcFs.Fs, f.cipher.EncryptDirName(srcRemote), f.cipher.EncryptDirName(dstRemote)) } // PutUnchecked uploads the object // // This will create a duplicate if we upload a new file without // checking to see if there is one already - use Put() for that. func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { do := f.Fs.Features().PutUnchecked if do == nil { return nil, errors.New("can't PutUnchecked") } wrappedIn, encrypter, err := f.cipher.encryptData(in) if err != nil { return nil, err } o, err := do(ctx, wrappedIn, f.newObjectInfo(src, encrypter.nonce)) if err != nil { return nil, err } return f.newObject(o), nil } // CleanUp the trash in the Fs // // Implement this if you have a way of emptying the trash or // otherwise cleaning up old versions of files. func (f *Fs) CleanUp(ctx context.Context) error { do := f.Fs.Features().CleanUp if do == nil { return errors.New("can't CleanUp") } return do(ctx) } // About gets quota information from the Fs func (f *Fs) About(ctx context.Context) (*fs.Usage, error) { do := f.Fs.Features().About if do == nil { return nil, errors.New("About not supported") } return do(ctx) } // UnWrap returns the Fs that this Fs is wrapping func (f *Fs) UnWrap() fs.Fs { return f.Fs } // WrapFs returns the Fs that is wrapping this Fs func (f *Fs) WrapFs() fs.Fs { return f.wrapper } // SetWrapper sets the Fs that is wrapping this Fs func (f *Fs) SetWrapper(wrapper fs.Fs) { f.wrapper = wrapper } // EncryptFileName returns an encrypted file name func (f *Fs) EncryptFileName(fileName string) string { return f.cipher.EncryptFileName(fileName) } // DecryptFileName returns a decrypted file name func (f *Fs) DecryptFileName(encryptedFileName string) (string, error) { return f.cipher.DecryptFileName(encryptedFileName) } // computeHashWithNonce takes the nonce and encrypts the contents of // src with it, and calculates the hash given by HashType on the fly // // Note that we break lots of encapsulation in this function. func (f *Fs) computeHashWithNonce(ctx context.Context, nonce nonce, src fs.Object, hashType hash.Type) (hashStr string, err error) { // Open the src for input in, err := src.Open(ctx) if err != nil { return "", errors.Wrap(err, "failed to open src") } defer fs.CheckClose(in, &err) // Now encrypt the src with the nonce out, err := f.cipher.newEncrypter(in, &nonce) if err != nil { return "", errors.Wrap(err, "failed to make encrypter") } // pipe into hash m, err := hash.NewMultiHasherTypes(hash.NewHashSet(hashType)) if err != nil { return "", errors.Wrap(err, "failed to make hasher") } _, err = io.Copy(m, out) if err != nil { return "", errors.Wrap(err, "failed to hash data") } return m.Sums()[hashType], nil } // ComputeHash takes the nonce from o, and encrypts the contents of // src with it, and calculates the hash given by HashType on the fly // // Note that we break lots of encapsulation in this function. func (f *Fs) ComputeHash(ctx context.Context, o *Object, src fs.Object, hashType hash.Type) (hashStr string, err error) { // Read the nonce - opening the file is sufficient to read the nonce in // use a limited read so we only read the header in, err := o.Object.Open(ctx, &fs.RangeOption{Start: 0, End: int64(fileHeaderSize) - 1}) if err != nil { return "", errors.Wrap(err, "failed to open object to read nonce") } d, err := f.cipher.newDecrypter(in) if err != nil { _ = in.Close() return "", errors.Wrap(err, "failed to open object to read nonce") } nonce := d.nonce // fs.Debugf(o, "Read nonce % 2x", nonce) // Check nonce isn't all zeros isZero := true for i := range nonce { if nonce[i] != 0 { isZero = false } } if isZero { fs.Errorf(o, "empty nonce read") } // Close d (and hence in) once we have read the nonce err = d.Close() if err != nil { return "", errors.Wrap(err, "failed to close nonce read") } return f.computeHashWithNonce(ctx, nonce, src, hashType) } // MergeDirs merges the contents of all the directories passed // in into the first one and rmdirs the other directories. func (f *Fs) MergeDirs(ctx context.Context, dirs []fs.Directory) error { do := f.Fs.Features().MergeDirs if do == nil { return errors.New("MergeDirs not supported") } out := make([]fs.Directory, len(dirs)) for i, dir := range dirs { out[i] = fs.NewDirCopy(ctx, dir).SetRemote(f.cipher.EncryptDirName(dir.Remote())) } return do(ctx, out) } // DirCacheFlush resets the directory cache - used in testing // as an optional interface func (f *Fs) DirCacheFlush() { do := f.Fs.Features().DirCacheFlush if do != nil { do() } } // PublicLink generates a public link to the remote path (usually readable by anyone) func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (string, error) { do := f.Fs.Features().PublicLink if do == nil { return "", errors.New("PublicLink not supported") } o, err := f.NewObject(ctx, remote) if err != nil { // assume it is a directory return do(ctx, f.cipher.EncryptDirName(remote), expire, unlink) } return do(ctx, o.(*Object).Object.Remote(), expire, unlink) } // ChangeNotify calls the passed function with a path // that has had changes. If the implementation // uses polling, it should adhere to the given interval. func (f *Fs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryType), pollIntervalChan <-chan time.Duration) { do := f.Fs.Features().ChangeNotify if do == nil { return } wrappedNotifyFunc := func(path string, entryType fs.EntryType) { // fs.Debugf(f, "ChangeNotify: path %q entryType %d", path, entryType) var ( err error decrypted string ) switch entryType { case fs.EntryDirectory: decrypted, err = f.cipher.DecryptDirName(path) case fs.EntryObject: decrypted, err = f.cipher.DecryptFileName(path) default: fs.Errorf(path, "crypt ChangeNotify: ignoring unknown EntryType %d", entryType) return } if err != nil { fs.Logf(f, "ChangeNotify was unable to decrypt %q: %s", path, err) return } notifyFunc(decrypted, entryType) } do(ctx, wrappedNotifyFunc, pollIntervalChan) } var commandHelp = []fs.CommandHelp{ { Name: "encode", Short: "Encode the given filename(s)", Long: `This encodes the filenames given as arguments returning a list of strings of the encoded results. Usage Example: rclone backend encode crypt: file1 [file2...] rclone rc backend/command command=encode fs=crypt: file1 [file2...] `, }, { Name: "decode", Short: "Decode the given filename(s)", Long: `This decodes the filenames given as arguments returning a list of strings of the decoded results. It will return an error if any of the inputs are invalid. Usage Example: rclone backend decode crypt: encryptedfile1 [encryptedfile2...] rclone rc backend/command command=decode fs=crypt: encryptedfile1 [encryptedfile2...] `, }, } // Command the backend to run a named command // // The command run is name // args may be used to read arguments from // opts may be used to read optional arguments from // // The result should be capable of being JSON encoded // If it is a string or a []string it will be shown to the user // otherwise it will be JSON encoded and shown to the user like that func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (out interface{}, err error) { switch name { case "decode": out := make([]string, 0, len(arg)) for _, encryptedFileName := range arg { fileName, err := f.DecryptFileName(encryptedFileName) if err != nil { return out, errors.Wrap(err, fmt.Sprintf("Failed to decrypt : %s", encryptedFileName)) } out = append(out, fileName) } return out, nil case "encode": out := make([]string, 0, len(arg)) for _, fileName := range arg { encryptedFileName := f.EncryptFileName(fileName) out = append(out, encryptedFileName) } return out, nil default: return nil, fs.ErrorCommandNotFound } } // Object describes a wrapped for being read from the Fs // // This decrypts the remote name and decrypts the data type Object struct { fs.Object f *Fs } func (f *Fs) newObject(o fs.Object) *Object { return &Object{ Object: o, f: f, } } // Fs returns read only access to the Fs that this object is part of func (o *Object) Fs() fs.Info { return o.f } // Return a string version func (o *Object) String() string { if o == nil { return "<nil>" } return o.Remote() } // Remote returns the remote path func (o *Object) Remote() string { remote := o.Object.Remote() decryptedName, err := o.f.cipher.DecryptFileName(remote) if err != nil { fs.Debugf(remote, "Undecryptable file name: %v", err) return remote } return decryptedName } // Size returns the size of the file func (o *Object) Size() int64 { size, err := o.f.cipher.DecryptedSize(o.Object.Size()) if err != nil { fs.Debugf(o, "Bad size for decrypt: %v", err) } return size } // Hash returns the selected checksum of the file // If no checksum is available it returns "" func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) { return "", hash.ErrUnsupported } // UnWrap returns the wrapped Object func (o *Object) UnWrap() fs.Object { return o.Object } // Open opens the file for read. Call Close() on the returned io.ReadCloser func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.ReadCloser, err error) { var openOptions []fs.OpenOption var offset, limit int64 = 0, -1 for _, option := range options { switch x := option.(type) { case *fs.SeekOption: offset = x.Offset case *fs.RangeOption: offset, limit = x.Decode(o.Size()) default: // pass on Options to underlying open if appropriate openOptions = append(openOptions, option) } } rc, err = o.f.cipher.DecryptDataSeek(ctx, func(ctx context.Context, underlyingOffset, underlyingLimit int64) (io.ReadCloser, error) { if underlyingOffset == 0 && underlyingLimit < 0 { // Open with no seek return o.Object.Open(ctx, openOptions...) } // Open stream with a range of underlyingOffset, underlyingLimit end := int64(-1) if underlyingLimit >= 0 { end = underlyingOffset + underlyingLimit - 1 if end >= o.Object.Size() { end = -1 } } newOpenOptions := append(openOptions, &fs.RangeOption{Start: underlyingOffset, End: end}) return o.Object.Open(ctx, newOpenOptions...) }, offset, limit) if err != nil { return nil, err } return rc, nil } // Update in to the object with the modTime given of the given size func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error { update := func(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { return o.Object, o.Object.Update(ctx, in, src, options...) } _, err := o.f.put(ctx, in, src, options, update) return err } // newDir returns a dir with the Name decrypted func (f *Fs) newDir(ctx context.Context, dir fs.Directory) fs.Directory { newDir := fs.NewDirCopy(ctx, dir) remote := dir.Remote() decryptedRemote, err := f.cipher.DecryptDirName(remote) if err != nil { fs.Debugf(remote, "Undecryptable dir name: %v", err) } else { newDir.SetRemote(decryptedRemote) } return newDir } // UserInfo returns info about the connected user func (f *Fs) UserInfo(ctx context.Context) (map[string]string, error) { do := f.Fs.Features().UserInfo if do == nil { return nil, fs.ErrorNotImplemented } return do(ctx) } // Disconnect the current user func (f *Fs) Disconnect(ctx context.Context) error { do := f.Fs.Features().Disconnect if do == nil { return fs.ErrorNotImplemented } return do(ctx) } // ObjectInfo describes a wrapped fs.ObjectInfo for being the source // // This encrypts the remote name and adjusts the size type ObjectInfo struct { fs.ObjectInfo f *Fs nonce nonce } func (f *Fs) newObjectInfo(src fs.ObjectInfo, nonce nonce) *ObjectInfo { return &ObjectInfo{ ObjectInfo: src, f: f, nonce: nonce, } } // Fs returns read only access to the Fs that this object is part of func (o *ObjectInfo) Fs() fs.Info { return o.f } // Remote returns the remote path func (o *ObjectInfo) Remote() string { return o.f.cipher.EncryptFileName(o.ObjectInfo.Remote()) } // Size returns the size of the file func (o *ObjectInfo) Size() int64 { size := o.ObjectInfo.Size() if size < 0 { return size } return o.f.cipher.EncryptedSize(size) } // Hash returns the selected checksum of the file // If no checksum is available it returns "" func (o *ObjectInfo) Hash(ctx context.Context, hash hash.Type) (string, error) { var srcObj fs.Object var ok bool // Get the underlying object if there is one if srcObj, ok = o.ObjectInfo.(fs.Object); ok { // Prefer direct interface assertion } else if do, ok := o.ObjectInfo.(fs.ObjectUnWrapper); ok { // Otherwise likely is an operations.OverrideRemote srcObj = do.UnWrap() } else { return "", nil } // if this is wrapping a local object then we work out the hash if srcObj.Fs().Features().IsLocal { // Read the data and encrypt it to calculate the hash fs.Debugf(o, "Computing %v hash of encrypted source", hash) return o.f.computeHashWithNonce(ctx, o.nonce, srcObj, hash) } return "", nil } // ID returns the ID of the Object if known, or "" if not func (o *Object) ID() string { do, ok := o.Object.(fs.IDer) if !ok { return "" } return do.ID() } // SetTier performs changing storage tier of the Object if // multiple storage classes supported func (o *Object) SetTier(tier string) error { do, ok := o.Object.(fs.SetTierer) if !ok { return errors.New("crypt: underlying remote does not support SetTier") } return do.SetTier(tier) } // GetTier returns storage tier or class of the Object func (o *Object) GetTier() string { do, ok := o.Object.(fs.GetTierer) if !ok { return "" } return do.GetTier() } // Check the interfaces are satisfied var ( _ fs.Fs = (*Fs)(nil) _ fs.Purger = (*Fs)(nil) _ fs.Copier = (*Fs)(nil) _ fs.Mover = (*Fs)(nil) _ fs.DirMover = (*Fs)(nil) _ fs.Commander = (*Fs)(nil) _ fs.PutUncheckeder = (*Fs)(nil) _ fs.PutStreamer = (*Fs)(nil) _ fs.CleanUpper = (*Fs)(nil) _ fs.UnWrapper = (*Fs)(nil) _ fs.ListRer = (*Fs)(nil) _ fs.Abouter = (*Fs)(nil) _ fs.Wrapper = (*Fs)(nil) _ fs.MergeDirser = (*Fs)(nil) _ fs.DirCacheFlusher = (*Fs)(nil) _ fs.ChangeNotifier = (*Fs)(nil) _ fs.PublicLinker = (*Fs)(nil) _ fs.UserInfoer = (*Fs)(nil) _ fs.Disconnecter = (*Fs)(nil) _ fs.ObjectInfo = (*ObjectInfo)(nil) _ fs.Object = (*Object)(nil) _ fs.ObjectUnWrapper = (*Object)(nil) _ fs.IDer = (*Object)(nil) _ fs.SetTierer = (*Object)(nil) _ fs.GetTierer = (*Object)(nil) )