{"text":"package handlers\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/rancher\/go-machine-service\/events\"\n\t\"github.com\/rancher\/go-machine-service\/handlers\/providers\"\n\t\"github.com\/rancher\/go-rancher\/client\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tlevelInfo = \"level=\\\"info\\\"\"\n\tlevelError = \"level=\\\"error\\\"\"\n\terrorCreatingMachine = \"Error creating machine: \"\n\tCREATED_FILE = \"created\"\n)\n\nvar regExDockerMsg = regexp.MustCompile(\"msg=.*\")\nvar regExHyphen = regexp.MustCompile(\"([a-z])([A-Z])\")\n\nfunc CreateMachine(event *events.Event, apiClient *client.RancherClient) (err error) {\n\tlog.WithFields(log.Fields{\n\t\t\"resourceId\": event.ResourceId,\n\t\t\"eventId\": event.Id,\n\t}).Info(\"Creating Machine\")\n\n\tmachine, err := getMachine(event.ResourceId, apiClient)\n\tif err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\t\/\/ Idempotency. If the resource has the property, we're done.\n\tif _, ok := machine.Data[machineDirField]; ok {\n\t\treply := newReply(event)\n\t\treturn publishReply(reply, apiClient)\n\t}\n\n\tmachineDir, err := buildBaseMachineDir(machine.ExternalId)\n\tif err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcleanupResources(machineDir, machine.Name)\n\t\t}\n\t}()\n\n\tdataUpdates := map[string]interface{}{machineDirField: machineDir}\n\teventDataWrapper := map[string]interface{}{\"+data\": dataUpdates}\n\n\t\/\/Idempotency, if the same request is sent, without the machineDir & extractedConfig Field, we need to handle that\n\tif _, err := os.Stat(filepath.Join(machineDir, \"machines\", machine.Name, CREATED_FILE)); !os.IsNotExist(err) {\n\t\textractedConfig, extractionErr := getIdempotentExtractedConfig(machine, machineDir, apiClient)\n\t\tif extractionErr != nil {\n\t\t\treturn handleByIdError(extractionErr, event, apiClient)\n\t\t}\n\t\tdataUpdates[\"+fields\"] = map[string]interface{}{\"extractedConfig\": extractedConfig}\n\t\treply := newReply(event)\n\t\treply.Data = eventDataWrapper\n\t\treturn publishReply(reply, apiClient)\n\t}\n\n\tproviderHandler := providers.GetProviderHandler(machine.Driver)\n\n\tif err := providerHandler.HandleCreate(machine, machineDir); err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\tcommand, err := buildCreateCommand(machine, machineDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/Setup republishing timer\n\tpublishChan := make(chan string, 10)\n\tgo republishTransitioningReply(publishChan, event, apiClient)\n\n\tpublishChan <- \"Contacting \" + machine.Driver\n\talreadyClosed := false\n\tdefer func() {\n\t\tif !alreadyClosed {\n\t\t\tclose(publishChan)\n\t\t}\n\t}()\n\n\treaderStdout, readerStderr, err := startReturnOutput(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrChan := make(chan string, 1)\n\tgo logProgress(readerStdout, readerStderr, publishChan, machine, event, errChan, providerHandler)\n\n\terr = command.Wait()\n\n\tif err != nil {\n\t\tselect {\n\t\tcase errString := <-errChan:\n\t\t\tif errString != \"\" {\n\t\t\t\treturn fmt.Errorf(errString)\n\t\t\t}\n\t\tcase <-time.After(10 * time.Second):\n\t\t\tlog.Error(\"Waited 10 seconds to break after command.Wait(). Please review logProgress.\")\n\t\t}\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"resourceId\": event.ResourceId,\n\t\t\"machineExternalId\": machine.ExternalId,\n\t}).Info(\"Machine Created\")\n\n\tif f, err := os.Create(filepath.Join(machineDir, \"machines\", machine.Name, CREATED_FILE)); err != nil {\n\t\treturn err\n\t} else {\n\t\tf.Close()\n\t}\n\n\tdestFile, err := createExtractedConfig(event, machine)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif destFile != \"\" {\n\t\tpublishChan <- \"Saving Machine Config\"\n\t\textractedConf, err := getExtractedConfig(destFile, machine, apiClient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdataUpdates[\"+fields\"] = map[string]string{\"extractedConfig\": extractedConf}\n\t}\n\n\treply := newReply(event)\n\treply.Data = eventDataWrapper\n\n\t\/\/ Explicitly close publish channel so that it doesn't conflict with final reply\n\tclose(publishChan)\n\talreadyClosed = true\n\treturn publishReply(reply, apiClient)\n}\n\nfunc logProgress(readerStdout io.Reader, readerStderr io.Reader, publishChan chan<- string, machine *client.Machine, event *events.Event, errChan chan<- string, providerHandler providers.Provider) {\n\t\/\/ We will just log stdout first, then stderr, ignoring all errors.\n\tdefer close(errChan)\n\tscanner := bufio.NewScanner(readerStdout)\n\tfor scanner.Scan() {\n\t\tmsg := scanner.Text()\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"resourceId: \": event.ResourceId,\n\t\t}).Infof(\"stdout: %s\", msg)\n\t\ttransitionMsg := filterDockerMessage(msg, machine, errChan, providerHandler)\n\t\tif transitionMsg != \"\" {\n\t\t\tpublishChan <- transitionMsg\n\t\t}\n\t}\n\tscanner = bufio.NewScanner(readerStderr)\n\tfor scanner.Scan() {\n\t\tmsg := scanner.Text()\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"resourceId\": event.ResourceId,\n\t\t}).Infof(\"stderr: %s\", msg)\n\t\tfilterDockerMessage(msg, machine, errChan, providerHandler)\n\t}\n}\n\nfunc filterDockerMessage(msg string, machine *client.Machine, errChan chan<- string, providerHandler providers.Provider) string {\n\tif strings.Contains(msg, errorCreatingMachine) {\n\t\terrChan <- providerHandler.HandleError(strings.Replace(msg, errorCreatingMachine, \"\", 1))\n\t\treturn \"\"\n\t}\n\tif strings.Contains(msg, machine.ExternalId) || strings.Contains(msg, machine.Name) {\n\t\treturn \"\"\n\t}\n\treturn msg\n}\n\nfunc startReturnOutput(command *exec.Cmd) (io.Reader, io.Reader, error) {\n\treaderStdout, err := command.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treaderStderr, err := command.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = command.Start()\n\tif err != nil {\n\n\t\tdefer readerStdout.Close()\n\t\tdefer readerStderr.Close()\n\t\treturn nil, nil, err\n\t}\n\treturn readerStdout, readerStderr, nil\n}\n\nfunc buildCreateCommand(machine *client.Machine, machineDir string) (*exec.Cmd, error) {\n\tcmdArgs, err := buildMachineCreateCmd(machine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommand := buildCommand(machineDir, cmdArgs)\n\treturn command, nil\n}\n\nfunc buildMachineCreateCmd(machine *client.Machine) ([]string, error) {\n\tsDriver := strings.ToLower(machine.Driver)\n\tcmd := []string{\"create\", \"-d\", sDriver}\n\n\tvalueOfMachine := reflect.ValueOf(machine).Elem()\n\n\t\/\/ Grab the reflected Value of XyzConfig (i.e. DigitaloceanConfig) based on the machine driver\n\tdriverConfig := valueOfMachine.FieldByName(strings.ToUpper(sDriver[:1]) + sDriver[1:] + \"Config\").Elem()\n\ttypeOfDriverConfig := driverConfig.Type()\n\n\tfor i := 0; i < driverConfig.NumField(); i++ {\n\t\t\/\/ We are ignoring the Resource Field as we don't need it.\n\t\tnameConfigField := typeOfDriverConfig.Field(i).Name\n\t\tif nameConfigField == \"Resource\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tf := driverConfig.Field(i)\n\n\t\t\/\/ This converts all field name of ParameterName to ---parameter-name\n\t\t\/\/ i.e. AccessToken parameter for DigitalOcean driver becomes --digitalocean-access-token\n\t\tdmField := \"--\" + sDriver + \"-\" + strings.ToLower(regExHyphen.ReplaceAllString(nameConfigField, \"${1}-${2}\"))\n\n\t\t\/\/ For now, we only support bool and string. Will add more as required.\n\t\tswitch f.Interface().(type) {\n\t\tcase bool:\n\t\t\t\/\/ dm only accepts field or field=true if value=true\n\t\t\tif f.Bool() {\n\t\t\t\tcmd = append(cmd, dmField)\n\t\t\t}\n\t\tcase string:\n\t\t\tif f.String() != \"\" {\n\t\t\t\tcmd = append(cmd, dmField, f.String())\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Unsupported type: %v\", f.Type())\n\t\t}\n\n\t}\n\n\tcmd = append(cmd, machine.Name)\n\tlog.Infof(\"Cmd slice: %v\", cmd)\n\treturn cmd, nil\n}\nstart parsing string slices as wellpackage handlers\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/rancher\/go-machine-service\/events\"\n\t\"github.com\/rancher\/go-machine-service\/handlers\/providers\"\n\t\"github.com\/rancher\/go-rancher\/client\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tlevelInfo = \"level=\\\"info\\\"\"\n\tlevelError = \"level=\\\"error\\\"\"\n\terrorCreatingMachine = \"Error creating machine: \"\n\tCREATED_FILE = \"created\"\n)\n\nvar regExDockerMsg = regexp.MustCompile(\"msg=.*\")\nvar regExHyphen = regexp.MustCompile(\"([a-z])([A-Z])\")\n\nfunc CreateMachine(event *events.Event, apiClient *client.RancherClient) (err error) {\n\tlog.WithFields(log.Fields{\n\t\t\"resourceId\": event.ResourceId,\n\t\t\"eventId\": event.Id,\n\t}).Info(\"Creating Machine\")\n\n\tmachine, err := getMachine(event.ResourceId, apiClient)\n\tif err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\t\/\/ Idempotency. If the resource has the property, we're done.\n\tif _, ok := machine.Data[machineDirField]; ok {\n\t\treply := newReply(event)\n\t\treturn publishReply(reply, apiClient)\n\t}\n\n\tmachineDir, err := buildBaseMachineDir(machine.ExternalId)\n\tif err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcleanupResources(machineDir, machine.Name)\n\t\t}\n\t}()\n\n\tdataUpdates := map[string]interface{}{machineDirField: machineDir}\n\teventDataWrapper := map[string]interface{}{\"+data\": dataUpdates}\n\n\t\/\/Idempotency, if the same request is sent, without the machineDir & extractedConfig Field, we need to handle that\n\tif _, err := os.Stat(filepath.Join(machineDir, \"machines\", machine.Name, CREATED_FILE)); !os.IsNotExist(err) {\n\t\textractedConfig, extractionErr := getIdempotentExtractedConfig(machine, machineDir, apiClient)\n\t\tif extractionErr != nil {\n\t\t\treturn handleByIdError(extractionErr, event, apiClient)\n\t\t}\n\t\tdataUpdates[\"+fields\"] = map[string]interface{}{\"extractedConfig\": extractedConfig}\n\t\treply := newReply(event)\n\t\treply.Data = eventDataWrapper\n\t\treturn publishReply(reply, apiClient)\n\t}\n\n\tproviderHandler := providers.GetProviderHandler(machine.Driver)\n\n\tif err := providerHandler.HandleCreate(machine, machineDir); err != nil {\n\t\treturn handleByIdError(err, event, apiClient)\n\t}\n\n\tcommand, err := buildCreateCommand(machine, machineDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/Setup republishing timer\n\tpublishChan := make(chan string, 10)\n\tgo republishTransitioningReply(publishChan, event, apiClient)\n\n\tpublishChan <- \"Contacting \" + machine.Driver\n\talreadyClosed := false\n\tdefer func() {\n\t\tif !alreadyClosed {\n\t\t\tclose(publishChan)\n\t\t}\n\t}()\n\n\treaderStdout, readerStderr, err := startReturnOutput(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrChan := make(chan string, 1)\n\tgo logProgress(readerStdout, readerStderr, publishChan, machine, event, errChan, providerHandler)\n\n\terr = command.Wait()\n\n\tif err != nil {\n\t\tselect {\n\t\tcase errString := <-errChan:\n\t\t\tif errString != \"\" {\n\t\t\t\treturn fmt.Errorf(errString)\n\t\t\t}\n\t\tcase <-time.After(10 * time.Second):\n\t\t\tlog.Error(\"Waited 10 seconds to break after command.Wait(). Please review logProgress.\")\n\t\t}\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"resourceId\": event.ResourceId,\n\t\t\"machineExternalId\": machine.ExternalId,\n\t}).Info(\"Machine Created\")\n\n\tif f, err := os.Create(filepath.Join(machineDir, \"machines\", machine.Name, CREATED_FILE)); err != nil {\n\t\treturn err\n\t} else {\n\t\tf.Close()\n\t}\n\n\tdestFile, err := createExtractedConfig(event, machine)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif destFile != \"\" {\n\t\tpublishChan <- \"Saving Machine Config\"\n\t\textractedConf, err := getExtractedConfig(destFile, machine, apiClient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdataUpdates[\"+fields\"] = map[string]string{\"extractedConfig\": extractedConf}\n\t}\n\n\treply := newReply(event)\n\treply.Data = eventDataWrapper\n\n\t\/\/ Explicitly close publish channel so that it doesn't conflict with final reply\n\tclose(publishChan)\n\talreadyClosed = true\n\treturn publishReply(reply, apiClient)\n}\n\nfunc logProgress(readerStdout io.Reader, readerStderr io.Reader, publishChan chan<- string, machine *client.Machine, event *events.Event, errChan chan<- string, providerHandler providers.Provider) {\n\t\/\/ We will just log stdout first, then stderr, ignoring all errors.\n\tdefer close(errChan)\n\tscanner := bufio.NewScanner(readerStdout)\n\tfor scanner.Scan() {\n\t\tmsg := scanner.Text()\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"resourceId: \": event.ResourceId,\n\t\t}).Infof(\"stdout: %s\", msg)\n\t\ttransitionMsg := filterDockerMessage(msg, machine, errChan, providerHandler)\n\t\tif transitionMsg != \"\" {\n\t\t\tpublishChan <- transitionMsg\n\t\t}\n\t}\n\tscanner = bufio.NewScanner(readerStderr)\n\tfor scanner.Scan() {\n\t\tmsg := scanner.Text()\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"resourceId\": event.ResourceId,\n\t\t}).Infof(\"stderr: %s\", msg)\n\t\tfilterDockerMessage(msg, machine, errChan, providerHandler)\n\t}\n}\n\nfunc filterDockerMessage(msg string, machine *client.Machine, errChan chan<- string, providerHandler providers.Provider) string {\n\tif strings.Contains(msg, errorCreatingMachine) {\n\t\terrChan <- providerHandler.HandleError(strings.Replace(msg, errorCreatingMachine, \"\", 1))\n\t\treturn \"\"\n\t}\n\tif strings.Contains(msg, machine.ExternalId) || strings.Contains(msg, machine.Name) {\n\t\treturn \"\"\n\t}\n\treturn msg\n}\n\nfunc startReturnOutput(command *exec.Cmd) (io.Reader, io.Reader, error) {\n\treaderStdout, err := command.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treaderStderr, err := command.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = command.Start()\n\tif err != nil {\n\n\t\tdefer readerStdout.Close()\n\t\tdefer readerStderr.Close()\n\t\treturn nil, nil, err\n\t}\n\treturn readerStdout, readerStderr, nil\n}\n\nfunc buildCreateCommand(machine *client.Machine, machineDir string) (*exec.Cmd, error) {\n\tcmdArgs, err := buildMachineCreateCmd(machine)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommand := buildCommand(machineDir, cmdArgs)\n\treturn command, nil\n}\n\nfunc buildMachineCreateCmd(machine *client.Machine) ([]string, error) {\n\tsDriver := strings.ToLower(machine.Driver)\n\tcmd := []string{\"create\", \"-d\", sDriver}\n\n\tvalueOfMachine := reflect.ValueOf(machine).Elem()\n\n\t\/\/ Grab the reflected Value of XyzConfig (i.e. DigitaloceanConfig) based on the machine driver\n\tdriverConfig := valueOfMachine.FieldByName(strings.ToUpper(sDriver[:1]) + sDriver[1:] + \"Config\").Elem()\n\ttypeOfDriverConfig := driverConfig.Type()\n\n\tfor i := 0; i < driverConfig.NumField(); i++ {\n\t\t\/\/ We are ignoring the Resource Field as we don't need it.\n\t\tnameConfigField := typeOfDriverConfig.Field(i).Name\n\t\tif nameConfigField == \"Resource\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tf := driverConfig.Field(i)\n\n\t\t\/\/ This converts all field name of ParameterName to ---parameter-name\n\t\t\/\/ i.e. AccessToken parameter for DigitalOcean driver becomes --digitalocean-access-token\n\t\tdmField := \"--\" + sDriver + \"-\" + strings.ToLower(regExHyphen.ReplaceAllString(nameConfigField, \"${1}-${2}\"))\n\n\t\t\/\/ For now, we only support bool and string. Will add more as required.\n\t\tswitch f.Interface().(type) {\n\t\tcase bool:\n\t\t\t\/\/ dm only accepts field or field=true if value=true\n\t\t\tif f.Bool() {\n\t\t\t\tcmd = append(cmd, dmField)\n\t\t\t}\n\t\tcase string:\n\t\t\tif f.String() != \"\" {\n\t\t\t\tcmd = append(cmd, dmField, f.String())\n\t\t\t}\n\t\tcase []string:\n\t\t\tfor i := 0; i < f.Len(); i++ {\n\t\t\t\tcmd = append(cmd, dmField, f.Index(i).String())\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Unsupported type: %v\", f.Type())\n\t\t}\n\n\t}\n\n\tcmd = append(cmd, machine.Name)\n\tlog.Infof(\"Cmd slice: %v\", cmd)\n\treturn cmd, nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage migration\n\nimport (\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/version\"\n\n\t\"github.com\/juju\/juju\/tools\"\n)\n\n\/\/ PrecheckBackend defines the interface to query Juju's state\n\/\/ for migration prechecks.\ntype PrecheckBackend interface {\n\tNeedsCleanup() (bool, error)\n\tAgentVersion() (version.Number, error)\n\tAllMachines() ([]PrecheckMachine, error)\n}\n\n\/\/ PrecheckMachine describes state interface for a machine needed by\n\/\/ migration prechecks.\ntype PrecheckMachine interface {\n\tId() string\n\tAgentTools() (*tools.Tools, error)\n}\n\n\/\/ SourcePrecheck checks the state of the source controller to make\n\/\/ sure that the preconditions for model migration are met. The\n\/\/ backend provided must be for the model to be migrated.\nfunc SourcePrecheck(backend PrecheckBackend) error {\n\tcleanupNeeded, err := backend.NeedsCleanup()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"checking cleanups\")\n\t}\n\tif cleanupNeeded {\n\t\treturn errors.New(\"cleanup needed\")\n\t}\n\n\tmodelVersion, err := backend.AgentVersion()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"retrieving model version\")\n\t}\n\n\tmachines, err := backend.AllMachines()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"retrieving machines\")\n\t}\n\tfor _, machine := range machines {\n\t\ttools, err := machine.AgentTools()\n\t\tif err != nil {\n\t\t\treturn errors.Annotatef(err, \"retrieving tools for machine %s\", machine.Id())\n\t\t}\n\t\tmachineVersion := tools.Version.Number\n\t\tif machineVersion != modelVersion {\n\t\t\treturn errors.Errorf(\"machine %s tools don't match model (%s != %s)\",\n\t\t\t\tmachine.Id(), machineVersion, modelVersion)\n\t\t}\n\t}\n\n\treturn nil\n}\nmigration: Add list of prechecks to implement\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage migration\n\nimport (\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/version\"\n\n\t\"github.com\/juju\/juju\/tools\"\n)\n\n\/*\n# TODO - remaining prechecks\n\n## Source model\n\n- model machines have errors\n- machines that are dying or dead\n- pending reboots\n- machine or unit is being provisioned\n- application is being provisioned?\n- units that are dying or dead\n- model is being imported as part of another migration\n\n## Source controller\n\n- controller is upgrading\n * all machine versions must match agent version\n\n- source controller has upgrade info doc (IsUpgrading)\n- controller machines have errors\n- controller machines that are dying or dead\n- pending reboots\n\n## Target controller\n\n- target controller tools are less than source model tools\n\n- target controller is upgrading\n * all machine versions must match agent version\n\n- source controller has upgrade info doc (IsUpgrading)\n\n- target controller machines have errors\n- target controller already has a model with the same owner:name\n- target controller already has a model with the same UUID\n - what about if left over from previous failed attempt?\n\n*\/\n\n\/\/ PrecheckBackend defines the interface to query Juju's state\n\/\/ for migration prechecks.\ntype PrecheckBackend interface {\n\tNeedsCleanup() (bool, error)\n\tAgentVersion() (version.Number, error)\n\tAllMachines() ([]PrecheckMachine, error)\n}\n\n\/\/ PrecheckMachine describes state interface for a machine needed by\n\/\/ migration prechecks.\ntype PrecheckMachine interface {\n\tId() string\n\tAgentTools() (*tools.Tools, error)\n}\n\n\/\/ SourcePrecheck checks the state of the source controller to make\n\/\/ sure that the preconditions for model migration are met. The\n\/\/ backend provided must be for the model to be migrated.\nfunc SourcePrecheck(backend PrecheckBackend) error {\n\tcleanupNeeded, err := backend.NeedsCleanup()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"checking cleanups\")\n\t}\n\tif cleanupNeeded {\n\t\treturn errors.New(\"cleanup needed\")\n\t}\n\n\tmodelVersion, err := backend.AgentVersion()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"retrieving model version\")\n\t}\n\n\tmachines, err := backend.AllMachines()\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"retrieving machines\")\n\t}\n\tfor _, machine := range machines {\n\t\ttools, err := machine.AgentTools()\n\t\tif err != nil {\n\t\t\treturn errors.Annotatef(err, \"retrieving tools for machine %s\", machine.Id())\n\t\t}\n\t\tmachineVersion := tools.Version.Number\n\t\tif machineVersion != modelVersion {\n\t\t\treturn errors.Errorf(\"machine %s tools don't match model (%s != %s)\",\n\t\t\t\tmachine.Id(), machineVersion, modelVersion)\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package msdns\n\nimport (\n\t\"encoding\/json\"\n\t\"runtime\"\n\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/models\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/pkg\/printer\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/pkg\/txtutil\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/providers\"\n)\n\n\/\/ This is the struct that matches either (or both) of the Registrar and\/or DNSProvider interfaces:\ntype msdnsProvider struct {\n\tdnsserver string \/\/ Which DNS Server to update\n\tpssession string \/\/ Remote machine to PSSession to\n\tpsusername string \/\/ Remote username for PSSession\n\tpspassword string \/\/ Remote password for PSSession\n\tshell DNSAccessor \/\/ Handle for\u001a\u001a\n}\n\nvar features = providers.DocumentationNotes{\n\tproviders.CanGetZones: providers.Can(),\n\tproviders.CanUseAlias: providers.Cannot(),\n\tproviders.CanUseCAA: providers.Cannot(),\n\tproviders.CanUseDS: providers.Unimplemented(),\n\tproviders.CanUseNAPTR: providers.Can(),\n\tproviders.CanUsePTR: providers.Can(),\n\tproviders.CanUseSRV: providers.Can(),\n\tproviders.CanUseTLSA: providers.Unimplemented(),\n\tproviders.DocCreateDomains: providers.Cannot(\"This provider assumes the zone already existing on the dns server\"),\n\tproviders.DocDualHost: providers.Cannot(\"This driver does not manage NS records, so should not be used for dual-host scenarios\"),\n\tproviders.DocOfficiallySupported: providers.Can(),\n}\n\n\/\/ Register with the dnscontrol system.\n\/\/\n\/\/\tThis establishes the name (all caps), and the function to call to initialize it.\nfunc init() {\n\tfns := providers.DspFuncs{\n\t\tInitializer: newDNS,\n\t\tRecordAuditor: AuditRecords,\n\t}\n\tproviders.RegisterDomainServiceProviderType(\"MSDNS\", fns, features)\n}\n\nfunc newDNS(config map[string]string, metadata json.RawMessage) (providers.DNSServiceProvider, error) {\n\n\tif runtime.GOOS != \"windows\" {\n\t\tprinter.Println(\"INFO: PowerShell not available. Disabling Active Directory provider.\")\n\t\treturn providers.None{}, nil\n\t}\n\n\tvar err error\n\n\tp := &msdnsProvider{\n\t\tdnsserver: config[\"dnsserver\"],\n\t\tpssession: config[\"pssession\"],\n\t\tpsusername: config[\"psusername\"],\n\t\tpspassword: config[\"pspassword\"],\n\t}\n\tp.shell, err = newPowerShell(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Section 3: Domain Service Provider (DSP) related functions\n\n\/\/ NB(tal): To future-proof your code, all new providers should\n\/\/ implement GetDomainCorrections exactly as you see here\n\/\/ (byte-for-byte the same). In 3.0\n\/\/ we plan on using just the individual calls to GetZoneRecords,\n\/\/ PostProcessRecords, and so on.\n\/\/\n\/\/ Currently every provider does things differently, which prevents\n\/\/ us from doing things like using GetZoneRecords() of a provider\n\/\/ to make convertzone work with all providers.\n\n\/\/ GetDomainCorrections get the current and existing records,\n\/\/ post-process them, and generate corrections.\nfunc (client *msdnsProvider) GetDomainCorrections(dc *models.DomainConfig) ([]*models.Correction, error) {\n\texisting, err := client.GetZoneRecords(dc.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodels.PostProcessRecords(existing)\n\ttxtutil.SplitSingleLongTxt(dc.Records) \/\/ Autosplit long TXT records\n\n\tclean := PrepFoundRecords(existing)\n\tPrepDesiredRecords(dc)\n\treturn client.GenerateDomainCorrections(dc, clean)\n}\n\n\/\/ GetZoneRecords gathers the DNS records and converts them to\n\/\/ dnscontrol's format.\nfunc (client *msdnsProvider) GetZoneRecords(domain string) (models.Records, error) {\n\n\t\/\/ Get the existing DNS records in native format.\n\tnativeExistingRecords, err := client.shell.GetDNSZoneRecords(client.dnsserver, domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Convert them to DNScontrol's native format:\n\texistingRecords := make([]*models.RecordConfig, 0, len(nativeExistingRecords))\n\tfor _, rr := range nativeExistingRecords {\n\t\trc, err := nativeToRecords(rr, domain)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif rc != nil {\n\t\t\texistingRecords = append(existingRecords, rc)\n\t\t}\n\t}\n\n\treturn existingRecords, nil\n}\n\n\/\/ PrepFoundRecords munges any records to make them compatible with\n\/\/ this provider. Usually this is a no-op.\nfunc PrepFoundRecords(recs models.Records) models.Records {\n\t\/\/ If there are records that need to be modified, removed, etc. we\n\t\/\/ do it here. Usually this is a no-op.\n\treturn recs\n}\n\n\/\/ PrepDesiredRecords munges any records to best suit this provider.\nfunc PrepDesiredRecords(dc *models.DomainConfig) {\n\t\/\/ Sort through the dc.Records, eliminate any that can't be\n\t\/\/ supported; modify any that need adjustments to work with the\n\t\/\/ provider. We try to do minimal changes otherwise it gets\n\t\/\/ confusing.\n\n\tdc.Punycode()\n}\n\n\/\/ NB(tlim): If we want to implement a registrar, refer to\n\/\/ http:\/\/go.microsoft.com\/fwlink\/?LinkId=288158\n\/\/ (Get-DnsServerZoneDelegation) for hints about which PowerShell\n\/\/ commands to use.\nMSDNS: MSDNS auto-disable message is now more accurate (#1719)package msdns\n\nimport (\n\t\"encoding\/json\"\n\t\"runtime\"\n\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/models\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/pkg\/printer\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/pkg\/txtutil\"\n\t\"github.com\/StackExchange\/dnscontrol\/v3\/providers\"\n)\n\n\/\/ This is the struct that matches either (or both) of the Registrar and\/or DNSProvider interfaces:\ntype msdnsProvider struct {\n\tdnsserver string \/\/ Which DNS Server to update\n\tpssession string \/\/ Remote machine to PSSession to\n\tpsusername string \/\/ Remote username for PSSession\n\tpspassword string \/\/ Remote password for PSSession\n\tshell DNSAccessor \/\/ Handle for\u001a\u001a\n}\n\nvar features = providers.DocumentationNotes{\n\tproviders.CanGetZones: providers.Can(),\n\tproviders.CanUseAlias: providers.Cannot(),\n\tproviders.CanUseCAA: providers.Cannot(),\n\tproviders.CanUseDS: providers.Unimplemented(),\n\tproviders.CanUseNAPTR: providers.Can(),\n\tproviders.CanUsePTR: providers.Can(),\n\tproviders.CanUseSRV: providers.Can(),\n\tproviders.CanUseTLSA: providers.Unimplemented(),\n\tproviders.DocCreateDomains: providers.Cannot(\"This provider assumes the zone already existing on the dns server\"),\n\tproviders.DocDualHost: providers.Cannot(\"This driver does not manage NS records, so should not be used for dual-host scenarios\"),\n\tproviders.DocOfficiallySupported: providers.Can(),\n}\n\n\/\/ Register with the dnscontrol system.\n\/\/\n\/\/\tThis establishes the name (all caps), and the function to call to initialize it.\nfunc init() {\n\tfns := providers.DspFuncs{\n\t\tInitializer: newDNS,\n\t\tRecordAuditor: AuditRecords,\n\t}\n\tproviders.RegisterDomainServiceProviderType(\"MSDNS\", fns, features)\n}\n\nfunc newDNS(config map[string]string, metadata json.RawMessage) (providers.DNSServiceProvider, error) {\n\n\tif runtime.GOOS != \"windows\" {\n\t\tprinter.Println(\"INFO: MSDNS deactivated. Required OS not detected.\")\n\t\treturn providers.None{}, nil\n\t}\n\n\tvar err error\n\n\tp := &msdnsProvider{\n\t\tdnsserver: config[\"dnsserver\"],\n\t\tpssession: config[\"pssession\"],\n\t\tpsusername: config[\"psusername\"],\n\t\tpspassword: config[\"pspassword\"],\n\t}\n\tp.shell, err = newPowerShell(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Section 3: Domain Service Provider (DSP) related functions\n\n\/\/ NB(tal): To future-proof your code, all new providers should\n\/\/ implement GetDomainCorrections exactly as you see here\n\/\/ (byte-for-byte the same). In 3.0\n\/\/ we plan on using just the individual calls to GetZoneRecords,\n\/\/ PostProcessRecords, and so on.\n\/\/\n\/\/ Currently every provider does things differently, which prevents\n\/\/ us from doing things like using GetZoneRecords() of a provider\n\/\/ to make convertzone work with all providers.\n\n\/\/ GetDomainCorrections get the current and existing records,\n\/\/ post-process them, and generate corrections.\nfunc (client *msdnsProvider) GetDomainCorrections(dc *models.DomainConfig) ([]*models.Correction, error) {\n\texisting, err := client.GetZoneRecords(dc.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodels.PostProcessRecords(existing)\n\ttxtutil.SplitSingleLongTxt(dc.Records) \/\/ Autosplit long TXT records\n\n\tclean := PrepFoundRecords(existing)\n\tPrepDesiredRecords(dc)\n\treturn client.GenerateDomainCorrections(dc, clean)\n}\n\n\/\/ GetZoneRecords gathers the DNS records and converts them to\n\/\/ dnscontrol's format.\nfunc (client *msdnsProvider) GetZoneRecords(domain string) (models.Records, error) {\n\n\t\/\/ Get the existing DNS records in native format.\n\tnativeExistingRecords, err := client.shell.GetDNSZoneRecords(client.dnsserver, domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Convert them to DNScontrol's native format:\n\texistingRecords := make([]*models.RecordConfig, 0, len(nativeExistingRecords))\n\tfor _, rr := range nativeExistingRecords {\n\t\trc, err := nativeToRecords(rr, domain)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif rc != nil {\n\t\t\texistingRecords = append(existingRecords, rc)\n\t\t}\n\t}\n\n\treturn existingRecords, nil\n}\n\n\/\/ PrepFoundRecords munges any records to make them compatible with\n\/\/ this provider. Usually this is a no-op.\nfunc PrepFoundRecords(recs models.Records) models.Records {\n\t\/\/ If there are records that need to be modified, removed, etc. we\n\t\/\/ do it here. Usually this is a no-op.\n\treturn recs\n}\n\n\/\/ PrepDesiredRecords munges any records to best suit this provider.\nfunc PrepDesiredRecords(dc *models.DomainConfig) {\n\t\/\/ Sort through the dc.Records, eliminate any that can't be\n\t\/\/ supported; modify any that need adjustments to work with the\n\t\/\/ provider. We try to do minimal changes otherwise it gets\n\t\/\/ confusing.\n\n\tdc.Punycode()\n}\n\n\/\/ NB(tlim): If we want to implement a registrar, refer to\n\/\/ http:\/\/go.microsoft.com\/fwlink\/?LinkId=288158\n\/\/ (Get-DnsServerZoneDelegation) for hints about which PowerShell\n\/\/ commands to use.\n<|endoftext|>"} {"text":"package b2\n\nimport (\n\t\"context\"\n\t\"hash\"\n\t\"io\"\n\t\"net\/http\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/restic\/restic\/internal\/backend\"\n\t\"github.com\/restic\/restic\/internal\/backend\/sema\"\n\t\"github.com\/restic\/restic\/internal\/debug\"\n\t\"github.com\/restic\/restic\/internal\/errors\"\n\t\"github.com\/restic\/restic\/internal\/restic\"\n\n\t\"github.com\/cenkalti\/backoff\/v4\"\n\t\"github.com\/kurin\/blazer\/b2\"\n)\n\n\/\/ b2Backend is a backend which stores its data on Backblaze B2.\ntype b2Backend struct {\n\tclient *b2.Client\n\tbucket *b2.Bucket\n\tcfg Config\n\tlistMaxItems int\n\tbackend.Layout\n\tsem sema.Semaphore\n}\n\n\/\/ Billing happens in 1000 item granlarity, but we are more interested in reducing the number of network round trips\nconst defaultListMaxItems = 10 * 1000\n\n\/\/ ensure statically that *b2Backend implements restic.Backend.\nvar _ restic.Backend = &b2Backend{}\n\nfunc newClient(ctx context.Context, cfg Config, rt http.RoundTripper) (*b2.Client, error) {\n\topts := []b2.ClientOption{b2.Transport(rt)}\n\n\t\/\/ if the connection B2 fails, this can cause the client to hang\n\t\/\/ cancel the connection after a minute to at least provide some feedback to the user\n\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\tdefer cancel()\n\tc, err := b2.NewClient(ctx, cfg.AccountID, cfg.Key.Unwrap(), opts...)\n\tif err == context.DeadlineExceeded {\n\t\treturn nil, errors.New(\"connection to B2 failed\")\n\t} else if err != nil {\n\t\treturn nil, errors.Wrap(err, \"b2.NewClient\")\n\t}\n\treturn c, nil\n}\n\n\/\/ Open opens a connection to the B2 service.\nfunc Open(ctx context.Context, cfg Config, rt http.RoundTripper) (restic.Backend, error) {\n\tdebug.Log(\"cfg %#v\", cfg)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tclient, err := newClient(ctx, cfg, rt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbucket, err := client.Bucket(ctx, cfg.Bucket)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Bucket\")\n\t}\n\n\tsem, err := sema.New(cfg.Connections)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe := &b2Backend{\n\t\tclient: client,\n\t\tbucket: bucket,\n\t\tcfg: cfg,\n\t\tLayout: &backend.DefaultLayout{\n\t\t\tJoin: path.Join,\n\t\t\tPath: cfg.Prefix,\n\t\t},\n\t\tlistMaxItems: defaultListMaxItems,\n\t\tsem: sem,\n\t}\n\n\treturn be, nil\n}\n\n\/\/ Create opens a connection to the B2 service. If the bucket does not exist yet,\n\/\/ it is created.\nfunc Create(ctx context.Context, cfg Config, rt http.RoundTripper) (restic.Backend, error) {\n\tdebug.Log(\"cfg %#v\", cfg)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tclient, err := newClient(ctx, cfg, rt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tattr := b2.BucketAttrs{\n\t\tType: b2.Private,\n\t}\n\tbucket, err := client.NewBucket(ctx, cfg.Bucket, &attr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"NewBucket\")\n\t}\n\n\tsem, err := sema.New(cfg.Connections)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe := &b2Backend{\n\t\tclient: client,\n\t\tbucket: bucket,\n\t\tcfg: cfg,\n\t\tLayout: &backend.DefaultLayout{\n\t\t\tJoin: path.Join,\n\t\t\tPath: cfg.Prefix,\n\t\t},\n\t\tlistMaxItems: defaultListMaxItems,\n\t\tsem: sem,\n\t}\n\n\tpresent, err := be.Test(ctx, restic.Handle{Type: restic.ConfigFile})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif present {\n\t\treturn nil, errors.New(\"config already exists\")\n\t}\n\n\treturn be, nil\n}\n\n\/\/ SetListMaxItems sets the number of list items to load per request.\nfunc (be *b2Backend) SetListMaxItems(i int) {\n\tbe.listMaxItems = i\n}\n\nfunc (be *b2Backend) Connections() uint {\n\treturn be.cfg.Connections\n}\n\n\/\/ Location returns the location for the backend.\nfunc (be *b2Backend) Location() string {\n\treturn be.cfg.Bucket\n}\n\n\/\/ Hasher may return a hash function for calculating a content hash for the backend\nfunc (be *b2Backend) Hasher() hash.Hash {\n\treturn nil\n}\n\n\/\/ HasAtomicReplace returns whether Save() can atomically replace files\nfunc (be *b2Backend) HasAtomicReplace() bool {\n\treturn true\n}\n\n\/\/ IsNotExist returns true if the error is caused by a non-existing file.\nfunc (be *b2Backend) IsNotExist(err error) bool {\n\treturn b2.IsNotExist(errors.Cause(err))\n}\n\n\/\/ Load runs fn with a reader that yields the contents of the file at h at the\n\/\/ given offset.\nfunc (be *b2Backend) Load(ctx context.Context, h restic.Handle, length int, offset int64, fn func(rd io.Reader) error) error {\n\treturn backend.DefaultLoad(ctx, h, length, offset, be.openReader, fn)\n}\n\nfunc (be *b2Backend) openReader(ctx context.Context, h restic.Handle, length int, offset int64) (io.ReadCloser, error) {\n\tdebug.Log(\"Load %v, length %v, offset %v from %v\", h, length, offset, be.Filename(h))\n\tif err := h.Valid(); err != nil {\n\t\treturn nil, backoff.Permanent(err)\n\t}\n\n\tif offset < 0 {\n\t\treturn nil, errors.New(\"offset is negative\")\n\t}\n\n\tif length < 0 {\n\t\treturn nil, errors.Errorf(\"invalid length %d\", length)\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\n\tbe.sem.GetToken()\n\n\tname := be.Layout.Filename(h)\n\tobj := be.bucket.Object(name)\n\n\tif offset == 0 && length == 0 {\n\t\trd := obj.NewReader(ctx)\n\t\treturn be.sem.ReleaseTokenOnClose(rd, cancel), nil\n\t}\n\n\t\/\/ pass a negative length to NewRangeReader so that the remainder of the\n\t\/\/ file is read.\n\tif length == 0 {\n\t\tlength = -1\n\t}\n\n\trd := obj.NewRangeReader(ctx, offset, int64(length))\n\treturn be.sem.ReleaseTokenOnClose(rd, cancel), nil\n}\n\n\/\/ Save stores data in the backend at the handle.\nfunc (be *b2Backend) Save(ctx context.Context, h restic.Handle, rd restic.RewindReader) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tif err := h.Valid(); err != nil {\n\t\treturn backoff.Permanent(err)\n\t}\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tname := be.Filename(h)\n\tdebug.Log(\"Save %v, name %v\", h, name)\n\tobj := be.bucket.Object(name)\n\n\t\/\/ b2 always requires sha1 checksums for uploaded file parts\n\tw := obj.NewWriter(ctx)\n\tn, err := io.Copy(w, rd)\n\tdebug.Log(\" saved %d bytes, err %v\", n, err)\n\n\tif err != nil {\n\t\t_ = w.Close()\n\t\treturn errors.Wrap(err, \"Copy\")\n\t}\n\n\t\/\/ sanity check\n\tif n != rd.Length() {\n\t\treturn errors.Errorf(\"wrote %d bytes instead of the expected %d bytes\", n, rd.Length())\n\t}\n\treturn errors.Wrap(w.Close(), \"Close\")\n}\n\n\/\/ Stat returns information about a blob.\nfunc (be *b2Backend) Stat(ctx context.Context, h restic.Handle) (bi restic.FileInfo, err error) {\n\tdebug.Log(\"Stat %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tname := be.Filename(h)\n\tobj := be.bucket.Object(name)\n\tinfo, err := obj.Attrs(ctx)\n\tif err != nil {\n\t\tdebug.Log(\"Attrs() err %v\", err)\n\t\treturn restic.FileInfo{}, errors.Wrap(err, \"Stat\")\n\t}\n\treturn restic.FileInfo{Size: info.Size, Name: h.Name}, nil\n}\n\n\/\/ Test returns true if a blob of the given type and name exists in the backend.\nfunc (be *b2Backend) Test(ctx context.Context, h restic.Handle) (bool, error) {\n\tdebug.Log(\"Test %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tfound := false\n\tname := be.Filename(h)\n\tobj := be.bucket.Object(name)\n\tinfo, err := obj.Attrs(ctx)\n\tif err == nil && info != nil && info.Status == b2.Uploaded {\n\t\tfound = true\n\t}\n\treturn found, nil\n}\n\n\/\/ Remove removes the blob with the given name and type.\nfunc (be *b2Backend) Remove(ctx context.Context, h restic.Handle) error {\n\tdebug.Log(\"Remove %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\t\/\/ the retry backend will also repeat the remove method up to 10 times\n\tfor i := 0; i < 3; i++ {\n\t\tobj := be.bucket.Object(be.Filename(h))\n\t\terr := obj.Delete(ctx)\n\t\tif err == nil {\n\t\t\t\/\/ keep deleting until we are sure that no leftover file versions exist\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ consider a file as removed if b2 informs us that it does not exist\n\t\tif b2.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"Delete\")\n\t}\n\n\treturn errors.New(\"failed to delete all file versions\")\n}\n\ntype semLocker struct {\n\tsema.Semaphore\n}\n\nfunc (sm *semLocker) Lock() { sm.GetToken() }\nfunc (sm *semLocker) Unlock() { sm.ReleaseToken() }\n\n\/\/ List returns a channel that yields all names of blobs of type t.\nfunc (be *b2Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {\n\tdebug.Log(\"List %v\", t)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tprefix, _ := be.Basedir(t)\n\titer := be.bucket.List(ctx, b2.ListPrefix(prefix), b2.ListPageSize(be.listMaxItems), b2.ListLocker(&semLocker{be.sem}))\n\n\tfor iter.Next() {\n\t\tobj := iter.Object()\n\n\t\tattrs, err := obj.Attrs(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfi := restic.FileInfo{\n\t\t\tName: path.Base(obj.Name()),\n\t\t\tSize: attrs.Size,\n\t\t}\n\n\t\tif err := fn(fi); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := iter.Err(); err != nil {\n\t\tdebug.Log(\"List: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Remove keys for a specified backend type.\nfunc (be *b2Backend) removeKeys(ctx context.Context, t restic.FileType) error {\n\tdebug.Log(\"removeKeys %v\", t)\n\treturn be.List(ctx, t, func(fi restic.FileInfo) error {\n\t\treturn be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})\n\t})\n}\n\n\/\/ Delete removes all restic keys in the bucket. It will not remove the bucket itself.\nfunc (be *b2Backend) Delete(ctx context.Context) error {\n\talltypes := []restic.FileType{\n\t\trestic.PackFile,\n\t\trestic.KeyFile,\n\t\trestic.LockFile,\n\t\trestic.SnapshotFile,\n\t\trestic.IndexFile}\n\n\tfor _, t := range alltypes {\n\t\terr := be.removeKeys(ctx, t)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\terr := be.Remove(ctx, restic.Handle{Type: restic.ConfigFile})\n\tif err != nil && b2.IsNotExist(errors.Cause(err)) {\n\t\terr = nil\n\t}\n\n\treturn err\n}\n\n\/\/ Close does nothing\nfunc (be *b2Backend) Close() error { return nil }\nb2: sniff the error that caused init retry loopspackage b2\n\nimport (\n\t\"context\"\n\t\"hash\"\n\t\"io\"\n\t\"net\/http\"\n\t\"path\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/restic\/restic\/internal\/backend\"\n\t\"github.com\/restic\/restic\/internal\/backend\/sema\"\n\t\"github.com\/restic\/restic\/internal\/debug\"\n\t\"github.com\/restic\/restic\/internal\/errors\"\n\t\"github.com\/restic\/restic\/internal\/restic\"\n\n\t\"github.com\/cenkalti\/backoff\/v4\"\n\t\"github.com\/kurin\/blazer\/b2\"\n)\n\n\/\/ b2Backend is a backend which stores its data on Backblaze B2.\ntype b2Backend struct {\n\tclient *b2.Client\n\tbucket *b2.Bucket\n\tcfg Config\n\tlistMaxItems int\n\tbackend.Layout\n\tsem sema.Semaphore\n}\n\n\/\/ Billing happens in 1000 item granlarity, but we are more interested in reducing the number of network round trips\nconst defaultListMaxItems = 10 * 1000\n\n\/\/ ensure statically that *b2Backend implements restic.Backend.\nvar _ restic.Backend = &b2Backend{}\n\ntype sniffingRoundTripper struct {\n\tsync.Mutex\n\tlastErr error\n\thttp.RoundTripper\n}\n\nfunc (s *sniffingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tres, err := s.RoundTripper.RoundTrip(req)\n\tif err != nil {\n\t\ts.Lock()\n\t\ts.lastErr = err\n\t\ts.Unlock()\n\t}\n\treturn res, err\n}\n\nfunc newClient(ctx context.Context, cfg Config, rt http.RoundTripper) (*b2.Client, error) {\n\tsniffer := &sniffingRoundTripper{RoundTripper: rt}\n\topts := []b2.ClientOption{b2.Transport(sniffer)}\n\n\t\/\/ if the connection B2 fails, this can cause the client to hang\n\t\/\/ cancel the connection after a minute to at least provide some feedback to the user\n\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\tdefer cancel()\n\tc, err := b2.NewClient(ctx, cfg.AccountID, cfg.Key.Unwrap(), opts...)\n\tif err == context.DeadlineExceeded {\n\t\tif sniffer.lastErr != nil {\n\t\t\treturn nil, sniffer.lastErr\n\t\t}\n\t\treturn nil, errors.New(\"connection to B2 failed\")\n\t} else if err != nil {\n\t\treturn nil, errors.Wrap(err, \"b2.NewClient\")\n\t}\n\treturn c, nil\n}\n\n\/\/ Open opens a connection to the B2 service.\nfunc Open(ctx context.Context, cfg Config, rt http.RoundTripper) (restic.Backend, error) {\n\tdebug.Log(\"cfg %#v\", cfg)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tclient, err := newClient(ctx, cfg, rt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbucket, err := client.Bucket(ctx, cfg.Bucket)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Bucket\")\n\t}\n\n\tsem, err := sema.New(cfg.Connections)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe := &b2Backend{\n\t\tclient: client,\n\t\tbucket: bucket,\n\t\tcfg: cfg,\n\t\tLayout: &backend.DefaultLayout{\n\t\t\tJoin: path.Join,\n\t\t\tPath: cfg.Prefix,\n\t\t},\n\t\tlistMaxItems: defaultListMaxItems,\n\t\tsem: sem,\n\t}\n\n\treturn be, nil\n}\n\n\/\/ Create opens a connection to the B2 service. If the bucket does not exist yet,\n\/\/ it is created.\nfunc Create(ctx context.Context, cfg Config, rt http.RoundTripper) (restic.Backend, error) {\n\tdebug.Log(\"cfg %#v\", cfg)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tclient, err := newClient(ctx, cfg, rt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tattr := b2.BucketAttrs{\n\t\tType: b2.Private,\n\t}\n\tbucket, err := client.NewBucket(ctx, cfg.Bucket, &attr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"NewBucket\")\n\t}\n\n\tsem, err := sema.New(cfg.Connections)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe := &b2Backend{\n\t\tclient: client,\n\t\tbucket: bucket,\n\t\tcfg: cfg,\n\t\tLayout: &backend.DefaultLayout{\n\t\t\tJoin: path.Join,\n\t\t\tPath: cfg.Prefix,\n\t\t},\n\t\tlistMaxItems: defaultListMaxItems,\n\t\tsem: sem,\n\t}\n\n\tpresent, err := be.Test(ctx, restic.Handle{Type: restic.ConfigFile})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif present {\n\t\treturn nil, errors.New(\"config already exists\")\n\t}\n\n\treturn be, nil\n}\n\n\/\/ SetListMaxItems sets the number of list items to load per request.\nfunc (be *b2Backend) SetListMaxItems(i int) {\n\tbe.listMaxItems = i\n}\n\nfunc (be *b2Backend) Connections() uint {\n\treturn be.cfg.Connections\n}\n\n\/\/ Location returns the location for the backend.\nfunc (be *b2Backend) Location() string {\n\treturn be.cfg.Bucket\n}\n\n\/\/ Hasher may return a hash function for calculating a content hash for the backend\nfunc (be *b2Backend) Hasher() hash.Hash {\n\treturn nil\n}\n\n\/\/ HasAtomicReplace returns whether Save() can atomically replace files\nfunc (be *b2Backend) HasAtomicReplace() bool {\n\treturn true\n}\n\n\/\/ IsNotExist returns true if the error is caused by a non-existing file.\nfunc (be *b2Backend) IsNotExist(err error) bool {\n\treturn b2.IsNotExist(errors.Cause(err))\n}\n\n\/\/ Load runs fn with a reader that yields the contents of the file at h at the\n\/\/ given offset.\nfunc (be *b2Backend) Load(ctx context.Context, h restic.Handle, length int, offset int64, fn func(rd io.Reader) error) error {\n\treturn backend.DefaultLoad(ctx, h, length, offset, be.openReader, fn)\n}\n\nfunc (be *b2Backend) openReader(ctx context.Context, h restic.Handle, length int, offset int64) (io.ReadCloser, error) {\n\tdebug.Log(\"Load %v, length %v, offset %v from %v\", h, length, offset, be.Filename(h))\n\tif err := h.Valid(); err != nil {\n\t\treturn nil, backoff.Permanent(err)\n\t}\n\n\tif offset < 0 {\n\t\treturn nil, errors.New(\"offset is negative\")\n\t}\n\n\tif length < 0 {\n\t\treturn nil, errors.Errorf(\"invalid length %d\", length)\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\n\tbe.sem.GetToken()\n\n\tname := be.Layout.Filename(h)\n\tobj := be.bucket.Object(name)\n\n\tif offset == 0 && length == 0 {\n\t\trd := obj.NewReader(ctx)\n\t\treturn be.sem.ReleaseTokenOnClose(rd, cancel), nil\n\t}\n\n\t\/\/ pass a negative length to NewRangeReader so that the remainder of the\n\t\/\/ file is read.\n\tif length == 0 {\n\t\tlength = -1\n\t}\n\n\trd := obj.NewRangeReader(ctx, offset, int64(length))\n\treturn be.sem.ReleaseTokenOnClose(rd, cancel), nil\n}\n\n\/\/ Save stores data in the backend at the handle.\nfunc (be *b2Backend) Save(ctx context.Context, h restic.Handle, rd restic.RewindReader) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tif err := h.Valid(); err != nil {\n\t\treturn backoff.Permanent(err)\n\t}\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tname := be.Filename(h)\n\tdebug.Log(\"Save %v, name %v\", h, name)\n\tobj := be.bucket.Object(name)\n\n\t\/\/ b2 always requires sha1 checksums for uploaded file parts\n\tw := obj.NewWriter(ctx)\n\tn, err := io.Copy(w, rd)\n\tdebug.Log(\" saved %d bytes, err %v\", n, err)\n\n\tif err != nil {\n\t\t_ = w.Close()\n\t\treturn errors.Wrap(err, \"Copy\")\n\t}\n\n\t\/\/ sanity check\n\tif n != rd.Length() {\n\t\treturn errors.Errorf(\"wrote %d bytes instead of the expected %d bytes\", n, rd.Length())\n\t}\n\treturn errors.Wrap(w.Close(), \"Close\")\n}\n\n\/\/ Stat returns information about a blob.\nfunc (be *b2Backend) Stat(ctx context.Context, h restic.Handle) (bi restic.FileInfo, err error) {\n\tdebug.Log(\"Stat %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tname := be.Filename(h)\n\tobj := be.bucket.Object(name)\n\tinfo, err := obj.Attrs(ctx)\n\tif err != nil {\n\t\tdebug.Log(\"Attrs() err %v\", err)\n\t\treturn restic.FileInfo{}, errors.Wrap(err, \"Stat\")\n\t}\n\treturn restic.FileInfo{Size: info.Size, Name: h.Name}, nil\n}\n\n\/\/ Test returns true if a blob of the given type and name exists in the backend.\nfunc (be *b2Backend) Test(ctx context.Context, h restic.Handle) (bool, error) {\n\tdebug.Log(\"Test %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\tfound := false\n\tname := be.Filename(h)\n\tobj := be.bucket.Object(name)\n\tinfo, err := obj.Attrs(ctx)\n\tif err == nil && info != nil && info.Status == b2.Uploaded {\n\t\tfound = true\n\t}\n\treturn found, nil\n}\n\n\/\/ Remove removes the blob with the given name and type.\nfunc (be *b2Backend) Remove(ctx context.Context, h restic.Handle) error {\n\tdebug.Log(\"Remove %v\", h)\n\n\tbe.sem.GetToken()\n\tdefer be.sem.ReleaseToken()\n\n\t\/\/ the retry backend will also repeat the remove method up to 10 times\n\tfor i := 0; i < 3; i++ {\n\t\tobj := be.bucket.Object(be.Filename(h))\n\t\terr := obj.Delete(ctx)\n\t\tif err == nil {\n\t\t\t\/\/ keep deleting until we are sure that no leftover file versions exist\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ consider a file as removed if b2 informs us that it does not exist\n\t\tif b2.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"Delete\")\n\t}\n\n\treturn errors.New(\"failed to delete all file versions\")\n}\n\ntype semLocker struct {\n\tsema.Semaphore\n}\n\nfunc (sm *semLocker) Lock() { sm.GetToken() }\nfunc (sm *semLocker) Unlock() { sm.ReleaseToken() }\n\n\/\/ List returns a channel that yields all names of blobs of type t.\nfunc (be *b2Backend) List(ctx context.Context, t restic.FileType, fn func(restic.FileInfo) error) error {\n\tdebug.Log(\"List %v\", t)\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tprefix, _ := be.Basedir(t)\n\titer := be.bucket.List(ctx, b2.ListPrefix(prefix), b2.ListPageSize(be.listMaxItems), b2.ListLocker(&semLocker{be.sem}))\n\n\tfor iter.Next() {\n\t\tobj := iter.Object()\n\n\t\tattrs, err := obj.Attrs(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfi := restic.FileInfo{\n\t\t\tName: path.Base(obj.Name()),\n\t\t\tSize: attrs.Size,\n\t\t}\n\n\t\tif err := fn(fi); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := iter.Err(); err != nil {\n\t\tdebug.Log(\"List: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Remove keys for a specified backend type.\nfunc (be *b2Backend) removeKeys(ctx context.Context, t restic.FileType) error {\n\tdebug.Log(\"removeKeys %v\", t)\n\treturn be.List(ctx, t, func(fi restic.FileInfo) error {\n\t\treturn be.Remove(ctx, restic.Handle{Type: t, Name: fi.Name})\n\t})\n}\n\n\/\/ Delete removes all restic keys in the bucket. It will not remove the bucket itself.\nfunc (be *b2Backend) Delete(ctx context.Context) error {\n\talltypes := []restic.FileType{\n\t\trestic.PackFile,\n\t\trestic.KeyFile,\n\t\trestic.LockFile,\n\t\trestic.SnapshotFile,\n\t\trestic.IndexFile}\n\n\tfor _, t := range alltypes {\n\t\terr := be.removeKeys(ctx, t)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\terr := be.Remove(ctx, restic.Handle{Type: restic.ConfigFile})\n\tif err != nil && b2.IsNotExist(errors.Cause(err)) {\n\t\terr = nil\n\t}\n\n\treturn err\n}\n\n\/\/ Close does nothing\nfunc (be *b2Backend) Close() error { return nil }\n<|endoftext|>"} {"text":"package frame\n\nimport (\n\t\"image\"\n\t\"image\/draw\"\n)\n\nconst (\n\tTickOff = 0\n\tTickOn = 1\n)\n\nfunc (f *Frame) Untick() {\n\tif f.p0 == f.p1 {\n\t\tf.tickat(f.PointOf(int64(f.p0)), false)\n\t}\n}\nfunc (f *Frame) Tick() {\n\tif f.p0 == f.p1 {\n\t\tf.tickat(f.PointOf(int64(f.p0)), true)\n\t}\n}\n\nfunc (f *Frame) SetTick(style int) {\n\tf.tickoff = style == TickOff\n}\nfunc mktick(fontY int) (boxw int, linew int) {\n\tconst magic = 12\n\tboxw = 3 + 1*(fontY\/magic)\n\tfor boxw%3 != 0 {\n\t\tboxw--\n\t}\n\tif boxw < 3 {\n\t\tboxw = 3\n\t}\n\n\tlinew = boxw \/ 3\n\tfor boxw%linew != 0 {\n\t\tboxw--\n\t}\n\tif linew < 1 {\n\t\tlinew = 1\n\t}\n\treturn\n}\n\nfunc (f *Frame) tickbg() image.Image {\n\treturn f.Color.Text\n\t\/*\n\t\tr, g, b, a := f.Color.Hi.Back.At(0,0).RGBA()\n\t\ta=a\n\t\treturn image.NewUniform(color.RGBA{\n\t\t\tuint8(r),\n\t\t\tuint8(g),\n\t\t\tuint8(b),\n\t\t\tuint8(0),\n\t\t})\n\t*\/\n\n}\nfunc (f *Frame) inittick() {\n\the := f.Font.Height()\n\tas := f.Font.Ascent()\n\tde := f.Font.Descent()\n\tboxw, linew := mktick(he)\n\tlinew2 := linew \/ 2\n\tif linew < 1 {\n\t\tlinew = 1\n\t}\n\tlinew2 = linew2\n\tz0 := de + (he - as) + (he-as)\/2\n\tr := image.Rect(0, z0, boxw, he-(he-as)\/2+f.Font.Letting()\/2)\n\tr = r.Sub(image.Pt(r.Dx()\/2, 0))\n\tf.tick = image.NewRGBA(r)\n\tf.tickback = image.NewRGBA(r)\n\tdraw.Draw(f.tick, f.tick.Bounds().Inset(1), f.Color.Hi.Back, image.ZP, draw.Src)\n\ttbg := f.tickbg()\n\tdrawtick := func(x0, y0, x1, y1 int) {\n\t\tdraw.Draw(f.tick, image.Rect(x0-3, y0, x1-3, y1), tbg, image.ZP, draw.Src)\n\t}\n\tdrawtick(r.Min.X, r.Min.Y, r.Max.X, r.Min.Y+boxw)\n\tdrawtick(r.Min.X, r.Max.Y-(boxw), r.Max.X, r.Max.Y)\n\tif boxw%2 != 0 {\n\t\tdrawtick(-linew2, 0, linew2+1, r.Max.Y)\n\t} else {\n\t\tdrawtick(-linew2, 0, linew2, r.Max.Y)\n\t}\n\tdrawtick = drawtick\n\n}\n\n\/\/ Put\nfunc (f *Frame) tickat(pt image.Point, ticked bool) {\n\tif f.Ticked == ticked || f.tick == nil || !pt.In(f.Bounds().Inset(-1)) {\n\t\treturn\n\t}\n\tpt.X -= 1\n\tpt.Y -= f.Font.Letting() \/ 4\n\tr := f.tick.Bounds().Add(pt)\n\tif r.Max.X > f.r.Max.X {\n\t\tr.Max.X = f.r.Max.X\n\t}\n\tif ticked {\n\t\tf.Draw(f.tickback, f.tickback.Bounds(), f.b, pt.Add(f.tickback.Bounds().Min), draw.Src)\n\t\tf.Draw(f.b, r, f.tick, f.tick.Bounds().Min, draw.Src)\n\t} else {\n\t\tf.Draw(f.b, r, f.tickback, f.tickback.Bounds().Min, draw.Src)\n\t}\n\tf.Flush(r.Inset(-1))\n\tf.Ticked = ticked\n}\nframe: fix tickpackage frame\n\nimport (\n\t\"image\"\n\t\"image\/draw\"\n)\n\nconst (\n\tTickOff = 0\n\tTickOn = 1\n)\n\nfunc (f *Frame) Untick() {\n\tif f.p0 == f.p1 {\n\t\tf.tickat(f.PointOf(int64(f.p0)), false)\n\t}\n}\nfunc (f *Frame) Tick() {\n\tif f.p0 == f.p1 {\n\t\tf.tickat(f.PointOf(int64(f.p0)), true)\n\t}\n}\n\nfunc (f *Frame) SetTick(style int) {\n\tf.tickoff = style == TickOff\n}\nfunc mktick(fontY int) (boxw int, linew int) {\n\tconst magic = 12\n\tboxw = 3 + 1*(fontY\/magic)\n\tfor boxw%3 != 0 {\n\t\tboxw--\n\t}\n\tif boxw < 3 {\n\t\tboxw = 3\n\t}\n\n\tlinew = boxw \/ 3\n\tfor boxw%linew != 0 {\n\t\tboxw--\n\t}\n\tif linew < 1 {\n\t\tlinew = 1\n\t}\n\treturn\n}\n\nfunc (f *Frame) tickbg() image.Image {\n\treturn f.Color.Text\n\t\/*\n\t\tr, g, b, a := f.Color.Hi.Back.At(0,0).RGBA()\n\t\ta=a\n\t\treturn image.NewUniform(color.RGBA{\n\t\t\tuint8(r),\n\t\t\tuint8(g),\n\t\t\tuint8(b),\n\t\t\tuint8(0),\n\t\t})\n\t*\/\n\n}\n\nfunc (f *Frame) inittick() {\n\n\the := f.Font.Height()\n\tas := f.Font.Ascent()\n\tde := f.Font.Descent()\n\tboxw, linew := mktick(he)\n\tlinew2 := linew \/ 2\n\tif linew < 1 {\n\t\tlinew = 1\n\t}\n\tlinew2 = linew2\n\tz0 := de - 2\n\tr := image.Rect(0, z0, boxw, he-(he-as)\/2+f.Font.Letting()\/2)\n\tr = r.Sub(image.Pt(r.Dx()\/2, 0))\n\tf.tick = image.NewRGBA(r)\n\tf.tickback = image.NewRGBA(r)\n\tdraw.Draw(f.tick, f.tick.Bounds(), f.Color.Back, image.ZP, draw.Src)\n\ttbg := f.tickbg()\n\tdrawtick := func(x0, y0, x1, y1 int) {\n\t\tdraw.Draw(f.tick, image.Rect(x0, y0, x1, y1), tbg, image.ZP, draw.Src)\n\t}\n\tdrawtick(r.Min.X, r.Min.Y, r.Max.X, r.Min.Y+boxw)\n\tdrawtick(r.Min.X, r.Max.Y-(boxw), r.Max.X, r.Max.Y)\n\tif boxw%2 != 0 {\n\t\tdrawtick(-linew2, 0, linew2+1, r.Max.Y)\n\t} else {\n\t\tdrawtick(-linew2, 0, linew2, r.Max.Y)\n\t}\n\tdrawtick = drawtick\n\n}\n\n\/\/ Put\nfunc (f *Frame) tickat(pt image.Point, ticked bool) {\n\tif f.Ticked == ticked || f.tick == nil || !pt.In(f.Bounds().Inset(-1)) {\n\t\treturn\n\t}\n\tpt.X -= 1\n\t\/\/pt.Y -= f.Font.Letting() \/ 4\n\tr := f.tick.Bounds().Add(pt)\n\tif r.Max.X > f.r.Max.X {\n\t\tr.Max.X = f.r.Max.X\n\t}\n\tif ticked {\n\t\tf.Draw(f.tickback, f.tickback.Bounds(), f.b, pt.Add(f.tickback.Bounds().Min), draw.Src)\n\t\tf.Draw(f.b, r, f.tick, f.tick.Bounds().Min, draw.Src)\n\t} else {\n\t\tf.Draw(f.b, r, f.tickback, f.tickback.Bounds().Min, draw.Src)\n\t}\n\t\/\/f.Flush(r.Inset(-1))\n\tf.Ticked = ticked\n}\n<|endoftext|>"} {"text":"package agent\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/jrallison\/go-workers\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Agent runs codeflow and collects data based on the given config\ntype Agent struct {\n\tQueueing bool\n\tEvents chan Event\n\tTestEvents chan Event\n\tShutdown chan struct{}\n\tPlugins []*RunningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent() (*Agent, error) {\n\tif len(viper.GetStringMap(\"plugins\")) == 0 {\n\t\tlog.Fatalf(\"Error: no plugins found, did you provide a valid config file?\")\n\t}\n\n\tagent := &Agent{}\n\n\t\/\/ channel shared between all plugin threads for accumulating events\n\tagent.Events = make(chan Event, 10000)\n\n\t\/\/ channel shared between all plugin threads to trigger shutdown\n\tagent.Shutdown = make(chan struct{})\n\n\tif err := agent.LoadPlugins(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn agent, nil\n}\n\n\/\/ NewTestAgent returns an Agent struct based off the given Config\nfunc NewTestAgent(config []byte) (*Agent, error) {\n\tvar err error\n\tvar agent *Agent\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.ReadConfig(bytes.NewBuffer(config))\n\n\tif agent, err = NewAgent(); err != nil {\n\t\tlog.Fatalf(\"Error while initializing agent: %v\", err)\n\t}\n\n\tagent.TestEvents = make(chan Event, 10000)\n\tagent.Queueing = false\n\n\treturn agent, nil\n}\n\nfunc (a *Agent) LoadPlugins() error {\n\tvar err error\n\n\tep := viper.GetString(\"run\")\n\trunPlugins := strings.Split(strings.Trim(ep, \"[]\"), \",\")\n\tfor name := range viper.GetStringMap(\"plugins\") {\n\t\tif err = a.addPlugin(name); err != nil {\n\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t}\n\t\tif ep == \"\" || SliceContains(name, runPlugins) {\n\t\t\tif err = a.enablePlugin(name); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns a list of strings of the configured plugins.\nfunc (a *Agent) PluginNames() []string {\n\tvar name []string\n\tfor key, _ := range viper.GetStringMap(\"plugins\") {\n\t\tname = append(name, key)\n\t}\n\treturn name\n}\n\nfunc (a *Agent) addPlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tcreator, ok := PluginRegistry[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Undefined but requested Plugin: %s\", name)\n\t}\n\tplugin := creator()\n\n\tviper.UnmarshalKey(fmt.Sprint(\"plugins.\", name), plugin)\n\n\twork := func(message *workers.Msg) {\n\t\te, _ := json.Marshal(message.Args())\n\t\tevent := Event{}\n\t\tjson.Unmarshal([]byte(e), &event)\n\t\tif err := MapPayload(event.PayloadModel, &event); err != nil {\n\t\t\tevent.Error = fmt.Errorf(\"PayloadModel not found: %s. Did you add it to ApiRegistry?\", event.PayloadModel)\n\t\t}\n\n\t\t\/\/ For debugging purposes\n\t\tevent.Dump()\n\n\t\tplugin.Process(event)\n\t}\n\n\trp := &RunningPlugin{\n\t\tName: name,\n\t\tPlugin: plugin,\n\t\tWork: work,\n\t\tEnabled: false,\n\t}\n\n\ta.Plugins = append(a.Plugins, rp)\n\n\treturn nil\n}\n\nfunc (a *Agent) enablePlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tif viper.GetInt(\"plugins.\"+name+\".workers\") <= 0 {\n\t\treturn nil\n\t}\n\n\tfor _, rp := range a.Plugins {\n\t\tif rp.Name == name {\n\t\t\trp.Enabled = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ flusher monitors the events plugin channel and schedules them to correct queues\nfunc (a *Agent) flusher() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.Shutdown:\n\t\t\tlog.Println(\"Hang on, flushing any cached metrics before shutdown\")\n\t\t\treturn\n\t\tcase e := <-a.Events:\n\t\t\tev_handled := false\n\n\t\t\tfor _, plugin := range a.Plugins {\n\t\t\t\tif plugin.Enabled {\n\t\t\t\t\tsubscribedTo := plugin.Plugin.Subscribe()\n\t\t\t\t\tif SliceContains(e.PayloadModel, subscribedTo) || SliceContains(e.Name, subscribedTo) {\n\t\t\t\t\t\tev_handled = true\n\t\t\t\t\t\tif a.Queueing {\n\t\t\t\t\t\t\tlog.Printf(\"Enqueue event %v for %v\\n\", e.Name, plugin.Name)\n\t\t\t\t\t\t\tworkers.Enqueue(plugin.Name, \"Event\", e)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tplugin.Plugin.Process(e)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif a.TestEvents != nil {\n\t\t\t\ta.TestEvents <- e\n\t\t\t} else if !ev_handled {\n\t\t\t\tlog.Printf(\"Event not handled by any plugin: %s\\n\", e.Name)\n\t\t\t\tspew.Dump(e)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Run runs the agent daemon\nfunc (a *Agent) Run() error {\n\tvar wg sync.WaitGroup\n\n\tif a.Queueing {\n\t\tworkers.Middleware = workers.NewMiddleware(\n\t\t\t&workers.MiddlewareRetry{},\n\t\t\t&workers.MiddlewareStats{},\n\t\t)\n\n\t\tworkers.Configure(map[string]string{\n\t\t\t\"server\": viper.GetString(\"redis.server\"),\n\t\t\t\"database\": viper.GetString(\"redis.database\"),\n\t\t\t\"pool\": viper.GetString(\"redis.pool\"),\n\t\t\t\"process\": uuid.New(),\n\t\t})\n\t}\n\n\tfor _, plugin := range a.Plugins {\n\t\tif !plugin.Enabled {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Start service of any Plugins\n\t\tswitch p := plugin.Plugin.(type) {\n\t\tcase Plugin:\n\t\t\tif err := p.Start(a.Events); err != nil {\n\t\t\t\tlog.Printf(\"Service for plugin %s failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tplugin.Name, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer p.Stop()\n\n\t\t\tif a.Queueing {\n\t\t\t\tworkers.Process(plugin.Name, plugin.Work, viper.GetInt(\"plugins.\"+plugin.Name+\".workers\"))\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ta.flusher()\n\t}()\n\n\tif a.Queueing {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers.Run()\n\t\t\ta.Stop()\n\t\t}()\n\n\t\t\/\/wg.Add(1)\n\t\t\/\/go func() {\n\t\t\/\/\tdefer wg.Done()\n\t\t\/\/\tworkers.StatsServer(8080)\n\t\t\/\/}()\n\t}\n\n\twg.Wait()\n\treturn nil\n}\n\n\/\/ Shutdown the agent daemon\nfunc (a *Agent) Stop() {\n\tclose(a.Shutdown)\n}\n\n\/\/ GetTestEvent listens and returns requested event\nfunc (a *Agent) GetTestEvent(name string, timeout time.Duration) Event {\n\t\/\/ timeout in the case that we don't get requested event\n\ttimer := time.NewTimer(time.Second * timeout)\n\tgo func() {\n\t\t<-timer.C\n\t\ta.Stop()\n\t\tlog.Fatalf(\"Timer expired waiting for event: %v\", name)\n\t}()\n\n\tfor e := range a.TestEvents {\n\t\tif e.Name == name {\n\t\t\ttimer.Stop()\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn Event{}\n}\nDisable code that checks for enabled pluginpackage agent\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/jrallison\/go-workers\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Agent runs codeflow and collects data based on the given config\ntype Agent struct {\n\tQueueing bool\n\tEvents chan Event\n\tTestEvents chan Event\n\tShutdown chan struct{}\n\tPlugins []*RunningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent() (*Agent, error) {\n\tif len(viper.GetStringMap(\"plugins\")) == 0 {\n\t\tlog.Fatalf(\"Error: no plugins found, did you provide a valid config file?\")\n\t}\n\n\tagent := &Agent{}\n\n\t\/\/ channel shared between all plugin threads for accumulating events\n\tagent.Events = make(chan Event, 10000)\n\n\t\/\/ channel shared between all plugin threads to trigger shutdown\n\tagent.Shutdown = make(chan struct{})\n\n\tif err := agent.LoadPlugins(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn agent, nil\n}\n\n\/\/ NewTestAgent returns an Agent struct based off the given Config\nfunc NewTestAgent(config []byte) (*Agent, error) {\n\tvar err error\n\tvar agent *Agent\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.ReadConfig(bytes.NewBuffer(config))\n\n\tif agent, err = NewAgent(); err != nil {\n\t\tlog.Fatalf(\"Error while initializing agent: %v\", err)\n\t}\n\n\tagent.TestEvents = make(chan Event, 10000)\n\tagent.Queueing = false\n\n\treturn agent, nil\n}\n\nfunc (a *Agent) LoadPlugins() error {\n\tvar err error\n\n\tep := viper.GetString(\"run\")\n\trunPlugins := strings.Split(strings.Trim(ep, \"[]\"), \",\")\n\tfor name := range viper.GetStringMap(\"plugins\") {\n\t\tif err = a.addPlugin(name); err != nil {\n\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t}\n\t\tif ep == \"\" || SliceContains(name, runPlugins) {\n\t\t\tif err = a.enablePlugin(name); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns a list of strings of the configured plugins.\nfunc (a *Agent) PluginNames() []string {\n\tvar name []string\n\tfor key, _ := range viper.GetStringMap(\"plugins\") {\n\t\tname = append(name, key)\n\t}\n\treturn name\n}\n\nfunc (a *Agent) addPlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tcreator, ok := PluginRegistry[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Undefined but requested Plugin: %s\", name)\n\t}\n\tplugin := creator()\n\n\tviper.UnmarshalKey(fmt.Sprint(\"plugins.\", name), plugin)\n\n\twork := func(message *workers.Msg) {\n\t\te, _ := json.Marshal(message.Args())\n\t\tevent := Event{}\n\t\tjson.Unmarshal([]byte(e), &event)\n\t\tif err := MapPayload(event.PayloadModel, &event); err != nil {\n\t\t\tevent.Error = fmt.Errorf(\"PayloadModel not found: %s. Did you add it to ApiRegistry?\", event.PayloadModel)\n\t\t}\n\n\t\t\/\/ For debugging purposes\n\t\tevent.Dump()\n\n\t\tplugin.Process(event)\n\t}\n\n\trp := &RunningPlugin{\n\t\tName: name,\n\t\tPlugin: plugin,\n\t\tWork: work,\n\t\tEnabled: false,\n\t}\n\n\ta.Plugins = append(a.Plugins, rp)\n\n\treturn nil\n}\n\nfunc (a *Agent) enablePlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\t\/\/if viper.GetInt(\"plugins.\"+name+\".workers\") <= 0 {\n\t\/\/\treturn nil\n\t\/\/}\n\n\tfor _, rp := range a.Plugins {\n\t\tif rp.Name == name {\n\t\t\trp.Enabled = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ flusher monitors the events plugin channel and schedules them to correct queues\nfunc (a *Agent) flusher() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.Shutdown:\n\t\t\tlog.Println(\"Hang on, flushing any cached metrics before shutdown\")\n\t\t\treturn\n\t\tcase e := <-a.Events:\n\t\t\tev_handled := false\n\n\t\t\tfor _, plugin := range a.Plugins {\n\t\t\t\tif plugin.Enabled {\n\t\t\t\t\tsubscribedTo := plugin.Plugin.Subscribe()\n\t\t\t\t\tif SliceContains(e.PayloadModel, subscribedTo) || SliceContains(e.Name, subscribedTo) {\n\t\t\t\t\t\tev_handled = true\n\t\t\t\t\t\tif a.Queueing {\n\t\t\t\t\t\t\tlog.Printf(\"Enqueue event %v for %v\\n\", e.Name, plugin.Name)\n\t\t\t\t\t\t\tworkers.Enqueue(plugin.Name, \"Event\", e)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tplugin.Plugin.Process(e)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif a.TestEvents != nil {\n\t\t\t\ta.TestEvents <- e\n\t\t\t} else if !ev_handled {\n\t\t\t\tlog.Printf(\"Event not handled by any plugin: %s\\n\", e.Name)\n\t\t\t\tspew.Dump(e)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Run runs the agent daemon\nfunc (a *Agent) Run() error {\n\tvar wg sync.WaitGroup\n\n\tif a.Queueing {\n\t\tworkers.Middleware = workers.NewMiddleware(\n\t\t\t&workers.MiddlewareRetry{},\n\t\t\t&workers.MiddlewareStats{},\n\t\t)\n\n\t\tworkers.Configure(map[string]string{\n\t\t\t\"server\": viper.GetString(\"redis.server\"),\n\t\t\t\"database\": viper.GetString(\"redis.database\"),\n\t\t\t\"pool\": viper.GetString(\"redis.pool\"),\n\t\t\t\"process\": uuid.New(),\n\t\t})\n\t}\n\n\tfor _, plugin := range a.Plugins {\n\t\tif !plugin.Enabled {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Start service of any Plugins\n\t\tswitch p := plugin.Plugin.(type) {\n\t\tcase Plugin:\n\t\t\tif err := p.Start(a.Events); err != nil {\n\t\t\t\tlog.Printf(\"Service for plugin %s failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tplugin.Name, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer p.Stop()\n\n\t\t\tif a.Queueing {\n\t\t\t\tworkers.Process(plugin.Name, plugin.Work, viper.GetInt(\"plugins.\"+plugin.Name+\".workers\"))\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ta.flusher()\n\t}()\n\n\tif a.Queueing {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers.Run()\n\t\t\ta.Stop()\n\t\t}()\n\n\t\t\/\/wg.Add(1)\n\t\t\/\/go func() {\n\t\t\/\/\tdefer wg.Done()\n\t\t\/\/\tworkers.StatsServer(8080)\n\t\t\/\/}()\n\t}\n\n\twg.Wait()\n\treturn nil\n}\n\n\/\/ Shutdown the agent daemon\nfunc (a *Agent) Stop() {\n\tclose(a.Shutdown)\n}\n\n\/\/ GetTestEvent listens and returns requested event\nfunc (a *Agent) GetTestEvent(name string, timeout time.Duration) Event {\n\t\/\/ timeout in the case that we don't get requested event\n\ttimer := time.NewTimer(time.Second * timeout)\n\tgo func() {\n\t\t<-timer.C\n\t\ta.Stop()\n\t\tlog.Fatalf(\"Timer expired waiting for event: %v\", name)\n\t}()\n\n\tfor e := range a.TestEvents {\n\t\tif e.Name == name {\n\t\t\ttimer.Stop()\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn Event{}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage registry\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/kubernetes-incubator\/external-dns\/endpoint\"\n\t\"github.com\/kubernetes-incubator\/external-dns\/plan\"\n\t\"github.com\/kubernetes-incubator\/external-dns\/provider\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ TXTRegistry implements registry interface with ownership implemented via associated TXT records\ntype TXTRegistry struct {\n\tprovider provider.Provider\n\townerID string \/\/refers to the owner id of the current instance\n\tmapper nameMapper\n\n\t\/\/ cache the records in memory and update on an interval instead.\n\trecordsCache []*endpoint.Endpoint\n\trecordsCacheRefreshTime time.Time\n\tcacheInterval time.Duration\n}\n\n\/\/ NewTXTRegistry returns new TXTRegistry object\nfunc NewTXTRegistry(provider provider.Provider, txtPrefix, ownerID string, cacheInterval time.Duration) (*TXTRegistry, error) {\n\tif ownerID == \"\" {\n\t\treturn nil, errors.New(\"owner id cannot be empty\")\n\t}\n\n\tmapper := newPrefixNameMapper(txtPrefix)\n\n\treturn &TXTRegistry{\n\t\tprovider: provider,\n\t\townerID: ownerID,\n\t\tmapper: mapper,\n\t\tcacheInterval: cacheInterval,\n\t}, nil\n}\n\n\/\/ Records returns the current records from the registry excluding TXT Records\n\/\/ If TXT records was created previously to indicate ownership its corresponding value\n\/\/ will be added to the endpoints Labels map\nfunc (im *TXTRegistry) Records() ([]*endpoint.Endpoint, error) {\n\t\/\/ If we have the zones cached AND we have refreshed the cache since the\n\t\/\/ last given interval, then just use the cached results.\n\tif im.recordsCache != nil && time.Since(im.recordsCacheRefreshTime) < im.cacheInterval {\n\t\tlog.Debug(\"Using cached records.\")\n\t\treturn im.recordsCache, nil\n\t}\n\n\trecords, err := im.provider.Records()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoints := []*endpoint.Endpoint{}\n\n\tlabelMap := map[string]endpoint.Labels{}\n\n\tfor _, record := range records {\n\t\tif record.RecordType != endpoint.RecordTypeTXT {\n\t\t\tendpoints = append(endpoints, record)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ We simply assume that TXT records for the registry will always have only one target.\n\t\tlabels, err := endpoint.NewLabelsFromString(record.Targets[0])\n\t\tif err == endpoint.ErrInvalidHeritage {\n\t\t\t\/\/if no heritage is found or it is invalid\n\t\t\t\/\/case when value of txt record cannot be identified\n\t\t\t\/\/record will not be removed as it will have empty owner\n\t\t\tendpoints = append(endpoints, record)\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpointDNSName := im.mapper.toEndpointName(record.DNSName)\n\t\tlabelMap[endpointDNSName] = labels\n\t}\n\n\tfor _, ep := range endpoints {\n\t\tep.Labels = endpoint.NewLabels()\n\t\tif labels, ok := labelMap[ep.DNSName]; ok {\n\t\t\tfor k, v := range labels {\n\t\t\t\tep.Labels[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Update the cache.\n\tif im.cacheInterval > 0 {\n\t\tim.recordsCache = endpoints\n\t\tim.recordsCacheRefreshTime = time.Now()\n\t}\n\n\treturn endpoints, nil\n}\n\n\/\/ ApplyChanges updates dns provider with the changes\n\/\/ for each created\/deleted record it will also take into account TXT records for creation\/deletion\nfunc (im *TXTRegistry) ApplyChanges(changes *plan.Changes) error {\n\tfilteredChanges := &plan.Changes{\n\t\tCreate: changes.Create,\n\t\tUpdateNew: filterOwnedRecords(im.ownerID, changes.UpdateNew),\n\t\tUpdateOld: filterOwnedRecords(im.ownerID, changes.UpdateOld),\n\t\tDelete: filterOwnedRecords(im.ownerID, changes.Delete),\n\t}\n\tfor _, r := range filteredChanges.Create {\n\t\tif r.Labels == nil {\n\t\t\tr.Labels = make(map[string]string)\n\t\t}\n\t\tr.Labels[endpoint.OwnerLabelKey] = im.ownerID\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\tfilteredChanges.Create = append(filteredChanges.Create, txt)\n\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.addToCache(r)\n\t\t}\n\t}\n\n\tfor _, r := range filteredChanges.Delete {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\n\t\t\/\/ when we delete TXT records for which value has changed (due to new label) this would still work because\n\t\t\/\/ !!! TXT record value is uniquely generated from the Labels of the endpoint. Hence old TXT record can be uniquely reconstructed\n\t\tfilteredChanges.Delete = append(filteredChanges.Delete, txt)\n\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.removeFromCache(r)\n\t\t}\n\t}\n\n\t\/\/ make sure TXT records are consistently updated as well\n\tfor _, r := range filteredChanges.UpdateOld {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\t\/\/ when we updateOld TXT records for which value has changed (due to new label) this would still work because\n\t\t\/\/ !!! TXT record value is uniquely generated from the Labels of the endpoint. Hence old TXT record can be uniquely reconstructed\n\t\tfilteredChanges.UpdateOld = append(filteredChanges.UpdateOld, txt)\n\t\t\/\/ remove old version of record from cache\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.removeFromCache(r)\n\t\t}\n\t}\n\n\t\/\/ make sure TXT records are consistently updated as well\n\tfor _, r := range filteredChanges.UpdateNew {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\tfilteredChanges.UpdateNew = append(filteredChanges.UpdateNew, txt)\n\t\t\/\/ add new version of record to cache\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.addToCache(r)\n\t\t}\n\t}\n\n\treturn im.provider.ApplyChanges(filteredChanges)\n}\n\n\/**\n TXT registry specific private methods\n*\/\n\n\/**\n nameMapper defines interface which maps the dns name defined for the source\n to the dns name which TXT record will be created with\n*\/\n\ntype nameMapper interface {\n\ttoEndpointName(string) string\n\ttoTXTName(string) string\n}\n\ntype prefixNameMapper struct {\n\tprefix string\n}\n\nvar _ nameMapper = prefixNameMapper{}\n\nfunc newPrefixNameMapper(prefix string) prefixNameMapper {\n\treturn prefixNameMapper{prefix: prefix}\n}\n\nfunc (pr prefixNameMapper) toEndpointName(txtDNSName string) string {\n\tif strings.HasPrefix(txtDNSName, pr.prefix) {\n\t\treturn strings.TrimPrefix(txtDNSName, pr.prefix)\n\t}\n\treturn \"\"\n}\n\nfunc (pr prefixNameMapper) toTXTName(endpointDNSName string) string {\n\treturn pr.prefix + endpointDNSName\n}\n\nfunc (im *TXTRegistry) addToCache(ep *endpoint.Endpoint) {\n\tif im.recordsCache != nil {\n\t\tim.recordsCache = append(im.recordsCache, ep)\n\t}\n}\n\nfunc (im *TXTRegistry) removeFromCache(ep *endpoint.Endpoint) {\n\tif im.recordsCache == nil || ep == nil {\n\t\t\/\/ return early.\n\t\treturn\n\t}\n\n\tfor i, e := range im.recordsCache {\n\t\tif e.DNSName == ep.DNSName && e.RecordType == ep.RecordType && e.Targets.Same(ep.Targets) {\n\t\t\t\/\/ We found a match delete the endpoint from the cache.\n\t\t\tim.recordsCache = append(im.recordsCache[:i], im.recordsCache[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\nFix txt prefix bug, should be lowercased because when writing to dns it is lowercased\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage registry\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/kubernetes-incubator\/external-dns\/endpoint\"\n\t\"github.com\/kubernetes-incubator\/external-dns\/plan\"\n\t\"github.com\/kubernetes-incubator\/external-dns\/provider\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ TXTRegistry implements registry interface with ownership implemented via associated TXT records\ntype TXTRegistry struct {\n\tprovider provider.Provider\n\townerID string \/\/refers to the owner id of the current instance\n\tmapper nameMapper\n\n\t\/\/ cache the records in memory and update on an interval instead.\n\trecordsCache []*endpoint.Endpoint\n\trecordsCacheRefreshTime time.Time\n\tcacheInterval time.Duration\n}\n\n\/\/ NewTXTRegistry returns new TXTRegistry object\nfunc NewTXTRegistry(provider provider.Provider, txtPrefix, ownerID string, cacheInterval time.Duration) (*TXTRegistry, error) {\n\tif ownerID == \"\" {\n\t\treturn nil, errors.New(\"owner id cannot be empty\")\n\t}\n\n\tmapper := newPrefixNameMapper(txtPrefix)\n\n\treturn &TXTRegistry{\n\t\tprovider: provider,\n\t\townerID: ownerID,\n\t\tmapper: mapper,\n\t\tcacheInterval: cacheInterval,\n\t}, nil\n}\n\n\/\/ Records returns the current records from the registry excluding TXT Records\n\/\/ If TXT records was created previously to indicate ownership its corresponding value\n\/\/ will be added to the endpoints Labels map\nfunc (im *TXTRegistry) Records() ([]*endpoint.Endpoint, error) {\n\t\/\/ If we have the zones cached AND we have refreshed the cache since the\n\t\/\/ last given interval, then just use the cached results.\n\tif im.recordsCache != nil && time.Since(im.recordsCacheRefreshTime) < im.cacheInterval {\n\t\tlog.Debug(\"Using cached records.\")\n\t\treturn im.recordsCache, nil\n\t}\n\n\trecords, err := im.provider.Records()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoints := []*endpoint.Endpoint{}\n\n\tlabelMap := map[string]endpoint.Labels{}\n\n\tfor _, record := range records {\n\t\tif record.RecordType != endpoint.RecordTypeTXT {\n\t\t\tendpoints = append(endpoints, record)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ We simply assume that TXT records for the registry will always have only one target.\n\t\tlabels, err := endpoint.NewLabelsFromString(record.Targets[0])\n\t\tif err == endpoint.ErrInvalidHeritage {\n\t\t\t\/\/if no heritage is found or it is invalid\n\t\t\t\/\/case when value of txt record cannot be identified\n\t\t\t\/\/record will not be removed as it will have empty owner\n\t\t\tendpoints = append(endpoints, record)\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendpointDNSName := im.mapper.toEndpointName(record.DNSName)\n\t\tlog.Debug(fmt.Sprintf(\"Parsed endpoint dns name is %s\", endpointDNSName))\n\t\tlabelMap[endpointDNSName] = labels\n\t}\n\n\tfor _, ep := range endpoints {\n\t\tep.Labels = endpoint.NewLabels()\n\t\tif labels, ok := labelMap[ep.DNSName]; ok {\n\t\t\tfor k, v := range labels {\n\t\t\t\tep.Labels[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Update the cache.\n\tif im.cacheInterval > 0 {\n\t\tim.recordsCache = endpoints\n\t\tim.recordsCacheRefreshTime = time.Now()\n\t}\n\n\treturn endpoints, nil\n}\n\n\/\/ ApplyChanges updates dns provider with the changes\n\/\/ for each created\/deleted record it will also take into account TXT records for creation\/deletion\nfunc (im *TXTRegistry) ApplyChanges(changes *plan.Changes) error {\n\tfilteredChanges := &plan.Changes{\n\t\tCreate: changes.Create,\n\t\tUpdateNew: filterOwnedRecords(im.ownerID, changes.UpdateNew),\n\t\tUpdateOld: filterOwnedRecords(im.ownerID, changes.UpdateOld),\n\t\tDelete: filterOwnedRecords(im.ownerID, changes.Delete),\n\t}\n\tfor _, r := range filteredChanges.Create {\n\t\tif r.Labels == nil {\n\t\t\tr.Labels = make(map[string]string)\n\t\t}\n\t\tr.Labels[endpoint.OwnerLabelKey] = im.ownerID\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\tfilteredChanges.Create = append(filteredChanges.Create, txt)\n\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.addToCache(r)\n\t\t}\n\t}\n\n\tfor _, r := range filteredChanges.Delete {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\n\t\t\/\/ when we delete TXT records for which value has changed (due to new label) this would still work because\n\t\t\/\/ !!! TXT record value is uniquely generated from the Labels of the endpoint. Hence old TXT record can be uniquely reconstructed\n\t\tfilteredChanges.Delete = append(filteredChanges.Delete, txt)\n\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.removeFromCache(r)\n\t\t}\n\t}\n\n\t\/\/ make sure TXT records are consistently updated as well\n\tfor _, r := range filteredChanges.UpdateOld {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\t\/\/ when we updateOld TXT records for which value has changed (due to new label) this would still work because\n\t\t\/\/ !!! TXT record value is uniquely generated from the Labels of the endpoint. Hence old TXT record can be uniquely reconstructed\n\t\tfilteredChanges.UpdateOld = append(filteredChanges.UpdateOld, txt)\n\t\t\/\/ remove old version of record from cache\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.removeFromCache(r)\n\t\t}\n\t}\n\n\t\/\/ make sure TXT records are consistently updated as well\n\tfor _, r := range filteredChanges.UpdateNew {\n\t\ttxt := endpoint.NewEndpoint(im.mapper.toTXTName(r.DNSName), endpoint.RecordTypeTXT, r.Labels.Serialize(true))\n\t\tfilteredChanges.UpdateNew = append(filteredChanges.UpdateNew, txt)\n\t\t\/\/ add new version of record to cache\n\t\tif im.cacheInterval > 0 {\n\t\t\tim.addToCache(r)\n\t\t}\n\t}\n\n\treturn im.provider.ApplyChanges(filteredChanges)\n}\n\n\/**\n TXT registry specific private methods\n*\/\n\n\/**\n nameMapper defines interface which maps the dns name defined for the source\n to the dns name which TXT record will be created with\n*\/\n\ntype nameMapper interface {\n\ttoEndpointName(string) string\n\ttoTXTName(string) string\n}\n\ntype prefixNameMapper struct {\n\tprefix string\n}\n\nvar _ nameMapper = prefixNameMapper{}\n\nfunc newPrefixNameMapper(prefix string) prefixNameMapper {\n\treturn prefixNameMapper{prefix: prefix}\n}\n\nfunc (pr prefixNameMapper) toEndpointName(txtDNSName string) string {\n\tlog.Debug(fmt.Sprintf(\"TXT record is %s\", txtDNSName))\n\tlog.Debug(fmt.Sprintf(\"Prefix is %s\", pr.prefix))\n\tprefixLower := strings.ToLower(pr.prefix)\n\tif strings.HasPrefix(txtDNSName, prefixLower) {\n\t\tlog.Debug(\"Will trim prefix\")\n\t\tlog.Debug(strings.TrimPrefix(txtDNSName, prefixLower))\n\t\treturn strings.TrimPrefix(txtDNSName, prefixLower)\n\t}\n\treturn \"\"\n}\n\nfunc (pr prefixNameMapper) toTXTName(endpointDNSName string) string {\n\treturn pr.prefix + endpointDNSName\n}\n\nfunc (im *TXTRegistry) addToCache(ep *endpoint.Endpoint) {\n\tif im.recordsCache != nil {\n\t\tim.recordsCache = append(im.recordsCache, ep)\n\t}\n}\n\nfunc (im *TXTRegistry) removeFromCache(ep *endpoint.Endpoint) {\n\tif im.recordsCache == nil || ep == nil {\n\t\t\/\/ return early.\n\t\treturn\n\t}\n\n\tfor i, e := range im.recordsCache {\n\t\tif e.DNSName == ep.DNSName && e.RecordType == ep.RecordType && e.Targets.Same(ep.Targets) {\n\t\t\t\/\/ We found a match delete the endpoint from the cache.\n\t\t\tim.recordsCache = append(im.recordsCache[:i], im.recordsCache[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package revmgo\n\nimport (\n\t\"errors\"\n\t\"github.com\/robfig\/revel\"\n\t\"labix.org\/v2\/mgo\"\n)\n\nvar (\n\tSession *mgo.Session \/\/ Global mgo Session\n\tDial string \/\/ http:\/\/godoc.org\/labix.org\/v2\/mgo#Dial\n\tMethod string \/\/ clone, copy, new http:\/\/godoc.org\/labix.org\/v2\/mgo#Session.New\n)\n\nfunc Init() {\n\t\/\/ Read configuration.\n\tvar found bool\n\tif Dial, found = revel.Config.String(\"revmgo.dial\"); !found {\n\t\t\/\/ Default to 'localhost'\n\t\tDial = \"localhost\"\n\t}\n\tif Method, found = revel.Config.String(\"db.spec\"); !found {\n\t\tMethod = \"clone\"\n\t} else if err := MethodError(Method); err != nil {\n\t\trevel.ERROR.Panic(err)\n\t}\n\n\tvar err error\n\tif Session == nil {\n\t\t\/\/ Read configuration.\n\t\tSession, err = mgo.Dial(Dial)\n\t\tif err != nil {\n\t\t\trevel.ERROR.Panic(err)\n\t\t}\n\t}\n\n\trevel.InterceptMethod((*MongoController).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*MongoController).End, revel.FINALLY)\n}\n\ntype MongoController struct {\n\t*revel.Controller\n\tMongoSession *mgo.Session \/\/ named MongoSession to avoid collision with revel.Session\n}\n\n\/\/ Connect to mgo if we haven't already and return a copy\/new\/clone of the session\nfunc (c *MongoController) Begin() revel.Result {\n\tswitch Method {\n\tcase \"clone\":\n\t\tc.MongoSession = Session.Clone()\n\tcase \"copy\":\n\t\tc.MongoSession = Session.Copy()\n\tcase \"new\":\n\t\tc.MongoSession = Session.New()\n\t}\n\treturn nil\n}\n\n\/\/ Close the controller session if we have an active one.\nfunc (c *MongoController) End() revel.Result {\n\tc.MongoSession.Close()\n\treturn nil\n}\n\nfunc MethodError(m string) error {\n\tswitch m {\n\tcase \"clone\", \"copy\", \"new\":\n\t\treturn nil\n\t}\n\treturn errors.New(\"revmgo: Invalid session instantiation method '%s'\")\n}\nMinor formatting adjustmentpackage revmgo\n\nimport (\n\t\"errors\"\n\t\"github.com\/robfig\/revel\"\n\t\"labix.org\/v2\/mgo\"\n)\n\nvar (\n\tSession *mgo.Session \/\/ Global mgo Session\n\tDial string \/\/ http:\/\/godoc.org\/labix.org\/v2\/mgo#Dial\n\tMethod string \/\/ clone, copy, new http:\/\/godoc.org\/labix.org\/v2\/mgo#Session.New\n)\n\nfunc Init() {\n\t\/\/ Read configuration.\n\tvar found bool\n\tif Dial, found = revel.Config.String(\"revmgo.dial\"); !found {\n\t\t\/\/ Default to 'localhost'\n\t\tDial = \"localhost\"\n\t}\n\tif Method, found = revel.Config.String(\"db.spec\"); !found {\n\t\tMethod = \"clone\"\n\t} else if err := MethodError(Method); err != nil {\n\t\trevel.ERROR.Panic(err)\n\t}\n\n\tvar err error\n\tif Session == nil {\n\t\t\/\/ Read configuration.\n\t\tif Session, err = mgo.Dial(Dial); err != nil {\n\t\t\trevel.ERROR.Panic(err)\n\t\t}\n\t}\n\n\trevel.InterceptMethod((*MongoController).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*MongoController).End, revel.FINALLY)\n}\n\ntype MongoController struct {\n\t*revel.Controller\n\tMongoSession *mgo.Session \/\/ named MongoSession to avoid collision with revel.Session\n}\n\n\/\/ Connect to mgo if we haven't already and return a copy\/new\/clone of the session\nfunc (c *MongoController) Begin() revel.Result {\n\tswitch Method {\n\tcase \"clone\":\n\t\tc.MongoSession = Session.Clone()\n\tcase \"copy\":\n\t\tc.MongoSession = Session.Copy()\n\tcase \"new\":\n\t\tc.MongoSession = Session.New()\n\t}\n\treturn nil\n}\n\n\/\/ Close the controller session if we have an active one.\nfunc (c *MongoController) End() revel.Result {\n\tc.MongoSession.Close()\n\treturn nil\n}\n\nfunc MethodError(m string) error {\n\tswitch m {\n\tcase \"clone\", \"copy\", \"new\":\n\t\treturn nil\n\t}\n\treturn errors.New(\"revmgo: Invalid session instantiation method '%s'\")\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ An android app that draws a green triangle on a red background.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"code.google.com\/p\/go.mobile\/app\"\n\t\"code.google.com\/p\/go.mobile\/gl\"\n)\n\nvar (\n\tprogram gl.Program\n\tvPosition gl.Attrib\n\tfColor gl.Uniform\n\tbuf gl.Buffer\n\tgreen float32\n)\n\nfunc main() {\n\tapp.Run(app.Callbacks{\n\t\tDraw: renderFrame,\n\t})\n}\n\n\/\/ TODO(crawshaw): Need an easier way to do GL-dependent initialization.\n\nfunc initGL() {\n\tvar err error\n\tprogram, err = createProgram(vertexShader, fragmentShader)\n\tif err != nil {\n\t\tlog.Printf(\"error creating GL program: %v\", err)\n\t\treturn\n\t}\n\n\tbuf = gl.GenBuffers(1)[0]\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.BufferData(gl.ARRAY_BUFFER, gl.STATIC_DRAW, triangleData)\n\n\tvPosition = gl.GetAttribLocation(program, \"vPosition\")\n\tfColor = gl.GetUniformLocation(program, \"fColor\")\n}\n\nfunc renderFrame() {\n\tif program == 0 {\n\t\tinitGL()\n\t\tlog.Printf(\"example\/basic rendering initialized\")\n\t}\n\n\tgl.ClearColor(1, 0, 0, 1)\n\tgl.Clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT)\n\n\tgl.UseProgram(program)\n\n\tgreen += 0.01\n\tif green > 1 {\n\t\tgreen = 0\n\t}\n\tgl.Uniform4f(fColor, 0, green, 0, 1)\n\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.EnableVertexAttribArray(vPosition)\n\tgl.VertexAttribPointer(vPosition, coordsPerVertex, gl.FLOAT, false, 0, 0)\n\tgl.DrawArrays(gl.TRIANGLES, 0, vertexCount)\n\tgl.DisableVertexAttribArray(vPosition)\n}\n\nvar triangleData []byte\n\nfunc init() {\n\tbuf := new(bytes.Buffer)\n\tif err := binary.Write(buf, binary.LittleEndian, triangleCoords); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttriangleData = buf.Bytes()\n}\n\nconst coordsPerVertex = 3\n\nvar triangleCoords = []float32{\n\t\/\/ in counterclockwise order:\n\t0.0, 0.622008459, 0.0, \/\/ top\n\t-0.5, -0.311004243, 0.0, \/\/ bottom left\n\t0.5, -0.311004243, 0.0, \/\/ bottom right\n}\nvar vertexCount = len(triangleCoords) \/ coordsPerVertex\n\nconst vertexShader = `\nattribute vec4 vPosition;\nvoid main() {\n gl_Position = vPosition;\n}`\n\nconst fragmentShader = `\nprecision mediump float;\nuniform vec4 fColor;\nvoid main() {\n gl_FragColor = fColor;\n}`\n\nfunc loadShader(shaderType gl.Enum, src string) (gl.Shader, error) {\n\tshader := gl.CreateShader(shaderType)\n\tif shader == 0 {\n\t\treturn 0, fmt.Errorf(\"could not create shader (type %v)\", shaderType)\n\t}\n\tgl.ShaderSource(shader, src)\n\tgl.CompileShader(shader)\n\tif gl.GetShaderi(shader, gl.COMPILE_STATUS) == 0 {\n\t\tdefer gl.DeleteShader(shader)\n\t\treturn 0, fmt.Errorf(\"shader compile: %s\", gl.GetShaderInfoLog(shader))\n\t}\n\treturn shader, nil\n}\n\n\/\/ TODO(crawshaw): Consider moving createProgram to a utility package.\n\nfunc createProgram(vertexSrc, fragmentSrc string) (gl.Program, error) {\n\tprogram := gl.CreateProgram()\n\tif program == 0 {\n\t\treturn 0, fmt.Errorf(\"cannot create program\")\n\t}\n\n\tvertexShader, err := loadShader(gl.VERTEX_SHADER, vertexSrc)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfragmentShader, err := loadShader(gl.FRAGMENT_SHADER, fragmentSrc)\n\tif err != nil {\n\t\tgl.DeleteShader(vertexShader)\n\t\treturn 0, err\n\t}\n\n\tgl.AttachShader(program, vertexShader)\n\tgl.AttachShader(program, fragmentShader)\n\tgl.LinkProgram(program)\n\n\t\/\/ Flag shaders for deletion when program is unlinked.\n\tgl.DeleteShader(vertexShader)\n\tgl.DeleteShader(fragmentShader)\n\n\tif gl.GetProgrami(program, gl.LINK_STATUS) == 0 {\n\t\tdefer gl.DeleteProgram(program)\n\t\treturn 0, fmt.Errorf(\"program link: %s\", gl.GetProgramInfoLog(program))\n\t}\n\treturn program, nil\n}\ngo.mobile\/example\/basic: respond to touch events\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ An android app that draws a green triangle on a red background.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"log\"\n\n\t\"code.google.com\/p\/go.mobile\/app\"\n\t\"code.google.com\/p\/go.mobile\/event\"\n\t\"code.google.com\/p\/go.mobile\/geom\"\n\t\"code.google.com\/p\/go.mobile\/gl\"\n\t\"code.google.com\/p\/go.mobile\/gl\/glutil\"\n)\n\nvar (\n\tprogram gl.Program\n\tposition gl.Attrib\n\toffset gl.Uniform\n\tcolor gl.Uniform\n\tbuf gl.Buffer\n\n\tgreen float32\n\ttouchLoc geom.Point\n)\n\nfunc main() {\n\tapp.Run(app.Callbacks{\n\t\tDraw: draw,\n\t\tTouch: touch,\n\t})\n}\n\n\/\/ TODO(crawshaw): Need an easier way to do GL-dependent initialization.\n\nfunc initGL() {\n\tvar err error\n\tprogram, err = glutil.CreateProgram(vertexShader, fragmentShader)\n\tif err != nil {\n\t\tlog.Printf(\"error creating GL program: %v\", err)\n\t\treturn\n\t}\n\n\tbuf = gl.GenBuffers(1)[0]\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.BufferData(gl.ARRAY_BUFFER, gl.STATIC_DRAW, triangleData)\n\n\tposition = gl.GetAttribLocation(program, \"position\")\n\tcolor = gl.GetUniformLocation(program, \"color\")\n\toffset = gl.GetUniformLocation(program, \"offset\")\n\ttouchLoc = geom.Point{geom.Width \/ 2, geom.Height \/ 2}\n}\n\nfunc touch(t event.Touch) {\n\ttouchLoc = t.Loc\n}\n\nfunc draw() {\n\tif program == 0 {\n\t\tinitGL()\n\t\tlog.Printf(\"example\/basic rendering initialized\")\n\t}\n\n\tgl.ClearColor(1, 0, 0, 1)\n\tgl.Clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT)\n\n\tgl.UseProgram(program)\n\n\tgreen += 0.01\n\tif green > 1 {\n\t\tgreen = 0\n\t}\n\tgl.Uniform4f(color, 0, green, 0, 1)\n\n\tgl.Uniform2f(offset, float32(touchLoc.X\/geom.Width), float32(touchLoc.Y\/geom.Height))\n\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.EnableVertexAttribArray(position)\n\tgl.VertexAttribPointer(position, coordsPerVertex, gl.FLOAT, false, 0, 0)\n\tgl.DrawArrays(gl.TRIANGLES, 0, vertexCount)\n\tgl.DisableVertexAttribArray(position)\n}\n\nvar triangleData []byte\n\nfunc init() {\n\tbuf := new(bytes.Buffer)\n\tif err := binary.Write(buf, binary.LittleEndian, triangleCoords); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttriangleData = buf.Bytes()\n}\n\nconst coordsPerVertex = 3\n\nvar triangleCoords = []float32{\n\t0, 0.4, 0, \/\/ top left\n\t0, 0, 0, \/\/ bottom left\n\t0.4, 0, 0, \/\/ bottom right\n}\nvar vertexCount = len(triangleCoords) \/ coordsPerVertex\n\nconst vertexShader = `\nuniform vec2 offset;\n\nattribute vec4 position;\nvoid main() {\n\t\/\/ offset comes in with x\/y values between 0 and 1.\n\t\/\/ position bounds are -1 to 1.\n\tvec4 offset4 = vec4(2.0*offset.x-1.0, 1.0-2.0*offset.y, 0, 0);\n\tgl_Position = position + offset4;\n}`\n\nconst fragmentShader = `\nprecision mediump float;\nuniform vec4 color;\nvoid main() {\n\tgl_FragColor = color;\n}`\n<|endoftext|>"} {"text":"package awsprovider\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\t\"koding\/kites\/kloud\/api\/amazon\"\n\t\"koding\/kites\/kloud\/contexthelper\/publickeys\"\n\t\"koding\/kites\/kloud\/contexthelper\/request\"\n\t\"koding\/kites\/kloud\/machinestate\"\n\t\"koding\/kites\/kloud\/userdata\"\n\n\tkiteprotocol \"github.com\/koding\/kite\/protocol\"\n\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar DefaultUbuntuImage = \"ami-d05e75b8\"\n\ntype BuildData struct {\n\t\/\/ This is passed directly to goamz to create the final instance\n\tEC2Data *ec2.RunInstances\n\tImageData *ImageData\n\tKiteId string\n}\n\ntype ImageData struct {\n\tblockDeviceMapping ec2.BlockDeviceMapping\n\timageId string\n}\n\nfunc (m *Machine) Build(ctx context.Context) (err error) {\n\treq, ok := request.FromContext(ctx)\n\tif !ok {\n\t\treturn errors.New(\"request context is not available\")\n\t}\n\n\t\/\/ the user might send us a snapshot id\n\tvar args struct {\n\t\tReason string\n\t}\n\n\terr = req.Args.One().Unmarshal(&args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treason := \"Machine is building.\"\n\tif args.Reason != \"\" {\n\t\treason += \"Custom reason: \" + args.Reason\n\t}\n\n\tif err := m.UpdateState(reason, machinestate.Building); err != nil {\n\t\treturn err\n\t}\n\n\tlatestState := m.State()\n\tdefer func() {\n\t\t\/\/ run any availabile cleanupFunction\n\t\tm.runCleanupFunctions()\n\n\t\t\/\/ if there is any error mark it as NotInitialized\n\t\tif err != nil {\n\t\t\tm.UpdateState(\"Machine is marked as \"+latestState.String(), latestState)\n\t\t}\n\t}()\n\n\tif m.Meta.InstanceName == \"\" {\n\t\tm.Meta.InstanceName = \"user-\" + m.Username + \"-\" + strconv.FormatInt(time.Now().UTC().UnixNano(), 10)\n\t}\n\n\t\/\/ if there is already a machine just check it again\n\tif m.Meta.InstanceId == \"\" {\n\t\tm.push(\"Generating and fetching build data\", 10, machinestate.Building)\n\n\t\tm.Log.Debug(\"Generating and fetching build data\")\n\t\tbuildData, err := m.buildData(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm.Meta.SourceAmi = buildData.ImageData.imageId\n\t\tm.QueryString = kiteprotocol.Kite{ID: buildData.KiteId}.String()\n\n\t\tm.push(\"Initiating build process\", 30, machinestate.Building)\n\t\tm.Log.Debug(\"Initiating creating process of instance\")\n\n\t\tm.Meta.InstanceId, err = m.Session.AWSClient.Build(buildData.EC2Data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := m.Session.DB.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\treturn c.UpdateId(\n\t\t\t\tm.Id,\n\t\t\t\tbson.M{\"$set\": bson.M{\n\t\t\t\t\t\"meta.instanceId\": m.Meta.InstanceId,\n\t\t\t\t\t\"meta.source_ami\": m.Meta.SourceAmi,\n\t\t\t\t\t\"meta.region\": m.Meta.Region,\n\t\t\t\t\t\"queryString\": m.QueryString,\n\t\t\t\t}},\n\t\t\t)\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tm.Log.Debug(\"Continue build process with data, instanceId: '%s' and queryString: '%s'\",\n\t\t\tm.Meta.InstanceId, m.QueryString)\n\t}\n\n\tm.push(\"Checking build process\", 40, machinestate.Building)\n\tm.Log.Debug(\"Checking build process of instanceId '%s'\", m.Meta.InstanceId)\n\n\tinstance, err := m.Session.AWSClient.CheckBuild(ctx, m.Meta.InstanceId, 50, 70)\n\tif err == amazon.ErrInstanceTerminated || err == amazon.ErrNoInstances {\n\t\tif err := m.markAsNotInitialized(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errors.New(\"instance is not available anymore\")\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.Meta.InstanceType = instance.InstanceType\n\tm.Meta.SourceAmi = instance.ImageId\n\tm.IpAddress = instance.PublicIpAddress\n\n\tm.push(\"Adding and setting up domains and tags\", 70, machinestate.Building)\n\tm.addDomainAndTags()\n\n\tm.push(fmt.Sprintf(\"Checking klient connection '%s'\", m.IpAddress), 80, machinestate.Building)\n\tif !m.isKlientReady() {\n\t\treturn errors.New(\"klient is not ready\")\n\t}\n\n\tresultInfo := fmt.Sprintf(\"username: [%s], instanceId: [%s], ipAdress: [%s], kiteQuery: [%s]\",\n\t\tm.Username, m.Meta.InstanceId, m.IpAddress, m.QueryString)\n\n\tm.Log.Info(\"========== BUILD results ========== %s\", resultInfo)\n\n\treason = \"Machine is build successfully.\"\n\tif args.Reason != \"\" {\n\t\treason += \"Custom reason: \" + args.Reason\n\t}\n\n\treturn m.Session.DB.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\treturn c.UpdateId(\n\t\t\tm.Id,\n\t\t\tbson.M{\"$set\": bson.M{\n\t\t\t\t\"ipAddress\": m.IpAddress,\n\t\t\t\t\"queryString\": m.QueryString,\n\t\t\t\t\"meta.instanceType\": m.Meta.InstanceType,\n\t\t\t\t\"meta.instanceName\": m.Meta.InstanceName,\n\t\t\t\t\"meta.instanceId\": m.Meta.InstanceId,\n\t\t\t\t\"meta.source_ami\": m.Meta.SourceAmi,\n\t\t\t\t\"status.state\": machinestate.Running.String(),\n\t\t\t\t\"status.modifiedAt\": time.Now().UTC(),\n\t\t\t\t\"status.reason\": reason,\n\t\t\t}},\n\t\t)\n\t})\n}\n\nfunc (m *Machine) imageData() (*ImageData, error) {\n\tif m.Meta.StorageSize == 0 {\n\t\treturn nil, errors.New(\"storage size is zero\")\n\t}\n\n\tm.Log.Debug(\"Fetching image which is tagged with '%s'\", m.Meta.SourceAmi)\n\n\timageId := DefaultUbuntuImage\n\tif m.Meta.SourceAmi != \"\" {\n\t\tm.Log.Critical(\"Source AMI is not set, using default Ubuntu AMI: %s\", DefaultUbuntuImage)\n\t\timageId = m.Meta.SourceAmi\n\t}\n\n\timage, err := m.Session.AWSClient.Image(imageId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice := image.BlockDevices[0]\n\n\t\/\/ The lowest commong storage size for public Images is 8. To have a\n\t\/\/ smaller storage size (like we do have for Koding, one must create new\n\t\/\/ image). We assume that nodody did this :)\n\tif m.Meta.StorageSize < 8 {\n\t\tm.Meta.StorageSize = 8\n\t}\n\n\t\/\/ Increase storage if it's passed to us, otherwise the default 3GB is\n\t\/\/ created already with the default AMI\n\tblockDeviceMapping := ec2.BlockDeviceMapping{\n\t\tDeviceName: device.DeviceName,\n\t\tVirtualName: device.VirtualName,\n\t\tVolumeType: \"standard\", \/\/ Use magnetic storage because it is cheaper\n\t\tVolumeSize: int64(m.Meta.StorageSize),\n\t\tDeleteOnTermination: true,\n\t\tEncrypted: false,\n\t}\n\n\tm.Log.Debug(\"Using image Id: %s and block device settings %v\", image.Id, blockDeviceMapping)\n\n\treturn &ImageData{\n\t\timageId: image.Id,\n\t\tblockDeviceMapping: blockDeviceMapping,\n\t}, nil\n}\n\n\/\/ buildData returns all necessary data that is needed to build a machine.\nfunc (m *Machine) buildData(ctx context.Context) (*BuildData, error) {\n\timageData, err := m.imageData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif m.Session.AWSClient.Builder.InstanceType == \"\" {\n\t\treturn nil, errors.New(\"instance type is empty\")\n\t}\n\n\tkiteUUID, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkiteId := kiteUUID.String()\n\n\tm.Log.Debug(\"Creating user data\")\n\n\tsshKeys := make([]string, len(m.User.SshKeys))\n\tfor i, sshKey := range m.User.SshKeys {\n\t\tsshKeys[i] = sshKey.Key\n\t}\n\n\tcloudInitConfig := &userdata.CloudInitConfig{\n\t\tUsername: m.Username,\n\t\tGroups: []string{\"sudo\"},\n\t\tUserSSHKeys: sshKeys,\n\t\tHostname: m.Username, \/\/ no typo here. hostname = username\n\t\tKiteId: kiteId,\n\t}\n\n\tuserdata, err := m.Session.Userdata.Create(cloudInitConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys, ok := publickeys.FromContext(ctx)\n\tif !ok {\n\t\treturn nil, errors.New(\"public keys are not available\")\n\t}\n\n\tsubnets, err := m.Session.AWSClient.ListSubnets()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(subnets.Subnets) == 0 {\n\t\treturn nil, errors.New(\"no subnets are available\")\n\t}\n\n\tvar subnetId string\n\tvar vpcId string\n\tfor _, subnet := range subnets.Subnets {\n\t\tif subnet.AvailableIpAddressCount == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tsubnetId = subnet.SubnetId\n\t\tvpcId = subnet.VpcId\n\t}\n\n\tif subnetId == \"\" {\n\t\treturn nil, errors.New(\"subnetId is empty\")\n\t}\n\n\tvar groupName = \"Koding-Kloud-SG\"\n\tvar group ec2.SecurityGroup\n\n\tgroup, err = m.Session.AWSClient.SecurityGroup(groupName)\n\tif err != nil {\n\t\t\/\/ TODO: parse the error code and only create if it's a `NotFound` error\n\t\t\/\/ assume it doesn't exists, go and create it\n\t\topts := ec2.SecurityGroup{\n\t\t\tName: groupName,\n\t\t\tDescription: \"Koding VMs group\",\n\t\t\tVpcId: vpcId,\n\t\t}\n\n\t\tresp, err := m.Session.AWSClient.Client.CreateSecurityGroup(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Authorize the SSH and Klient access\n\t\tperms := []ec2.IPPerm{\n\t\t\tec2.IPPerm{\n\t\t\t\tProtocol: \"tcp\",\n\t\t\t\tFromPort: 0,\n\t\t\t\tToPort: 65535,\n\t\t\t\tSourceIPs: []string{\"0.0.0.0\/0\"},\n\t\t\t},\n\t\t}\n\n\t\tgroup = resp.SecurityGroup\n\n\t\t\/\/ TODO: use retry mechanism\n\t\t\/\/ We loop and retry this a few times because sometimes the security\n\t\t\/\/ group isn't available immediately because AWS resources are eventaully\n\t\t\/\/ consistent.\n\t\tfor i := 0; i < 5; i++ {\n\t\t\t_, err = m.Session.AWSClient.Client.AuthorizeSecurityGroup(group, perms)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tm.Log.Error(\"Error authorizing. Will sleep and retry. %s\", err)\n\t\t\ttime.Sleep((time.Duration(i) * time.Second) + 1)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\tm.Session.AWSClient.Builder.KeyPair = keys.KeyName\n\tm.Session.AWSClient.Builder.PrivateKey = keys.PrivateKey\n\tm.Session.AWSClient.Builder.PublicKey = keys.PublicKey\n\n\tkeyName, err := m.Session.AWSClient.DeployKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tec2Data := &ec2.RunInstances{\n\t\tImageId: m.Meta.SourceAmi,\n\t\tMinCount: 1,\n\t\tMaxCount: 1,\n\t\tKeyName: keyName,\n\t\tInstanceType: m.Session.AWSClient.Builder.InstanceType,\n\t\tSubnetId: subnetId,\n\t\tSecurityGroups: []ec2.SecurityGroup{{Id: group.Id}},\n\t\tAssociatePublicIpAddress: true,\n\t\tBlockDevices: []ec2.BlockDeviceMapping{imageData.blockDeviceMapping},\n\t\tUserData: userdata,\n\t}\n\n\treturn &BuildData{\n\t\tEC2Data: ec2Data,\n\t\tImageData: imageData,\n\t\tKiteId: kiteId,\n\t}, nil\n}\n\nfunc (m *Machine) addDomainAndTags() {\n\t\/\/ this can happen when an Info method is called on a terminated instance.\n\t\/\/ This updates the DB records with the name that EC2 gives us, which is a\n\t\/\/ \"terminated-instance\"\n\tm.Log.Debug(\"Adding and setting up domain and tags\")\n\tif m.Meta.InstanceName == \"terminated-instance\" {\n\t\tm.Meta.InstanceName = \"user-\" + m.Username + \"-\" + strconv.FormatInt(time.Now().UTC().UnixNano(), 10)\n\t\tm.Log.Debug(\"Instance name is an artifact (terminated), changing to %s\", m.Meta.InstanceName)\n\t}\n\n\tm.push(\"Updating\/Creating domain\", 70, machinestate.Building)\n\tm.Log.Debug(\"Updating\/Creating domain %s\", m.IpAddress)\n\n\tif err := m.Session.DNSClient.Validate(m.Domain, m.Username); err != nil {\n\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t}\n\n\tif err := m.Session.DNSClient.Upsert(m.Domain, m.IpAddress); err != nil {\n\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t}\n\n\tm.push(\"Updating domain aliases\", 72, machinestate.Building)\n\tdomains, err := m.Session.DNSStorage.GetByMachine(m.Id.Hex())\n\tif err != nil {\n\t\tm.Log.Error(\"fetching domains for setting err: %s\", err.Error())\n\t}\n\n\tfor _, domain := range domains {\n\t\tif err := m.Session.DNSClient.Validate(domain.Name, m.Username); err != nil {\n\t\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t\t}\n\t\tif err := m.Session.DNSClient.Upsert(domain.Name, m.IpAddress); err != nil {\n\t\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t\t}\n\t}\n\n\ttags := []ec2.Tag{\n\t\t{Key: \"Name\", Value: m.Meta.InstanceName},\n\t\t{Key: \"koding-user\", Value: m.Username},\n\t\t{Key: \"koding-env\", Value: m.Session.Kite.Config.Environment},\n\t\t{Key: \"koding-machineId\", Value: m.Id.Hex()},\n\t\t{Key: \"koding-domain\", Value: m.Domain},\n\t}\n\n\tm.Log.Debug(\"Adding user tags %v\", tags)\n\tif err := m.Session.AWSClient.AddTags(m.Meta.InstanceId, tags); err != nil {\n\t\tm.Log.Error(\"Adding tags failed: %v\", err)\n\t}\n}\nkloud: fix aws passing empty for fallback imagepackage awsprovider\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\t\"koding\/kites\/kloud\/api\/amazon\"\n\t\"koding\/kites\/kloud\/contexthelper\/publickeys\"\n\t\"koding\/kites\/kloud\/contexthelper\/request\"\n\t\"koding\/kites\/kloud\/machinestate\"\n\t\"koding\/kites\/kloud\/userdata\"\n\n\tkiteprotocol \"github.com\/koding\/kite\/protocol\"\n\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar DefaultUbuntuImage = \"ami-d05e75b8\"\n\ntype BuildData struct {\n\t\/\/ This is passed directly to goamz to create the final instance\n\tEC2Data *ec2.RunInstances\n\tImageData *ImageData\n\tKiteId string\n}\n\ntype ImageData struct {\n\tblockDeviceMapping ec2.BlockDeviceMapping\n\timageId string\n}\n\nfunc (m *Machine) Build(ctx context.Context) (err error) {\n\treq, ok := request.FromContext(ctx)\n\tif !ok {\n\t\treturn errors.New(\"request context is not available\")\n\t}\n\n\t\/\/ the user might send us a snapshot id\n\tvar args struct {\n\t\tReason string\n\t}\n\n\terr = req.Args.One().Unmarshal(&args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treason := \"Machine is building.\"\n\tif args.Reason != \"\" {\n\t\treason += \"Custom reason: \" + args.Reason\n\t}\n\n\tif err := m.UpdateState(reason, machinestate.Building); err != nil {\n\t\treturn err\n\t}\n\n\tlatestState := m.State()\n\tdefer func() {\n\t\t\/\/ run any availabile cleanupFunction\n\t\tm.runCleanupFunctions()\n\n\t\t\/\/ if there is any error mark it as NotInitialized\n\t\tif err != nil {\n\t\t\tm.UpdateState(\"Machine is marked as \"+latestState.String(), latestState)\n\t\t}\n\t}()\n\n\tif m.Meta.InstanceName == \"\" {\n\t\tm.Meta.InstanceName = \"user-\" + m.Username + \"-\" + strconv.FormatInt(time.Now().UTC().UnixNano(), 10)\n\t}\n\n\t\/\/ if there is already a machine just check it again\n\tif m.Meta.InstanceId == \"\" {\n\t\tm.push(\"Generating and fetching build data\", 10, machinestate.Building)\n\n\t\tm.Log.Debug(\"Generating and fetching build data\")\n\t\tbuildData, err := m.buildData(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm.Meta.SourceAmi = buildData.ImageData.imageId\n\t\tm.QueryString = kiteprotocol.Kite{ID: buildData.KiteId}.String()\n\n\t\tm.push(\"Initiating build process\", 30, machinestate.Building)\n\t\tm.Log.Debug(\"Initiating creating process of instance\")\n\n\t\tm.Meta.InstanceId, err = m.Session.AWSClient.Build(buildData.EC2Data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := m.Session.DB.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\treturn c.UpdateId(\n\t\t\t\tm.Id,\n\t\t\t\tbson.M{\"$set\": bson.M{\n\t\t\t\t\t\"meta.instanceId\": m.Meta.InstanceId,\n\t\t\t\t\t\"meta.source_ami\": m.Meta.SourceAmi,\n\t\t\t\t\t\"meta.region\": m.Meta.Region,\n\t\t\t\t\t\"queryString\": m.QueryString,\n\t\t\t\t}},\n\t\t\t)\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tm.Log.Debug(\"Continue build process with data, instanceId: '%s' and queryString: '%s'\",\n\t\t\tm.Meta.InstanceId, m.QueryString)\n\t}\n\n\tm.push(\"Checking build process\", 40, machinestate.Building)\n\tm.Log.Debug(\"Checking build process of instanceId '%s'\", m.Meta.InstanceId)\n\n\tinstance, err := m.Session.AWSClient.CheckBuild(ctx, m.Meta.InstanceId, 50, 70)\n\tif err == amazon.ErrInstanceTerminated || err == amazon.ErrNoInstances {\n\t\tif err := m.markAsNotInitialized(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errors.New(\"instance is not available anymore\")\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.Meta.InstanceType = instance.InstanceType\n\tm.Meta.SourceAmi = instance.ImageId\n\tm.IpAddress = instance.PublicIpAddress\n\n\tm.push(\"Adding and setting up domains and tags\", 70, machinestate.Building)\n\tm.addDomainAndTags()\n\n\tm.push(fmt.Sprintf(\"Checking klient connection '%s'\", m.IpAddress), 80, machinestate.Building)\n\tif !m.isKlientReady() {\n\t\treturn errors.New(\"klient is not ready\")\n\t}\n\n\tresultInfo := fmt.Sprintf(\"username: [%s], instanceId: [%s], ipAdress: [%s], kiteQuery: [%s]\",\n\t\tm.Username, m.Meta.InstanceId, m.IpAddress, m.QueryString)\n\n\tm.Log.Info(\"========== BUILD results ========== %s\", resultInfo)\n\n\treason = \"Machine is build successfully.\"\n\tif args.Reason != \"\" {\n\t\treason += \"Custom reason: \" + args.Reason\n\t}\n\n\treturn m.Session.DB.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\treturn c.UpdateId(\n\t\t\tm.Id,\n\t\t\tbson.M{\"$set\": bson.M{\n\t\t\t\t\"ipAddress\": m.IpAddress,\n\t\t\t\t\"queryString\": m.QueryString,\n\t\t\t\t\"meta.instanceType\": m.Meta.InstanceType,\n\t\t\t\t\"meta.instanceName\": m.Meta.InstanceName,\n\t\t\t\t\"meta.instanceId\": m.Meta.InstanceId,\n\t\t\t\t\"meta.source_ami\": m.Meta.SourceAmi,\n\t\t\t\t\"status.state\": machinestate.Running.String(),\n\t\t\t\t\"status.modifiedAt\": time.Now().UTC(),\n\t\t\t\t\"status.reason\": reason,\n\t\t\t}},\n\t\t)\n\t})\n}\n\nfunc (m *Machine) imageData() (*ImageData, error) {\n\tif m.Meta.StorageSize == 0 {\n\t\treturn nil, errors.New(\"storage size is zero\")\n\t}\n\n\tm.Log.Debug(\"Fetching image which is tagged with '%s'\", m.Meta.SourceAmi)\n\n\timageId := DefaultUbuntuImage\n\tif m.Meta.SourceAmi != \"\" {\n\t\tm.Log.Critical(\"Source AMI is not set, using default Ubuntu AMI: %s\", DefaultUbuntuImage)\n\t\timageId = m.Meta.SourceAmi\n\t}\n\n\timage, err := m.Session.AWSClient.Image(imageId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdevice := image.BlockDevices[0]\n\n\t\/\/ The lowest commong storage size for public Images is 8. To have a\n\t\/\/ smaller storage size (like we do have for Koding, one must create new\n\t\/\/ image). We assume that nodody did this :)\n\tif m.Meta.StorageSize < 8 {\n\t\tm.Meta.StorageSize = 8\n\t}\n\n\t\/\/ Increase storage if it's passed to us, otherwise the default 3GB is\n\t\/\/ created already with the default AMI\n\tblockDeviceMapping := ec2.BlockDeviceMapping{\n\t\tDeviceName: device.DeviceName,\n\t\tVirtualName: device.VirtualName,\n\t\tVolumeType: \"standard\", \/\/ Use magnetic storage because it is cheaper\n\t\tVolumeSize: int64(m.Meta.StorageSize),\n\t\tDeleteOnTermination: true,\n\t\tEncrypted: false,\n\t}\n\n\tm.Log.Debug(\"Using image Id: %s and block device settings %v\", image.Id, blockDeviceMapping)\n\n\treturn &ImageData{\n\t\timageId: image.Id,\n\t\tblockDeviceMapping: blockDeviceMapping,\n\t}, nil\n}\n\n\/\/ buildData returns all necessary data that is needed to build a machine.\nfunc (m *Machine) buildData(ctx context.Context) (*BuildData, error) {\n\timageData, err := m.imageData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif m.Session.AWSClient.Builder.InstanceType == \"\" {\n\t\treturn nil, errors.New(\"instance type is empty\")\n\t}\n\n\tkiteUUID, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkiteId := kiteUUID.String()\n\n\tm.Log.Debug(\"Creating user data\")\n\n\tsshKeys := make([]string, len(m.User.SshKeys))\n\tfor i, sshKey := range m.User.SshKeys {\n\t\tsshKeys[i] = sshKey.Key\n\t}\n\n\tcloudInitConfig := &userdata.CloudInitConfig{\n\t\tUsername: m.Username,\n\t\tGroups: []string{\"sudo\"},\n\t\tUserSSHKeys: sshKeys,\n\t\tHostname: m.Username, \/\/ no typo here. hostname = username\n\t\tKiteId: kiteId,\n\t}\n\n\tuserdata, err := m.Session.Userdata.Create(cloudInitConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys, ok := publickeys.FromContext(ctx)\n\tif !ok {\n\t\treturn nil, errors.New(\"public keys are not available\")\n\t}\n\n\tsubnets, err := m.Session.AWSClient.ListSubnets()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(subnets.Subnets) == 0 {\n\t\treturn nil, errors.New(\"no subnets are available\")\n\t}\n\n\tvar subnetId string\n\tvar vpcId string\n\tfor _, subnet := range subnets.Subnets {\n\t\tif subnet.AvailableIpAddressCount == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tsubnetId = subnet.SubnetId\n\t\tvpcId = subnet.VpcId\n\t}\n\n\tif subnetId == \"\" {\n\t\treturn nil, errors.New(\"subnetId is empty\")\n\t}\n\n\tvar groupName = \"Koding-Kloud-SG\"\n\tvar group ec2.SecurityGroup\n\n\tgroup, err = m.Session.AWSClient.SecurityGroup(groupName)\n\tif err != nil {\n\t\t\/\/ TODO: parse the error code and only create if it's a `NotFound` error\n\t\t\/\/ assume it doesn't exists, go and create it\n\t\topts := ec2.SecurityGroup{\n\t\t\tName: groupName,\n\t\t\tDescription: \"Koding VMs group\",\n\t\t\tVpcId: vpcId,\n\t\t}\n\n\t\tresp, err := m.Session.AWSClient.Client.CreateSecurityGroup(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Authorize the SSH and Klient access\n\t\tperms := []ec2.IPPerm{\n\t\t\tec2.IPPerm{\n\t\t\t\tProtocol: \"tcp\",\n\t\t\t\tFromPort: 0,\n\t\t\t\tToPort: 65535,\n\t\t\t\tSourceIPs: []string{\"0.0.0.0\/0\"},\n\t\t\t},\n\t\t}\n\n\t\tgroup = resp.SecurityGroup\n\n\t\t\/\/ TODO: use retry mechanism\n\t\t\/\/ We loop and retry this a few times because sometimes the security\n\t\t\/\/ group isn't available immediately because AWS resources are eventaully\n\t\t\/\/ consistent.\n\t\tfor i := 0; i < 5; i++ {\n\t\t\t_, err = m.Session.AWSClient.Client.AuthorizeSecurityGroup(group, perms)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tm.Log.Error(\"Error authorizing. Will sleep and retry. %s\", err)\n\t\t\ttime.Sleep((time.Duration(i) * time.Second) + 1)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\tm.Session.AWSClient.Builder.KeyPair = keys.KeyName\n\tm.Session.AWSClient.Builder.PrivateKey = keys.PrivateKey\n\tm.Session.AWSClient.Builder.PublicKey = keys.PublicKey\n\n\tkeyName, err := m.Session.AWSClient.DeployKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tec2Data := &ec2.RunInstances{\n\t\tImageId: imageData.imageId,\n\t\tMinCount: 1,\n\t\tMaxCount: 1,\n\t\tKeyName: keyName,\n\t\tInstanceType: m.Session.AWSClient.Builder.InstanceType,\n\t\tSubnetId: subnetId,\n\t\tSecurityGroups: []ec2.SecurityGroup{{Id: group.Id}},\n\t\tAssociatePublicIpAddress: true,\n\t\tBlockDevices: []ec2.BlockDeviceMapping{imageData.blockDeviceMapping},\n\t\tUserData: userdata,\n\t}\n\n\treturn &BuildData{\n\t\tEC2Data: ec2Data,\n\t\tImageData: imageData,\n\t\tKiteId: kiteId,\n\t}, nil\n}\n\nfunc (m *Machine) addDomainAndTags() {\n\t\/\/ this can happen when an Info method is called on a terminated instance.\n\t\/\/ This updates the DB records with the name that EC2 gives us, which is a\n\t\/\/ \"terminated-instance\"\n\tm.Log.Debug(\"Adding and setting up domain and tags\")\n\tif m.Meta.InstanceName == \"terminated-instance\" {\n\t\tm.Meta.InstanceName = \"user-\" + m.Username + \"-\" + strconv.FormatInt(time.Now().UTC().UnixNano(), 10)\n\t\tm.Log.Debug(\"Instance name is an artifact (terminated), changing to %s\", m.Meta.InstanceName)\n\t}\n\n\tm.push(\"Updating\/Creating domain\", 70, machinestate.Building)\n\tm.Log.Debug(\"Updating\/Creating domain %s\", m.IpAddress)\n\n\tif err := m.Session.DNSClient.Validate(m.Domain, m.Username); err != nil {\n\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t}\n\n\tif err := m.Session.DNSClient.Upsert(m.Domain, m.IpAddress); err != nil {\n\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t}\n\n\tm.push(\"Updating domain aliases\", 72, machinestate.Building)\n\tdomains, err := m.Session.DNSStorage.GetByMachine(m.Id.Hex())\n\tif err != nil {\n\t\tm.Log.Error(\"fetching domains for setting err: %s\", err.Error())\n\t}\n\n\tfor _, domain := range domains {\n\t\tif err := m.Session.DNSClient.Validate(domain.Name, m.Username); err != nil {\n\t\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t\t}\n\t\tif err := m.Session.DNSClient.Upsert(domain.Name, m.IpAddress); err != nil {\n\t\t\tm.Log.Error(\"couldn't update machine domain: %s\", err.Error())\n\t\t}\n\t}\n\n\ttags := []ec2.Tag{\n\t\t{Key: \"Name\", Value: m.Meta.InstanceName},\n\t\t{Key: \"koding-user\", Value: m.Username},\n\t\t{Key: \"koding-env\", Value: m.Session.Kite.Config.Environment},\n\t\t{Key: \"koding-machineId\", Value: m.Id.Hex()},\n\t\t{Key: \"koding-domain\", Value: m.Domain},\n\t}\n\n\tm.Log.Debug(\"Adding user tags %v\", tags)\n\tif err := m.Session.AWSClient.AddTags(m.Meta.InstanceId, tags); err != nil {\n\t\tm.Log.Error(\"Adding tags failed: %v\", err)\n\t}\n}\n<|endoftext|>"} {"text":"package engine\n\n\/\/ #include \n\/\/ #include \"skiplist.h\"\n\/\/ #include \"kv_skiplist.h\"\nimport \"C\"\nimport (\n\t\"sync\/atomic\"\n\t\"unsafe\"\n)\n\n\/\/ byteToChar returns *C.char from byte slice.\nfunc byteToChar(b []byte) *C.char {\n\tvar c *C.char\n\tif len(b) > 0 {\n\t\tc = (*C.char)(unsafe.Pointer(&b[0]))\n\t}\n\treturn c\n}\n\ntype skipList struct {\n\tcsl *C.skiplist_raw\n\tclosed int32\n}\n\nfunc NewSkipList() *skipList {\n\treturn &skipList{\n\t\tcsl: C.kv_skiplist_create(),\n\t}\n}\n\nfunc (sl *skipList) Destroy() {\n\tatomic.StoreInt32(&sl.closed, 1)\n\tC.kv_skiplist_destroy(sl.csl)\n}\n\nfunc (sl *skipList) IsClosed() bool {\n\treturn atomic.LoadInt32(&sl.closed) == 1\n}\n\nfunc (sl *skipList) Len() int64 {\n\tcs := C.skiplist_get_size(sl.csl)\n\treturn int64(cs)\n}\n\nfunc (sl *skipList) NewIterator() *SkipListIterator {\n\t\/\/ the mutex RUnlock must be called while iterator is closed\n\treturn &SkipListIterator{\n\t\tsl: sl,\n\t\tcursor: nil,\n\t}\n}\n\nfunc (sl *skipList) Get(key []byte) ([]byte, error) {\n\tvar (\n\t\tcvsz C.size_t\n\t\tcKey = byteToChar(key)\n\t)\n\tcv := C.kv_skiplist_get(sl.csl, cKey, C.size_t(len(key)), &cvsz)\n\tif cv == nil {\n\t\treturn nil, nil\n\t}\n\tdefer C.free(unsafe.Pointer(cv))\n\treturn C.GoBytes(unsafe.Pointer(cv), C.int(cvsz)), nil\n}\n\nfunc (sl *skipList) Set(key []byte, value []byte) error {\n\tvar (\n\t\tcKey = byteToChar(key)\n\t\tcValue = byteToChar(value)\n\t)\n\tC.kv_skiplist_update(sl.csl, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))\n\treturn nil\n}\n\nfunc (sl *skipList) Delete(key []byte) error {\n\tcKey := byteToChar(key)\n\tC.kv_skiplist_del(sl.csl, cKey, C.size_t(len(key)))\n\treturn nil\n}\nfix compile for linuxpackage engine\n\n\/\/#cgo CXXFLAGS: -std=c++11\n\/\/ #include \n\/\/ #include \"skiplist.h\"\n\/\/ #include \"kv_skiplist.h\"\nimport \"C\"\nimport (\n\t\"sync\/atomic\"\n\t\"unsafe\"\n)\n\n\/\/ byteToChar returns *C.char from byte slice.\nfunc byteToChar(b []byte) *C.char {\n\tvar c *C.char\n\tif len(b) > 0 {\n\t\tc = (*C.char)(unsafe.Pointer(&b[0]))\n\t}\n\treturn c\n}\n\ntype skipList struct {\n\tcsl *C.skiplist_raw\n\tclosed int32\n}\n\nfunc NewSkipList() *skipList {\n\treturn &skipList{\n\t\tcsl: C.kv_skiplist_create(),\n\t}\n}\n\nfunc (sl *skipList) Destroy() {\n\tatomic.StoreInt32(&sl.closed, 1)\n\tC.kv_skiplist_destroy(sl.csl)\n}\n\nfunc (sl *skipList) IsClosed() bool {\n\treturn atomic.LoadInt32(&sl.closed) == 1\n}\n\nfunc (sl *skipList) Len() int64 {\n\tcs := C.skiplist_get_size(sl.csl)\n\treturn int64(cs)\n}\n\nfunc (sl *skipList) NewIterator() *SkipListIterator {\n\t\/\/ the mutex RUnlock must be called while iterator is closed\n\treturn &SkipListIterator{\n\t\tsl: sl,\n\t\tcursor: nil,\n\t}\n}\n\nfunc (sl *skipList) Get(key []byte) ([]byte, error) {\n\tvar (\n\t\tcvsz C.size_t\n\t\tcKey = byteToChar(key)\n\t)\n\tcv := C.kv_skiplist_get(sl.csl, cKey, C.size_t(len(key)), &cvsz)\n\tif cv == nil {\n\t\treturn nil, nil\n\t}\n\tdefer C.free(unsafe.Pointer(cv))\n\treturn C.GoBytes(unsafe.Pointer(cv), C.int(cvsz)), nil\n}\n\nfunc (sl *skipList) Set(key []byte, value []byte) error {\n\tvar (\n\t\tcKey = byteToChar(key)\n\t\tcValue = byteToChar(value)\n\t)\n\tC.kv_skiplist_update(sl.csl, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))\n\treturn nil\n}\n\nfunc (sl *skipList) Delete(key []byte) error {\n\tcKey := byteToChar(key)\n\tC.kv_skiplist_del(sl.csl, cKey, C.size_t(len(key)))\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t. \"koding\/db\/models\"\n\thelper \"koding\/db\/mongodb\/modelhelper\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\n\/\/ hard delete.\nfunc DeleteStatusUpdate(id string) error {\n\terr := RemoveComments(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\terr = RemovePostRelationships(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\terr = helper.DeleteStatusUpdateById(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\tlog.Info(\"Deleted Empty Status Update\")\n\treturn nil\n}\n\n\/\/Creates Relationships both in mongo and neo4j\nfunc CreateRelationship(relationship *Relationship) error {\n\terr := CreateGraphRelationship(relationship)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Add Mongo Relationship\")\n\treturn helper.AddRelationship(relationship)\n}\n\n\/\/Removes Relationships both from mongo and neo4j\nfunc RemoveRelationship(relationship *Relationship) error {\n\terr := RemoveGraphRelationship(relationship)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tselector := helper.Selector{\n\t\t\"sourceId\": relationship.SourceId,\n\t\t\"targetId\": relationship.TargetId,\n\t\t\"as\": relationship.As,\n\t}\n\tlog.Debug(\"Delete Mongo Relationship\")\n\treturn helper.DeleteRelationship(selector)\n}\n\n\/\/Finds synonym of a given tag by tagId\nfunc FindSynonym(tagId string) (*Tag, error) {\n\tselector := helper.Selector{\"sourceId\": helper.GetObjectId(tagId), \"as\": \"synonymOf\"}\n\tsynonymRel, err := helper.GetRelationship(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn helper.GetTagById(synonymRel.TargetId.Hex())\n}\n\nfunc RemoveComments(id string) error {\n\tobjectId := helper.GetObjectId(id)\n\tselector := helper.Selector{\"targetId\": objectId, \"sourceName\": \"JComment\"}\n\n\tremovedNodeIds := make([]bson.ObjectId, 0)\n\trels, err := helper.GetRelationships(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, rel := range rels {\n\t\terr = RemoveRelationship(&rel)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tremovedNodeIds = append(removedNodeIds, rel.SourceId)\n\t}\n\n\t\/\/remove comment relationships with opposite orientation\n\tselector = helper.Selector{\"targetId\": helper.Selector{\"$in\": removedNodeIds}}\n\terr = RemoveRelationships(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tselector = helper.Selector{\"_id\": helper.Selector{\"$in\": removedNodeIds}}\n\treturn helper.DeleteComment(selector)\n}\n\nfunc RemovePostRelationships(id string) error {\n\tobjectId := helper.GetObjectId(id)\n\t\/\/ remove post relationships\n\tselector := helper.Selector{\"$or\": []helper.Selector{\n\t\thelper.Selector{\"sourceId\": objectId},\n\t\thelper.Selector{\"targetId\": objectId},\n\t}}\n\treturn RemoveRelationships(selector)\n}\n\nfunc RemoveRelationships(selector helper.Selector) error {\n\trels, err := helper.GetRelationships(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, rel := range rels {\n\t\terr = RemoveRelationship(&rel)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\nModeration: while deleting empty posts return when post does not have any commentspackage main\n\nimport (\n\t. \"koding\/db\/models\"\n\thelper \"koding\/db\/mongodb\/modelhelper\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\n\/\/ hard delete.\nfunc DeleteStatusUpdate(id string) error {\n\terr := RemoveComments(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\terr = RemovePostRelationships(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\terr = helper.DeleteStatusUpdateById(id)\n\tif err != nil {\n\t\tlog.Error(\"Empty Status Update Cannot be deleted\")\n\t\treturn err\n\t}\n\n\tlog.Info(\"Deleted Empty Status Update\")\n\treturn nil\n}\n\n\/\/Creates Relationships both in mongo and neo4j\nfunc CreateRelationship(relationship *Relationship) error {\n\terr := CreateGraphRelationship(relationship)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Add Mongo Relationship\")\n\treturn helper.AddRelationship(relationship)\n}\n\n\/\/Removes Relationships both from mongo and neo4j\nfunc RemoveRelationship(relationship *Relationship) error {\n\terr := RemoveGraphRelationship(relationship)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tselector := helper.Selector{\n\t\t\"sourceId\": relationship.SourceId,\n\t\t\"targetId\": relationship.TargetId,\n\t\t\"as\": relationship.As,\n\t}\n\tlog.Debug(\"Delete Mongo Relationship\")\n\treturn helper.DeleteRelationship(selector)\n}\n\n\/\/Finds synonym of a given tag by tagId\nfunc FindSynonym(tagId string) (*Tag, error) {\n\tselector := helper.Selector{\"sourceId\": helper.GetObjectId(tagId), \"as\": \"synonymOf\"}\n\tsynonymRel, err := helper.GetRelationship(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn helper.GetTagById(synonymRel.TargetId.Hex())\n}\n\nfunc RemoveComments(id string) error {\n\tobjectId := helper.GetObjectId(id)\n\tselector := helper.Selector{\"targetId\": objectId, \"sourceName\": \"JComment\"}\n\n\tremovedNodeIds := make([]bson.ObjectId, 0)\n\trels, err := helper.GetRelationships(selector)\n\tif len(rels) == 0 {\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, rel := range rels {\n\t\terr = RemoveRelationship(&rel)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tremovedNodeIds = append(removedNodeIds, rel.SourceId)\n\t}\n\n\t\/\/remove comment relationships with opposite orientation\n\tselector = helper.Selector{\"targetId\": helper.Selector{\"$in\": removedNodeIds}}\n\terr = RemoveRelationships(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tselector = helper.Selector{\"_id\": helper.Selector{\"$in\": removedNodeIds}}\n\treturn helper.DeleteComment(selector)\n}\n\nfunc RemovePostRelationships(id string) error {\n\tobjectId := helper.GetObjectId(id)\n\t\/\/ remove post relationships\n\tselector := helper.Selector{\"$or\": []helper.Selector{\n\t\thelper.Selector{\"sourceId\": objectId},\n\t\thelper.Selector{\"targetId\": objectId},\n\t}}\n\treturn RemoveRelationships(selector)\n}\n\nfunc RemoveRelationships(selector helper.Selector) error {\n\trels, err := helper.GetRelationships(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, rel := range rels {\n\t\terr = RemoveRelationship(&rel)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package v1alpha1\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/h-fam\/errdiff\"\n\t\"github.com\/kr\/pretty\"\n\tsrlinuxv1 \"github.com\/srl-labs\/srl-controller\/api\/types\/v1alpha1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\tktest \"k8s.io\/client-go\/testing\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\tdynamicfake \"k8s.io\/client-go\/dynamic\/fake\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/rest\"\n\trestfake \"k8s.io\/client-go\/rest\/fake\"\n)\n\nvar (\n\tobj1 = &srlinuxv1.Srlinux{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Srlinux\",\n\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"obj1\",\n\t\t\tNamespace: \"test\",\n\t\t\tGeneration: 1,\n\t\t},\n\t\tStatus: srlinuxv1.SrlinuxStatus{},\n\t\tSpec: srlinuxv1.SrlinuxSpec{\n\t\t\tConfig: &srlinuxv1.NodeConfig{},\n\t\t\tNumInterfaces: 2,\n\t\t\tModel: \"fake\",\n\t\t\tVersion: \"1\",\n\t\t},\n\t}\n\n\tobj2 = &srlinuxv1.Srlinux{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Srlinux\",\n\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"obj2\",\n\t\t\tNamespace: \"test\",\n\t\t\tGeneration: 1,\n\t\t},\n\t\tStatus: srlinuxv1.SrlinuxStatus{},\n\t\tSpec: srlinuxv1.SrlinuxSpec{\n\t\t\tConfig: &srlinuxv1.NodeConfig{},\n\t\t\tNumInterfaces: 2,\n\t\t\tModel: \"fake1\",\n\t\t\tVersion: \"2\",\n\t\t},\n\t}\n)\n\nfunc setUp(t *testing.T) (*Clientset, *restfake.RESTClient) {\n\tt.Helper()\n\n\tgv := GV()\n\n\tfakeClient := &restfake.RESTClient{\n\t\tNegotiatedSerializer: scheme.Codecs.WithoutConversion(),\n\t\tGroupVersion: *gv,\n\t\tVersionedAPIPath: GVR().Version,\n\t}\n\n\tcs, err := NewForConfig(&rest.Config{})\n\tif err != nil {\n\t\tt.Fatalf(\"NewForConfig() failed: %v\", err)\n\t}\n\n\tobjs := []runtime.Object{obj1, obj2}\n\tcs.restClient = fakeClient\n\tf := dynamicfake.NewSimpleDynamicClient(scheme.Scheme, objs...)\n\tf.PrependReactor(\"get\", \"*\", func(action ktest.Action) (bool, runtime.Object, error) {\n\t\tgAction := action.(ktest.GetAction)\n\t\tswitch gAction.GetName() {\n\t\tcase \"obj1\":\n\t\t\treturn true, obj1, nil\n\t\tcase \"obj2\":\n\t\t\treturn true, obj2, nil\n\t\t}\n\n\t\treturn false, nil, nil\n\t})\n\n\tf.PrependReactor(\"update\", \"*\", func(action ktest.Action) (bool, runtime.Object, error) {\n\t\tuAction, ok := action.(ktest.UpdateAction)\n\t\tif !ok {\n\t\t\treturn false, nil, nil\n\t\t}\n\n\t\tuObj := uAction.GetObject().(*unstructured.Unstructured)\n\t\tsObj := &srlinuxv1.Srlinux{}\n\n\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(uObj.Object, sObj); err != nil {\n\t\t\treturn true, nil, fmt.Errorf(\"failed to convert object: %v\", err)\n\t\t}\n\n\t\tif sObj.ObjectMeta.Name == \"doesnotexist\" {\n\t\t\treturn true, nil, fmt.Errorf(\"doesnotexist\")\n\t\t}\n\n\t\treturn true, uAction.GetObject(), nil\n\t})\n\n\tcs.dInterface = f.Resource(GVR())\n\n\treturn cs, fakeClient\n}\n\nfunc TestCreate(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: obj1,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\tgot, err := tc.Create(context.Background(), tt.want)\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Fatalf(\"Create(%+v) failed: diff\\n%s\", tt.want, pretty.Diff(got, want))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestList(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.SrlinuxList\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: &srlinuxv1.SrlinuxList{\n\t\t\tItems: []srlinuxv1.Srlinux{*obj1, *obj2},\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\n\t\t\tgot, err := tc.List(context.Background(), metav1.ListOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Fatalf(\"List() failed: got %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: obj1,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\n\t\t\tgot, err := tc.Get(context.Background(), \"test\", metav1.GetOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Fatalf(\"Get() failed: got %v, want %v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\terr := tc.Delete(context.Background(), \"obj1\", metav1.DeleteOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWatch(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *watch.Event\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\tw, err := tc.Watch(context.Background(), metav1.ListOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\te := <-w.ResultChan()\n\t\t\tif !reflect.DeepEqual(e, tt.want) {\n\t\t\t\tt.Fatalf(\"Watch() failed: got %v, want %v\", e, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnstructured(t *testing.T) {\n\tcs, _ := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tin string\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\tin: \"missingObj\",\n\t\twantErr: `\"missingObj\" not found`,\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tin: obj1.GetObjectMeta().GetName(),\n\t\twant: obj1,\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tin: obj2.GetObjectMeta().GetName(),\n\t\twant: obj2,\n\t}}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"test\")\n\t\t\tgot, err := tc.Unstructured(context.Background(), tt.in, metav1.GetOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuObj1 := &srlinuxv1.Srlinux{}\n\t\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(got.Object, uObj1); err != nil {\n\t\t\t\tt.Fatalf(\"failed to turn response into a topology: %v\", err)\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(uObj1, tt.want) {\n\t\t\t\tt.Fatalf(\"Unstructured(%q) failed: got %+v, want %+v\", tt.in, uObj1, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUpdate(t *testing.T) {\n\tcs, _ := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twant: &srlinuxv1.Srlinux{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: \"Srlinux\",\n\t\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"doesnotexist\",\n\t\t\t\tNamespace: \"test\",\n\t\t\t\tGeneration: 1,\n\t\t\t},\n\t\t},\n\t\twantErr: \"doesnotexist\",\n\t}, {\n\t\tdesc: \"Valid Topology\",\n\t\twant: obj1,\n\t}}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\tsc := cs.Srlinux(\"test\")\n\t\t\tupdateObj := tt.want.DeepCopy()\n\t\t\tupdateObj.Spec.Version = \"updated version\"\n\n\t\t\tupdate, err := runtime.DefaultUnstructuredConverter.ToUnstructured(updateObj)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to generate update: %v\", err)\n\t\t\t}\n\n\t\t\tgot, err := sc.Update(context.Background(), &unstructured.Unstructured{\n\t\t\t\tObject: update,\n\t\t\t}, metav1.UpdateOptions{})\n\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, updateObj) {\n\t\t\t\tt.Fatalf(\"Update() failed: got %+v, want %+v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\nfix some more cuddlingpackage v1alpha1\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/h-fam\/errdiff\"\n\t\"github.com\/kr\/pretty\"\n\tsrlinuxv1 \"github.com\/srl-labs\/srl-controller\/api\/types\/v1alpha1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\tktest \"k8s.io\/client-go\/testing\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\tdynamicfake \"k8s.io\/client-go\/dynamic\/fake\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/rest\"\n\trestfake \"k8s.io\/client-go\/rest\/fake\"\n)\n\nvar (\n\tobj1 = &srlinuxv1.Srlinux{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Srlinux\",\n\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"obj1\",\n\t\t\tNamespace: \"test\",\n\t\t\tGeneration: 1,\n\t\t},\n\t\tStatus: srlinuxv1.SrlinuxStatus{},\n\t\tSpec: srlinuxv1.SrlinuxSpec{\n\t\t\tConfig: &srlinuxv1.NodeConfig{},\n\t\t\tNumInterfaces: 2,\n\t\t\tModel: \"fake\",\n\t\t\tVersion: \"1\",\n\t\t},\n\t}\n\n\tobj2 = &srlinuxv1.Srlinux{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Srlinux\",\n\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"obj2\",\n\t\t\tNamespace: \"test\",\n\t\t\tGeneration: 1,\n\t\t},\n\t\tStatus: srlinuxv1.SrlinuxStatus{},\n\t\tSpec: srlinuxv1.SrlinuxSpec{\n\t\t\tConfig: &srlinuxv1.NodeConfig{},\n\t\t\tNumInterfaces: 2,\n\t\t\tModel: \"fake1\",\n\t\t\tVersion: \"2\",\n\t\t},\n\t}\n)\n\nfunc setUp(t *testing.T) (*Clientset, *restfake.RESTClient) {\n\tt.Helper()\n\n\tgv := GV()\n\n\tfakeClient := &restfake.RESTClient{\n\t\tNegotiatedSerializer: scheme.Codecs.WithoutConversion(),\n\t\tGroupVersion: *gv,\n\t\tVersionedAPIPath: GVR().Version,\n\t}\n\n\tcs, err := NewForConfig(&rest.Config{})\n\tif err != nil {\n\t\tt.Fatalf(\"NewForConfig() failed: %v\", err)\n\t}\n\n\tobjs := []runtime.Object{obj1, obj2}\n\tcs.restClient = fakeClient\n\tf := dynamicfake.NewSimpleDynamicClient(scheme.Scheme, objs...)\n\tf.PrependReactor(\"get\", \"*\", func(action ktest.Action) (bool, runtime.Object, error) {\n\t\tgAction := action.(ktest.GetAction)\n\t\tswitch gAction.GetName() {\n\t\tcase \"obj1\":\n\t\t\treturn true, obj1, nil\n\t\tcase \"obj2\":\n\t\t\treturn true, obj2, nil\n\t\t}\n\n\t\treturn false, nil, nil\n\t})\n\n\tf.PrependReactor(\"update\", \"*\", func(action ktest.Action) (bool, runtime.Object, error) {\n\t\tuAction, ok := action.(ktest.UpdateAction)\n\t\tif !ok {\n\t\t\treturn false, nil, nil\n\t\t}\n\n\t\tuObj := uAction.GetObject().(*unstructured.Unstructured)\n\t\tsObj := &srlinuxv1.Srlinux{}\n\n\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(uObj.Object, sObj); err != nil {\n\t\t\treturn true, nil, fmt.Errorf(\"failed to convert object: %v\", err)\n\t\t}\n\n\t\tif sObj.ObjectMeta.Name == \"doesnotexist\" {\n\t\t\treturn true, nil, fmt.Errorf(\"doesnotexist\")\n\t\t}\n\n\t\treturn true, uAction.GetObject(), nil\n\t})\n\n\tcs.dInterface = f.Resource(GVR())\n\n\treturn cs, fakeClient\n}\n\nfunc TestCreate(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: obj1,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\tgot, err := tc.Create(context.Background(), tt.want)\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Fatalf(\"Create(%+v) failed: diff\\n%s\", tt.want, pretty.Diff(got, want))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestList(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.SrlinuxList\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: &srlinuxv1.SrlinuxList{\n\t\t\tItems: []srlinuxv1.Srlinux{*obj1, *obj2},\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\n\t\t\tgot, err := tc.List(context.Background(), metav1.ListOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Fatalf(\"List() failed: got %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t\twant: obj1,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\n\t\t\tgot, err := tc.Get(context.Background(), \"test\", metav1.GetOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, want) {\n\t\t\t\tt.Fatalf(\"Get() failed: got %v, want %v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tresp: &http.Response{\n\t\t\tStatusCode: http.StatusOK,\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\terr := tc.Delete(context.Background(), \"obj1\", metav1.DeleteOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestWatch(t *testing.T) {\n\tcs, fakeClient := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tresp *http.Response\n\t\twant *watch.Event\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twantErr: \"TEST ERROR\",\n\t}}\n\n\tfor _, tt := range tests {\n\t\tfakeClient.Err = nil\n\n\t\tif tt.wantErr != \"\" {\n\t\t\tfakeClient.Err = fmt.Errorf(tt.wantErr)\n\t\t}\n\n\t\tfakeClient.Resp = tt.resp\n\n\t\tif tt.want != nil {\n\t\t\tb, _ := json.Marshal(tt.want)\n\t\t\ttt.resp.Body = io.NopCloser(bytes.NewReader(b))\n\t\t}\n\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"foo\")\n\t\t\tw, err := tc.Watch(context.Background(), metav1.ListOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\te := <-w.ResultChan()\n\t\t\tif !reflect.DeepEqual(e, tt.want) {\n\t\t\t\tt.Fatalf(\"Watch() failed: got %v, want %v\", e, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnstructured(t *testing.T) {\n\tcs, _ := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\tin string\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\tin: \"missingObj\",\n\t\twantErr: `\"missingObj\" not found`,\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tin: obj1.GetObjectMeta().GetName(),\n\t\twant: obj1,\n\t}, {\n\t\tdesc: \"Valid Node\",\n\t\tin: obj2.GetObjectMeta().GetName(),\n\t\twant: obj2,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\ttc := cs.Srlinux(\"test\")\n\t\t\tgot, err := tc.Unstructured(context.Background(), tt.in, metav1.GetOptions{})\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuObj1 := &srlinuxv1.Srlinux{}\n\t\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(got.Object, uObj1); err != nil {\n\t\t\t\tt.Fatalf(\"failed to turn response into a topology: %v\", err)\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(uObj1, tt.want) {\n\t\t\t\tt.Fatalf(\"Unstructured(%q) failed: got %+v, want %+v\", tt.in, uObj1, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUpdate(t *testing.T) {\n\tcs, _ := setUp(t)\n\ttests := []struct {\n\t\tdesc string\n\t\twant *srlinuxv1.Srlinux\n\t\twantErr string\n\t}{{\n\t\tdesc: \"Error\",\n\t\twant: &srlinuxv1.Srlinux{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: \"Srlinux\",\n\t\t\t\tAPIVersion: \"kne.srlinux.dev\/v1alpha1\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"doesnotexist\",\n\t\t\t\tNamespace: \"test\",\n\t\t\t\tGeneration: 1,\n\t\t\t},\n\t\t},\n\t\twantErr: \"doesnotexist\",\n\t}, {\n\t\tdesc: \"Valid Topology\",\n\t\twant: obj1,\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\tsc := cs.Srlinux(\"test\")\n\t\t\tupdateObj := tt.want.DeepCopy()\n\t\t\tupdateObj.Spec.Version = \"updated version\"\n\n\t\t\tupdate, err := runtime.DefaultUnstructuredConverter.ToUnstructured(updateObj)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to generate update: %v\", err)\n\t\t\t}\n\n\t\t\tgot, err := sc.Update(context.Background(), &unstructured.Unstructured{\n\t\t\t\tObject: update,\n\t\t\t}, metav1.UpdateOptions{})\n\n\t\t\tif s := errdiff.Substring(err, tt.wantErr); s != \"\" {\n\t\t\t\tt.Fatalf(\"unexpected error: %s\", s)\n\t\t\t}\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twant := tt.want.DeepCopy()\n\t\t\twant.TypeMeta = metav1.TypeMeta{}\n\t\t\tif !reflect.DeepEqual(got, updateObj) {\n\t\t\t\tt.Fatalf(\"Update() failed: got %+v, want %+v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"} {"text":"package images\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tg \"github.com\/onsi\/ginkgo\"\n\to \"github.com\/onsi\/gomega\"\n\n\te2e \"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\n\texutil \"github.com\/openshift\/origin\/test\/extended\/util\"\n)\n\nvar _ = g.Describe(\"[sig-imageregistry][Serial][Suite:openshift\/registry\/serial] Image signature workflow\", func() {\n\tdefer g.GinkgoRecover()\n\n\tvar (\n\t\toc = exutil.NewCLI(\"registry-signing\")\n\t\tsignerBuildFixture = exutil.FixturePath(\"testdata\", \"signer-buildconfig.yaml\")\n\t)\n\n\tg.It(\"can push a signed image to openshift registry and verify it\", func() {\n\t\tg.By(\"building a signer image that knows how to sign images\")\n\t\toutput, err := oc.Run(\"create\").Args(\"-f\", signerBuildFixture).Output()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(g.GinkgoWriter, \"%s\\n\\n\", output)\n\t\t}\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\terr = exutil.WaitForAnImageStreamTag(oc, oc.Namespace(), \"signer\", \"latest\")\n\t\tcontainerLog, _ := oc.Run(\"logs\").Args(\"builds\/signer-1\").Output()\n\t\te2e.Logf(\"signer build logs:\\n%s\\n\", containerLog)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"looking up the openshift registry URL\")\n\t\tregistryURL, err := GetDockerRegistryURL(oc)\n\t\tsignerImage := fmt.Sprintf(\"%s\/%s\/signer:latest\", registryURL, oc.Namespace())\n\t\tsignedImage := fmt.Sprintf(\"%s\/%s\/signed:latest\", registryURL, oc.Namespace())\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"obtaining bearer token for the test user\")\n\t\tuser := oc.Username()\n\t\ttoken, err := oc.Run(\"whoami\").Args(\"-t\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"granting the image-signer role to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-cluster-role-to-user\", \"system:image-signer\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\/\/ TODO: The test user needs to be able to unlink the \/dev\/random which is owned by a\n\t\t\/\/ root. This cannot be done during image build time because the \/dev is plugged into\n\t\t\/\/ container after it starts. This SCC could be avoided in the future when \/dev\/random\n\t\t\/\/ issue is fixed in Docker.\n\t\tg.By(\"granting the anyuid scc to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-scc-to-user\", \"anyuid\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"preparing the image stream where the signed image will be pushed\")\n\t\t_, err = oc.Run(\"create\").Args(\"imagestream\", \"signed\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"granting the image-auditor role to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-cluster-role-to-user\", \"system:image-auditor\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tpod, err := exutil.NewPodExecutor(oc, \"sign-and-push\", signerImage)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\/\/ Generate GPG key\n\t\t\/\/ Note that we need to replace the \/dev\/random with \/dev\/urandom to get more entropy\n\t\t\/\/ into container so we can successfully generate the GPG keypair.\n\t\tg.By(\"creating dummy GPG key\")\n\t\tout, err := pod.Exec(\"rm -f \/dev\/random; ln -sf \/dev\/urandom \/dev\/random && \" +\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg gpg2 --batch --gen-key --pinentry-mode=loopback --passphrase '' dummy_key.conf && \" +\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg gpg2 --output=gnupg\/pubring.gpg --export joe@foo.bar\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"keybox '\/var\/lib\/origin\/gnupg\/pubring.kbx' created\"))\n\n\t\t\/\/ Create kubeconfig for oc\n\t\tg.By(\"logging as a test user\")\n\t\tout, err = pod.Exec(\"oc login https:\/\/$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT --token=\" + token + \" --certificate-authority=\/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"Logged in\"))\n\n\t\t\/\/ Sign and copy the memcached image into target image stream tag\n\t\tg.By(\"signing a just-built image and pushing it into openshift registry\")\n\t\tout, err = pod.Exec(strings.Join([]string{\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg\",\n\t\t\t\"skopeo\", \"--debug\",\n\t\t\t\"copy\", \"--sign-by\", \"joe@foo.bar\",\n\t\t\t\"--src-creds=\" + user + \":\" + token,\n\t\t\t\"--dest-creds=\" + user + \":\" + token,\n\n\t\t\t\/\/ Expect to use \/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt\n\t\t\t\"--src-cert-dir=\/run\/secrets\/kubernetes.io\/serviceaccount\",\n\t\t\t\"--dest-cert-dir=\/run\/secrets\/kubernetes.io\/serviceaccount\",\n\n\t\t\t\"docker:\/\/\" + signerImage,\n\t\t\t\"docker:\/\/\" + signedImage,\n\t\t}, \" \"))\n\t\tfmt.Fprintf(g.GinkgoWriter, \"output: %s\\n\", out)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\terr = exutil.WaitForAnImageStreamTag(oc, oc.Namespace(), \"signed\", \"latest\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"obtaining the signed:latest image name\")\n\t\timageName, err := oc.Run(\"get\").Args(\"istag\", \"signed:latest\", \"-o\", \"jsonpath={.image.metadata.name}\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"expecting the image to have unverified signature\")\n\t\tout, err = oc.Run(\"describe\").Args(\"istag\", \"signed:latest\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\te2e.Logf(out)\n\t\to.Expect(out).To(o.ContainSubstring(\"Unverified\"))\n\n\t\tout, err = pod.Exec(strings.Join([]string{\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg\",\n\t\t\t\"oc\", \"adm\",\n\t\t\t\"verify-image-signature\",\n\t\t\t\"--insecure=true\", \/\/ TODO: import the ca certificate into the signing pod\n\t\t\t\"--loglevel=8\",\n\t\t\timageName,\n\t\t\t\"--expected-identity=\" + signedImage,\n\t\t\t\"--save\",\n\t\t}, \" \"))\n\t\tfmt.Fprintf(g.GinkgoWriter, \"output: %s\\n\", out)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"identity is now confirmed\"))\n\n\t\tg.By(\"checking the signature is present on the image and it is now verified\")\n\t\tout, err = oc.Run(\"describe\").Args(\"istag\", \"signed:latest\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"Verified\"))\n\t})\n})\nBug 2057990: Add debug info for signature testpackage images\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tg \"github.com\/onsi\/ginkgo\"\n\to \"github.com\/onsi\/gomega\"\n\n\te2e \"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\n\texutil \"github.com\/openshift\/origin\/test\/extended\/util\"\n)\n\nvar _ = g.Describe(\"[sig-imageregistry][Serial][Suite:openshift\/registry\/serial] Image signature workflow\", func() {\n\tdefer g.GinkgoRecover()\n\n\tvar (\n\t\toc = exutil.NewCLI(\"registry-signing\")\n\t\tsignerBuildFixture = exutil.FixturePath(\"testdata\", \"signer-buildconfig.yaml\")\n\t)\n\n\tg.AfterEach(func() {\n\t\tif g.CurrentGinkgoTestDescription().Failed {\n\t\t\texutil.DumpPodStates(oc)\n\t\t\texutil.DumpConfigMapStates(oc)\n\t\t\texutil.DumpPodLogsStartingWith(\"\", oc)\n\t\t}\n\t})\n\n\tg.It(\"can push a signed image to openshift registry and verify it\", func() {\n\t\tg.By(\"building a signer image that knows how to sign images\")\n\t\toutput, err := oc.Run(\"create\").Args(\"-f\", signerBuildFixture).Output()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(g.GinkgoWriter, \"%s\\n\\n\", output)\n\t\t}\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\terr = exutil.WaitForAnImageStreamTag(oc, oc.Namespace(), \"signer\", \"latest\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"looking up the openshift registry URL\")\n\t\tregistryURL, err := GetDockerRegistryURL(oc)\n\t\tsignerImage := fmt.Sprintf(\"%s\/%s\/signer:latest\", registryURL, oc.Namespace())\n\t\tsignedImage := fmt.Sprintf(\"%s\/%s\/signed:latest\", registryURL, oc.Namespace())\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"obtaining bearer token for the test user\")\n\t\tuser := oc.Username()\n\t\ttoken, err := oc.Run(\"whoami\").Args(\"-t\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"granting the image-signer role to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-cluster-role-to-user\", \"system:image-signer\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\/\/ TODO: The test user needs to be able to unlink the \/dev\/random which is owned by a\n\t\t\/\/ root. This cannot be done during image build time because the \/dev is plugged into\n\t\t\/\/ container after it starts. This SCC could be avoided in the future when \/dev\/random\n\t\t\/\/ issue is fixed in Docker.\n\t\tg.By(\"granting the anyuid scc to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-scc-to-user\", \"anyuid\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"preparing the image stream where the signed image will be pushed\")\n\t\t_, err = oc.Run(\"create\").Args(\"imagestream\", \"signed\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"granting the image-auditor role to test user\")\n\t\t_, err = oc.AsAdmin().Run(\"adm\").Args(\"policy\", \"add-cluster-role-to-user\", \"system:image-auditor\", oc.Username()).Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tpod, err := exutil.NewPodExecutor(oc, \"sign-and-push\", signerImage)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\/\/ Generate GPG key\n\t\t\/\/ Note that we need to replace the \/dev\/random with \/dev\/urandom to get more entropy\n\t\t\/\/ into container so we can successfully generate the GPG keypair.\n\t\tg.By(\"creating dummy GPG key\")\n\t\tout, err := pod.Exec(\"rm -f \/dev\/random; ln -sf \/dev\/urandom \/dev\/random && \" +\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg gpg2 --batch --gen-key --pinentry-mode=loopback --passphrase '' dummy_key.conf && \" +\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg gpg2 --output=gnupg\/pubring.gpg --export joe@foo.bar\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"keybox '\/var\/lib\/origin\/gnupg\/pubring.kbx' created\"))\n\n\t\t\/\/ Create kubeconfig for oc\n\t\tg.By(\"logging as a test user\")\n\t\tout, err = pod.Exec(\"oc login https:\/\/$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT --token=\" + token + \" --certificate-authority=\/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"Logged in\"))\n\n\t\t\/\/ Sign and copy the memcached image into target image stream tag\n\t\tg.By(\"signing a just-built image and pushing it into openshift registry\")\n\t\tout, err = pod.Exec(strings.Join([]string{\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg\",\n\t\t\t\"skopeo\", \"--debug\",\n\t\t\t\"copy\", \"--sign-by\", \"joe@foo.bar\",\n\t\t\t\"--src-creds=\" + user + \":\" + token,\n\t\t\t\"--dest-creds=\" + user + \":\" + token,\n\n\t\t\t\/\/ Expect to use \/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt\n\t\t\t\"--src-cert-dir=\/run\/secrets\/kubernetes.io\/serviceaccount\",\n\t\t\t\"--dest-cert-dir=\/run\/secrets\/kubernetes.io\/serviceaccount\",\n\n\t\t\t\"docker:\/\/\" + signerImage,\n\t\t\t\"docker:\/\/\" + signedImage,\n\t\t}, \" \"))\n\t\tfmt.Fprintf(g.GinkgoWriter, \"output: %s\\n\", out)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\terr = exutil.WaitForAnImageStreamTag(oc, oc.Namespace(), \"signed\", \"latest\")\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"obtaining the signed:latest image name\")\n\t\timageName, err := oc.Run(\"get\").Args(\"istag\", \"signed:latest\", \"-o\", \"jsonpath={.image.metadata.name}\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\tg.By(\"expecting the image to have unverified signature\")\n\t\tout, err = oc.Run(\"describe\").Args(\"istag\", \"signed:latest\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\te2e.Logf(out)\n\t\to.Expect(out).To(o.ContainSubstring(\"Unverified\"))\n\n\t\tout, err = pod.Exec(strings.Join([]string{\n\t\t\t\"GNUPGHOME=\/var\/lib\/origin\/gnupg\",\n\t\t\t\"oc\", \"adm\",\n\t\t\t\"verify-image-signature\",\n\t\t\t\"--insecure=true\", \/\/ TODO: import the ca certificate into the signing pod\n\t\t\t\"--loglevel=8\",\n\t\t\timageName,\n\t\t\t\"--expected-identity=\" + signedImage,\n\t\t\t\"--save\",\n\t\t}, \" \"))\n\t\tfmt.Fprintf(g.GinkgoWriter, \"output: %s\\n\", out)\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"identity is now confirmed\"))\n\n\t\tg.By(\"checking the signature is present on the image and it is now verified\")\n\t\tout, err = oc.Run(\"describe\").Args(\"istag\", \"signed:latest\").Output()\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\to.Expect(out).To(o.ContainSubstring(\"Verified\"))\n\t})\n})\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/eaciit\/gocr\"\n)\n\nvar (\n\tsamplePath = func() string {\n\t\td, _ := os.Getwd()\n\t\treturn d\n\t}() + \"\/..\/..\/train_data\/\"\n)\n\nvar (\n\tmodelPath = func() string {\n\t\td, _ := os.Getwd()\n\t\treturn d\n\t}() + \"\/..\/..\/model\/\"\n)\n\nfunc main() {\n\t\/\/ Downloading english font dataset and index.csv\n\td, _ := os.Getwd()\n\t\/\/\n\t\/\/ Load the sample data and save it in .gob file\n\t\/\/ err := gocr.TrainAverage(d+\"\/English\/Fnt\/\", d+\"\/English\/\")\n\t\/\/ if err != nil {\n\t\/\/ \tpanic(err)\n\t\/\/ }\n\n\t\/\/ Read the image\n\timage, err := gocr.ReadImage(d + \"\/imagetext_2.png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tim := gocr.ImageToBinaryArray(image)\n\tgocr.ImageMatrixToImage(im, d+\"\/result\/image.png\", 255)\n\n}\nFixing error in examplespackage main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/eaciit\/gocr\"\n)\n\nvar (\n\tsamplePath = func() string {\n\t\td, _ := os.Getwd()\n\t\treturn d\n\t}() + \"\/..\/..\/train_data\/\"\n)\n\nvar (\n\tmodelPath = func() string {\n\t\td, _ := os.Getwd()\n\t\treturn d\n\t}() + \"\/..\/..\/model\/\"\n)\n\nfunc main() {\n\t\/\/ Downloading english font dataset and index.csv\n\td, _ := os.Getwd()\n\t\/\/\n\t\/\/ Load the sample data and save it in .gob file\n\t\/\/ err := gocr.TrainAverage(d+\"\/English\/Fnt\/\", d+\"\/English\/\")\n\t\/\/ if err != nil {\n\t\/\/ \tpanic(err)\n\t\/\/ }\n\n\t\/\/ Read the image\n\timage, err := gocr.ReadImage(d + \"\/imagetext_2.png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tim := gocr.ImageToGraysclaeArray(image)\n\tgocr.ImageMatrixToImage(im, d+\"\/result\/image.png\", 255)\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n \"time\"\n\t\"sort\"\n)\n\nvar colors = map[string]string{\n\t\"header\": \"\\033[95m\",\n\t\"blue\": \"\\033[94m\",\n\t\"green\": \"\\033[92m\",\n\t\"yellow\": \"\\033[93m\",\n\t\"red\": \"\\033[91m\",\n\t\"bold\": \"\\033[1m\",\n\t\"end\": \"\\033[0m\",\n}\n\nfunc color(color string, s string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", colors[color], s, colors[\"end\"])\n}\n\nvar rexes = map[string]*regexp.Regexp{\n\t\"pep8\": regexp.MustCompile(`\\w+:(\\d+):(\\d+):\\s(\\w+)\\s(.+)(?m)$`),\n\t\"pylint\": regexp.MustCompile(`(?m)^(\\w):\\s+(\\d+),\\s*(\\d+):\\s(.+)$`),\n\t\"blameName\": regexp.MustCompile(`\\(([\\w\\s]+)\\d{4}`),\n \"goBuild\": regexp.MustCompile(`\\w+:(\\d+):\\s(.+)(?m)$`),\n}\n\nvar config = map[string]string{\n\t\"workingDir\": \"\",\n}\n\ntype Environment struct {\n\tgitPath string\n\tgitName string\n}\n\nfunc (c *Environment) GitPath() string {\n\tif len(c.gitPath) == 0 {\n\t\tcmd := exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\")\n\t\tout, err := cmd.Output()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Failed to find git parent path.\")\n\t\t}\n\t\tc.gitPath = strings.TrimSpace(string(out))\n\t}\n\treturn c.gitPath\n}\n\nfunc (c *Environment) GitName() string {\n\tif len(c.gitName) == 0 {\n\t\tcmd := exec.Command(\"git\", \"config\", \"user.name\")\n\t\tout, err := cmd.Output()\n\t\tif err != nil {\n\t\t\tc.gitName = \"None\"\n\t\t} else {\n\t\t\tc.gitName = strings.TrimSpace(string(out))\n\t\t}\n\t}\n\treturn c.gitName\n}\n\nfunc (c Environment) CurrentGitBranch() string {\n\tcmd := exec.Command(\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\")\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to get git branch\")\n\t}\n\treturn strings.TrimSpace(string(out))\n}\n\nvar env = Environment{}\n\ntype Times []*time.Time\nfunc (s Times) Len() int { return len(s) }\nfunc (s Times) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\ntype ByTime struct{ Times }\nfunc (s ByTime) Less(i, j int) bool { return s.Times[i].Before(*s.Times[j]) }\n\n\ntype ModifiedTimes struct {\n\ttimeMap map[string]time.Time\n}\n\nfunc (m *ModifiedTimes) CheckTime(path string) bool {\n\thasChanged := false\n\n\tfileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\tlog.Println(\"Couldn't access \", path, \". Skipping it.\")\n\t} else {\n\t\tif fileInfo != nil {\n\t\t\tmt := fileInfo.ModTime()\n\t\t\tif storedTime, ok := m.timeMap[path]; ok {\n\t\t\t\tif !storedTime.Equal(mt) {\n\t\t\t\t\thasChanged = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thasChanged = true\n\t\t\t}\n\t\t\tif hasChanged {\n\t\t\t\tm.timeMap[path] = mt\n\t\t\t}\n\t\t}\n\t}\n\treturn hasChanged\n}\n\nfunc (m ModifiedTimes) MostRecent() string {\n\tvar returnPath string\n\tvar mostRecentTime time.Time\n\tfor path, time := range m.timeMap {\n\t\tif mostRecentTime.Before(time) {\n\t\t\treturnPath = path\n\t\t\tmostRecentTime = time\n\t\t}\n\t}\n\treturn returnPath\n}\n\nfunc (m ModifiedTimes) PathsByModTime() []string {\n size := len(m.timeMap)\n times := make(Times, size)\n timesToPaths := make(map[time.Time]string, size)\n returnSlice := make([]string, size)\n i := 0\n for path, time_ := range m.timeMap {\n times[i] = &time_\n timesToPaths[time_] = path\n i += 1\n }\n sort.Sort(ByTime{times})\n\n for i, time_ := range times {\n log.Print(\"time_: \", time_)\n returnSlice[i] = timesToPaths[*time_]\n }\n return returnSlice\n}\n\nfunc NewModifiedTimes() *ModifiedTimes {\n return &ModifiedTimes{timeMap: make(map[string]time.Time, 9)}\n}\n\n\n\ntype Wart struct {\n\tReporter string\n\tLine int\n\tColumn int\n\tIssueCode string\n\tMessage string\n}\n\nfunc (w Wart) String() string {\n\treturn fmt.Sprintf(\"%d: [%s %s] %s\", w.Line, w.Reporter, w.IssueCode, w.Message)\n}\n\ntype TargetFile struct {\n\tPath string\n\tContentLines []string\n\tBlameLines []string\n\tWarts map[int][]Wart\n}\n\nfunc (tf *TargetFile) Blame() {\n\tos.Chdir(config[\"workingDir\"])\n\tcmd := exec.Command(\"git\", \"blame\", tf.Path)\n\tresults, err := cmd.Output()\n\tif err != nil {\n\t\ttf.BlameLines = make([]string, 0)\n\t} else {\n \ttf.BlameLines = strings.Split(string(results), \"\\n\")\n }\n}\n\nfunc NewWart(reporter string, line string, column string, issueCode string, message string) Wart {\n\n\tline64, err := strconv.ParseInt(line, 10, 0)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed parsing line number %s\", line)\n\t}\n\tcol64, err := strconv.ParseInt(column, 10, 0)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed parsing column number %s\", column)\n\t}\n\tw := Wart{\n\t\tReporter: reporter,\n\t\tLine: int(line64),\n\t\tColumn: int(col64),\n\t\tIssueCode: issueCode,\n\t\tMessage: message,\n\t}\n\treturn w\n}\n\nfunc (tf TargetFile) ExtEquals(ext string) bool {\n return filepath.Ext(tf.Path) == ext\n}\n\nfunc (tf *TargetFile) AddWart(wart Wart) {\n if _, ok := tf.Warts[wart.Line]; !ok {\n tf.Warts[wart.Line] = make([]Wart, 0)\n }\n tf.Warts[wart.Line] = append(tf.Warts[wart.Line], wart)\n}\n\nfunc (tf *TargetFile) Pep8() {\n\tif filepath.Ext(tf.Path) != \".py\" {\n\t\treturn\n\t}\n\tcmd := exec.Command(\"pep8\", tf.Path)\n\tresults, _ := cmd.Output()\n\tparsed := rexes[\"pep8\"].FindAllStringSubmatch(string(results), -1)\n\tfor _, group := range parsed {\n\t\twart := NewWart(\"PEP8\", group[1], group[2], group[3], group[4])\n tf.AddWart(wart)\n\t}\n}\n\nfunc (tf *TargetFile) GoBuild() {\n if !tf.ExtEquals(\".go\") { return }\n os.Chdir(config[\"workingDir\"])\n _, file := filepath.Split(tf.Path)\n cmd := exec.Command(\"go\", \"build\", file)\n results, _ := cmd.CombinedOutput()\n parsed := rexes[\"goBuild\"].FindAllStringSubmatch(string(results), -1)\n for _, group := range parsed {\n wart := NewWart(\"gobuild\", group[1], \"0\", \"-\", group[2])\n tf.AddWart(wart)\n }\n}\n\nfunc (tf *TargetFile) PyLint() {\n\tif filepath.Ext(tf.Path) != \".py\" {\n\t\treturn\n\t}\n\tcmd := exec.Command(\"pylint\", \"--output-format=text\", tf.Path)\n\tresults, _ := cmd.Output()\n\tparsed := rexes[\"pylint\"].FindAllStringSubmatch(string(results), -1)\n for _, group := range parsed {\n wart := NewWart(\"Pylint\", group[2], group[3], group[1], group[4])\n tf.AddWart(wart)\n }\n}\n\nfunc (tf TargetFile) BlameName(line int) string {\n if len(tf.BlameLines) == 0 {\n return \"-\"\n }\n\tmatch := rexes[\"blameName\"].FindStringSubmatch(tf.BlameLines[line - 1])\n\treturn strings.TrimSpace(match[1])\n}\n\nfunc NewTargetFile(path string) *TargetFile {\n\ttf := TargetFile{\n\t\tPath: path,\n\t\tWarts: make(map[int][]Wart),\n\t}\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to read file \", path)\n\t}\n\ttf.ContentLines = strings.Split(string(bytes), \"\\n\")\n\ttf.Blame()\n\ttf.Pep8()\n tf.PyLint()\n tf.GoBuild()\n\treturn &tf\n}\n\nfunc getDirFiles(dirPath string) []string {\n\tfiles, err := ioutil.ReadDir(dirPath)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read directory\", dirPath)\n\t}\n\tfilepaths := make([]string, len(files))\n\tfor i, fileInfo := range files {\n\t\tfilepaths[i] = path.Join(dirPath, fileInfo.Name())\n\t}\n\treturn filterFiles(filepaths)\n}\n\nfunc gitBranchFiles() []string {\n\tdirtyFilesCmd := exec.Command(\"git\", \"diff\", \"--name-only\")\n\tdirtyFiles, err := dirtyFilesCmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to list dirty files\")\n\t}\n\n\tbranchFilesCmd := exec.Command(\"git\", \"diff\", \"--name-only\", \"master..HEAD\")\n\tbranchFiles, err := branchFilesCmd.Output()\n\tif err != nil {\n\t\tlog.Print(\"branchFiles: \", branchFiles)\n\t\tlog.Fatal(\"Failed to list branch files:\", err)\n\t}\n\n\tallFiles := append(\n\t\tstrings.Split(string(dirtyFiles), \"\\n\"),\n\t\tstrings.Split(string(branchFiles), \"\\n\")...,\n\t)\n\treturn filterFiles(allFiles)\n}\n\nfunc filterFiles(filepaths []string) []string {\n\tgoodstuffs := make([]string, 0)\n\tfor _, filepath := range filepaths {\n\t\tif len(filepath) > 0 {\n\t\t\tmatch, err := regexp.MatchString(\".py|.go\", path.Ext(filepath))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed checking %s's extension\", filepath)\n\t\t\t}\n if match == true {\n if !strings.HasPrefix(filepath, \"\/\") {\n filepath = path.Join(config[\"workingDir\"], filepath)\n }\n\t\t\t\tgoodstuffs = append(goodstuffs, filepath)\n\t\t\t}\n\t\t}\n\t}\n\treturn goodstuffs\n}\n\nfunc printWarts(targetFile *TargetFile) {\n\tfmt.Println(color(\"green\", targetFile.Path))\n\tif len(targetFile.Warts) == 0 {\n\t\tfmt.Println(color(\"bold\", \"- All clean!\"))\n\t}\n\tfor line, warts := range targetFile.Warts {\n\t\tblameName := targetFile.BlameName(line)\n\t\tnameColor := \"blue\"\n\t\tif blameName == env.GitName() {\n\t\t\tnameColor = \"yellow\"\n\t\t}\n\t\tfmt.Printf(\n\t\t\t\"%s: (%s) %s\\n\",\n\t\t\tcolor(\"bold\", fmt.Sprintf(\"%d\", line)),\n\t\t\tcolor(nameColor, blameName),\n\t\t\tstrings.TrimSpace(targetFile.ContentLines[line-1]),\n\t\t)\n\t\tfor _, wart := range warts {\n\t\t\tfmt.Printf(\n\t\t\t\t\" [%s %s] %s\\n\",\n\t\t\t\twart.Reporter,\n\t\t\t\twart.IssueCode,\n\t\t\t\tcolor(\"bold\", wart.Message),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc clear() {\n\tcmd := exec.Command(\"clear\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Run()\n fmt.Println(color(\"header\", \"--- LintBlame ---\"))\n}\n\nfunc makeTargetFile(filepath string, c chan *TargetFile) {\n\ttf := NewTargetFile(filepath)\n\tc <- tf\n}\n\nfunc update(filepaths []string) {\n\tc := make(chan *TargetFile)\n\tfor _, path := range filepaths {\n\t\tgo makeTargetFile(path, c)\n\t}\n\tcleared := false\n\tfor i := 0; i < len(filepaths); i++ {\n\t\tif !cleared {\n\t\t\tclear()\n\t\t\tcleared = true\n\t\t}\n\t\ttf := <-c\n\t\tprintWarts(tf)\n fmt.Println(\"\")\n\t}\n}\n\nfunc initialPaths() []string {\n var branch bool\n flag.BoolVar(&branch, \"b\", false, \"Run against current branch\")\n flag.Parse()\n\n var filepaths []string\n if branch {\n config[\"workingDir\"] = env.GitPath()\n filepaths = gitBranchFiles()\n } else {\n args := flag.Args()\n if len(args) > 0 {\n target := args[0]\n stat, err := os.Stat(target)\n if err != nil {\n log.Fatal(\"Unable to process argument: \", target)\n }\n absPath, err := filepath.Abs(target)\n if err != nil {\n log.Fatal(\"Unable to get absolute path of \", target)\n }\n if stat.IsDir() {\n config[\"workingDir\"] = absPath\n filepaths = getDirFiles(absPath)\n } else {\n dir, _ := filepath.Split(absPath)\n config[\"workingDir\"] = dir\n filepaths = filterFiles([]string{absPath})\n }\n }\n }\n return filepaths\n}\n\nfunc main() {\n filepaths := initialPaths()\n\tmodTimes := NewModifiedTimes()\n\n\tfor _, file := range filepaths {\n\t\tmodTimes.CheckTime(file)\n\t}\n\tupdate(modTimes.PathsByModTime())\n\tfor {\n\t\trunUpdate := false\n\t\tfor _, file := range filepaths {\n\t\t\tif modTimes.CheckTime(file) {\n\t\t\t\trunUpdate = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif runUpdate {\n\t\t\tupdate(modTimes.PathsByModTime())\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\nI _think_ sorting is working now?package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n \"time\"\n\t\"sort\"\n)\n\nvar colors = map[string]string{\n\t\"header\": \"\\033[95m\",\n\t\"blue\": \"\\033[94m\",\n\t\"green\": \"\\033[92m\",\n\t\"yellow\": \"\\033[93m\",\n\t\"red\": \"\\033[91m\",\n\t\"bold\": \"\\033[1m\",\n\t\"end\": \"\\033[0m\",\n}\n\nfunc color(color string, s string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", colors[color], s, colors[\"end\"])\n}\n\nvar rexes = map[string]*regexp.Regexp{\n\t\"pep8\": regexp.MustCompile(`\\w+:(\\d+):(\\d+):\\s(\\w+)\\s(.+)(?m)$`),\n\t\"pylint\": regexp.MustCompile(`(?m)^(\\w):\\s+(\\d+),\\s*(\\d+):\\s(.+)$`),\n\t\"blameName\": regexp.MustCompile(`\\(([\\w\\s]+)\\d{4}`),\n \"goBuild\": regexp.MustCompile(`\\w+:(\\d+):\\s(.+)(?m)$`),\n}\n\nvar config = map[string]string{\n\t\"workingDir\": \"\",\n}\n\ntype Environment struct {\n\tgitPath string\n\tgitName string\n}\n\nfunc (c *Environment) GitPath() string {\n\tif len(c.gitPath) == 0 {\n\t\tcmd := exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\")\n\t\tout, err := cmd.Output()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Failed to find git parent path.\")\n\t\t}\n\t\tc.gitPath = strings.TrimSpace(string(out))\n\t}\n\treturn c.gitPath\n}\n\nfunc (c *Environment) GitName() string {\n\tif len(c.gitName) == 0 {\n\t\tcmd := exec.Command(\"git\", \"config\", \"user.name\")\n\t\tout, err := cmd.Output()\n\t\tif err != nil {\n\t\t\tc.gitName = \"None\"\n\t\t} else {\n\t\t\tc.gitName = strings.TrimSpace(string(out))\n\t\t}\n\t}\n\treturn c.gitName\n}\n\nfunc (c Environment) CurrentGitBranch() string {\n\tcmd := exec.Command(\"git\", \"rev-parse\", \"--abbrev-ref\", \"HEAD\")\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to get git branch\")\n\t}\n\treturn strings.TrimSpace(string(out))\n}\n\nvar env = Environment{}\n\ntype Times []time.Time\nfunc (s Times) Len() int { return len(s) }\nfunc (s Times) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\ntype ByTime struct{ Times }\nfunc (s ByTime) Less(i, j int) bool { return s.Times[i].Before(s.Times[j]) }\n\n\ntype ModifiedTimes struct {\n\ttimeMap map[string]time.Time\n}\n\nfunc (m *ModifiedTimes) CheckTime(path string) bool {\n\thasChanged := false\n\n fileInfo, err := os.Stat(path)\n\tif err != nil {\n\t\tlog.Println(\"Couldn't access \", path, \". Skipping it.\")\n\t} else {\n\t\tif fileInfo != nil {\n\t\t\tmt := fileInfo.ModTime()\n if storedTime, ok := m.timeMap[path]; ok {\n if !storedTime.Equal(mt) {\n hasChanged = true\n }\n } else {\n hasChanged = true\n }\n if hasChanged {\n m.timeMap[path] = mt\n }\n\t\t}\n\t}\n\treturn hasChanged\n}\n\nfunc (m ModifiedTimes) MostRecent() string {\n\tvar returnPath string\n\tvar mostRecentTime time.Time\n\tfor path, time := range m.timeMap {\n\t\tif mostRecentTime.Before(time) {\n\t\t\treturnPath = path\n\t\t\tmostRecentTime = time\n\t\t}\n\t}\n\treturn returnPath\n}\n\nfunc (m ModifiedTimes) PathsByModTime() []string {\n size := len(m.timeMap)\n times := make(Times, size)\n timesToPaths := make(map[time.Time]string, size)\n returnSlice := make([]string, size)\n i := 0\n for path, time_ := range m.timeMap {\n times[i] = time_\n timesToPaths[time_] = path\n i += 1\n }\n sort.Sort(ByTime{times})\n\n for i, time_ := range times {\n returnSlice[i] = timesToPaths[time_]\n }\n return returnSlice\n}\n\nfunc NewModifiedTimes() *ModifiedTimes {\n return &ModifiedTimes{timeMap: make(map[string]time.Time, 9)}\n}\n\n\n\ntype Wart struct {\n\tReporter string\n\tLine int\n\tColumn int\n\tIssueCode string\n\tMessage string\n}\n\nfunc (w Wart) String() string {\n\treturn fmt.Sprintf(\"%d: [%s %s] %s\", w.Line, w.Reporter, w.IssueCode, w.Message)\n}\n\ntype TargetFile struct {\n\tPath string\n\tContentLines []string\n\tBlameLines []string\n\tWarts map[int][]Wart\n}\n\nfunc (tf *TargetFile) Blame() {\n\tos.Chdir(config[\"workingDir\"])\n\tcmd := exec.Command(\"git\", \"blame\", tf.Path)\n\tresults, err := cmd.Output()\n\tif err != nil {\n\t\ttf.BlameLines = make([]string, 0)\n\t} else {\n \ttf.BlameLines = strings.Split(string(results), \"\\n\")\n }\n}\n\nfunc NewWart(reporter string, line string, column string, issueCode string, message string) Wart {\n\n\tline64, err := strconv.ParseInt(line, 10, 0)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed parsing line number %s\", line)\n\t}\n\tcol64, err := strconv.ParseInt(column, 10, 0)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed parsing column number %s\", column)\n\t}\n\tw := Wart{\n\t\tReporter: reporter,\n\t\tLine: int(line64),\n\t\tColumn: int(col64),\n\t\tIssueCode: issueCode,\n\t\tMessage: message,\n\t}\n\treturn w\n}\n\nfunc (tf TargetFile) ExtEquals(ext string) bool {\n return filepath.Ext(tf.Path) == ext\n}\n\nfunc (tf *TargetFile) AddWart(wart Wart) {\n if _, ok := tf.Warts[wart.Line]; !ok {\n tf.Warts[wart.Line] = make([]Wart, 0)\n }\n tf.Warts[wart.Line] = append(tf.Warts[wart.Line], wart)\n}\n\nfunc (tf *TargetFile) Pep8() {\n\tif filepath.Ext(tf.Path) != \".py\" {\n\t\treturn\n\t}\n\tcmd := exec.Command(\"pep8\", tf.Path)\n\tresults, _ := cmd.Output()\n\tparsed := rexes[\"pep8\"].FindAllStringSubmatch(string(results), -1)\n\tfor _, group := range parsed {\n\t\twart := NewWart(\"PEP8\", group[1], group[2], group[3], group[4])\n tf.AddWart(wart)\n\t}\n}\n\nfunc (tf *TargetFile) GoBuild() {\n if !tf.ExtEquals(\".go\") { return }\n os.Chdir(config[\"workingDir\"])\n _, file := filepath.Split(tf.Path)\n cmd := exec.Command(\"go\", \"build\", file)\n results, _ := cmd.CombinedOutput()\n parsed := rexes[\"goBuild\"].FindAllStringSubmatch(string(results), -1)\n for _, group := range parsed {\n wart := NewWart(\"gobuild\", group[1], \"0\", \"-\", group[2])\n tf.AddWart(wart)\n }\n}\n\nfunc (tf *TargetFile) PyLint() {\n\tif filepath.Ext(tf.Path) != \".py\" {\n\t\treturn\n\t}\n\tcmd := exec.Command(\"pylint\", \"--output-format=text\", tf.Path)\n\tresults, _ := cmd.Output()\n\tparsed := rexes[\"pylint\"].FindAllStringSubmatch(string(results), -1)\n for _, group := range parsed {\n wart := NewWart(\"Pylint\", group[2], group[3], group[1], group[4])\n tf.AddWart(wart)\n }\n}\n\nfunc (tf TargetFile) BlameName(line int) string {\n if len(tf.BlameLines) == 0 {\n return \"-\"\n }\n\tmatch := rexes[\"blameName\"].FindStringSubmatch(tf.BlameLines[line - 1])\n\treturn strings.TrimSpace(match[1])\n}\n\nfunc NewTargetFile(path string) *TargetFile {\n\ttf := TargetFile{\n\t\tPath: path,\n\t\tWarts: make(map[int][]Wart),\n\t}\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to read file \", path)\n\t}\n\ttf.ContentLines = strings.Split(string(bytes), \"\\n\")\n\ttf.Blame()\n\ttf.Pep8()\n tf.PyLint()\n tf.GoBuild()\n\treturn &tf\n}\n\nfunc getDirFiles(dirPath string) []string {\n\tfiles, err := ioutil.ReadDir(dirPath)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read directory\", dirPath)\n\t}\n\tfilepaths := make([]string, len(files))\n\tfor i, fileInfo := range files {\n\t\tfilepaths[i] = path.Join(dirPath, fileInfo.Name())\n\t}\n\treturn filterFiles(filepaths)\n}\n\nfunc gitBranchFiles() []string {\n\tdirtyFilesCmd := exec.Command(\"git\", \"diff\", \"--name-only\")\n\tdirtyFiles, err := dirtyFilesCmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to list dirty files\")\n\t}\n\n\tbranchFilesCmd := exec.Command(\"git\", \"diff\", \"--name-only\", \"master..HEAD\")\n\tbranchFiles, err := branchFilesCmd.Output()\n\tif err != nil {\n\t\tlog.Print(\"branchFiles: \", branchFiles)\n\t\tlog.Fatal(\"Failed to list branch files:\", err)\n\t}\n\n\tallFiles := append(\n\t\tstrings.Split(string(dirtyFiles), \"\\n\"),\n\t\tstrings.Split(string(branchFiles), \"\\n\")...,\n\t)\n\treturn filterFiles(allFiles)\n}\n\nfunc filterFiles(filepaths []string) []string {\n\tgoodstuffs := make([]string, 0)\n\tfor _, filepath := range filepaths {\n\t\tif len(filepath) > 0 {\n\t\t\tmatch, err := regexp.MatchString(\".py|.go\", path.Ext(filepath))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed checking %s's extension\", filepath)\n\t\t\t}\n if match == true {\n if !strings.HasPrefix(filepath, \"\/\") {\n filepath = path.Join(config[\"workingDir\"], filepath)\n }\n\t\t\t\tgoodstuffs = append(goodstuffs, filepath)\n\t\t\t}\n\t\t}\n\t}\n\treturn goodstuffs\n}\n\nfunc printWarts(targetFile *TargetFile) {\n\tfmt.Println(color(\"green\", targetFile.Path))\n\tif len(targetFile.Warts) == 0 {\n\t\tfmt.Println(color(\"bold\", \"- All clean!\"))\n\t}\n\tfor line, warts := range targetFile.Warts {\n\t\tblameName := targetFile.BlameName(line)\n\t\tnameColor := \"blue\"\n\t\tif blameName == env.GitName() {\n\t\t\tnameColor = \"yellow\"\n\t\t}\n\t\tfmt.Printf(\n\t\t\t\"%s: (%s) %s\\n\",\n\t\t\tcolor(\"bold\", fmt.Sprintf(\"%d\", line)),\n\t\t\tcolor(nameColor, blameName),\n\t\t\tstrings.TrimSpace(targetFile.ContentLines[line-1]),\n\t\t)\n\t\tfor _, wart := range warts {\n\t\t\tfmt.Printf(\n\t\t\t\t\" [%s %s] %s\\n\",\n\t\t\t\twart.Reporter,\n\t\t\t\twart.IssueCode,\n\t\t\t\tcolor(\"bold\", wart.Message),\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunc clear() {\n\tcmd := exec.Command(\"clear\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Run()\n fmt.Println(color(\"header\", \"--- LintBlame ---\"))\n}\n\nfunc makeTargetFile(filepath string, c chan *TargetFile) {\n\ttf := NewTargetFile(filepath)\n\tc <- tf\n}\n\nfunc update(filepaths []string) {\n\tc := make(chan *TargetFile)\n\tfor _, path := range filepaths {\n\t\tgo makeTargetFile(path, c)\n\t}\n\tcleared := false\n\tfor i := 0; i < len(filepaths); i++ {\n\t\tif !cleared {\n\t\t\tclear()\n\t\t\tcleared = true\n\t\t}\n\t\ttf := <-c\n\t\tprintWarts(tf)\n fmt.Println(\"\")\n\t}\n}\n\nfunc initialPaths() []string {\n var branch bool\n flag.BoolVar(&branch, \"b\", false, \"Run against current branch\")\n flag.Parse()\n\n var filepaths []string\n if branch {\n config[\"workingDir\"] = env.GitPath()\n filepaths = gitBranchFiles()\n } else {\n args := flag.Args()\n if len(args) > 0 {\n target := args[0]\n stat, err := os.Stat(target)\n if err != nil {\n log.Fatal(\"Unable to process argument: \", target)\n }\n absPath, err := filepath.Abs(target)\n if err != nil {\n log.Fatal(\"Unable to get absolute path of \", target)\n }\n if stat.IsDir() {\n config[\"workingDir\"] = absPath\n filepaths = getDirFiles(absPath)\n } else {\n dir, _ := filepath.Split(absPath)\n config[\"workingDir\"] = dir\n filepaths = filterFiles([]string{absPath})\n }\n }\n }\n return filepaths\n}\n\nfunc main() {\n filepaths := initialPaths()\n\tmodTimes := NewModifiedTimes()\n\n\tfor _, file := range filepaths {\n\t\tmodTimes.CheckTime(file)\n\t}\n\tupdate(modTimes.PathsByModTime())\n\tfor {\n\t\trunUpdate := false\n\t\tfor _, file := range filepaths {\n\t\t\tif modTimes.CheckTime(file) {\n\t\t\t\trunUpdate = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif runUpdate {\n\t\t\tupdate(modTimes.PathsByModTime())\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n<|endoftext|>"} {"text":"package exp_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/doug-martin\/goqu\/v9\/exp\"\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\ntype bitwiseExpressionSuite struct {\n\tsuite.Suite\n}\n\nfunc TestBitwiseExpressionSuite(t *testing.T) {\n\tsuite.Run(t, &bitwiseExpressionSuite{})\n}\n\nfunc (bes *bitwiseExpressionSuite) TestClone() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(be, be.Clone())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestExpression() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(be, be.Expression())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAs() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseInversionOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewAliasExpression(be, \"a\"), be.As(\"a\"))\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAsc() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewOrderedExpression(be, exp.AscDir, exp.NoNullsSortType), be.Asc())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestDesc() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseOrOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewOrderedExpression(be, exp.DescSortDir, exp.NoNullsSortType), be.Desc())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAllOthers() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseRightShiftOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\trv := exp.NewRangeVal(1, 2)\n\tpattern := \"cast like%\"\n\tinVals := []interface{}{1, 2}\n\ttestCases := []struct {\n\t\tEx exp.Expression\n\t\tExpected exp.Expression\n\t}{\n\t\t{Ex: be.Eq(1), Expected: exp.NewBooleanExpression(exp.EqOp, be, 1)},\n\t\t{Ex: be.Neq(1), Expected: exp.NewBooleanExpression(exp.NeqOp, be, 1)},\n\t\t{Ex: be.Gt(1), Expected: exp.NewBooleanExpression(exp.GtOp, be, 1)},\n\t\t{Ex: be.Gte(1), Expected: exp.NewBooleanExpression(exp.GteOp, be, 1)},\n\t\t{Ex: be.Lt(1), Expected: exp.NewBooleanExpression(exp.LtOp, be, 1)},\n\t\t{Ex: be.Lte(1), Expected: exp.NewBooleanExpression(exp.LteOp, be, 1)},\n\t\t{Ex: be.Between(rv), Expected: exp.NewRangeExpression(exp.BetweenOp, be, rv)},\n\t\t{Ex: be.NotBetween(rv), Expected: exp.NewRangeExpression(exp.NotBetweenOp, be, rv)},\n\t\t{Ex: be.Like(pattern), Expected: exp.NewBooleanExpression(exp.LikeOp, be, pattern)},\n\t\t{Ex: be.NotLike(pattern), Expected: exp.NewBooleanExpression(exp.NotLikeOp, be, pattern)},\n\t\t{Ex: be.ILike(pattern), Expected: exp.NewBooleanExpression(exp.ILikeOp, be, pattern)},\n\t\t{Ex: be.NotILike(pattern), Expected: exp.NewBooleanExpression(exp.NotILikeOp, be, pattern)},\n\t\t{Ex: be.RegexpLike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpLikeOp, be, pattern)},\n\t\t{Ex: be.RegexpNotLike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpNotLikeOp, be, pattern)},\n\t\t{Ex: be.RegexpILike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpILikeOp, be, pattern)},\n\t\t{Ex: be.RegexpNotILike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpNotILikeOp, be, pattern)},\n\t\t{Ex: be.In(inVals), Expected: exp.NewBooleanExpression(exp.InOp, be, inVals)},\n\t\t{Ex: be.NotIn(inVals), Expected: exp.NewBooleanExpression(exp.NotInOp, be, inVals)},\n\t\t{Ex: be.Is(true), Expected: exp.NewBooleanExpression(exp.IsOp, be, true)},\n\t\t{Ex: be.IsNot(true), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, true)},\n\t\t{Ex: be.IsNull(), Expected: exp.NewBooleanExpression(exp.IsOp, be, nil)},\n\t\t{Ex: be.IsNotNull(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, nil)},\n\t\t{Ex: be.IsTrue(), Expected: exp.NewBooleanExpression(exp.IsOp, be, true)},\n\t\t{Ex: be.IsNotTrue(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, true)},\n\t\t{Ex: be.IsFalse(), Expected: exp.NewBooleanExpression(exp.IsOp, be, false)},\n\t\t{Ex: be.IsNotFalse(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, false)},\n\t\t{Ex: be.Distinct(), Expected: exp.NewSQLFunctionExpression(\"DISTINCT\", be)},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tbes.Equal(tc.Expected, tc.Ex)\n\t}\n}\nchore: fix linting issuespackage exp_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/doug-martin\/goqu\/v9\/exp\"\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\ntype bitwiseExpressionSuite struct {\n\tsuite.Suite\n}\n\nfunc TestBitwiseExpressionSuite(t *testing.T) {\n\tsuite.Run(t, &bitwiseExpressionSuite{})\n}\n\nfunc (bes *bitwiseExpressionSuite) TestClone() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(be, be.Clone())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestExpression() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(be, be.Expression())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAs() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseInversionOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewAliasExpression(be, \"a\"), be.As(\"a\"))\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAsc() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseAndOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewOrderedExpression(be, exp.AscDir, exp.NoNullsSortType), be.Asc())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestDesc() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseOrOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\tbes.Equal(exp.NewOrderedExpression(be, exp.DescSortDir, exp.NoNullsSortType), be.Desc())\n}\n\nfunc (bes *bitwiseExpressionSuite) TestAllOthers() {\n\tbe := exp.NewBitwiseExpression(exp.BitwiseRightShiftOp, exp.NewIdentifierExpression(\"\", \"\", \"col\"), 1)\n\trv := exp.NewRangeVal(1, 2)\n\tpattern := \"bitwiseExp like%\"\n\tinVals := []interface{}{1, 2}\n\ttestCases := []struct {\n\t\tEx exp.Expression\n\t\tExpected exp.Expression\n\t}{\n\t\t{Ex: be.Eq(1), Expected: exp.NewBooleanExpression(exp.EqOp, be, 1)},\n\t\t{Ex: be.Neq(1), Expected: exp.NewBooleanExpression(exp.NeqOp, be, 1)},\n\t\t{Ex: be.Gt(1), Expected: exp.NewBooleanExpression(exp.GtOp, be, 1)},\n\t\t{Ex: be.Gte(1), Expected: exp.NewBooleanExpression(exp.GteOp, be, 1)},\n\t\t{Ex: be.Lt(1), Expected: exp.NewBooleanExpression(exp.LtOp, be, 1)},\n\t\t{Ex: be.Lte(1), Expected: exp.NewBooleanExpression(exp.LteOp, be, 1)},\n\t\t{Ex: be.Between(rv), Expected: exp.NewRangeExpression(exp.BetweenOp, be, rv)},\n\t\t{Ex: be.NotBetween(rv), Expected: exp.NewRangeExpression(exp.NotBetweenOp, be, rv)},\n\t\t{Ex: be.Like(pattern), Expected: exp.NewBooleanExpression(exp.LikeOp, be, pattern)},\n\t\t{Ex: be.NotLike(pattern), Expected: exp.NewBooleanExpression(exp.NotLikeOp, be, pattern)},\n\t\t{Ex: be.ILike(pattern), Expected: exp.NewBooleanExpression(exp.ILikeOp, be, pattern)},\n\t\t{Ex: be.NotILike(pattern), Expected: exp.NewBooleanExpression(exp.NotILikeOp, be, pattern)},\n\t\t{Ex: be.RegexpLike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpLikeOp, be, pattern)},\n\t\t{Ex: be.RegexpNotLike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpNotLikeOp, be, pattern)},\n\t\t{Ex: be.RegexpILike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpILikeOp, be, pattern)},\n\t\t{Ex: be.RegexpNotILike(pattern), Expected: exp.NewBooleanExpression(exp.RegexpNotILikeOp, be, pattern)},\n\t\t{Ex: be.In(inVals), Expected: exp.NewBooleanExpression(exp.InOp, be, inVals)},\n\t\t{Ex: be.NotIn(inVals), Expected: exp.NewBooleanExpression(exp.NotInOp, be, inVals)},\n\t\t{Ex: be.Is(true), Expected: exp.NewBooleanExpression(exp.IsOp, be, true)},\n\t\t{Ex: be.IsNot(true), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, true)},\n\t\t{Ex: be.IsNull(), Expected: exp.NewBooleanExpression(exp.IsOp, be, nil)},\n\t\t{Ex: be.IsNotNull(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, nil)},\n\t\t{Ex: be.IsTrue(), Expected: exp.NewBooleanExpression(exp.IsOp, be, true)},\n\t\t{Ex: be.IsNotTrue(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, true)},\n\t\t{Ex: be.IsFalse(), Expected: exp.NewBooleanExpression(exp.IsOp, be, false)},\n\t\t{Ex: be.IsNotFalse(), Expected: exp.NewBooleanExpression(exp.IsNotOp, be, false)},\n\t\t{Ex: be.Distinct(), Expected: exp.NewSQLFunctionExpression(\"DISTINCT\", be)},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tbes.Equal(tc.Expected, tc.Ex)\n\t}\n}\n<|endoftext|>"} {"text":"package tips\n\n\/\/ Reflection in Go:\n\/\/ https:\/\/golang.org\/pkg\/reflect\/\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestReflectInt(t *testing.T) {\n\ti := 123\n\tti := reflect.TypeOf(i)\n\tif ti.Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ti.Kind())\n\t\treturn\n\t}\n\tv := reflect.ValueOf(i)\n\tif v.Type() != ti {\n\t\tt.Errorf(\"Expected %v but got %v\", ti, v.Type())\n\t\treturn\n\t}\n\t\/\/ Retrieve the actual value.\n\tvar ri int64 = v.Int()\n\tif ri != int64(i) {\n\t\tt.Errorf(\"Expected %d but got %d\", i, ri)\n\t}\n\t\/\/ Interestingly, this does not panic :)\n\tif v.String() != \"\" {\n\t\tt.Errorf(\"Expected an empty string but got %q\", v.String())\n\t}\n\t\/\/ This panics! (using unaddressable value)\n\t\/\/ v.SetInt(456)\n}\n\nfunc TestReflectIntPointer(t *testing.T) {\n\ti := 123\n\tvar p interface{} = &i\n\tty := reflect.TypeOf(p)\n\tif ty.Kind() != reflect.Ptr {\n\t\tt.Errorf(\"Expected reflect.Ptr but got %v\", ty.Kind())\n\t\treturn\n\t}\n\tv := reflect.ValueOf(p)\n\tif v.Type() != ty {\n\t\tt.Errorf(\"Expected %v but got %v\", ty, v.Type())\n\t\treturn\n\t}\n\tvar ev reflect.Value = v.Elem()\n\tif ev.Type().Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ev.Type().Kind())\n\t}\n\tif ev.Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ev.Kind())\n\t}\n\tif !ev.CanSet() {\n\t\tt.Error(\"CanSet must return true.\")\n\t}\n\t\/\/ Set value!\n\tv.Elem().SetInt(456)\n\tif i != 456 {\n\t\tt.Errorf(\"Expected value: %d\", i)\n\t}\n}\n\nfunc TestReflectStruct(t *testing.T) {\n\ttype entry struct {\n\t\tname string\n\t\tAge int `myattr:\"myvalue\"`\n\t}\n\te := entry{name: \"Alice\", Age: 13}\n\n\tty := reflect.TypeOf(e)\n\tif ty.Kind() != reflect.Struct {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\tif ty.NumField() != 2 {\n\t\tt.Errorf(\"Unexpected NumField(): %d\", ty.NumField())\n\t\treturn\n\t}\n\tvar f0 reflect.StructField = ty.Field(0)\n\tif f0.Name != \"name\" || f0.Type.Kind() != reflect.String {\n\t\tt.Errorf(\"Unexpected field attrs: name = %q, type = %s\", f0.Name, f0.Type)\n\t}\n\tf1 := ty.Field(1)\n\tif f1.Name != \"Age\" || f1.Type.Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected field attrs: name = %q, type = %s\", f1.Name, f1.Type)\n\t}\n\t\/\/ How to retrieve struct field tags.\n\t\/\/ https:\/\/golang.org\/pkg\/reflect\/#StructTag\n\tif f1.Tag.Get(\"myattr\") != \"myvalue\" {\n\t\tt.Errorf(\"Unexpected tag value: %q\", f1.Tag.Get(\"myattr\"))\n\t}\n\n\t\/\/ Value of struct.\n\tv := reflect.ValueOf(e)\n\tif v.Type() != ty {\n\t\tt.Errorf(\"Expected %v but got %v\", ty, v.Type())\n\t}\n\tif v.NumField() != 2 {\n\t\tt.Errorf(\"Unexpected NumField(): %d\", v.NumField())\n\t\treturn\n\t}\n\tvar vf0 reflect.Value = v.Field(0)\n\tif vf0.Type().Kind() != reflect.String {\n\t\tt.Errorf(\"Unexpected type for vf0: %v\", vf0.Type())\n\t}\n\tif vf0.String() != \"Alice\" {\n\t\tt.Errorf(\"Unexpected value: %q\", vf0.String())\n\t}\n\tvf1 := v.Field(1)\n\tif vf1.Type().Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected type for vf1: %v\", vf1.Type())\n\t}\n\tif vf0.String() != \"Alice\" {\n\t\tt.Errorf(\"Unexpected value: %q\", vf0.String())\n\t}\n\tif vf1.Int() != 13 {\n\t\tt.Errorf(\"Unexpected value: %d\", vf1.Int())\n\t}\n\t\/\/ fields of struct are not settable.\n\tif vf0.CanSet() || vf1.CanSet() {\n\t\tt.Error(\"CanSet of all fields must return false\")\n\t}\n\n\t\/\/ This panics \"using value obtained using unexported field\".\n\t\/\/ vf0.SetString(\"hello\")\n\t\/\/\n\t\/\/ This panics with \"using unaddressable value\".\n\t\/\/ vf1.SetInt(20)\n}\n\nfunc TestReflectStructPointer(t *testing.T) {\n\ttype entry struct {\n\t\tname string\n\t\tAge int `myattr:\"myvalue\"`\n\t}\n\tp := &entry{name: \"Alice\", Age: 13}\n\tty := reflect.TypeOf(p)\n\tif ty.Kind() != reflect.Ptr {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\t\/\/ Set field values.\n\tv := reflect.ValueOf(p)\n\tv.Elem().Field(1).SetInt(24)\n\tif p.Age != 24 {\n\t\tt.Errorf(\"Unexpected value: %v\", p.Age)\n\t}\n\t\/\/ This panics \"using value obtained using unexported field\".\n\t\/\/ v.Elem().Field(0).SetString(\"Bob\")\n}\n\nfunc TestRelectEmbed(t *testing.T) {\n\ttype embed struct {\n\t\tstr string\n\t\tStr string\n\t}\n\ttype Embed struct {\n\t\tInt int\n\t\tinteger int\n\t}\n\ttype entry struct {\n\t\tF float32\n\t\tembed\n\t\tEmbed\n\t\tfloat64\n\t}\n\te := entry{\n\t\tF: 3.14,\n\t\tembed: embed{\n\t\t\tstr: \"hello\",\n\t\t\tStr: \"World\",\n\t\t},\n\t\tEmbed: Embed{\n\t\t\tInt: 100,\n\t\t\tinteger: 10,\n\t\t},\n\t\tfloat64: 12.34,\n\t}\n\tty := reflect.TypeOf(e)\n\t\/\/ Embeded struct are treated as fields as you may expect.\n\tif ty.NumField() != 4 {\n\t\tt.Errorf(\"Unexpected NumField() = %d\", ty.NumField())\n\t\treturn\n\t}\n\tf := ty.Field(0)\n\tif !(f.Name == \"F\" && !f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(1)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"embed\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(2)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"Embed\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(3)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"float64\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\n\t\/\/ TODO: Investigate Value.\n}\n\nfunc TestReflectFunc(t *testing.T) {\n\tsum := func(x int, y int32) float32 {\n\t\treturn float32(x + int(y))\n\t}\n\tvar inter interface{} = sum\n\tty := reflect.TypeOf(inter)\n\tif ty.Kind() != reflect.Func {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\t\/\/ Types of arguments and return values.\n\tif ty.NumIn() != 2 {\n\t\tt.Errorf(\"Unexpected NumIn() = %v\", ty.NumIn())\n\t}\n\tif ty.NumOut() != 1 {\n\t\tt.Errorf(\"Unexpected NumOut() = %v\", ty.NumOut())\n\t}\n\tif ty.In(0).Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected first arg type: %v\", ty.In(0).Kind())\n\t}\n\tif ty.Out(0).Kind() != reflect.Float32 {\n\t\tt.Errorf(\"Unexpected first arg type: %v\", ty.Out(0).Kind())\n\t}\n\n\t\/\/ Invoke\n\tv := reflect.ValueOf(inter)\n\treturns := v.Call([]reflect.Value{\n\t\treflect.ValueOf(12),\n\t\treflect.ValueOf(int32(34)),\n\t})\n\tif len(returns) != 1 {\n\t\tt.Errorf(\"Unexpected size of slice was returned: %d\", len(returns))\n\t\treturn\n\t}\n\tf := returns[0].Float()\n\tif f != 46.0 {\n\t\tt.Errorf(\"Unexpected return value: %f\", f)\n\t}\n\n\t\/\/ Call panics if arguments are invalid.\n\t\/\/ v.Call([]reflect.Value{})\n}\n\nfunc TestReflectSlice(t *testing.T) {\n\tslicePtr := reflect.New(reflect.SliceOf(reflect.TypeOf(int(0))))\n\tfor i := 0; i < 10; i++ {\n\t\tslicePtr.Elem().Set(reflect.Append(slicePtr.Elem(), reflect.ValueOf(i*i)))\n\t}\n\ts := slicePtr.Elem().Interface().([]int)\n\texpected := []int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n\tif !reflect.DeepEqual(s, expected) {\n\t\tt.Errorf(\"Expected %v but got %v\", expected, s)\n\t}\n}\n\nfunc TestInterfaceToInterface(t *testing.T) {\n\tvar err error\n\tvar i interface{} = err\n\tif i != nil {\n\t\tt.Error(\"An interface from a nil interface must be nil too in Go.\")\n\t}\n\tv := reflect.ValueOf(i)\n\tif v.IsValid() {\n\t\tt.Error(\"The value of nil must not be valid\")\n\t}\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif recover() == nil {\n\t\t\t\tt.Error(\"v.IsNil() below must panic.\")\n\t\t\t}\n\t\t}()\n\t\t\/\/ Wow, this panics!\n\t\tv.IsNil()\n\t}()\n\tfunc() {\n\t\tdefer func() {\n\t\t\tp := recover()\n\t\t\tif p == nil {\n\t\t\t\tt.Error(\"The code must panic.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := p.(error)\n\t\t\tif !strings.Contains(err.Error(), \"interface is nil, not error\") {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t}()\n\t\terr = i.(error)\n\t}()\n}\n\nfunc TestNilAndCall(t *testing.T) {\n\terrorType := reflect.TypeOf((*error)(nil)).Elem()\n\tif errorType.Name() != \"error\" {\n\t\tt.Errorf(\"Unexpected errorType: %v\", errorType)\n\t}\n\n\tfn := func(e error) error {\n\t\tif e != nil {\n\t\t\tpanic(\"Call this function with nil!\")\n\t\t}\n\t\treturn nil\n\t}\n\tv := reflect.ValueOf(fn)\n\n\t\/\/ NG\n\t\/\/ arg := reflect.ValueOf(nil)\n\targ := reflect.New(errorType).Elem()\n\trets := v.Call([]reflect.Value{arg})\n\tif len(rets) != 1 {\n\t\tt.Errorf(\"Unexpected len(ret): %d\", len(rets))\n\t\treturn\n\t}\n\tret := rets[0]\n\t\/\/ Unlike the test above, a nil interface in the return values is not invalid and has a type.\n\tif !ret.IsValid() {\n\t\tt.Error(\"ret is invalid unexpectedly\")\n\t}\n\tif !ret.IsNil() {\n\t\tt.Error(\"ret.IsNil() returned false unexpectedly\")\n\t}\n\tif ret.Type() != errorType {\n\t\tt.Errorf(\"Unexpected type: %v\", ret.Type())\n\t}\n}\n\ntype myInt int\n\nfunc TestReflectNamedType(t *testing.T) {\n\tvar a interface{} = myInt(3)\n\tva := reflect.ValueOf(a)\n\tta := reflect.TypeOf(a)\n\tintType := reflect.TypeOf(0)\n\tif ta.String() != \"tips.myInt\" {\n\t\tt.Errorf(\"ta.String() must be \\\"tips.myInt\\\", but got %q\", ta.String())\n\t}\n\tif ta == intType {\n\t\tt.Errorf(\"typeof(myInt) == typeof(int) must be false\")\n\t}\n\tif ta.Name() != \"myInt\" {\n\t\tt.Errorf(\"ta.Name() must be \\\"myInt\\\", but got %q\", ta.Name())\n\t}\n\tif va.Kind() != reflect.Int {\n\t\t\/\/ Although typeof(myInt) != typeof(int), Kind() returns reflect.Int.\n\t\tt.Error(\"va.Kind() must be reflect.Int\")\n\t}\n\tif va.Int() != 3 {\n\t\tt.Errorf(\"va.Int() must be 3, but got %v\", va.Int())\n\t}\n}\n\nfunc TestReflectAddr(t *testing.T) {\n\tv := reflect.ValueOf(10)\n\tif v.CanAddr() {\n\t\tt.Errorf(\"v.CanAddr() must return false\")\n\t}\n\tv = reflect.New(reflect.TypeOf(0))\n\tif !v.Elem().CanAddr() {\n\t\tt.Errorf(\"v.Elem().CanAddr() must return true\")\n\t}\n}\nLearn how to access unexported fields with reflectpackage tips\n\n\/\/ Reflection in Go:\n\/\/ https:\/\/golang.org\/pkg\/reflect\/\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\nfunc TestReflectInt(t *testing.T) {\n\ti := 123\n\tti := reflect.TypeOf(i)\n\tif ti.Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ti.Kind())\n\t\treturn\n\t}\n\tv := reflect.ValueOf(i)\n\tif v.Type() != ti {\n\t\tt.Errorf(\"Expected %v but got %v\", ti, v.Type())\n\t\treturn\n\t}\n\t\/\/ Retrieve the actual value.\n\tvar ri int64 = v.Int()\n\tif ri != int64(i) {\n\t\tt.Errorf(\"Expected %d but got %d\", i, ri)\n\t}\n\t\/\/ Interestingly, this does not panic :)\n\tif v.String() != \"\" {\n\t\tt.Errorf(\"Expected an empty string but got %q\", v.String())\n\t}\n\t\/\/ This panics! (using unaddressable value)\n\t\/\/ v.SetInt(456)\n}\n\nfunc TestReflectIntPointer(t *testing.T) {\n\ti := 123\n\tvar p interface{} = &i\n\tty := reflect.TypeOf(p)\n\tif ty.Kind() != reflect.Ptr {\n\t\tt.Errorf(\"Expected reflect.Ptr but got %v\", ty.Kind())\n\t\treturn\n\t}\n\tv := reflect.ValueOf(p)\n\tif v.Type() != ty {\n\t\tt.Errorf(\"Expected %v but got %v\", ty, v.Type())\n\t\treturn\n\t}\n\tvar ev reflect.Value = v.Elem()\n\tif ev.Type().Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ev.Type().Kind())\n\t}\n\tif ev.Kind() != reflect.Int {\n\t\tt.Errorf(\"Expected reflect.Int but got %v\", ev.Kind())\n\t}\n\tif !ev.CanSet() {\n\t\tt.Error(\"CanSet must return true.\")\n\t}\n\t\/\/ Set value!\n\tv.Elem().SetInt(456)\n\tif i != 456 {\n\t\tt.Errorf(\"Expected value: %d\", i)\n\t}\n}\n\nfunc TestReflectStruct(t *testing.T) {\n\ttype entry struct {\n\t\tname string\n\t\tAge int `myattr:\"myvalue\"`\n\t}\n\te := entry{name: \"Alice\", Age: 13}\n\n\tty := reflect.TypeOf(e)\n\tif ty.Kind() != reflect.Struct {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\tif ty.NumField() != 2 {\n\t\tt.Errorf(\"Unexpected NumField(): %d\", ty.NumField())\n\t\treturn\n\t}\n\tvar f0 reflect.StructField = ty.Field(0)\n\tif f0.Name != \"name\" || f0.Type.Kind() != reflect.String {\n\t\tt.Errorf(\"Unexpected field attrs: name = %q, type = %s\", f0.Name, f0.Type)\n\t}\n\tf1 := ty.Field(1)\n\tif f1.Name != \"Age\" || f1.Type.Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected field attrs: name = %q, type = %s\", f1.Name, f1.Type)\n\t}\n\t\/\/ How to retrieve struct field tags.\n\t\/\/ https:\/\/golang.org\/pkg\/reflect\/#StructTag\n\tif f1.Tag.Get(\"myattr\") != \"myvalue\" {\n\t\tt.Errorf(\"Unexpected tag value: %q\", f1.Tag.Get(\"myattr\"))\n\t}\n\n\t\/\/ Value of struct.\n\tv := reflect.ValueOf(e)\n\tif v.Type() != ty {\n\t\tt.Errorf(\"Expected %v but got %v\", ty, v.Type())\n\t}\n\tif v.NumField() != 2 {\n\t\tt.Errorf(\"Unexpected NumField(): %d\", v.NumField())\n\t\treturn\n\t}\n\tvar vf0 reflect.Value = v.Field(0)\n\tif vf0.Type().Kind() != reflect.String {\n\t\tt.Errorf(\"Unexpected type for vf0: %v\", vf0.Type())\n\t}\n\tif vf0.String() != \"Alice\" {\n\t\tt.Errorf(\"Unexpected value: %q\", vf0.String())\n\t}\n\tvf1 := v.Field(1)\n\tif vf1.Type().Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected type for vf1: %v\", vf1.Type())\n\t}\n\tif vf0.String() != \"Alice\" {\n\t\tt.Errorf(\"Unexpected value: %q\", vf0.String())\n\t}\n\tif vf1.Int() != 13 {\n\t\tt.Errorf(\"Unexpected value: %d\", vf1.Int())\n\t}\n\t\/\/ fields of struct are not settable.\n\tif vf0.CanSet() || vf1.CanSet() {\n\t\tt.Error(\"CanSet of all fields must return false\")\n\t}\n\n\t\/\/ This panics \"using value obtained using unexported field\".\n\t\/\/ vf0.SetString(\"hello\")\n\t\/\/\n\t\/\/ This panics with \"using unaddressable value\".\n\t\/\/ vf1.SetInt(20)\n}\n\nfunc TestReflectStructPointer(t *testing.T) {\n\ttype entry struct {\n\t\tname string\n\t\tAge int `myattr:\"myvalue\"`\n\t}\n\tp := &entry{name: \"Alice\", Age: 13}\n\tty := reflect.TypeOf(p)\n\tif ty.Kind() != reflect.Ptr {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\t\/\/ Set field values.\n\tv := reflect.ValueOf(p)\n\tv.Elem().Field(1).SetInt(24)\n\tif p.Age != 24 {\n\t\tt.Errorf(\"Unexpected value: %v\", p.Age)\n\t}\n\t\/\/ This panics \"using value obtained using unexported field\".\n\t\/\/ v.Elem().Field(0).SetString(\"Bob\")\n}\n\nfunc TestRelectEmbed(t *testing.T) {\n\ttype embed struct {\n\t\tstr string\n\t\tStr string\n\t}\n\ttype Embed struct {\n\t\tInt int\n\t\tinteger int\n\t}\n\ttype entry struct {\n\t\tF float32\n\t\tembed\n\t\tEmbed\n\t\tfloat64\n\t}\n\te := entry{\n\t\tF: 3.14,\n\t\tembed: embed{\n\t\t\tstr: \"hello\",\n\t\t\tStr: \"World\",\n\t\t},\n\t\tEmbed: Embed{\n\t\t\tInt: 100,\n\t\t\tinteger: 10,\n\t\t},\n\t\tfloat64: 12.34,\n\t}\n\tty := reflect.TypeOf(e)\n\t\/\/ Embeded struct are treated as fields as you may expect.\n\tif ty.NumField() != 4 {\n\t\tt.Errorf(\"Unexpected NumField() = %d\", ty.NumField())\n\t\treturn\n\t}\n\tf := ty.Field(0)\n\tif !(f.Name == \"F\" && !f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(1)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"embed\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(2)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"Embed\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\tf = ty.Field(3)\n\t\/\/ Anonymous is true if the field is an embedded field.\n\tif !(f.Name == \"float64\" && f.Anonymous) {\n\t\tt.Errorf(\"Unexpected: %#v\", f)\n\t}\n\n\t\/\/ TODO: Investigate Value.\n}\n\nfunc TestReflectFunc(t *testing.T) {\n\tsum := func(x int, y int32) float32 {\n\t\treturn float32(x + int(y))\n\t}\n\tvar inter interface{} = sum\n\tty := reflect.TypeOf(inter)\n\tif ty.Kind() != reflect.Func {\n\t\tt.Errorf(\"Unexpected kind: %v\", ty.Kind())\n\t\treturn\n\t}\n\t\/\/ Types of arguments and return values.\n\tif ty.NumIn() != 2 {\n\t\tt.Errorf(\"Unexpected NumIn() = %v\", ty.NumIn())\n\t}\n\tif ty.NumOut() != 1 {\n\t\tt.Errorf(\"Unexpected NumOut() = %v\", ty.NumOut())\n\t}\n\tif ty.In(0).Kind() != reflect.Int {\n\t\tt.Errorf(\"Unexpected first arg type: %v\", ty.In(0).Kind())\n\t}\n\tif ty.Out(0).Kind() != reflect.Float32 {\n\t\tt.Errorf(\"Unexpected first arg type: %v\", ty.Out(0).Kind())\n\t}\n\n\t\/\/ Invoke\n\tv := reflect.ValueOf(inter)\n\treturns := v.Call([]reflect.Value{\n\t\treflect.ValueOf(12),\n\t\treflect.ValueOf(int32(34)),\n\t})\n\tif len(returns) != 1 {\n\t\tt.Errorf(\"Unexpected size of slice was returned: %d\", len(returns))\n\t\treturn\n\t}\n\tf := returns[0].Float()\n\tif f != 46.0 {\n\t\tt.Errorf(\"Unexpected return value: %f\", f)\n\t}\n\n\t\/\/ Call panics if arguments are invalid.\n\t\/\/ v.Call([]reflect.Value{})\n}\n\nfunc TestReflectSlice(t *testing.T) {\n\tslicePtr := reflect.New(reflect.SliceOf(reflect.TypeOf(int(0))))\n\tfor i := 0; i < 10; i++ {\n\t\tslicePtr.Elem().Set(reflect.Append(slicePtr.Elem(), reflect.ValueOf(i*i)))\n\t}\n\ts := slicePtr.Elem().Interface().([]int)\n\texpected := []int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}\n\tif !reflect.DeepEqual(s, expected) {\n\t\tt.Errorf(\"Expected %v but got %v\", expected, s)\n\t}\n}\n\nfunc TestInterfaceToInterface(t *testing.T) {\n\tvar err error\n\tvar i interface{} = err\n\tif i != nil {\n\t\tt.Error(\"An interface from a nil interface must be nil too in Go.\")\n\t}\n\tv := reflect.ValueOf(i)\n\tif v.IsValid() {\n\t\tt.Error(\"The value of nil must not be valid\")\n\t}\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif recover() == nil {\n\t\t\t\tt.Error(\"v.IsNil() below must panic.\")\n\t\t\t}\n\t\t}()\n\t\t\/\/ Wow, this panics!\n\t\tv.IsNil()\n\t}()\n\tfunc() {\n\t\tdefer func() {\n\t\t\tp := recover()\n\t\t\tif p == nil {\n\t\t\t\tt.Error(\"The code must panic.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := p.(error)\n\t\t\tif !strings.Contains(err.Error(), \"interface is nil, not error\") {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t}()\n\t\terr = i.(error)\n\t}()\n}\n\nfunc TestNilAndCall(t *testing.T) {\n\terrorType := reflect.TypeOf((*error)(nil)).Elem()\n\tif errorType.Name() != \"error\" {\n\t\tt.Errorf(\"Unexpected errorType: %v\", errorType)\n\t}\n\n\tfn := func(e error) error {\n\t\tif e != nil {\n\t\t\tpanic(\"Call this function with nil!\")\n\t\t}\n\t\treturn nil\n\t}\n\tv := reflect.ValueOf(fn)\n\n\t\/\/ NG\n\t\/\/ arg := reflect.ValueOf(nil)\n\targ := reflect.New(errorType).Elem()\n\trets := v.Call([]reflect.Value{arg})\n\tif len(rets) != 1 {\n\t\tt.Errorf(\"Unexpected len(ret): %d\", len(rets))\n\t\treturn\n\t}\n\tret := rets[0]\n\t\/\/ Unlike the test above, a nil interface in the return values is not invalid and has a type.\n\tif !ret.IsValid() {\n\t\tt.Error(\"ret is invalid unexpectedly\")\n\t}\n\tif !ret.IsNil() {\n\t\tt.Error(\"ret.IsNil() returned false unexpectedly\")\n\t}\n\tif ret.Type() != errorType {\n\t\tt.Errorf(\"Unexpected type: %v\", ret.Type())\n\t}\n}\n\ntype myInt int\n\nfunc TestReflectNamedType(t *testing.T) {\n\tvar a interface{} = myInt(3)\n\tva := reflect.ValueOf(a)\n\tta := reflect.TypeOf(a)\n\tintType := reflect.TypeOf(0)\n\tif ta.String() != \"tips.myInt\" {\n\t\tt.Errorf(\"ta.String() must be \\\"tips.myInt\\\", but got %q\", ta.String())\n\t}\n\tif ta == intType {\n\t\tt.Errorf(\"typeof(myInt) == typeof(int) must be false\")\n\t}\n\tif ta.Name() != \"myInt\" {\n\t\tt.Errorf(\"ta.Name() must be \\\"myInt\\\", but got %q\", ta.Name())\n\t}\n\tif va.Kind() != reflect.Int {\n\t\t\/\/ Although typeof(myInt) != typeof(int), Kind() returns reflect.Int.\n\t\tt.Error(\"va.Kind() must be reflect.Int\")\n\t}\n\tif va.Int() != 3 {\n\t\tt.Errorf(\"va.Int() must be 3, but got %v\", va.Int())\n\t}\n}\n\nfunc TestReflectAddr(t *testing.T) {\n\tv := reflect.ValueOf(10)\n\tif v.CanAddr() {\n\t\tt.Errorf(\"v.CanAddr() must return false\")\n\t}\n\tv = reflect.New(reflect.TypeOf(0))\n\tif !v.Elem().CanAddr() {\n\t\tt.Errorf(\"v.Elem().CanAddr() must return true\")\n\t}\n}\n\ntype childField struct {\n\ts string\n}\n\ntype structWithUnexported struct {\n\ti int8\n\tf float32\n\tchild childField\n}\n\nfunc expectUnexportedError(t *testing.T) {\n\tr := recover()\n\tif r == nil {\n\t\tt.Errorf(\"Expected panic but no panic was thrown\")\n\t}\n\tif msg, _ := r.(string); !strings.Contains(msg, \"unexported field\") {\n\t\tt.Errorf(\"Unexpected error: %v\", r)\n\t}\n}\n\nfunc TestStructUnexportedField(t *testing.T) {\n\tu := structWithUnexported{12, 3.4, childField{\"hello\"}}\n\tv := reflect.ValueOf(&u).Elem()\n\n\t\/\/ You can read unexported fields with reflect.\n\tif v.Field(0).Kind() != reflect.Int8 {\n\t\tt.Errorf(\"Expected %v but got %v\", reflect.Int8, v.Field(0).Kind())\n\t}\n\ti := int8(v.Field(0).Int())\n\tif i != u.i {\n\t\tt.Errorf(\"Expected %v but got %v\", u.i, i)\n\t}\n\ts := v.FieldByName(\"child\").FieldByName(\"s\").String()\n\tif s != u.child.s {\n\t\tt.Errorf(\"Expected %q but got %q\", u.child.s, s)\n\t}\n\n\t\/\/ But you can not use Interface() to read unexported fields for some reasons.\n\tfunc() {\n\t\tdefer expectUnexportedError(t)\n\t\tv.FieldByName(\"i\").Interface()\n\t}()\n\n\t\/\/ You can not set unexported fields normally.\n\tfunc() {\n\t\tdefer expectUnexportedError(t)\n\t\tv.FieldByName(\"f\").SetFloat(5.6)\n\t}()\n\t\/\/ But, you can set values to unexported fields with unsafe.\n\t\/\/ Ref: https:\/\/stackoverflow.com\/questions\/42664837\/access-unexported-fields-in-golang-reflect\n\tff := v.FieldByName(\"f\")\n\tnewF := float32(7.8)\n\treflect.NewAt(ff.Type(), unsafe.Pointer(ff.UnsafeAddr())).Elem().SetFloat(float64(newF))\n\tif u.f != newF {\n\t\tt.Errorf(\"Expected %v but got %v\", newF, u.f)\n\t}\n}\n<|endoftext|>"} {"text":"package torrent\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\" \/\/ nolint: gosec\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/bitfield\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peer\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerconn\/peerreader\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerconn\/peerwriter\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerprotocol\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/piecewriter\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/tracker\"\n\t\"github.com\/cenkalti\/rain\/torrent\/metainfo\"\n)\n\nfunc (t *Torrent) handlePeerMessage(pm peer.Message) {\n\tpe := pm.Peer\n\tswitch msg := pm.Message.(type) {\n\tcase peerprotocol.HaveMessage:\n\t\t\/\/ Save have messages for processesing later received while we don't have info yet.\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"unexpected piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\t\/\/ pe.Logger().Debug(\"Peer \", pe.String(), \" has piece #\", pi.Index)\n\t\tt.piecePicker.HandleHave(pe, pi.Index)\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.BitfieldMessage:\n\t\t\/\/ Save bitfield messages while we don't have info yet.\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tnumBytes := uint32(bitfield.NumBytes(t.info.NumPieces))\n\t\tif uint32(len(msg.Data)) != numBytes {\n\t\t\tpe.Logger().Errorln(\"invalid bitfield length:\", len(msg.Data))\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tbf := bitfield.NewBytes(msg.Data, t.info.NumPieces)\n\t\tpe.Logger().Debugln(\"Received bitfield:\", bf.Hex())\n\t\tfor i := uint32(0); i < bf.Len(); i++ {\n\t\t\tif bf.Test(i) {\n\t\t\t\tt.piecePicker.HandleHave(pe, i)\n\t\t\t}\n\t\t}\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.HaveAllMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tfor _, pi := range t.pieces {\n\t\t\tt.piecePicker.HandleHave(pe, pi.Index)\n\t\t}\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.HaveNoneMessage: \/\/ TODO handle?\n\tcase peerprotocol.AllowedFastMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid allowed fast piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\tpe.Logger().Debug(\"Peer \", pe.String(), \" has allowed fast for piece #\", pi.Index)\n\t\tt.piecePicker.HandleAllowedFast(pe, msg.Index)\n\tcase peerprotocol.UnchokeMessage:\n\t\tpe.PeerChoking = false\n\t\tif pd, ok := t.pieceDownloaders[pe]; ok {\n\t\t\tpd.RequestBlocks(t.config.RequestQueueLength)\n\t\t}\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.ChokeMessage:\n\t\tpe.PeerChoking = true\n\t\tif pd, ok := t.pieceDownloaders[pe]; ok {\n\t\t\tpd.Choked()\n\t\t\tt.pieceDownloadersChoked[pe] = pd\n\t\t\tt.startPieceDownloaders()\n\t\t}\n\tcase peerprotocol.InterestedMessage:\n\t\t\/\/ TODO handle intereseted messages\n\tcase peerprotocol.NotInterestedMessage:\n\t\t\/\/ TODO handle not intereseted messages\n\tcase peerreader.Piece:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"piece received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= uint32(len(t.pieces)) {\n\t\t\tpe.Logger().Errorln(\"invalid piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpiece := &t.pieces[msg.Index]\n\t\tblock := piece.Blocks.Find(msg.Begin, uint32(len(msg.Data)))\n\t\tif block == nil {\n\t\t\tpe.Logger().Errorln(\"invalid piece begin:\", msg.Begin, \"length:\", len(msg.Data))\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpe.BytesDownlaodedInChokePeriod += int64(len(msg.Data))\n\t\tt.bytesDownloaded += int64(len(msg.Data))\n\t\tpd, ok := t.pieceDownloaders[pe]\n\t\tif !ok {\n\t\t\tt.bytesWasted += int64(len(msg.Data))\n\t\t\tbreak\n\t\t}\n\t\tif pd.Piece.Index != msg.Index {\n\t\t\tt.bytesWasted += int64(len(msg.Data))\n\t\t\tbreak\n\t\t}\n\t\tpd.GotBlock(block, msg.Data)\n\t\tif !pd.Done() {\n\t\t\tpd.RequestBlocks(t.config.RequestQueueLength)\n\t\t\tpe.StartSnubTimer(t.config.RequestTimeout, t.peerSnubbedC)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ t.log.Debugln(\"piece download completed. index:\", pd.Piece.Index)\n\t\tt.closePieceDownloader(pd)\n\t\tpe.StopSnubTimer()\n\n\t\tok = piece.VerifyHash(pd.Bytes, sha1.New()) \/\/ nolint: gosec\n\t\tif !ok {\n\t\t\t\/\/ TODO handle corrupt piece\n\t\t\tt.log.Error(\"received corrupt piece\")\n\t\t\tt.closePeer(pd.Peer)\n\t\t\tt.startPieceDownloaders()\n\t\t\tbreak\n\t\t}\n\n\t\tfor pe := range t.piecePicker.RequestedPeers(piece.Index) {\n\t\t\tpd2 := t.pieceDownloaders[pe]\n\t\t\tt.closePieceDownloader(pd2)\n\t\t\tpd2.CancelPending()\n\t\t}\n\n\t\tt.piecePicker.HandleWriting(piece.Index)\n\t\tpw := piecewriter.New(piece)\n\t\tt.pieceWriters[pw] = struct{}{}\n\t\tgo pw.Run(pd.Bytes, t.pieceWriterResultC)\n\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.RequestMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"request received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid request index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Begin+msg.Length > t.pieces[msg.Index].Length {\n\t\t\tpe.Logger().Errorln(\"invalid request length:\", msg.Length)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\tif pe.AmChoking {\n\t\t\tif pe.FastExtension {\n\t\t\t\tm := peerprotocol.RejectMessage{RequestMessage: msg}\n\t\t\t\tpe.SendMessage(m)\n\t\t\t}\n\t\t} else {\n\t\t\tpe.SendPiece(msg, pi.Data)\n\t\t}\n\tcase peerprotocol.RejectMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"reject received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid reject index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpiece := &t.pieces[msg.Index]\n\t\tblock := piece.Blocks.Find(msg.Begin, msg.Length)\n\t\tif block == nil {\n\t\t\tpe.Logger().Errorln(\"invalid reject begin:\", msg.Begin, \"length:\", msg.Length)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ TODO check piece index\n\t\t\/\/ TODO check piece index on cancel\n\t\tpd, ok := t.pieceDownloaders[pe]\n\t\tif !ok {\n\t\t\tpe.Logger().Error(\"reject received but we don't have active download\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpd.Rejected(block)\n\tcase peerprotocol.CancelMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"cancel received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid cancel index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpe.CancelRequest(msg)\n\tcase peerwriter.BlockUploaded:\n\t\tt.bytesUploaded += int64(msg.Length)\n\t\tpe.BytesUploadedInChokePeriod += int64(msg.Length)\n\t\/\/ TODO make extension messages value type\n\tcase *peerprotocol.ExtensionHandshakeMessage:\n\t\tpe.Logger().Debugln(\"extension handshake received:\", msg)\n\t\tif pe.ExtensionHandshake != nil {\n\t\t\tpe.Logger().Debugln(\"peer changed extensions\")\n\t\t\tbreak\n\t\t}\n\t\tpe.ExtensionHandshake = msg\n\n\t\tif _, ok := msg.M[peerprotocol.ExtensionKeyMetadata]; ok {\n\t\t\tt.startInfoDownloaders()\n\t\t}\n\t\tif _, ok := msg.M[peerprotocol.ExtensionKeyPEX]; ok {\n\t\t\tif t.info != nil && t.info.Private != 1 {\n\t\t\t\tpe.StartPEX(t.peers)\n\t\t\t}\n\t\t}\n\tcase *peerprotocol.ExtensionMetadataMessage:\n\t\tswitch msg.Type {\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeRequest:\n\t\t\textMsgID, ok := pe.ExtensionHandshake.M[peerprotocol.ExtensionKeyMetadata]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.info == nil {\n\t\t\t\t\/\/ Send reject\n\t\t\t\tdataMsg := peerprotocol.ExtensionMetadataMessage{\n\t\t\t\t\tType: peerprotocol.ExtensionMetadataMessageTypeReject,\n\t\t\t\t\tPiece: msg.Piece,\n\t\t\t\t}\n\t\t\t\textDataMsg := peerprotocol.ExtensionMessage{\n\t\t\t\t\tExtendedMessageID: extMsgID,\n\t\t\t\t\tPayload: &dataMsg,\n\t\t\t\t}\n\t\t\t\tpe.SendMessage(extDataMsg)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif msg.Piece >= uint32(len(t.pieces)) {\n\t\t\t\tpe.Logger().Errorln(\"peer requested invalid metadata piece:\", msg.Piece)\n\t\t\t\tt.closePeer(pe)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ TODO Clients MAY implement flood protection by rejecting request messages after a certain number of them have been served. Typically the number of pieces of metadata times a factor.\n\t\t\tstart := 16 * 1024 * msg.Piece\n\t\t\tend := 16 * 1024 * (msg.Piece + 1)\n\t\t\ttotalSize := uint32(len(t.info.Bytes))\n\t\t\tif end > totalSize {\n\t\t\t\tend = totalSize\n\t\t\t}\n\t\t\tdata := t.info.Bytes[start:end]\n\t\t\tdataMsg := peerprotocol.ExtensionMetadataMessage{\n\t\t\t\tType: peerprotocol.ExtensionMetadataMessageTypeData,\n\t\t\t\tPiece: msg.Piece,\n\t\t\t\tTotalSize: totalSize,\n\t\t\t\tData: data,\n\t\t\t}\n\t\t\textDataMsg := peerprotocol.ExtensionMessage{\n\t\t\t\tExtendedMessageID: extMsgID,\n\t\t\t\tPayload: &dataMsg,\n\t\t\t}\n\t\t\tpe.SendMessage(extDataMsg)\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeData:\n\t\t\tid, ok := t.infoDownloaders[pe]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr := id.GotBlock(msg.Piece, msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tpe.Logger().Error(err)\n\t\t\t\tt.closePeer(pe)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !id.Done() {\n\t\t\t\tid.RequestBlocks(t.config.RequestQueueLength)\n\t\t\t\tpe.StartSnubTimer(t.config.RequestTimeout, t.peerSnubbedC)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpe.StopSnubTimer()\n\n\t\t\thash := sha1.New() \/\/ nolint: gosec\n\t\t\thash.Write(id.Bytes) \/\/ nolint: gosec\n\t\t\tif !bytes.Equal(hash.Sum(nil), t.infoHash[:]) { \/\/ nolint: gosec\n\t\t\t\tpe.Logger().Errorln(\"received info does not match with hash\")\n\t\t\t\tt.closePeer(id.Peer)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.stopInfoDownloaders()\n\n\t\t\tt.info, err = metainfo.NewInfo(id.Bytes)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"cannot parse info bytes: %s\", err)\n\t\t\t\tt.log.Error(err)\n\t\t\t\tt.stop(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.info.Private == 1 {\n\t\t\t\terr = errors.New(\"private torrent from magnet\")\n\t\t\t\tt.log.Error(err)\n\t\t\t\tt.stop(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.resume != nil {\n\t\t\t\terr = t.resume.WriteInfo(t.info.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"cannot write resume info: %s\", err)\n\t\t\t\t\tt.log.Error(err)\n\t\t\t\t\tt.stop(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.startAllocator()\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeReject:\n\t\t\tid, ok := t.infoDownloaders[pe]\n\t\t\tif ok {\n\t\t\t\tt.closePeer(id.Peer)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t}\n\t\t}\n\tcase *peerprotocol.ExtensionPEXMessage:\n\t\taddrs, err := tracker.DecodePeersCompact([]byte(msg.Added))\n\t\tif err != nil {\n\t\t\tt.log.Error(err)\n\t\t\tbreak\n\t\t}\n\t\tt.handleNewPeers(addrs, \"pex\")\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unhandled peer message type: %T\", msg))\n\t}\n}\n\nfunc (t *Torrent) updateInterestedState(pe *peer.Peer) {\n\tif t.pieces == nil || t.bitfield == nil {\n\t\treturn\n\t}\n\tinterested := false\n\tfor i := uint32(0); i < t.bitfield.Len(); i++ {\n\t\tweHave := t.bitfield.Test(i)\n\t\tpeerHave := t.piecePicker.DoesHave(pe, i)\n\t\tif !weHave && peerHave {\n\t\t\tinterested = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !pe.AmInterested && interested {\n\t\tpe.AmInterested = true\n\t\tmsg := peerprotocol.InterestedMessage{}\n\t\tpe.SendMessage(msg)\n\t\treturn\n\t}\n\tif pe.AmInterested && !interested {\n\t\tpe.AmInterested = false\n\t\tmsg := peerprotocol.NotInterestedMessage{}\n\t\tpe.SendMessage(msg)\n\t\treturn\n\t}\n}\nremove todopackage torrent\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\" \/\/ nolint: gosec\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/bitfield\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peer\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerconn\/peerreader\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerconn\/peerwriter\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/peerprotocol\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/piecewriter\"\n\t\"github.com\/cenkalti\/rain\/torrent\/internal\/tracker\"\n\t\"github.com\/cenkalti\/rain\/torrent\/metainfo\"\n)\n\nfunc (t *Torrent) handlePeerMessage(pm peer.Message) {\n\tpe := pm.Peer\n\tswitch msg := pm.Message.(type) {\n\tcase peerprotocol.HaveMessage:\n\t\t\/\/ Save have messages for processesing later received while we don't have info yet.\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"unexpected piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\t\/\/ pe.Logger().Debug(\"Peer \", pe.String(), \" has piece #\", pi.Index)\n\t\tt.piecePicker.HandleHave(pe, pi.Index)\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.BitfieldMessage:\n\t\t\/\/ Save bitfield messages while we don't have info yet.\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tnumBytes := uint32(bitfield.NumBytes(t.info.NumPieces))\n\t\tif uint32(len(msg.Data)) != numBytes {\n\t\t\tpe.Logger().Errorln(\"invalid bitfield length:\", len(msg.Data))\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tbf := bitfield.NewBytes(msg.Data, t.info.NumPieces)\n\t\tpe.Logger().Debugln(\"Received bitfield:\", bf.Hex())\n\t\tfor i := uint32(0); i < bf.Len(); i++ {\n\t\t\tif bf.Test(i) {\n\t\t\t\tt.piecePicker.HandleHave(pe, i)\n\t\t\t}\n\t\t}\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.HaveAllMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tfor _, pi := range t.pieces {\n\t\t\tt.piecePicker.HandleHave(pe, pi.Index)\n\t\t}\n\t\tt.updateInterestedState(pe)\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.HaveNoneMessage:\n\tcase peerprotocol.AllowedFastMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Messages = append(pe.Messages, msg)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid allowed fast piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\tpe.Logger().Debug(\"Peer \", pe.String(), \" has allowed fast for piece #\", pi.Index)\n\t\tt.piecePicker.HandleAllowedFast(pe, msg.Index)\n\tcase peerprotocol.UnchokeMessage:\n\t\tpe.PeerChoking = false\n\t\tif pd, ok := t.pieceDownloaders[pe]; ok {\n\t\t\tpd.RequestBlocks(t.config.RequestQueueLength)\n\t\t}\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.ChokeMessage:\n\t\tpe.PeerChoking = true\n\t\tif pd, ok := t.pieceDownloaders[pe]; ok {\n\t\t\tpd.Choked()\n\t\t\tt.pieceDownloadersChoked[pe] = pd\n\t\t\tt.startPieceDownloaders()\n\t\t}\n\tcase peerprotocol.InterestedMessage:\n\t\t\/\/ TODO handle intereseted messages\n\tcase peerprotocol.NotInterestedMessage:\n\t\t\/\/ TODO handle not intereseted messages\n\tcase peerreader.Piece:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"piece received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= uint32(len(t.pieces)) {\n\t\t\tpe.Logger().Errorln(\"invalid piece index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpiece := &t.pieces[msg.Index]\n\t\tblock := piece.Blocks.Find(msg.Begin, uint32(len(msg.Data)))\n\t\tif block == nil {\n\t\t\tpe.Logger().Errorln(\"invalid piece begin:\", msg.Begin, \"length:\", len(msg.Data))\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpe.BytesDownlaodedInChokePeriod += int64(len(msg.Data))\n\t\tt.bytesDownloaded += int64(len(msg.Data))\n\t\tpd, ok := t.pieceDownloaders[pe]\n\t\tif !ok {\n\t\t\tt.bytesWasted += int64(len(msg.Data))\n\t\t\tbreak\n\t\t}\n\t\tif pd.Piece.Index != msg.Index {\n\t\t\tt.bytesWasted += int64(len(msg.Data))\n\t\t\tbreak\n\t\t}\n\t\tpd.GotBlock(block, msg.Data)\n\t\tif !pd.Done() {\n\t\t\tpd.RequestBlocks(t.config.RequestQueueLength)\n\t\t\tpe.StartSnubTimer(t.config.RequestTimeout, t.peerSnubbedC)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ t.log.Debugln(\"piece download completed. index:\", pd.Piece.Index)\n\t\tt.closePieceDownloader(pd)\n\t\tpe.StopSnubTimer()\n\n\t\tok = piece.VerifyHash(pd.Bytes, sha1.New()) \/\/ nolint: gosec\n\t\tif !ok {\n\t\t\t\/\/ TODO handle corrupt piece\n\t\t\tt.log.Error(\"received corrupt piece\")\n\t\t\tt.closePeer(pd.Peer)\n\t\t\tt.startPieceDownloaders()\n\t\t\tbreak\n\t\t}\n\n\t\tfor pe := range t.piecePicker.RequestedPeers(piece.Index) {\n\t\t\tpd2 := t.pieceDownloaders[pe]\n\t\t\tt.closePieceDownloader(pd2)\n\t\t\tpd2.CancelPending()\n\t\t}\n\n\t\tt.piecePicker.HandleWriting(piece.Index)\n\t\tpw := piecewriter.New(piece)\n\t\tt.pieceWriters[pw] = struct{}{}\n\t\tgo pw.Run(pd.Bytes, t.pieceWriterResultC)\n\n\t\tt.startPieceDownloaders()\n\tcase peerprotocol.RequestMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"request received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid request index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tif msg.Begin+msg.Length > t.pieces[msg.Index].Length {\n\t\t\tpe.Logger().Errorln(\"invalid request length:\", msg.Length)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpi := &t.pieces[msg.Index]\n\t\tif pe.AmChoking {\n\t\t\tif pe.FastExtension {\n\t\t\t\tm := peerprotocol.RejectMessage{RequestMessage: msg}\n\t\t\t\tpe.SendMessage(m)\n\t\t\t}\n\t\t} else {\n\t\t\tpe.SendPiece(msg, pi.Data)\n\t\t}\n\tcase peerprotocol.RejectMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"reject received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid reject index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpiece := &t.pieces[msg.Index]\n\t\tblock := piece.Blocks.Find(msg.Begin, msg.Length)\n\t\tif block == nil {\n\t\t\tpe.Logger().Errorln(\"invalid reject begin:\", msg.Begin, \"length:\", msg.Length)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ TODO check piece index\n\t\t\/\/ TODO check piece index on cancel\n\t\tpd, ok := t.pieceDownloaders[pe]\n\t\tif !ok {\n\t\t\tpe.Logger().Error(\"reject received but we don't have active download\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpd.Rejected(block)\n\tcase peerprotocol.CancelMessage:\n\t\tif t.pieces == nil || t.bitfield == nil {\n\t\t\tpe.Logger().Error(\"cancel received but we don't have info\")\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\n\t\tif msg.Index >= t.info.NumPieces {\n\t\t\tpe.Logger().Errorln(\"invalid cancel index:\", msg.Index)\n\t\t\tt.closePeer(pe)\n\t\t\tbreak\n\t\t}\n\t\tpe.CancelRequest(msg)\n\tcase peerwriter.BlockUploaded:\n\t\tt.bytesUploaded += int64(msg.Length)\n\t\tpe.BytesUploadedInChokePeriod += int64(msg.Length)\n\t\/\/ TODO make extension messages value type\n\tcase *peerprotocol.ExtensionHandshakeMessage:\n\t\tpe.Logger().Debugln(\"extension handshake received:\", msg)\n\t\tif pe.ExtensionHandshake != nil {\n\t\t\tpe.Logger().Debugln(\"peer changed extensions\")\n\t\t\tbreak\n\t\t}\n\t\tpe.ExtensionHandshake = msg\n\n\t\tif _, ok := msg.M[peerprotocol.ExtensionKeyMetadata]; ok {\n\t\t\tt.startInfoDownloaders()\n\t\t}\n\t\tif _, ok := msg.M[peerprotocol.ExtensionKeyPEX]; ok {\n\t\t\tif t.info != nil && t.info.Private != 1 {\n\t\t\t\tpe.StartPEX(t.peers)\n\t\t\t}\n\t\t}\n\tcase *peerprotocol.ExtensionMetadataMessage:\n\t\tswitch msg.Type {\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeRequest:\n\t\t\textMsgID, ok := pe.ExtensionHandshake.M[peerprotocol.ExtensionKeyMetadata]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.info == nil {\n\t\t\t\t\/\/ Send reject\n\t\t\t\tdataMsg := peerprotocol.ExtensionMetadataMessage{\n\t\t\t\t\tType: peerprotocol.ExtensionMetadataMessageTypeReject,\n\t\t\t\t\tPiece: msg.Piece,\n\t\t\t\t}\n\t\t\t\textDataMsg := peerprotocol.ExtensionMessage{\n\t\t\t\t\tExtendedMessageID: extMsgID,\n\t\t\t\t\tPayload: &dataMsg,\n\t\t\t\t}\n\t\t\t\tpe.SendMessage(extDataMsg)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif msg.Piece >= uint32(len(t.pieces)) {\n\t\t\t\tpe.Logger().Errorln(\"peer requested invalid metadata piece:\", msg.Piece)\n\t\t\t\tt.closePeer(pe)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ TODO Clients MAY implement flood protection by rejecting request messages after a certain number of them have been served. Typically the number of pieces of metadata times a factor.\n\t\t\tstart := 16 * 1024 * msg.Piece\n\t\t\tend := 16 * 1024 * (msg.Piece + 1)\n\t\t\ttotalSize := uint32(len(t.info.Bytes))\n\t\t\tif end > totalSize {\n\t\t\t\tend = totalSize\n\t\t\t}\n\t\t\tdata := t.info.Bytes[start:end]\n\t\t\tdataMsg := peerprotocol.ExtensionMetadataMessage{\n\t\t\t\tType: peerprotocol.ExtensionMetadataMessageTypeData,\n\t\t\t\tPiece: msg.Piece,\n\t\t\t\tTotalSize: totalSize,\n\t\t\t\tData: data,\n\t\t\t}\n\t\t\textDataMsg := peerprotocol.ExtensionMessage{\n\t\t\t\tExtendedMessageID: extMsgID,\n\t\t\t\tPayload: &dataMsg,\n\t\t\t}\n\t\t\tpe.SendMessage(extDataMsg)\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeData:\n\t\t\tid, ok := t.infoDownloaders[pe]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr := id.GotBlock(msg.Piece, msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tpe.Logger().Error(err)\n\t\t\t\tt.closePeer(pe)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !id.Done() {\n\t\t\t\tid.RequestBlocks(t.config.RequestQueueLength)\n\t\t\t\tpe.StartSnubTimer(t.config.RequestTimeout, t.peerSnubbedC)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpe.StopSnubTimer()\n\n\t\t\thash := sha1.New() \/\/ nolint: gosec\n\t\t\thash.Write(id.Bytes) \/\/ nolint: gosec\n\t\t\tif !bytes.Equal(hash.Sum(nil), t.infoHash[:]) { \/\/ nolint: gosec\n\t\t\t\tpe.Logger().Errorln(\"received info does not match with hash\")\n\t\t\t\tt.closePeer(id.Peer)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.stopInfoDownloaders()\n\n\t\t\tt.info, err = metainfo.NewInfo(id.Bytes)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"cannot parse info bytes: %s\", err)\n\t\t\t\tt.log.Error(err)\n\t\t\t\tt.stop(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.info.Private == 1 {\n\t\t\t\terr = errors.New(\"private torrent from magnet\")\n\t\t\t\tt.log.Error(err)\n\t\t\t\tt.stop(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif t.resume != nil {\n\t\t\t\terr = t.resume.WriteInfo(t.info.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"cannot write resume info: %s\", err)\n\t\t\t\t\tt.log.Error(err)\n\t\t\t\t\tt.stop(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.startAllocator()\n\t\tcase peerprotocol.ExtensionMetadataMessageTypeReject:\n\t\t\tid, ok := t.infoDownloaders[pe]\n\t\t\tif ok {\n\t\t\t\tt.closePeer(id.Peer)\n\t\t\t\tt.startInfoDownloaders()\n\t\t\t}\n\t\t}\n\tcase *peerprotocol.ExtensionPEXMessage:\n\t\taddrs, err := tracker.DecodePeersCompact([]byte(msg.Added))\n\t\tif err != nil {\n\t\t\tt.log.Error(err)\n\t\t\tbreak\n\t\t}\n\t\tt.handleNewPeers(addrs, \"pex\")\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unhandled peer message type: %T\", msg))\n\t}\n}\n\nfunc (t *Torrent) updateInterestedState(pe *peer.Peer) {\n\tif t.pieces == nil || t.bitfield == nil {\n\t\treturn\n\t}\n\tinterested := false\n\tfor i := uint32(0); i < t.bitfield.Len(); i++ {\n\t\tweHave := t.bitfield.Test(i)\n\t\tpeerHave := t.piecePicker.DoesHave(pe, i)\n\t\tif !weHave && peerHave {\n\t\t\tinterested = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !pe.AmInterested && interested {\n\t\tpe.AmInterested = true\n\t\tmsg := peerprotocol.InterestedMessage{}\n\t\tpe.SendMessage(msg)\n\t\treturn\n\t}\n\tif pe.AmInterested && !interested {\n\t\tpe.AmInterested = false\n\t\tmsg := peerprotocol.NotInterestedMessage{}\n\t\tpe.SendMessage(msg)\n\t\treturn\n\t}\n}\n<|endoftext|>"} {"text":"package bitset\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n)\n\nconst (\n\tsw_64 uint64 = 64\n\tslg2_64 uint64 = 5\n\tm1_64 uint64 = 0x5555555555555555 \/\/ 0101...\n\tm2_64 uint64 = 0x3333333333333333 \/\/ 00110011..\n\tm4_64 uint64 = 0x0f0f0f0f0f0f0f0f \/\/ 00001111...\n\thff_64 uint64 = 0xffffffffffffffff \/\/ all ones\n)\n\nfunc wordsNeeded64(n uint64) uint64 {\n\tif n == 0 {\n\t\treturn 1\n\t} else if n > math.MaxUint64-sw_64 {\n\t\treturn math.MaxUint64 >> slg2_64\n\t}\n\treturn (n + (sw_64 - 1)) >> slg2_64\n}\n\ntype Bitset64 struct {\n\tn uint64\n\tb []uint64\n}\n\n\/\/ Returns the current size of the bitset.\nfunc (b *Bitset64) Len() uint64 {\n\treturn b.n\n}\n\n\/\/ Test whether bit i is set.\nfunc (b *Bitset64) Test(i uint64) bool {\n\tif i >= b.n {\n\t\treturn false\n\t}\n\treturn ((b.b[i>>slg2_64] & (1 << (i & (sw_64 - 1)))) != 0)\n}\n\n\/\/ Set bit i to 1.\nfunc (b *Bitset64) Set(i uint64) {\n\tif i >= b.n {\n\t\tnsize := wordsNeeded64(i + 1)\n\t\tl := uint64(len(b.b))\n\t\tif nsize > l {\n\t\t\tnb := make([]uint64, nsize-l)\n\t\t\tb.b = append(b.b, nb...)\n\t\t}\n\t\tb.n = i + 1\n\t}\n\tb.b[i>>slg2_64] |= (1 << (i & (sw_64 - 1)))\n}\n\n\/\/ Set bit i to 0.\nfunc (b *Bitset64) Clear(i uint64) {\n\tif i >= b.n {\n\t\treturn\n\t}\n\tb.b[i>>slg2_64] &^= 1 << (i & (sw_64 - 1))\n}\n\n\/\/ Flip bit i.\nfunc (b *Bitset64) Flip(i uint64) {\n\tif i >= b.n {\n\t\tb.Set(i)\n\t}\n\tb.b[i>>slg2_64] ^= 1 << (i & (sw_64 - 1))\n}\n\n\/\/ Clear all bits in the bitset.\nfunc (b *Bitset64) Reset() {\n\tfor i := range b.b {\n\t\tb.b[i] = 0\n\t}\n}\n\n\/\/ Get the number of words used in the bitset.\nfunc (b *Bitset64) wordCount() uint64 {\n\treturn wordsNeeded64(b.n)\n}\n\n\/\/ Clone the bitset.\nfunc (b *Bitset64) Clone() *Bitset64 {\n\tc := New64(b.n)\n\tcopy(c.b, b.b)\n\treturn c\n}\n\n\/\/ Copy the bitset into another bitset, returning the size of the destination\n\/\/ bitset.\nfunc (b *Bitset64) Copy(c *Bitset64) (n uint64) {\n\tcopy(c.b, b.b)\n\tn = c.n\n\tif b.n < c.n {\n\t\tn = b.n\n\t}\n\treturn\n}\n\nfunc popCountUint64(x uint64) uint64 {\n\tx -= (x >> 1) & m1_64 \/\/ put count of each 2 bits into those 2 bits\n\tx = (x & m2_64) + ((x >> 2) & m2_64) \/\/ put count of each 4 bits into those 4 bits \n\tx = (x + (x >> 4)) & m4_64 \/\/ put count of each 8 bits into those 8 bits \n\tx += x >> 8 \/\/ put count of each 16 bits into their lowest 8 bits\n\tx += x >> 16 \/\/ put count of each 32 bits into their lowest 8 bits\n\tx += x >> 32 \/\/ put count of each 64 bits into their lowest 8 bits\n\treturn x & 0x7f\n}\n\n\/\/ Get the number of set bits in the bitset.\nfunc (b *Bitset64) Count() uint64 {\n\tsum := uint64(0)\n\tfor _, w := range b.b {\n\t\tsum += popCountUint64(w)\n\t}\n\treturn sum\n}\n\n\/\/ Test if two bitsets are equal. Returns true if both bitsets are the same\n\/\/ size and all the same bits are set in both bitsets.\nfunc (b *Bitset64) Equal(c *Bitset64) bool {\n\tif b.n != c.n {\n\t\treturn false\n\t}\n\tfor p, v := range b.b {\n\t\tif c.b[p] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Bitset &^ (and or); difference between receiver and another set.\nfunc (b *Bitset64) Difference(ob *Bitset64) (result *Bitset64) {\n\tresult = b.Clone() \/\/ clone b (in case b is bigger than ob)\n\tszl := ob.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] &^ ob.b[i]\n\t}\n\treturn\n}\n\nfunc sortByLength64(a *Bitset64, b *Bitset64) (ap *Bitset64, bp *Bitset64) {\n\tif a.n <= b.n {\n\t\tap, bp = a, b\n\t} else {\n\t\tap, bp = b, a\n\t}\n\treturn\n}\n\n\/\/ Bitset & (and); intersection of receiver and another set.\nfunc (b *Bitset64) Intersection(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\tresult = New64(b.n)\n\tfor i, w := range b.b {\n\t\tresult.b[i] = w & ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Bitset | (or); union of receiver and another set.\nfunc (b *Bitset64) Union(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\tresult = ob.Clone()\n\tszl := ob.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] | ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Bitset ^ (xor); symmetric difference of receiver and another set.\nfunc (b *Bitset64) SymmetricDifference(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\t\/\/ ob is bigger, so clone it\n\tresult = ob.Clone()\n\tszl := b.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] ^ ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Return true if the bitset's length is a multiple of the word size.\nfunc (b *Bitset64) isEven() bool {\n\treturn (b.n % sw_64) == 0\n}\n\n\/\/ Clean last word by setting unused bits to 0.\nfunc (b *Bitset64) cleanLastWord() {\n\tif !b.isEven() {\n\t\tb.b[wordsNeeded64(b.n)-1] &= (hff_64 >> (sw_64 - (b.n % sw_64)))\n\t}\n}\n\n\/\/ Return the (local) complement of a bitset (up to n bits).\n\/\/ func (b *Bitset64) Complement() (result *Bitset64) {\n\/\/ \tresult = New64(b.n)\n\/\/ \tfor i, w := range b.b {\n\/\/ \t\tresult.b[i] = ^(w)\n\/\/ \t}\n\/\/ \tresult.cleanLastWord()\n\/\/ \treturn\n\/\/ }\n\n\/\/ Returns true if all bits in the bitset are set.\nfunc (b *Bitset64) All() bool {\n\treturn b.Count() == b.n\n}\n\n\/\/ Returns true if no bit in the bitset is set.\nfunc (b *Bitset64) None() bool {\n\tfor _, w := range b.b {\n\t\tif w > 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Return true if any bit in the bitset is set.\nfunc (b *Bitset64) Any() bool {\n\treturn !b.None()\n}\n\n\/\/ Get a string representation of the words in the bitset.\nfunc (b *Bitset64) String() string {\n\tf := bytes.NewBufferString(\"\")\n\tfor i := int(wordsNeeded64(b.n) - 1); i >= 0; i-- {\n\t\tfmt.Fprintf(f, \"%064b.\", b.b[i])\n\t}\n\treturn f.String()\n}\n\n\/\/ Make a new bitset with a starting capacity of n bits. The bitset expands\n\/\/ automatically.\nfunc New64(n uint64) *Bitset64 {\n\tnWords := wordsNeeded64(n)\n\tif nWords > math.MaxInt32-1 {\n\t\tpanic(fmt.Sprintf(\"Bitset64 needs %d %d-bit words to store %d bits, but slices cannot hold more than %d items.\", nWords, sw_64, n, math.MaxInt32-1))\n\t}\n\tb := &Bitset64{\n\t\tn,\n\t\tmake([]uint64, nWords),\n\t}\n\treturn b\n}\nlog2(64) is 6package bitset\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n)\n\nconst (\n\tsw_64 uint64 = 64\n\tslg2_64 uint64 = 6\n\tm1_64 uint64 = 0x5555555555555555 \/\/ 0101...\n\tm2_64 uint64 = 0x3333333333333333 \/\/ 00110011..\n\tm4_64 uint64 = 0x0f0f0f0f0f0f0f0f \/\/ 00001111...\n\thff_64 uint64 = 0xffffffffffffffff \/\/ all ones\n)\n\nfunc wordsNeeded64(n uint64) uint64 {\n\tif n == 0 {\n\t\treturn 1\n\t} else if n > math.MaxUint64-sw_64 {\n\t\treturn math.MaxUint64 >> slg2_64\n\t}\n\treturn (n + (sw_64 - 1)) >> slg2_64\n}\n\ntype Bitset64 struct {\n\tn uint64\n\tb []uint64\n}\n\n\/\/ Returns the current size of the bitset.\nfunc (b *Bitset64) Len() uint64 {\n\treturn b.n\n}\n\n\/\/ Test whether bit i is set.\nfunc (b *Bitset64) Test(i uint64) bool {\n\tif i >= b.n {\n\t\treturn false\n\t}\n\treturn ((b.b[i>>slg2_64] & (1 << (i & (sw_64 - 1)))) != 0)\n}\n\n\/\/ Set bit i to 1.\nfunc (b *Bitset64) Set(i uint64) {\n\tif i >= b.n {\n\t\tnsize := wordsNeeded64(i + 1)\n\t\tl := uint64(len(b.b))\n\t\tif nsize > l {\n\t\t\tnb := make([]uint64, nsize-l)\n\t\t\tb.b = append(b.b, nb...)\n\t\t}\n\t\tb.n = i + 1\n\t}\n\tb.b[i>>slg2_64] |= (1 << (i & (sw_64 - 1)))\n}\n\n\/\/ Set bit i to 0.\nfunc (b *Bitset64) Clear(i uint64) {\n\tif i >= b.n {\n\t\treturn\n\t}\n\tb.b[i>>slg2_64] &^= 1 << (i & (sw_64 - 1))\n}\n\n\/\/ Flip bit i.\nfunc (b *Bitset64) Flip(i uint64) {\n\tif i >= b.n {\n\t\tb.Set(i)\n\t}\n\tb.b[i>>slg2_64] ^= 1 << (i & (sw_64 - 1))\n}\n\n\/\/ Clear all bits in the bitset.\nfunc (b *Bitset64) Reset() {\n\tfor i := range b.b {\n\t\tb.b[i] = 0\n\t}\n}\n\n\/\/ Get the number of words used in the bitset.\nfunc (b *Bitset64) wordCount() uint64 {\n\treturn wordsNeeded64(b.n)\n}\n\n\/\/ Clone the bitset.\nfunc (b *Bitset64) Clone() *Bitset64 {\n\tc := New64(b.n)\n\tcopy(c.b, b.b)\n\treturn c\n}\n\n\/\/ Copy the bitset into another bitset, returning the size of the destination\n\/\/ bitset.\nfunc (b *Bitset64) Copy(c *Bitset64) (n uint64) {\n\tcopy(c.b, b.b)\n\tn = c.n\n\tif b.n < c.n {\n\t\tn = b.n\n\t}\n\treturn\n}\n\nfunc popCountUint64(x uint64) uint64 {\n\tx -= (x >> 1) & m1_64 \/\/ put count of each 2 bits into those 2 bits\n\tx = (x & m2_64) + ((x >> 2) & m2_64) \/\/ put count of each 4 bits into those 4 bits \n\tx = (x + (x >> 4)) & m4_64 \/\/ put count of each 8 bits into those 8 bits \n\tx += x >> 8 \/\/ put count of each 16 bits into their lowest 8 bits\n\tx += x >> 16 \/\/ put count of each 32 bits into their lowest 8 bits\n\tx += x >> 32 \/\/ put count of each 64 bits into their lowest 8 bits\n\treturn x & 0x7f\n}\n\n\/\/ Get the number of set bits in the bitset.\nfunc (b *Bitset64) Count() uint64 {\n\tsum := uint64(0)\n\tfor _, w := range b.b {\n\t\tsum += popCountUint64(w)\n\t}\n\treturn sum\n}\n\n\/\/ Test if two bitsets are equal. Returns true if both bitsets are the same\n\/\/ size and all the same bits are set in both bitsets.\nfunc (b *Bitset64) Equal(c *Bitset64) bool {\n\tif b.n != c.n {\n\t\treturn false\n\t}\n\tfor p, v := range b.b {\n\t\tif c.b[p] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Bitset &^ (and or); difference between receiver and another set.\nfunc (b *Bitset64) Difference(ob *Bitset64) (result *Bitset64) {\n\tresult = b.Clone() \/\/ clone b (in case b is bigger than ob)\n\tszl := ob.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] &^ ob.b[i]\n\t}\n\treturn\n}\n\nfunc sortByLength64(a *Bitset64, b *Bitset64) (ap *Bitset64, bp *Bitset64) {\n\tif a.n <= b.n {\n\t\tap, bp = a, b\n\t} else {\n\t\tap, bp = b, a\n\t}\n\treturn\n}\n\n\/\/ Bitset & (and); intersection of receiver and another set.\nfunc (b *Bitset64) Intersection(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\tresult = New64(b.n)\n\tfor i, w := range b.b {\n\t\tresult.b[i] = w & ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Bitset | (or); union of receiver and another set.\nfunc (b *Bitset64) Union(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\tresult = ob.Clone()\n\tszl := ob.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] | ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Bitset ^ (xor); symmetric difference of receiver and another set.\nfunc (b *Bitset64) SymmetricDifference(ob *Bitset64) (result *Bitset64) {\n\tb, ob = sortByLength64(b, ob)\n\t\/\/ ob is bigger, so clone it\n\tresult = ob.Clone()\n\tszl := b.wordCount()\n\tl := uint64(len(b.b))\n\tfor i := uint64(0); i < l; i++ {\n\t\tif i >= szl {\n\t\t\tbreak\n\t\t}\n\t\tresult.b[i] = b.b[i] ^ ob.b[i]\n\t}\n\treturn\n}\n\n\/\/ Return true if the bitset's length is a multiple of the word size.\nfunc (b *Bitset64) isEven() bool {\n\treturn (b.n % sw_64) == 0\n}\n\n\/\/ Clean last word by setting unused bits to 0.\nfunc (b *Bitset64) cleanLastWord() {\n\tif !b.isEven() {\n\t\tb.b[wordsNeeded64(b.n)-1] &= (hff_64 >> (sw_64 - (b.n % sw_64)))\n\t}\n}\n\n\/\/ Return the (local) complement of a bitset (up to n bits).\n\/\/ func (b *Bitset64) Complement() (result *Bitset64) {\n\/\/ \tresult = New64(b.n)\n\/\/ \tfor i, w := range b.b {\n\/\/ \t\tresult.b[i] = ^(w)\n\/\/ \t}\n\/\/ \tresult.cleanLastWord()\n\/\/ \treturn\n\/\/ }\n\n\/\/ Returns true if all bits in the bitset are set.\nfunc (b *Bitset64) All() bool {\n\treturn b.Count() == b.n\n}\n\n\/\/ Returns true if no bit in the bitset is set.\nfunc (b *Bitset64) None() bool {\n\tfor _, w := range b.b {\n\t\tif w > 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Return true if any bit in the bitset is set.\nfunc (b *Bitset64) Any() bool {\n\treturn !b.None()\n}\n\n\/\/ Get a string representation of the words in the bitset.\nfunc (b *Bitset64) String() string {\n\tf := bytes.NewBufferString(\"\")\n\tfor i := int(wordsNeeded64(b.n) - 1); i >= 0; i-- {\n\t\tfmt.Fprintf(f, \"%064b.\", b.b[i])\n\t}\n\treturn f.String()\n}\n\n\/\/ Make a new bitset with a starting capacity of n bits. The bitset expands\n\/\/ automatically.\nfunc New64(n uint64) *Bitset64 {\n\tnWords := wordsNeeded64(n)\n\tif nWords > math.MaxInt32-1 {\n\t\tpanic(fmt.Sprintf(\"Bitset64 needs %d %d-bit words to store %d bits, but slices cannot hold more than %d items.\", nWords, sw_64, n, math.MaxInt32-1))\n\t}\n\tb := &Bitset64{\n\t\tn,\n\t\tmake([]uint64, nWords),\n\t}\n\treturn b\n}\n<|endoftext|>"} {"text":"package engine\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/coreos\/coreinit\/job\"\n\t\"github.com\/coreos\/coreinit\/machine\"\n\t\"github.com\/coreos\/coreinit\/registry\"\n)\n\nconst (\n\tDefaultJobWatchClaimTTL = \"10s\"\n\tDefaultRefreshInterval = \"60s\"\n)\n\ntype JobWatcher struct {\n\tregistry *registry.Registry\n\tscheduler *Scheduler\n\tmachine *machine.Machine\n\tclaimTTL time.Duration\n\trefreshInterval time.Duration\n\twatches map[string]job.JobWatch\n\tmachines map[string]machine.Machine\n}\n\nfunc NewJobWatcher(reg *registry.Registry, scheduler *Scheduler, m *machine.Machine) *JobWatcher {\n\tclaimTTL, _ := time.ParseDuration(DefaultJobWatchClaimTTL)\n\trefreshInterval, _ := time.ParseDuration(DefaultRefreshInterval)\n\treturn &JobWatcher{reg, scheduler, m, claimTTL, refreshInterval, make(map[string]job.JobWatch, 0), make(map[string]machine.Machine, 0)}\n}\n\nfunc (self *JobWatcher) StartHeartbeatThread() {\n\theartbeat := func() {\n\t\tfor _, watch := range self.watches {\n\t\t\tself.registry.ClaimJobWatch(&watch, self.machine, self.claimTTL)\n\t\t}\n\t}\n\n\tloop := func() {\n\t\tfor true {\n\t\t\theartbeat()\n\t\t\ttime.Sleep(self.claimTTL \/ 2)\n\t\t}\n\t}\n\n\tgo loop()\n}\n\nfunc (self *JobWatcher) StartRefreshThread() {\n\trefresh := func() {\n\t\tmachines := make(map[string]machine.Machine, 0)\n\t\tfor _, m := range self.registry.GetActiveMachines() {\n\t\t\tmachines[m.BootId] = m\n\t\t}\n\t\tself.machines = machines\n\t}\n\n\tloop := func() {\n\t\tfor true {\n\t\t\trefresh()\n\t\t\ttime.Sleep(self.refreshInterval)\n\t\t}\n\t}\n\n\tgo loop()\n}\n\nfunc (self *JobWatcher) AddJobWatch(watch *job.JobWatch) bool {\n\tif !self.registry.ClaimJobWatch(watch, self.machine, self.claimTTL) {\n\t\treturn false\n\t}\n\n\tself.watches[watch.Payload.Name] = *watch\n\tsched := NewSchedule()\n\n\tif watch.Count == -1 {\n\t\tfor _, m := range self.machines {\n\t\t\tname := fmt.Sprintf(\"%s.%s\", m.BootId, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"EventJobWatchCreated(%s): adding to schedule job=%s machine=%s\", watch.Payload.Name, name, m.BootId)\n\t\t\tsched.Add(*j, m)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < watch.Count; i++ {\n\t\t\tm := pickRandomMachine(self.machines)\n\t\t\tname := fmt.Sprintf(\"%s.%s\", m.BootId, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"EventJobWatchCreated(%s): adding to schedule job=%s machine=%s\", watch.Payload.Name, name, m.BootId)\n\t\t\tsched.Add(*j, *m)\n\t\t}\n\t}\n\n\tif len(sched) > 0 {\n\t\tlog.Printf(\"EventJobWatchCreated(%s): submitting schedule\", watch.Payload.Name)\n\t\tself.submitSchedule(sched)\n\t} else {\n\t\tlog.Printf(\"EventJobWatchCreated(%s): no schedule changes made\", watch.Payload.Name)\n\t}\n\n\treturn true\n}\n\nfunc (self *JobWatcher) RemoveJobWatch(watch *job.JobWatch) bool {\n\tif _, ok := self.watches[watch.Payload.Name]; !ok {\n\t\treturn false\n\t}\n\n\tdelete(self.watches, watch.Payload.Name)\n\treturn true\n}\n\nfunc (self *JobWatcher) submitSchedule(schedule Schedule) {\n\tfor j, m := range schedule {\n\t\tself.registry.ScheduleMachineJob(&j, m)\n\t}\n}\n\nfunc (self *JobWatcher) TrackMachine(m *machine.Machine) {\n\tself.machines[m.BootId] = *m\n\n\tsched := NewSchedule()\n\tfor _, watch := range self.watches {\n\t\tif watch.Count == -1 {\n\t\t\tname := fmt.Sprintf(\"%s.%s\", m.BootId, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"Adding to schedule job=%s machine=%s\", name, m.BootId)\n\t\t\tsched.Add(*j, *m)\n\t\t}\n\t}\n\n\tif len(sched) > 0 {\n\t\tlog.Printf(\"Submitting schedule\")\n\t\tself.submitSchedule(sched)\n\t} else {\n\t\tlog.Printf(\"No schedule changes made\")\n\t}\n}\n\nfunc (self *JobWatcher) DropMachine(m *machine.Machine) {\n\tif _, ok := self.machines[m.BootId]; ok {\n\t\tdelete(self.machines, m.BootId)\n\t}\n}\nrefactor(JobWatcher): track schedules for ease of Job deletionpackage engine\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/coreos\/coreinit\/job\"\n\t\"github.com\/coreos\/coreinit\/machine\"\n\t\"github.com\/coreos\/coreinit\/registry\"\n)\n\nconst (\n\tDefaultJobWatchClaimTTL = \"10s\"\n\tDefaultRefreshInterval = \"60s\"\n)\n\ntype JobWatcher struct {\n\tregistry *registry.Registry\n\tscheduler *Scheduler\n\tmachine *machine.Machine\n\tclaimTTL time.Duration\n\trefreshInterval time.Duration\n\twatches map[string]job.JobWatch\n\tschedules map[string]Schedule\n\tmachines map[string]machine.Machine\n}\n\nfunc NewJobWatcher(reg *registry.Registry, scheduler *Scheduler, m *machine.Machine) *JobWatcher {\n\tclaimTTL, _ := time.ParseDuration(DefaultJobWatchClaimTTL)\n\trefreshInterval, _ := time.ParseDuration(DefaultRefreshInterval)\n\treturn &JobWatcher{reg, scheduler, m, claimTTL, refreshInterval, make(map[string]job.JobWatch, 0),make(map[string]Schedule, 0), make(map[string]machine.Machine, 0)}\n}\n\nfunc (self *JobWatcher) StartHeartbeatThread() {\n\theartbeat := func() {\n\t\tfor _, watch := range self.watches {\n\t\t\tself.registry.ClaimJobWatch(&watch, self.machine, self.claimTTL)\n\t\t}\n\t}\n\n\tloop := func() {\n\t\tfor true {\n\t\t\theartbeat()\n\t\t\ttime.Sleep(self.claimTTL \/ 2)\n\t\t}\n\t}\n\n\tgo loop()\n}\n\nfunc (self *JobWatcher) StartRefreshThread() {\n\trefresh := func() {\n\t\tmachines := make(map[string]machine.Machine, 0)\n\t\tfor _, m := range self.registry.GetActiveMachines() {\n\t\t\tmachines[m.BootId] = m\n\t\t}\n\t\tself.machines = machines\n\t}\n\n\tloop := func() {\n\t\tfor true {\n\t\t\trefresh()\n\t\t\ttime.Sleep(self.refreshInterval)\n\t\t}\n\t}\n\n\tgo loop()\n}\n\nfunc (self *JobWatcher) AddJobWatch(watch *job.JobWatch) bool {\n\tif !self.registry.ClaimJobWatch(watch, self.machine, self.claimTTL) {\n\t\treturn false\n\t}\n\n\tself.watches[watch.Payload.Name] = *watch\n\tsched := NewSchedule()\n\tself.schedules[watch.Payload.Name] = sched\n\n\tif watch.Count == -1 {\n\t\tfor _, m := range self.machines {\n\t\t\tname := fmt.Sprintf(\"%s.%s\", m.BootId, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"EventJobWatchCreated(%s): adding to schedule job=%s machine=%s\", watch.Payload.Name, name, m.BootId)\n\t\t\tsched.Add(*j, m)\n\t\t}\n\t} else {\n\t\tfor i := 1; i <= watch.Count; i++ {\n\t\t\tm := pickRandomMachine(self.machines)\n\t\t\tname := fmt.Sprintf(\"%d.%s\", i, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"EventJobWatchCreated(%s): adding to schedule job=%s machine=%s\", watch.Payload.Name, name, m.BootId)\n\t\t\tsched.Add(*j, *m)\n\t\t}\n\t}\n\n\tif len(sched) > 0 {\n\t\tlog.Printf(\"EventJobWatchCreated(%s): submitting schedule\", watch.Payload.Name)\n\t\tself.submitSchedule(sched)\n\t} else {\n\t\tlog.Printf(\"EventJobWatchCreated(%s): no schedule changes made\", watch.Payload.Name)\n\t}\n\n\treturn true\n}\n\nfunc (self *JobWatcher) RemoveJobWatch(watch *job.JobWatch) bool {\n\tif _, ok := self.watches[watch.Payload.Name]; !ok {\n\t\treturn false\n\t}\n\n\tdelete(self.watches, watch.Payload.Name)\n\n\twatchSchedule := self.schedules[watch.Payload.Name]\n\tdelete(self.schedules, watch.Payload.Name)\n\n\tfor job, mach := range watchSchedule {\n\t\tself.registry.RemoveMachineJob(&job, mach)\n\t}\n\n\treturn true\n}\n\nfunc (self *JobWatcher) submitSchedule(schedule Schedule) {\n\tfor j, m := range schedule {\n\t\tself.registry.ScheduleMachineJob(&j, m)\n\t}\n}\n\nfunc (self *JobWatcher) TrackMachine(m *machine.Machine) {\n\tself.machines[m.BootId] = *m\n\n\tpartial := NewSchedule()\n\tfor _, watch := range self.watches {\n\t\tif watch.Count == -1 {\n\t\t\tname := fmt.Sprintf(\"%s.%s\", m.BootId, watch.Payload.Name)\n\t\t\tj, _ := job.NewJob(name, nil, watch.Payload)\n\t\t\tlog.Printf(\"Adding to schedule job=%s machine=%s\", name, m.BootId)\n\t\t\tpartial.Add(*j, *m)\n\n\t\t\tsched := self.schedules[watch.Payload.Name]\n\t\t\tsched.Add(*j, *m)\n\t\t}\n\t}\n\n\tif len(partial) > 0 {\n\t\tlog.Printf(\"Submitting schedule\")\n\t\tself.submitSchedule(partial)\n\t} else {\n\t\tlog.Printf(\"No schedule changes made\")\n\t}\n}\n\nfunc (self *JobWatcher) DropMachine(m *machine.Machine) {\n\tif _, ok := self.machines[m.BootId]; ok {\n\t\tdelete(self.machines, m.BootId)\n\t}\n}\n<|endoftext|>"} {"text":"package operatingsystem\n\nimport (\n \"io\/ioutil\"\n \"os\"\n \"strings\"\n)\n\nfunc Load() string {\n\n \/\/ redhat\/centos\/scientific\n \/\/ if \/etc\/redhat-release exists then we're dealing with redhat, centos, or scientific\n\tif _, err := os.Stat(\"\/etc\/redhat-release\"); err == nil {\n\n\t results, err := ioutil.ReadFile(\"\/etc\/redhat-release\")\n\t if err != nil {\n\t panic(err)\n\t }\n\t return(string(results))\n\t\t \n\t}\n\t\n \/\/ ubuntu\n \/\/ if \/etc\/lsb-release exists then we're dealing with an ubuntu host\n if _, err := os.Stat(\"\/etc\/lsb-release\"); err == nil {\n\n \/\/ Read in \/etc\/lsb-release\n results, err := ioutil.ReadFile(\"\/etc\/lsb-release\")\n if err != nil {\n panic(err)\n }\n\n \/\/ scan through results w\/ strings.Split\n for _, line := range strings.Split(string(results), \"\\n\") {\n s := strings.Split(line, \"=\")\n if s[0] == \"DISTRIB_DESCRIPTION\" {\n return(strings.Replace(s[1], `\"`, \"\", -1))\n }\n }\n }\n\n\treturn(string(\"error: cannot detect operating system\"))\n}\n\nfixing operating system to return just the OS name for redhat family OSespackage operatingsystem\n\nimport (\n \"github.com\/poblahblahblah\/gofigure\/lib\/factfuncts\"\n \"io\/ioutil\"\n \"os\"\n \"regexp\"\n \"strings\"\n)\n\nfunc Load() string {\n\n \/\/ try to detect which OS we are\n \/\/ if \/etc\/redhat-release exists then we're dealing with redhat, centos, or scientific\n if _, err := os.Stat(\"\/etc\/redhat-release\"); err == nil {\n\n centos_regexp, err := regexp.Compile(`(?i)centos`)\n fedora_regexp, err := regexp.Compile(`(?i)fedora`)\n redhat_regexp, err := regexp.Compile(`(?i)redhat`)\n scientific_regexp, err := regexp.Compile(`(?i)scientific`)\n\n results, err := ioutil.ReadFile(\"\/etc\/redhat-release\")\n if err != nil {\n panic(err)\n }\n\n os_long_string := factfuncts.Chomp(string(results))\n\n if centos_regexp.MatchString(os_long_string) == true {\n return string(\"CentOS\")\n } else if redhat_regexp.MatchString(os_long_string) == true {\n return string(\"RedHat\")\n } else if scientific_regexp.MatchString(os_long_string) == true {\n return string(\"Scientific Linux\")\n }\n }\n\n\t\n \/\/ if \/etc\/debian_release exists, then we're using debian or a derivative\n if _, err := os.Stat(\"\/etc\/debian_release\"); err == nil {\n\n \/\/ if \/etc\/lsb-release\n if _, err := os.Stat(\"\/etc\/lsb-release\"); err == nil {\n\n \/\/ Read in \/etc\/lsb-release\n results, err := ioutil.ReadFile(\"\/etc\/lsb-release\")\n if err != nil {\n panic(err)\n }\n\n \/\/ scan through results w\/ strings.Split\n for _, line := range strings.Split(string(results), \"\\n\") {\n s := strings.Split(line, \"=\")\n if s[0] == \"DISTRIB_DESCRIPTION\" {\n return(strings.Replace(s[1], `\"`, \"\", -1))\n }\n }\n }\n }\n\n \/\/ FIXME:\n \/\/ Add Solaris, the BSDs, etc.\n\n return(string(\"error: cannot detect operating system\"))\n}\n\n<|endoftext|>"} {"text":"package llog\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestOnlyErrorLogging(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, ERROR)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\")\n}\n\nfunc TestWarningOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, WARNING)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\")\n}\n\nfunc TestInfoOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, INFO)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\", \"Info\", \"Infof\")\n}\n\nfunc TestDebugOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, DEBUG)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\", \"Info\", \"Infof\", \"Debug\", \"Debugf\")\n}\n\nfunc logAndAssertNoError(t *testing.T, fn func(...interface{}) error, msg ...interface{}) {\n\terr := fn(msg...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc logfAndAssertNoError(t *testing.T, fn func(string, ...interface{}) error, fmt string, msg ...interface{}) {\n\terr := fn(fmt, msg...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc verifyLogEntries(t *testing.T, b *bytes.Buffer, entries ...string) {\n\teb := new(bytes.Buffer)\n\n\tfor _, e := range entries {\n\t\teb.WriteString(fmt.Sprintln(e))\n\t}\n\n\tif eb.String() != b.String() {\n\t\tt.Errorf(\"Expected entries log does not match\\nExpected: %s\\nGot: %s\\n\", eb.String(), b.String())\n\t}\n}\nAdd test for SetLevelpackage llog\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestOnlyErrorLogging(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, ERROR)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\")\n}\n\nfunc TestWarningOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, WARNING)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\")\n}\n\nfunc TestInfoOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, INFO)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\", \"Info\", \"Infof\")\n}\n\nfunc TestDebugOrHigher(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, DEBUG)\n\n\tlogAndAssertNoError(t, l.Error, \"Error\")\n\tlogfAndAssertNoError(t, l.Errorf, \"%s\", \"Errorf\")\n\n\tlogAndAssertNoError(t, l.Warning, \"Warning\")\n\tlogfAndAssertNoError(t, l.Warningf, \"%s\", \"Warningf\")\n\n\tlogAndAssertNoError(t, l.Info, \"Info\")\n\tlogfAndAssertNoError(t, l.Infof, \"%s\", \"Infof\")\n\n\tlogAndAssertNoError(t, l.Debug, \"Debug\")\n\tlogfAndAssertNoError(t, l.Debugf, \"%s\", \"Debugf\")\n\n\tverifyLogEntries(t, b, \"Error\", \"Errorf\", \"Warning\", \"Warningf\", \"Info\", \"Infof\", \"Debug\", \"Debugf\")\n}\n\nfunc TestSetLevel(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tl := New(b, INFO)\n\n\tlogAndAssertNoError(t, l.Debug, \"Error\")\n\tl.SetLevel(DEBUG)\n\tlogAndAssertNoError(t, l.Debug, \"Error\")\n\n\tverifyLogEntries(t, b, \"Error\")\n}\n\nfunc logAndAssertNoError(t *testing.T, fn func(...interface{}) error, msg ...interface{}) {\n\terr := fn(msg...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc logfAndAssertNoError(t *testing.T, fn func(string, ...interface{}) error, fmt string, msg ...interface{}) {\n\terr := fn(fmt, msg...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc verifyLogEntries(t *testing.T, b *bytes.Buffer, entries ...string) {\n\teb := new(bytes.Buffer)\n\n\tfor _, e := range entries {\n\t\teb.WriteString(fmt.Sprintln(e))\n\t}\n\n\tif eb.String() != b.String() {\n\t\tt.Errorf(\"Expected entries log does not match\\nExpected: %s\\nGot: %s\\n\", eb.String(), b.String())\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Code generated by protoc-gen-yarpc-go. DO NOT EDIT.\n\/\/ source: echo.proto\n\npackage echo\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"reflect\"\n\n\t\"github.com\/gogo\/protobuf\/jsonpb\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"go.uber.org\/fx\"\n\t\"go.uber.org\/yarpc\"\n\t\"go.uber.org\/yarpc\/api\/transport\"\n\t\"go.uber.org\/yarpc\/encoding\/protobuf\"\n\t\"go.uber.org\/yarpc\/encoding\/protobuf\/reflection\"\n)\n\nvar _ = ioutil.NopCloser\n\n\/\/ EchoYARPCClient is the YARPC client-side interface for the Echo service.\ntype EchoYARPCClient interface {\n\tEcho(context.Context, *Request, ...yarpc.CallOption) (*Response, error)\n}\n\nfunc newEchoYARPCClient(clientConfig transport.ClientConfig, anyResolver jsonpb.AnyResolver, options ...protobuf.ClientOption) EchoYARPCClient {\n\treturn &_EchoYARPCCaller{protobuf.NewStreamClient(\n\t\tprotobuf.ClientParams{\n\t\t\tServiceName: \"echo.Echo\",\n\t\t\tClientConfig: clientConfig,\n\t\t\tAnyResolver: anyResolver,\n\t\t\tOptions: options,\n\t\t},\n\t)}\n}\n\n\/\/ NewEchoYARPCClient builds a new YARPC client for the Echo service.\nfunc NewEchoYARPCClient(clientConfig transport.ClientConfig, options ...protobuf.ClientOption) EchoYARPCClient {\n\treturn newEchoYARPCClient(clientConfig, nil, options...)\n}\n\n\/\/ EchoYARPCServer is the YARPC server-side interface for the Echo service.\ntype EchoYARPCServer interface {\n\tEcho(context.Context, *Request) (*Response, error)\n}\n\ntype buildEchoYARPCProceduresParams struct {\n\tServer EchoYARPCServer\n\tAnyResolver jsonpb.AnyResolver\n}\n\nfunc buildEchoYARPCProcedures(params buildEchoYARPCProceduresParams) []transport.Procedure {\n\thandler := &_EchoYARPCHandler{params.Server}\n\treturn protobuf.BuildProcedures(\n\t\tprotobuf.BuildProceduresParams{\n\t\t\tServiceName: \"echo.Echo\",\n\t\t\tUnaryHandlerParams: []protobuf.BuildProceduresUnaryHandlerParams{\n\t\t\t\t{\n\t\t\t\t\tMethodName: \"Echo\",\n\t\t\t\t\tHandler: protobuf.NewUnaryHandler(\n\t\t\t\t\t\tprotobuf.UnaryHandlerParams{\n\t\t\t\t\t\t\tHandle: handler.Echo,\n\t\t\t\t\t\t\tNewRequest: newEchoServiceEchoYARPCRequest,\n\t\t\t\t\t\t\tAnyResolver: params.AnyResolver,\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tOnewayHandlerParams: []protobuf.BuildProceduresOnewayHandlerParams{},\n\t\t\tStreamHandlerParams: []protobuf.BuildProceduresStreamHandlerParams{},\n\t\t},\n\t)\n}\n\n\/\/ BuildEchoYARPCProcedures prepares an implementation of the Echo service for YARPC registration.\nfunc BuildEchoYARPCProcedures(server EchoYARPCServer) []transport.Procedure {\n\treturn buildEchoYARPCProcedures(buildEchoYARPCProceduresParams{Server: server})\n}\n\n\/\/ FxEchoYARPCClientParams defines the input\n\/\/ for NewFxEchoYARPCClient. It provides the\n\/\/ paramaters to get a EchoYARPCClient in an\n\/\/ Fx application.\ntype FxEchoYARPCClientParams struct {\n\tfx.In\n\n\tProvider yarpc.ClientConfig\n\tAnyResolver jsonpb.AnyResolver `name:\"yarpcfx\" optional:\"true\"`\n}\n\n\/\/ FxEchoYARPCClientResult defines the output\n\/\/ of NewFxEchoYARPCClient. It provides a\n\/\/ EchoYARPCClient to an Fx application.\ntype FxEchoYARPCClientResult struct {\n\tfx.Out\n\n\tClient EchoYARPCClient\n\n\t\/\/ We are using an fx.Out struct here instead of just returning a client\n\t\/\/ so that we can add more values or add named versions of the client in\n\t\/\/ the future without breaking any existing code.\n}\n\n\/\/ NewFxEchoYARPCClient provides a EchoYARPCClient\n\/\/ to an Fx application using the given name for routing.\n\/\/\n\/\/ fx.Provide(\n\/\/ echo.NewFxEchoYARPCClient(\"service-name\"),\n\/\/ ...\n\/\/ )\nfunc NewFxEchoYARPCClient(name string, options ...protobuf.ClientOption) interface{} {\n\treturn func(params FxEchoYARPCClientParams) FxEchoYARPCClientResult {\n\t\treturn FxEchoYARPCClientResult{\n\t\t\tClient: newEchoYARPCClient(params.Provider.ClientConfig(name), params.AnyResolver, options...),\n\t\t}\n\t}\n}\n\n\/\/ FxEchoYARPCProceduresParams defines the input\n\/\/ for NewFxEchoYARPCProcedures. It provides the\n\/\/ paramaters to get EchoYARPCServer procedures in an\n\/\/ Fx application.\ntype FxEchoYARPCProceduresParams struct {\n\tfx.In\n\n\tServer EchoYARPCServer\n\tAnyResolver jsonpb.AnyResolver `name:\"yarpcfx\" optional:\"true\"`\n}\n\n\/\/ FxEchoYARPCProceduresResult defines the output\n\/\/ of NewFxEchoYARPCProcedures. It provides\n\/\/ EchoYARPCServer procedures to an Fx application.\n\/\/\n\/\/ The procedures are provided to the \"yarpcfx\" value group.\n\/\/ Dig 1.2 or newer must be used for this feature to work.\ntype FxEchoYARPCProceduresResult struct {\n\tfx.Out\n\n\tProcedures []transport.Procedure `group:\"yarpcfx\"`\n\tReflectionMeta reflection.ServerMeta `group:\"yarpcfx\"`\n}\n\n\/\/ NewFxEchoYARPCProcedures provides EchoYARPCServer procedures to an Fx application.\n\/\/ It expects a EchoYARPCServer to be present in the container.\n\/\/\n\/\/ fx.Provide(\n\/\/ echo.NewFxEchoYARPCProcedures(),\n\/\/ ...\n\/\/ )\nfunc NewFxEchoYARPCProcedures() interface{} {\n\treturn func(params FxEchoYARPCProceduresParams) FxEchoYARPCProceduresResult {\n\t\treturn FxEchoYARPCProceduresResult{\n\t\t\tProcedures: buildEchoYARPCProcedures(buildEchoYARPCProceduresParams{\n\t\t\t\tServer: params.Server,\n\t\t\t\tAnyResolver: params.AnyResolver,\n\t\t\t}),\n\t\t\tReflectionMeta: reflection.ServerMeta{\n\t\t\t\tServiceName: \"echo.Echo\",\n\t\t\t\tFileDescriptors: yarpcFileDescriptorClosure08134aea513e0001,\n\t\t\t},\n\t\t}\n\t}\n}\n\ntype _EchoYARPCCaller struct {\n\tstreamClient protobuf.StreamClient\n}\n\nfunc (c *_EchoYARPCCaller) Echo(ctx context.Context, request *Request, options ...yarpc.CallOption) (*Response, error) {\n\tresponseMessage, err := c.streamClient.Call(ctx, \"Echo\", request, newEchoServiceEchoYARPCResponse, options...)\n\tif responseMessage == nil {\n\t\treturn nil, err\n\t}\n\tresponse, ok := responseMessage.(*Response)\n\tif !ok {\n\t\treturn nil, protobuf.CastError(emptyEchoServiceEchoYARPCResponse, responseMessage)\n\t}\n\treturn response, err\n}\n\ntype _EchoYARPCHandler struct {\n\tserver EchoYARPCServer\n}\n\nfunc (h *_EchoYARPCHandler) Echo(ctx context.Context, requestMessage proto.Message) (proto.Message, error) {\n\tvar request *Request\n\tvar ok bool\n\tif requestMessage != nil {\n\t\trequest, ok = requestMessage.(*Request)\n\t\tif !ok {\n\t\t\treturn nil, protobuf.CastError(emptyEchoServiceEchoYARPCRequest, requestMessage)\n\t\t}\n\t}\n\tresponse, err := h.server.Echo(ctx, request)\n\tif response == nil {\n\t\treturn nil, err\n\t}\n\treturn response, err\n}\n\nfunc newEchoServiceEchoYARPCRequest() proto.Message {\n\treturn &Request{}\n}\n\nfunc newEchoServiceEchoYARPCResponse() proto.Message {\n\treturn &Response{}\n}\n\nvar (\n\temptyEchoServiceEchoYARPCRequest = &Request{}\n\temptyEchoServiceEchoYARPCResponse = &Response{}\n)\n\nvar yarpcFileDescriptorClosure08134aea513e0001 = [][]byte{\n\t\/\/ echo.proto\n\t[]byte{\n\t\t0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4a, 0x4d, 0xce, 0xc8,\n\t\t0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0xb1, 0x95, 0x94, 0xb9, 0xd8, 0x83, 0x52,\n\t\t0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x24, 0xb8, 0xd8, 0x73, 0x53, 0x8b, 0x8b, 0x13, 0xd3, 0x53,\n\t\t0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x60, 0x5c, 0x25, 0x15, 0x2e, 0x8e, 0xa0, 0xd4, 0xe2,\n\t\t0x82, 0xfc, 0xbc, 0xe2, 0x54, 0xdc, 0xaa, 0x8c, 0x74, 0xb9, 0x58, 0x5c, 0x93, 0x33, 0xf2, 0x85,\n\t\t0x54, 0xa1, 0x34, 0xaf, 0x1e, 0xd8, 0x36, 0xa8, 0xf1, 0x52, 0x7c, 0x30, 0x2e, 0xc4, 0xa0, 0x24,\n\t\t0x36, 0xb0, 0x33, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xe1, 0x1c, 0xf0, 0xfd, 0x94, 0x00,\n\t\t0x00, 0x00,\n\t},\n}\n\nfunc init() {\n\tyarpc.RegisterClientBuilder(\n\t\tfunc(clientConfig transport.ClientConfig, structField reflect.StructField) EchoYARPCClient {\n\t\t\treturn NewEchoYARPCClient(clientConfig, protobuf.ClientBuilderOptions(clientConfig, structField)...)\n\t\t},\n\t)\n}\nRebasing master and standardizing goimports\/\/ Code generated by protoc-gen-yarpc-go. DO NOT EDIT.\n\/\/ source: clients\/echo\/echo.proto\n\npackage echo\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"reflect\"\n\n\t\"github.com\/gogo\/protobuf\/jsonpb\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"go.uber.org\/fx\"\n\t\"go.uber.org\/yarpc\"\n\t\"go.uber.org\/yarpc\/api\/transport\"\n\t\"go.uber.org\/yarpc\/encoding\/protobuf\"\n\t\"go.uber.org\/yarpc\/encoding\/protobuf\/reflection\"\n)\n\nvar _ = ioutil.NopCloser\n\n\/\/ EchoYARPCClient is the YARPC client-side interface for the Echo service.\ntype EchoYARPCClient interface {\n\tEcho(context.Context, *Request, ...yarpc.CallOption) (*Response, error)\n}\n\nfunc newEchoYARPCClient(clientConfig transport.ClientConfig, anyResolver jsonpb.AnyResolver, options ...protobuf.ClientOption) EchoYARPCClient {\n\treturn &_EchoYARPCCaller{protobuf.NewStreamClient(\n\t\tprotobuf.ClientParams{\n\t\t\tServiceName: \"echo.Echo\",\n\t\t\tClientConfig: clientConfig,\n\t\t\tAnyResolver: anyResolver,\n\t\t\tOptions: options,\n\t\t},\n\t)}\n}\n\n\/\/ NewEchoYARPCClient builds a new YARPC client for the Echo service.\nfunc NewEchoYARPCClient(clientConfig transport.ClientConfig, options ...protobuf.ClientOption) EchoYARPCClient {\n\treturn newEchoYARPCClient(clientConfig, nil, options...)\n}\n\n\/\/ EchoYARPCServer is the YARPC server-side interface for the Echo service.\ntype EchoYARPCServer interface {\n\tEcho(context.Context, *Request) (*Response, error)\n}\n\ntype buildEchoYARPCProceduresParams struct {\n\tServer EchoYARPCServer\n\tAnyResolver jsonpb.AnyResolver\n}\n\nfunc buildEchoYARPCProcedures(params buildEchoYARPCProceduresParams) []transport.Procedure {\n\thandler := &_EchoYARPCHandler{params.Server}\n\treturn protobuf.BuildProcedures(\n\t\tprotobuf.BuildProceduresParams{\n\t\t\tServiceName: \"echo.Echo\",\n\t\t\tUnaryHandlerParams: []protobuf.BuildProceduresUnaryHandlerParams{\n\t\t\t\t{\n\t\t\t\t\tMethodName: \"Echo\",\n\t\t\t\t\tHandler: protobuf.NewUnaryHandler(\n\t\t\t\t\t\tprotobuf.UnaryHandlerParams{\n\t\t\t\t\t\t\tHandle: handler.Echo,\n\t\t\t\t\t\t\tNewRequest: newEchoServiceEchoYARPCRequest,\n\t\t\t\t\t\t\tAnyResolver: params.AnyResolver,\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tOnewayHandlerParams: []protobuf.BuildProceduresOnewayHandlerParams{},\n\t\t\tStreamHandlerParams: []protobuf.BuildProceduresStreamHandlerParams{},\n\t\t},\n\t)\n}\n\n\/\/ BuildEchoYARPCProcedures prepares an implementation of the Echo service for YARPC registration.\nfunc BuildEchoYARPCProcedures(server EchoYARPCServer) []transport.Procedure {\n\treturn buildEchoYARPCProcedures(buildEchoYARPCProceduresParams{Server: server})\n}\n\n\/\/ FxEchoYARPCClientParams defines the input\n\/\/ for NewFxEchoYARPCClient. It provides the\n\/\/ paramaters to get a EchoYARPCClient in an\n\/\/ Fx application.\ntype FxEchoYARPCClientParams struct {\n\tfx.In\n\n\tProvider yarpc.ClientConfig\n\tAnyResolver jsonpb.AnyResolver `name:\"yarpcfx\" optional:\"true\"`\n}\n\n\/\/ FxEchoYARPCClientResult defines the output\n\/\/ of NewFxEchoYARPCClient. It provides a\n\/\/ EchoYARPCClient to an Fx application.\ntype FxEchoYARPCClientResult struct {\n\tfx.Out\n\n\tClient EchoYARPCClient\n\n\t\/\/ We are using an fx.Out struct here instead of just returning a client\n\t\/\/ so that we can add more values or add named versions of the client in\n\t\/\/ the future without breaking any existing code.\n}\n\n\/\/ NewFxEchoYARPCClient provides a EchoYARPCClient\n\/\/ to an Fx application using the given name for routing.\n\/\/\n\/\/ fx.Provide(\n\/\/ echo.NewFxEchoYARPCClient(\"service-name\"),\n\/\/ ...\n\/\/ )\nfunc NewFxEchoYARPCClient(name string, options ...protobuf.ClientOption) interface{} {\n\treturn func(params FxEchoYARPCClientParams) FxEchoYARPCClientResult {\n\t\treturn FxEchoYARPCClientResult{\n\t\t\tClient: newEchoYARPCClient(params.Provider.ClientConfig(name), params.AnyResolver, options...),\n\t\t}\n\t}\n}\n\n\/\/ FxEchoYARPCProceduresParams defines the input\n\/\/ for NewFxEchoYARPCProcedures. It provides the\n\/\/ paramaters to get EchoYARPCServer procedures in an\n\/\/ Fx application.\ntype FxEchoYARPCProceduresParams struct {\n\tfx.In\n\n\tServer EchoYARPCServer\n\tAnyResolver jsonpb.AnyResolver `name:\"yarpcfx\" optional:\"true\"`\n}\n\n\/\/ FxEchoYARPCProceduresResult defines the output\n\/\/ of NewFxEchoYARPCProcedures. It provides\n\/\/ EchoYARPCServer procedures to an Fx application.\n\/\/\n\/\/ The procedures are provided to the \"yarpcfx\" value group.\n\/\/ Dig 1.2 or newer must be used for this feature to work.\ntype FxEchoYARPCProceduresResult struct {\n\tfx.Out\n\n\tProcedures []transport.Procedure `group:\"yarpcfx\"`\n\tReflectionMeta reflection.ServerMeta `group:\"yarpcfx\"`\n}\n\n\/\/ NewFxEchoYARPCProcedures provides EchoYARPCServer procedures to an Fx application.\n\/\/ It expects a EchoYARPCServer to be present in the container.\n\/\/\n\/\/ fx.Provide(\n\/\/ echo.NewFxEchoYARPCProcedures(),\n\/\/ ...\n\/\/ )\nfunc NewFxEchoYARPCProcedures() interface{} {\n\treturn func(params FxEchoYARPCProceduresParams) FxEchoYARPCProceduresResult {\n\t\treturn FxEchoYARPCProceduresResult{\n\t\t\tProcedures: buildEchoYARPCProcedures(buildEchoYARPCProceduresParams{\n\t\t\t\tServer: params.Server,\n\t\t\t\tAnyResolver: params.AnyResolver,\n\t\t\t}),\n\t\t\tReflectionMeta: reflection.ServerMeta{\n\t\t\t\tServiceName: \"echo.Echo\",\n\t\t\t\tFileDescriptors: yarpcFileDescriptorClosure6caa5dd77ae15c91,\n\t\t\t},\n\t\t}\n\t}\n}\n\ntype _EchoYARPCCaller struct {\n\tstreamClient protobuf.StreamClient\n}\n\nfunc (c *_EchoYARPCCaller) Echo(ctx context.Context, request *Request, options ...yarpc.CallOption) (*Response, error) {\n\tresponseMessage, err := c.streamClient.Call(ctx, \"Echo\", request, newEchoServiceEchoYARPCResponse, options...)\n\tif responseMessage == nil {\n\t\treturn nil, err\n\t}\n\tresponse, ok := responseMessage.(*Response)\n\tif !ok {\n\t\treturn nil, protobuf.CastError(emptyEchoServiceEchoYARPCResponse, responseMessage)\n\t}\n\treturn response, err\n}\n\ntype _EchoYARPCHandler struct {\n\tserver EchoYARPCServer\n}\n\nfunc (h *_EchoYARPCHandler) Echo(ctx context.Context, requestMessage proto.Message) (proto.Message, error) {\n\tvar request *Request\n\tvar ok bool\n\tif requestMessage != nil {\n\t\trequest, ok = requestMessage.(*Request)\n\t\tif !ok {\n\t\t\treturn nil, protobuf.CastError(emptyEchoServiceEchoYARPCRequest, requestMessage)\n\t\t}\n\t}\n\tresponse, err := h.server.Echo(ctx, request)\n\tif response == nil {\n\t\treturn nil, err\n\t}\n\treturn response, err\n}\n\nfunc newEchoServiceEchoYARPCRequest() proto.Message {\n\treturn &Request{}\n}\n\nfunc newEchoServiceEchoYARPCResponse() proto.Message {\n\treturn &Response{}\n}\n\nvar (\n\temptyEchoServiceEchoYARPCRequest = &Request{}\n\temptyEchoServiceEchoYARPCResponse = &Response{}\n)\n\nvar yarpcFileDescriptorClosure6caa5dd77ae15c91 = [][]byte{\n\t\/\/ clients\/echo\/echo.proto\n\t[]byte{\n\t\t0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xce, 0xc9, 0x4c,\n\t\t0xcd, 0x2b, 0x29, 0xd6, 0x4f, 0x4d, 0xce, 0xc8, 0x07, 0x13, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9,\n\t\t0x42, 0x2c, 0x20, 0xb6, 0x92, 0x32, 0x17, 0x7b, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x90,\n\t\t0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, 0x62, 0x7a, 0xaa, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67,\n\t\t0x10, 0x8c, 0xab, 0xa4, 0xc2, 0xc5, 0x11, 0x94, 0x5a, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x8a, 0x5b,\n\t\t0x95, 0x91, 0x2e, 0x17, 0x8b, 0x6b, 0x72, 0x46, 0xbe, 0x90, 0x2a, 0x94, 0xe6, 0xd5, 0x03, 0xdb,\n\t\t0x06, 0x35, 0x5e, 0x8a, 0x0f, 0xc6, 0x85, 0x18, 0x94, 0xc4, 0x06, 0x76, 0x86, 0x31, 0x20, 0x00,\n\t\t0x00, 0xff, 0xff, 0xe9, 0xcf, 0xa3, 0x1b, 0xa1, 0x00, 0x00, 0x00,\n\t},\n}\n\nfunc init() {\n\tyarpc.RegisterClientBuilder(\n\t\tfunc(clientConfig transport.ClientConfig, structField reflect.StructField) EchoYARPCClient {\n\t\t\treturn NewEchoYARPCClient(clientConfig, protobuf.ClientBuilderOptions(clientConfig, structField)...)\n\t\t},\n\t)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"k8s.io\/frakti\/test\/e2e\/framework\"\n\tinternalapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\"\n\tkubeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\/v1alpha1\/runtime\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = framework.KubeDescribe(\"Test streaming in container\", func() {\n\tf := framework.NewDefaultFramework(\"test\")\n\n\tvar (\n\t\truntimeClient internalapi.RuntimeService\n\t\timageClient internalapi.ImageManagerService\n\t)\n\n\tBeforeEach(func() {\n\t\truntimeClient = f.Client.FraktiRuntimeService\n\t\timageClient = f.Client.FraktiImageService\n\t})\n\n\tIt(\"test exec a command in container synchronously and successfully\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podId string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"exec command in container synchronously\")\n\t\tmagicWords := \"blablabla\"\n\t\tstdout, stderr, err := runtimeClient.ExecSync(cID, []string{\"echo\", magicWords}, 0)\n\t\tframework.ExpectNoError(err, \"Failed to exec cmd in container: %v\", err)\n\t\tframework.Logf(\"stdout: %q, stderr: %q\", string(stdout), string(stderr))\n\t\tExpect(len(stderr)).To(Equal(0), \"stderr should not have content\")\n\t\tExpect(string(stdout)).To(BeIdenticalTo(magicWords+\"\\n\"), \"stdout should be same as defined\")\n\t})\n\n\tIt(\"test exec a command in container synchronously and failed\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podID string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"exec command in container synchronously\")\n\t\tmagicCmd := \"blablabla\"\n\t\tstdout, stderr, err := runtimeClient.ExecSync(cID, []string{magicCmd}, 0)\n\t\tExpect(err).NotTo(Equal(nil), \"Exec non-exist cmd should failed\")\n\t\tframework.Logf(\"stdout: %q, stderr: %q\", string(stdout), string(stderr))\n\t\tExpect(len(stderr)).NotTo(Equal(0), \"stderr should have content\")\n\t})\n\n\tIt(\"test get a exec url\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podID string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"prepare exec command url in container\")\n\t\tmagicCmd := []string{\"blablabla\"}\n\t\texecReq := &kubeapi.ExecRequest{\n\t\t\tContainerId: &cID,\n\t\t\tCmd: magicCmd,\n\t\t}\n\t\tresp, err := runtimeClient.Exec(execReq)\n\t\tframework.ExpectNoError(err, \"Failed to get exec url in container: %v\", err)\n\t\tframework.Logf(\"ExecUrl: %q\", resp.GetUrl())\n\t\texpectedUrl := buildExpectedExecAttachURL(\"exec\", cID, magicCmd, false, false)\n\t\tExpect(resp.GetUrl()).To(Equal(expectedUrl), \"exec url should equal to expected\")\n\t})\n})\n\nfunc startLongRunningContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService) (podId, containerId string) {\n\tpodName := \"simple-sandbox-\" + framework.NewUUID()\n\tBy(\"create a podSandbox\")\n\tpodConfig := &kubeapi.PodSandboxConfig{\n\t\tMetadata: &kubeapi.PodSandboxMetadata{\n\t\t\tName: &podName,\n\t\t},\n\t}\n\tpodId, err := rc.RunPodSandbox(podConfig)\n\tframework.ExpectNoError(err, \"Failed to create podsandbox: %v\", err)\n\n\tBy(\"pull necessary image\")\n\timageSpec := &kubeapi.ImageSpec{\n\t\tImage: &latestTestImageRef,\n\t}\n\terr = ic.PullImage(imageSpec, nil)\n\tframework.ExpectNoError(err, \"Failed to pull image: %v\", err)\n\n\tBy(\"create container in pod\")\n\tcontainerName := \"simple-container-\" + framework.NewUUID()\n\tcontainerConfig := &kubeapi.ContainerConfig{\n\t\tMetadata: &kubeapi.ContainerMetadata{\n\t\t\tName: &containerName,\n\t\t},\n\t\tImage: imageSpec,\n\t\tCommand: []string{\"sh\", \"-c\", \"top\"},\n\t}\n\tcontainerId, err = rc.CreateContainer(podId, containerConfig, podConfig)\n\tframework.ExpectNoError(err, \"Failed to create container: %v\", err)\n\n\tBy(\"start container\")\n\terr = rc.StartContainer(containerId)\n\tframework.ExpectNoError(err, \"Failed to start container: %v\", err)\n\n\t\/\/ sleep 2s to make sure container start is ready, workaround for random failed in travis\n\t\/\/ TODO: remove this\n\ttime.Sleep(2 * time.Second)\n\n\treturn podId, containerId\n}\n\nfunc buildExpectedExecAttachURL(method, containerID string, cmd []string, stdin, tty bool) string {\n\tquery := \"\"\n\t\/\/ build cmd\n\tfor i, c := range cmd {\n\t\tif i == 0 {\n\t\t\tquery += \"?\"\n\t\t} else {\n\t\t\tquery += \"&\"\n\t\t}\n\t\tquery += fmt.Sprintf(\"command=%s\", c)\n\t}\n\tif len(cmd) == 0 {\n\t\tquery += \"?\"\n\t} else {\n\t\tquery += \"&\"\n\t}\n\t\/\/ build io setting\n\tif !tty {\n\t\tquery += \"error=1&\"\n\t}\n\tif stdin {\n\t\tquery += \"input=1&\"\n\t}\n\t\/\/ stdout is set default\n\tquery += \"output=1&\"\n\tif tty {\n\t\tquery += \"tty=1&\"\n\t}\n\t\/\/ remove traval '&'\n\tquery = query[:len(query)-1]\n\n\t\/\/ TODO: http schema and address should generate from frakti config\n\treturn fmt.Sprintf(\"http:\/\/0.0.0.0:22521\/%s\/%s%s\", method, containerID, query)\n}\nadd test for get attach url api\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"k8s.io\/frakti\/test\/e2e\/framework\"\n\tinternalapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\"\n\tkubeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\/v1alpha1\/runtime\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = framework.KubeDescribe(\"Test streaming in container\", func() {\n\tf := framework.NewDefaultFramework(\"test\")\n\n\tvar (\n\t\truntimeClient internalapi.RuntimeService\n\t\timageClient internalapi.ImageManagerService\n\t)\n\n\tBeforeEach(func() {\n\t\truntimeClient = f.Client.FraktiRuntimeService\n\t\timageClient = f.Client.FraktiImageService\n\t})\n\n\tIt(\"test exec a command in container synchronously and successfully\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podId string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"exec command in container synchronously\")\n\t\tmagicWords := \"blablabla\"\n\t\tstdout, stderr, err := runtimeClient.ExecSync(cID, []string{\"echo\", magicWords}, 0)\n\t\tframework.ExpectNoError(err, \"Failed to exec cmd in container: %v\", err)\n\t\tframework.Logf(\"stdout: %q, stderr: %q\", string(stdout), string(stderr))\n\t\tExpect(len(stderr)).To(Equal(0), \"stderr should not have content\")\n\t\tExpect(string(stdout)).To(BeIdenticalTo(magicWords+\"\\n\"), \"stdout should be same as defined\")\n\t})\n\n\tIt(\"test exec a command in container synchronously and failed\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podID string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"exec command in container synchronously\")\n\t\tmagicCmd := \"blablabla\"\n\t\tstdout, stderr, err := runtimeClient.ExecSync(cID, []string{magicCmd}, 0)\n\t\tExpect(err).NotTo(Equal(nil), \"Exec non-exist cmd should failed\")\n\t\tframework.Logf(\"stdout: %q, stderr: %q\", string(stdout), string(stderr))\n\t\tExpect(len(stderr)).NotTo(Equal(0), \"stderr should have content\")\n\t})\n\n\tIt(\"test get a exec url\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podID string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"prepare exec command url in container\")\n\t\tmagicCmd := []string{\"blablabla\"}\n\t\texecReq := &kubeapi.ExecRequest{\n\t\t\tContainerId: &cID,\n\t\t\tCmd: magicCmd,\n\t\t}\n\t\tresp, err := runtimeClient.Exec(execReq)\n\t\tframework.ExpectNoError(err, \"Failed to get exec url in container: %v\", err)\n\t\tframework.Logf(\"ExecUrl: %q\", resp.GetUrl())\n\t\texpectedUrl := buildExpectedExecAttachURL(\"exec\", cID, magicCmd, false, false)\n\t\tExpect(resp.GetUrl()).To(Equal(expectedUrl), \"exec url should equal to expected\")\n\t})\n\n\tIt(\"test get a attach url\", func() {\n\t\tpodID, cID := startLongRunningContainer(runtimeClient, imageClient)\n\t\tdefer func(podID string) {\n\t\t\tBy(\"delete pod sandbox\")\n\t\t\truntimeClient.RemovePodSandbox(podID)\n\t\t}(podID)\n\n\t\tBy(\"prepare attach command url in container\")\n\t\tstdin := true\n\t\tattachReq := &kubeapi.AttachRequest{\n\t\t\tContainerId: &cID,\n\t\t\tStdin: &stdin,\n\t\t}\n\t\tresp, err := runtimeClient.Attach(attachReq)\n\t\tframework.ExpectNoError(err, \"Failed to get attach url in container: %v\", err)\n\t\tframework.Logf(\"AttachUrl: %q\", resp.GetUrl())\n\t\texpectedUrl := buildExpectedExecAttachURL(\"attach\", cID, nil, stdin, false)\n\t\tExpect(resp.GetUrl()).To(Equal(expectedUrl), \"attach url should equal to expected\")\n\t})\n})\n\nfunc startLongRunningContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService) (podId, containerId string) {\n\tpodName := \"simple-sandbox-\" + framework.NewUUID()\n\tBy(\"create a podSandbox\")\n\tpodConfig := &kubeapi.PodSandboxConfig{\n\t\tMetadata: &kubeapi.PodSandboxMetadata{\n\t\t\tName: &podName,\n\t\t},\n\t}\n\tpodId, err := rc.RunPodSandbox(podConfig)\n\tframework.ExpectNoError(err, \"Failed to create podsandbox: %v\", err)\n\n\tBy(\"pull necessary image\")\n\timageSpec := &kubeapi.ImageSpec{\n\t\tImage: &latestTestImageRef,\n\t}\n\terr = ic.PullImage(imageSpec, nil)\n\tframework.ExpectNoError(err, \"Failed to pull image: %v\", err)\n\n\tBy(\"create container in pod\")\n\tcontainerName := \"simple-container-\" + framework.NewUUID()\n\tcontainerConfig := &kubeapi.ContainerConfig{\n\t\tMetadata: &kubeapi.ContainerMetadata{\n\t\t\tName: &containerName,\n\t\t},\n\t\tImage: imageSpec,\n\t\tCommand: []string{\"sh\", \"-c\", \"top\"},\n\t}\n\tcontainerId, err = rc.CreateContainer(podId, containerConfig, podConfig)\n\tframework.ExpectNoError(err, \"Failed to create container: %v\", err)\n\n\tBy(\"start container\")\n\terr = rc.StartContainer(containerId)\n\tframework.ExpectNoError(err, \"Failed to start container: %v\", err)\n\n\t\/\/ sleep 2s to make sure container start is ready, workaround for random failed in travis\n\t\/\/ TODO: remove this\n\ttime.Sleep(2 * time.Second)\n\n\treturn podId, containerId\n}\n\nfunc buildExpectedExecAttachURL(method, containerID string, cmd []string, stdin, tty bool) string {\n\tquery := \"\"\n\t\/\/ build cmd\n\tfor i, c := range cmd {\n\t\tif i == 0 {\n\t\t\tquery += \"?\"\n\t\t} else {\n\t\t\tquery += \"&\"\n\t\t}\n\t\tquery += fmt.Sprintf(\"command=%s\", c)\n\t}\n\tif len(cmd) == 0 {\n\t\tquery += \"?\"\n\t} else {\n\t\tquery += \"&\"\n\t}\n\t\/\/ build io setting\n\tif !tty {\n\t\tquery += \"error=1&\"\n\t}\n\tif stdin {\n\t\tquery += \"input=1&\"\n\t}\n\t\/\/ stdout is set default\n\tquery += \"output=1&\"\n\tif tty {\n\t\tquery += \"tty=1&\"\n\t}\n\t\/\/ remove traval '&'\n\tquery = query[:len(query)-1]\n\n\t\/\/ TODO: http schema and address should generate from frakti config\n\treturn fmt.Sprintf(\"http:\/\/0.0.0.0:22521\/%s\/%s%s\", method, containerID, query)\n}\n<|endoftext|>"} {"text":"package relay\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/libp2p\/go-libp2p-core\/network\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n\t\"github.com\/libp2p\/go-libp2p-core\/routing\"\n\n\tautonat \"github.com\/libp2p\/go-libp2p-autonat\"\n\t_ \"github.com\/libp2p\/go-libp2p-circuit\"\n\tdiscovery \"github.com\/libp2p\/go-libp2p-discovery\"\n\tbasic \"github.com\/libp2p\/go-libp2p\/p2p\/host\/basic\"\n\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\tmanet \"github.com\/multiformats\/go-multiaddr-net\"\n)\n\nconst (\n\tRelayRendezvous = \"\/libp2p\/relay\"\n)\n\nvar (\n\tDesiredRelays = 3\n\n\tBootDelay = 20 * time.Second\n)\n\n\/\/ AutoRelay is a Host that uses relays for connectivity when a NAT is detected.\ntype AutoRelay struct {\n\thost *basic.BasicHost\n\tdiscover discovery.Discoverer\n\trouter routing.PeerRouting\n\tautonat autonat.AutoNAT\n\taddrsF basic.AddrsFactory\n\n\tdisconnect chan struct{}\n\n\tmx sync.Mutex\n\trelays map[peer.ID]struct{}\n\tstatus autonat.NATStatus\n\n\tcachedAddrs []ma.Multiaddr\n\tcachedAddrsExpiry time.Time\n}\n\nfunc NewAutoRelay(ctx context.Context, bhost *basic.BasicHost, discover discovery.Discoverer, router routing.PeerRouting) *AutoRelay {\n\tar := &AutoRelay{\n\t\thost: bhost,\n\t\tdiscover: discover,\n\t\trouter: router,\n\t\taddrsF: bhost.AddrsFactory,\n\t\trelays: make(map[peer.ID]struct{}),\n\t\tdisconnect: make(chan struct{}, 1),\n\t\tstatus: autonat.NATStatusUnknown,\n\t}\n\tar.autonat = autonat.NewAutoNAT(ctx, bhost, ar.baseAddrs)\n\tbhost.AddrsFactory = ar.hostAddrs\n\tbhost.Network().Notify(ar)\n\tgo ar.background(ctx)\n\treturn ar\n}\n\nfunc (ar *AutoRelay) baseAddrs() []ma.Multiaddr {\n\treturn ar.addrsF(ar.host.AllAddrs())\n}\n\nfunc (ar *AutoRelay) hostAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {\n\treturn ar.relayAddrs(ar.addrsF(addrs))\n}\n\nfunc (ar *AutoRelay) background(ctx context.Context) {\n\tselect {\n\tcase <-time.After(autonat.AutoNATBootDelay + BootDelay):\n\tcase <-ctx.Done():\n\t\treturn\n\t}\n\n\t\/\/ when true, we need to identify push\n\tpush := false\n\n\tfor {\n\t\twait := autonat.AutoNATRefreshInterval\n\t\tswitch ar.autonat.Status() {\n\t\tcase autonat.NATStatusUnknown:\n\t\t\tar.mx.Lock()\n\t\t\tar.status = autonat.NATStatusUnknown\n\t\t\tar.mx.Unlock()\n\t\t\twait = autonat.AutoNATRetryInterval\n\n\t\tcase autonat.NATStatusPublic:\n\t\t\tar.mx.Lock()\n\t\t\tif ar.status != autonat.NATStatusPublic {\n\t\t\t\tpush = true\n\t\t\t}\n\t\t\tar.status = autonat.NATStatusPublic\n\t\t\tar.mx.Unlock()\n\n\t\tcase autonat.NATStatusPrivate:\n\t\t\tupdate := ar.findRelays(ctx)\n\t\t\tar.mx.Lock()\n\t\t\tif update || ar.status != autonat.NATStatusPrivate {\n\t\t\t\tpush = true\n\t\t\t}\n\t\t\tar.status = autonat.NATStatusPrivate\n\t\t\tar.mx.Unlock()\n\t\t}\n\n\t\tif push {\n\t\t\tar.mx.Lock()\n\t\t\tar.cachedAddrs = nil\n\t\t\tar.mx.Unlock()\n\t\t\tpush = false\n\t\t\tar.host.PushIdentify()\n\t\t}\n\n\t\tselect {\n\t\tcase <-ar.disconnect:\n\t\t\tpush = true\n\t\tcase <-time.After(wait):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (ar *AutoRelay) findRelays(ctx context.Context) bool {\n\tif ar.numRelays() >= DesiredRelays {\n\t\treturn false\n\t}\n\n\tupdate := false\n\tfor retry := 0; retry < 5; retry++ {\n\t\tif retry > 0 {\n\t\t\tlog.Debug(\"no relays connected; retrying in 30s\")\n\t\t\tselect {\n\t\t\tcase <-time.After(30 * time.Second):\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn update\n\t\t\t}\n\t\t}\n\n\t\tupdate = ar.findRelaysOnce(ctx) || update\n\t\tif ar.numRelays() > 0 {\n\t\t\treturn update\n\t\t}\n\t}\n\treturn update\n}\n\nfunc (ar *AutoRelay) findRelaysOnce(ctx context.Context) bool {\n\tpis, err := ar.discoverRelays(ctx)\n\tif err != nil {\n\t\tlog.Debugf(\"error discovering relays: %s\", err)\n\t\treturn false\n\t}\n\tlog.Debugf(\"discovered %d relays\", len(pis))\n\tpis = ar.selectRelays(ctx, pis)\n\tlog.Debugf(\"selected %d relays\", len(pis))\n\n\tupdate := false\n\tfor _, pi := range pis {\n\t\tupdate = ar.tryRelay(ctx, pi) || update\n\t\tif ar.numRelays() >= DesiredRelays {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn update\n}\n\nfunc (ar *AutoRelay) numRelays() int {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\treturn len(ar.relays)\n}\n\n\/\/ usingRelay returns if we're currently using the given relay.\nfunc (ar *AutoRelay) usingRelay(p peer.ID) bool {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\t_, ok := ar.relays[p]\n\treturn ok\n}\n\n\/\/ addRelay adds the given relay to our set of relays.\n\/\/ returns true when we add a new relay\nfunc (ar *AutoRelay) tryRelay(ctx context.Context, pi peer.AddrInfo) bool {\n\tif ar.usingRelay(pi.ID) {\n\t\treturn false\n\t}\n\n\tif !ar.connect(ctx, pi) {\n\t\treturn false\n\t}\n\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\t\/\/ make sure we're still connected.\n\tif ar.host.Network().Connectedness(pi.ID) != network.Connected {\n\t\treturn false\n\t}\n\tar.relays[pi.ID] = struct{}{}\n\n\treturn true\n}\n\nfunc (ar *AutoRelay) connect(ctx context.Context, pi peer.AddrInfo) bool {\n\tctx, cancel := context.WithTimeout(ctx, 60*time.Second)\n\tdefer cancel()\n\n\tif len(pi.Addrs) == 0 {\n\t\tvar err error\n\t\tpi, err = ar.router.FindPeer(ctx, pi.ID)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"error finding relay peer %s: %s\", pi.ID, err.Error())\n\t\t\treturn false\n\t\t}\n\t}\n\n\terr := ar.host.Connect(ctx, pi)\n\tif err != nil {\n\t\tlog.Debugf(\"error connecting to relay %s: %s\", pi.ID, err.Error())\n\t\treturn false\n\t}\n\n\t\/\/ tag the connection as very important\n\tar.host.ConnManager().TagPeer(pi.ID, \"relay\", 42)\n\treturn true\n}\n\nfunc (ar *AutoRelay) discoverRelays(ctx context.Context) ([]peer.AddrInfo, error) {\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\treturn discovery.FindPeers(ctx, ar.discover, RelayRendezvous, discovery.Limit(1000))\n}\n\nfunc (ar *AutoRelay) selectRelays(ctx context.Context, pis []peer.AddrInfo) []peer.AddrInfo {\n\t\/\/ TODO better relay selection strategy; this just selects random relays\n\t\/\/ but we should probably use ping latency as the selection metric\n\n\tshuffleRelays(pis)\n\treturn pis\n}\n\n\/\/ This function is computes the NATed relay addrs when our status is private:\n\/\/ - The public addrs are removed from the address set.\n\/\/ - The non-public addrs are included verbatim so that peers behind the same NAT\/firewall\n\/\/ can still dial us directly.\n\/\/ - On top of those, we add the relay-specific addrs for the relays to which we are\n\/\/ connected. For each non-private relay addr, we encapsulate the p2p-circuit addr\n\/\/ through which we can be dialed.\nfunc (ar *AutoRelay) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\tif ar.status != autonat.NATStatusPrivate {\n\t\treturn addrs\n\t}\n\n\tif ar.cachedAddrs != nil && time.Now().Before(ar.cachedAddrsExpiry) {\n\t\treturn ar.cachedAddrs\n\t}\n\n\traddrs := make([]ma.Multiaddr, 0, 4*len(ar.relays)+4)\n\n\t\/\/ only keep private addrs from the original addr set\n\tfor _, addr := range addrs {\n\t\tif manet.IsPrivateAddr(addr) {\n\t\t\traddrs = append(raddrs, addr)\n\t\t}\n\t}\n\n\t\/\/ add relay specific addrs to the list\n\tfor p := range ar.relays {\n\t\taddrs := cleanupAddressSet(ar.host.Peerstore().Addrs(p))\n\n\t\tcircuit, err := ma.NewMultiaddr(fmt.Sprintf(\"\/p2p\/%s\/p2p-circuit\", p.Pretty()))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tpub := addr.Encapsulate(circuit)\n\t\t\traddrs = append(raddrs, pub)\n\t\t}\n\t}\n\n\tar.cachedAddrs = raddrs\n\tar.cachedAddrsExpiry = time.Now().Add(30 * time.Second)\n\n\treturn raddrs\n}\n\nfunc shuffleRelays(pis []peer.AddrInfo) {\n\tfor i := range pis {\n\t\tj := rand.Intn(i + 1)\n\t\tpis[i], pis[j] = pis[j], pis[i]\n\t}\n}\n\n\/\/ Notifee\nfunc (ar *AutoRelay) Listen(network.Network, ma.Multiaddr) {}\nfunc (ar *AutoRelay) ListenClose(network.Network, ma.Multiaddr) {}\nfunc (ar *AutoRelay) Connected(network.Network, network.Conn) {}\n\nfunc (ar *AutoRelay) Disconnected(net network.Network, c network.Conn) {\n\tp := c.RemotePeer()\n\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\tif ar.host.Network().Connectedness(p) == network.Connected {\n\t\t\/\/ We have a second connection.\n\t\treturn\n\t}\n\n\tif _, ok := ar.relays[p]; ok {\n\t\tdelete(ar.relays, p)\n\t\tselect {\n\t\tcase ar.disconnect <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc (ar *AutoRelay) OpenedStream(network.Network, network.Stream) {}\nfunc (ar *AutoRelay) ClosedStream(network.Network, network.Stream) {}\nautorelay: ensure candidate relays can hoppackage relay\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/libp2p\/go-libp2p-core\/network\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n\t\"github.com\/libp2p\/go-libp2p-core\/routing\"\n\n\tautonat \"github.com\/libp2p\/go-libp2p-autonat\"\n\tcircuit \"github.com\/libp2p\/go-libp2p-circuit\"\n\tdiscovery \"github.com\/libp2p\/go-libp2p-discovery\"\n\tbasic \"github.com\/libp2p\/go-libp2p\/p2p\/host\/basic\"\n\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\tmanet \"github.com\/multiformats\/go-multiaddr-net\"\n)\n\nconst (\n\tRelayRendezvous = \"\/libp2p\/relay\"\n)\n\nvar (\n\tDesiredRelays = 3\n\n\tBootDelay = 20 * time.Second\n)\n\n\/\/ AutoRelay is a Host that uses relays for connectivity when a NAT is detected.\ntype AutoRelay struct {\n\thost *basic.BasicHost\n\tdiscover discovery.Discoverer\n\trouter routing.PeerRouting\n\tautonat autonat.AutoNAT\n\taddrsF basic.AddrsFactory\n\n\tdisconnect chan struct{}\n\n\tmx sync.Mutex\n\trelays map[peer.ID]struct{}\n\tstatus autonat.NATStatus\n\n\tcachedAddrs []ma.Multiaddr\n\tcachedAddrsExpiry time.Time\n}\n\nfunc NewAutoRelay(ctx context.Context, bhost *basic.BasicHost, discover discovery.Discoverer, router routing.PeerRouting) *AutoRelay {\n\tar := &AutoRelay{\n\t\thost: bhost,\n\t\tdiscover: discover,\n\t\trouter: router,\n\t\taddrsF: bhost.AddrsFactory,\n\t\trelays: make(map[peer.ID]struct{}),\n\t\tdisconnect: make(chan struct{}, 1),\n\t\tstatus: autonat.NATStatusUnknown,\n\t}\n\tar.autonat = autonat.NewAutoNAT(ctx, bhost, ar.baseAddrs)\n\tbhost.AddrsFactory = ar.hostAddrs\n\tbhost.Network().Notify(ar)\n\tgo ar.background(ctx)\n\treturn ar\n}\n\nfunc (ar *AutoRelay) baseAddrs() []ma.Multiaddr {\n\treturn ar.addrsF(ar.host.AllAddrs())\n}\n\nfunc (ar *AutoRelay) hostAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {\n\treturn ar.relayAddrs(ar.addrsF(addrs))\n}\n\nfunc (ar *AutoRelay) background(ctx context.Context) {\n\tselect {\n\tcase <-time.After(autonat.AutoNATBootDelay + BootDelay):\n\tcase <-ctx.Done():\n\t\treturn\n\t}\n\n\t\/\/ when true, we need to identify push\n\tpush := false\n\n\tfor {\n\t\twait := autonat.AutoNATRefreshInterval\n\t\tswitch ar.autonat.Status() {\n\t\tcase autonat.NATStatusUnknown:\n\t\t\tar.mx.Lock()\n\t\t\tar.status = autonat.NATStatusUnknown\n\t\t\tar.mx.Unlock()\n\t\t\twait = autonat.AutoNATRetryInterval\n\n\t\tcase autonat.NATStatusPublic:\n\t\t\tar.mx.Lock()\n\t\t\tif ar.status != autonat.NATStatusPublic {\n\t\t\t\tpush = true\n\t\t\t}\n\t\t\tar.status = autonat.NATStatusPublic\n\t\t\tar.mx.Unlock()\n\n\t\tcase autonat.NATStatusPrivate:\n\t\t\tupdate := ar.findRelays(ctx)\n\t\t\tar.mx.Lock()\n\t\t\tif update || ar.status != autonat.NATStatusPrivate {\n\t\t\t\tpush = true\n\t\t\t}\n\t\t\tar.status = autonat.NATStatusPrivate\n\t\t\tar.mx.Unlock()\n\t\t}\n\n\t\tif push {\n\t\t\tar.mx.Lock()\n\t\t\tar.cachedAddrs = nil\n\t\t\tar.mx.Unlock()\n\t\t\tpush = false\n\t\t\tar.host.PushIdentify()\n\t\t}\n\n\t\tselect {\n\t\tcase <-ar.disconnect:\n\t\t\tpush = true\n\t\tcase <-time.After(wait):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (ar *AutoRelay) findRelays(ctx context.Context) bool {\n\tif ar.numRelays() >= DesiredRelays {\n\t\treturn false\n\t}\n\n\tupdate := false\n\tfor retry := 0; retry < 5; retry++ {\n\t\tif retry > 0 {\n\t\t\tlog.Debug(\"no relays connected; retrying in 30s\")\n\t\t\tselect {\n\t\t\tcase <-time.After(30 * time.Second):\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn update\n\t\t\t}\n\t\t}\n\n\t\tupdate = ar.findRelaysOnce(ctx) || update\n\t\tif ar.numRelays() > 0 {\n\t\t\treturn update\n\t\t}\n\t}\n\treturn update\n}\n\nfunc (ar *AutoRelay) findRelaysOnce(ctx context.Context) bool {\n\tpis, err := ar.discoverRelays(ctx)\n\tif err != nil {\n\t\tlog.Debugf(\"error discovering relays: %s\", err)\n\t\treturn false\n\t}\n\tlog.Debugf(\"discovered %d relays\", len(pis))\n\tpis = ar.selectRelays(ctx, pis)\n\tlog.Debugf(\"selected %d relays\", len(pis))\n\n\tupdate := false\n\tfor _, pi := range pis {\n\t\tupdate = ar.tryRelay(ctx, pi) || update\n\t\tif ar.numRelays() >= DesiredRelays {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn update\n}\n\nfunc (ar *AutoRelay) numRelays() int {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\treturn len(ar.relays)\n}\n\n\/\/ usingRelay returns if we're currently using the given relay.\nfunc (ar *AutoRelay) usingRelay(p peer.ID) bool {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\t_, ok := ar.relays[p]\n\treturn ok\n}\n\n\/\/ addRelay adds the given relay to our set of relays.\n\/\/ returns true when we add a new relay\nfunc (ar *AutoRelay) tryRelay(ctx context.Context, pi peer.AddrInfo) bool {\n\tif ar.usingRelay(pi.ID) {\n\t\treturn false\n\t}\n\n\tif !ar.connect(ctx, pi) {\n\t\treturn false\n\t}\n\n\tok, err := circuit.CanHop(ctx, ar.host, pi.ID)\n\tif err != nil {\n\t\tlog.Debugf(\"error querying relay: %s\", err.Error())\n\t\treturn false\n\t}\n\n\tif !ok {\n\t\t\/\/ not a hop relay\n\t\treturn false\n\t}\n\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\t\/\/ make sure we're still connected.\n\tif ar.host.Network().Connectedness(pi.ID) != network.Connected {\n\t\treturn false\n\t}\n\tar.relays[pi.ID] = struct{}{}\n\n\treturn true\n}\n\nfunc (ar *AutoRelay) connect(ctx context.Context, pi peer.AddrInfo) bool {\n\tctx, cancel := context.WithTimeout(ctx, 60*time.Second)\n\tdefer cancel()\n\n\tif len(pi.Addrs) == 0 {\n\t\tvar err error\n\t\tpi, err = ar.router.FindPeer(ctx, pi.ID)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"error finding relay peer %s: %s\", pi.ID, err.Error())\n\t\t\treturn false\n\t\t}\n\t}\n\n\terr := ar.host.Connect(ctx, pi)\n\tif err != nil {\n\t\tlog.Debugf(\"error connecting to relay %s: %s\", pi.ID, err.Error())\n\t\treturn false\n\t}\n\n\t\/\/ tag the connection as very important\n\tar.host.ConnManager().TagPeer(pi.ID, \"relay\", 42)\n\treturn true\n}\n\nfunc (ar *AutoRelay) discoverRelays(ctx context.Context) ([]peer.AddrInfo, error) {\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\treturn discovery.FindPeers(ctx, ar.discover, RelayRendezvous, discovery.Limit(1000))\n}\n\nfunc (ar *AutoRelay) selectRelays(ctx context.Context, pis []peer.AddrInfo) []peer.AddrInfo {\n\t\/\/ TODO better relay selection strategy; this just selects random relays\n\t\/\/ but we should probably use ping latency as the selection metric\n\n\tshuffleRelays(pis)\n\treturn pis\n}\n\n\/\/ This function is computes the NATed relay addrs when our status is private:\n\/\/ - The public addrs are removed from the address set.\n\/\/ - The non-public addrs are included verbatim so that peers behind the same NAT\/firewall\n\/\/ can still dial us directly.\n\/\/ - On top of those, we add the relay-specific addrs for the relays to which we are\n\/\/ connected. For each non-private relay addr, we encapsulate the p2p-circuit addr\n\/\/ through which we can be dialed.\nfunc (ar *AutoRelay) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\tif ar.status != autonat.NATStatusPrivate {\n\t\treturn addrs\n\t}\n\n\tif ar.cachedAddrs != nil && time.Now().Before(ar.cachedAddrsExpiry) {\n\t\treturn ar.cachedAddrs\n\t}\n\n\traddrs := make([]ma.Multiaddr, 0, 4*len(ar.relays)+4)\n\n\t\/\/ only keep private addrs from the original addr set\n\tfor _, addr := range addrs {\n\t\tif manet.IsPrivateAddr(addr) {\n\t\t\traddrs = append(raddrs, addr)\n\t\t}\n\t}\n\n\t\/\/ add relay specific addrs to the list\n\tfor p := range ar.relays {\n\t\taddrs := cleanupAddressSet(ar.host.Peerstore().Addrs(p))\n\n\t\tcircuit, err := ma.NewMultiaddr(fmt.Sprintf(\"\/p2p\/%s\/p2p-circuit\", p.Pretty()))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tpub := addr.Encapsulate(circuit)\n\t\t\traddrs = append(raddrs, pub)\n\t\t}\n\t}\n\n\tar.cachedAddrs = raddrs\n\tar.cachedAddrsExpiry = time.Now().Add(30 * time.Second)\n\n\treturn raddrs\n}\n\nfunc shuffleRelays(pis []peer.AddrInfo) {\n\tfor i := range pis {\n\t\tj := rand.Intn(i + 1)\n\t\tpis[i], pis[j] = pis[j], pis[i]\n\t}\n}\n\n\/\/ Notifee\nfunc (ar *AutoRelay) Listen(network.Network, ma.Multiaddr) {}\nfunc (ar *AutoRelay) ListenClose(network.Network, ma.Multiaddr) {}\nfunc (ar *AutoRelay) Connected(network.Network, network.Conn) {}\n\nfunc (ar *AutoRelay) Disconnected(net network.Network, c network.Conn) {\n\tp := c.RemotePeer()\n\n\tar.mx.Lock()\n\tdefer ar.mx.Unlock()\n\n\tif ar.host.Network().Connectedness(p) == network.Connected {\n\t\t\/\/ We have a second connection.\n\t\treturn\n\t}\n\n\tif _, ok := ar.relays[p]; ok {\n\t\tdelete(ar.relays, p)\n\t\tselect {\n\t\tcase ar.disconnect <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc (ar *AutoRelay) OpenedStream(network.Network, network.Stream) {}\nfunc (ar *AutoRelay) ClosedStream(network.Network, network.Stream) {}\n<|endoftext|>"} {"text":"package keystore\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/cossacklabs\/acra\/utils\"\n\t\"github.com\/cossacklabs\/acra\/zone\"\n\t\"github.com\/cossacklabs\/themis\/gothemis\/keys\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"crypto\/rand\"\n\t\"sync\"\n)\n\ntype FilesystemKeyStore struct {\n\tkeys map[string][]byte\n\tprivateKeyDirectory string\n\tpublicKeyDirectory string\n\tdirectory string\n\tlock *sync.RWMutex\n\tencryptor KeyEncryptor\n}\n\nfunc NewFilesystemKeyStore(directory string, encryptor KeyEncryptor) (*FilesystemKeyStore, error) {\n\treturn NewFilesystemKeyStoreTwoPath(directory, directory, encryptor)\n}\n\nfunc NewFilesystemKeyStoreTwoPath(privateKeyFolder, publicKeyFolder string, encryptor KeyEncryptor) (*FilesystemKeyStore, error) {\n\t\/\/ check folder for private key\n\tdirectory, err := utils.AbsPath(privateKeyFolder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfi, err := os.Stat(directory)\n\tif nil == err && runtime.GOOS == \"linux\" && fi.Mode().Perm().String() != \"-rwx------\" {\n\t\tlog.Errorln(\" key store folder has an incorrect permissions\")\n\t\treturn nil, errors.New(\"key store folder has an incorrect permissions\")\n\t}\n\tif privateKeyFolder != publicKeyFolder {\n\t\t\/\/ check folder for public key\n\t\tdirectory, err = utils.AbsPath(privateKeyFolder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfi, err = os.Stat(directory)\n\t\tif nil != err && !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &FilesystemKeyStore{privateKeyDirectory: privateKeyFolder, publicKeyDirectory: publicKeyFolder,\n\t\tkeys: make(map[string][]byte), lock: &sync.RWMutex{}, encryptor: encryptor}, nil\n}\n\nfunc (store *FilesystemKeyStore) generateKeyPair(filename string, clientId []byte) (*keys.Keypair, error) {\n\tkeypair, err := keys.New(keys.KEYTYPE_EC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdirpath := filepath.Dir(store.getPrivateKeyFilePath(filename))\n\terr = os.MkdirAll(dirpath, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tencryptedPrivate, err := store.encryptor.Encrypt(keypair.Private.Value, clientId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPrivateKeyFilePath(filename), encryptedPrivate, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPublicKeyFilePath(fmt.Sprintf(\"%s.pub\", filename)), keypair.Public.Value, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn keypair, nil\n}\n\nfunc (store *FilesystemKeyStore) generateKey(filename string, length uint8) ([]byte, error) {\n\trandomBytes := make([]byte, length)\n\t_, err := rand.Read(randomBytes)\n\t\/\/ Note that err == nil only if we read len(b) bytes.\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdirpath := filepath.Dir(store.getPrivateKeyFilePath(filename))\n\terr = os.MkdirAll(dirpath, 0700)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPrivateKeyFilePath(filename), randomBytes, 0600)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn randomBytes, nil\n}\n\nfunc (store *FilesystemKeyStore) GenerateZoneKey() ([]byte, []byte, error) {\n\t\/* save private key in fs, return id and public key*\/\n\tvar id []byte\n\tfor {\n\t\t\/\/ generate until key not exists\n\t\tid = zone.GenerateZoneId()\n\t\tif !store.HasZonePrivateKey(id) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tkeypair, err := store.generateKeyPair(getZoneKeyFilename(id), id)\n\tif err != nil {\n\t\treturn []byte{}, []byte{}, err\n\t}\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\t\/\/ cache key\n\tstore.keys[getZoneKeyFilename(id)] = keypair.Private.Value\n\treturn id, keypair.Public.Value, nil\n}\n\nfunc (store *FilesystemKeyStore) getPrivateKeyFilePath(filename string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", store.privateKeyDirectory, string(os.PathSeparator), filename)\n}\n\nfunc (store *FilesystemKeyStore) getPublicKeyFilePath(filename string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", store.publicKeyDirectory, string(os.PathSeparator), filename)\n}\n\nfunc (store *FilesystemKeyStore) GetZonePrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getZoneKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) HasZonePrivateKey(id []byte) bool {\n\tif !ValidateId(id) {\n\t\treturn false\n\t}\n\t\/\/ add caching false answers. now if key doesn't exists than always checks on fs\n\t\/\/ it's system call and slow.\n\tif len(id) == 0 {\n\t\treturn false\n\t}\n\tfname := getZoneKeyFilename(id)\n\tstore.lock.RLock()\n\tdefer store.lock.RUnlock()\n\t_, ok := store.keys[fname]\n\tif ok {\n\t\treturn true\n\t}\n\texists, _ := utils.FileExists(store.getPrivateKeyFilePath(fname))\n\treturn exists\n}\n\nfunc (store *FilesystemKeyStore) GetPeerPublicKey(id []byte) (*keys.PublicKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getPublicKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PublicKey{Value: key}, nil\n\t}\n\tpublicKey, err := utils.LoadPublicKey(store.getPublicKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = publicKey.Value\n\treturn publicKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GetPrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getServerKeyFilename(id)\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GetServerDecryptionPrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getServerDecryptionKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GenerateProxyKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\tfilename := getProxyKeyFilename(id)\n\n\t_, err := store.generateKeyPair(filename, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\nfunc (store *FilesystemKeyStore) GenerateServerKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\tfilename := getServerKeyFilename(id)\n\t_, err := store.generateKeyPair(filename, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ generate key pair for data encryption\/decryption\nfunc (store *FilesystemKeyStore) GenerateDataEncryptionKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\t_, err := store.generateKeyPair(getServerDecryptionKeyFilename(id), id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ clear all cached keys\nfunc (store *FilesystemKeyStore) Reset() {\n\tstore.keys = make(map[string][]byte)\n}\n\nfunc (store *FilesystemKeyStore) GetPoisonKeyPair() (*keys.Keypair, error) {\n\tprivatePath := store.getPrivateKeyFilePath(POISON_KEY_FILENAME)\n\tpublicPath := store.getPublicKeyFilePath(fmt.Sprintf(\"%s.pub\", POISON_KEY_FILENAME))\n\tprivateExists, err := utils.FileExists(privatePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicExists, err := utils.FileExists(publicPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateExists && publicExists {\n\t\tprivate, err := utils.LoadPrivateKey(privatePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif private.Value, err = store.encryptor.Decrypt(private.Value, []byte(POISON_KEY_FILENAME)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpublic, err := utils.LoadPublicKey(publicPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &keys.Keypair{Public: public, Private: private}, nil\n\t}\n\tlog.Infoln(\"Generate poison key pair\")\n\treturn store.generateKeyPair(POISON_KEY_FILENAME, []byte(POISON_KEY_FILENAME))\n}\n\nfunc (store *FilesystemKeyStore) GetAuthKey(remove bool) ([]byte, error) {\n\tkeyPath := store.getPrivateKeyFilePath(BASIC_AUTH_KEY_FILENAME)\n\tkeyExists, err := utils.FileExists(keyPath)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tif keyExists && !remove {\n\t\tkey, err := utils.ReadFile(keyPath)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\treturn key, nil\n\t}\n\tlog.Infof(\"Generate basic auth key for AcraConfigUI to %v\", keyPath)\n\treturn store.generateKey(BASIC_AUTH_KEY_FILENAME, BASIC_AUTH_KEY_LENGTH)\n}\ncreate dir if not exists for public keys (#148)package keystore\n\nimport (\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/cossacklabs\/acra\/utils\"\n\t\"github.com\/cossacklabs\/acra\/zone\"\n\t\"github.com\/cossacklabs\/themis\/gothemis\/keys\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sync\"\n)\n\ntype FilesystemKeyStore struct {\n\tkeys map[string][]byte\n\tprivateKeyDirectory string\n\tpublicKeyDirectory string\n\tdirectory string\n\tlock *sync.RWMutex\n\tencryptor KeyEncryptor\n}\n\nfunc NewFilesystemKeyStore(directory string, encryptor KeyEncryptor) (*FilesystemKeyStore, error) {\n\treturn NewFilesystemKeyStoreTwoPath(directory, directory, encryptor)\n}\n\nfunc NewFilesystemKeyStoreTwoPath(privateKeyFolder, publicKeyFolder string, encryptor KeyEncryptor) (*FilesystemKeyStore, error) {\n\t\/\/ check folder for private key\n\tdirectory, err := utils.AbsPath(privateKeyFolder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfi, err := os.Stat(directory)\n\tif nil == err && runtime.GOOS == \"linux\" && fi.Mode().Perm().String() != \"-rwx------\" {\n\t\tlog.Errorln(\" key store folder has an incorrect permissions\")\n\t\treturn nil, errors.New(\"key store folder has an incorrect permissions\")\n\t}\n\tif privateKeyFolder != publicKeyFolder {\n\t\t\/\/ check folder for public key\n\t\tdirectory, err = utils.AbsPath(privateKeyFolder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfi, err = os.Stat(directory)\n\t\tif nil != err && !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &FilesystemKeyStore{privateKeyDirectory: privateKeyFolder, publicKeyDirectory: publicKeyFolder,\n\t\tkeys: make(map[string][]byte), lock: &sync.RWMutex{}, encryptor: encryptor}, nil\n}\n\nfunc (store *FilesystemKeyStore) generateKeyPair(filename string, clientId []byte) (*keys.Keypair, error) {\n\tkeypair, err := keys.New(keys.KEYTYPE_EC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateKeysFolder := filepath.Dir(store.getPrivateKeyFilePath(filename))\n\terr = os.MkdirAll(privateKeysFolder, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpublicKeysFolder := filepath.Dir(store.getPublicKeyFilePath(filename))\n\terr = os.MkdirAll(publicKeysFolder, 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tencryptedPrivate, err := store.encryptor.Encrypt(keypair.Private.Value, clientId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPrivateKeyFilePath(filename), encryptedPrivate, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPublicKeyFilePath(fmt.Sprintf(\"%s.pub\", filename)), keypair.Public.Value, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn keypair, nil\n}\n\nfunc (store *FilesystemKeyStore) generateKey(filename string, length uint8) ([]byte, error) {\n\trandomBytes := make([]byte, length)\n\t_, err := rand.Read(randomBytes)\n\t\/\/ Note that err == nil only if we read len(b) bytes.\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdirpath := filepath.Dir(store.getPrivateKeyFilePath(filename))\n\terr = os.MkdirAll(dirpath, 0700)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(store.getPrivateKeyFilePath(filename), randomBytes, 0600)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn randomBytes, nil\n}\n\nfunc (store *FilesystemKeyStore) GenerateZoneKey() ([]byte, []byte, error) {\n\t\/* save private key in fs, return id and public key*\/\n\tvar id []byte\n\tfor {\n\t\t\/\/ generate until key not exists\n\t\tid = zone.GenerateZoneId()\n\t\tif !store.HasZonePrivateKey(id) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tkeypair, err := store.generateKeyPair(getZoneKeyFilename(id), id)\n\tif err != nil {\n\t\treturn []byte{}, []byte{}, err\n\t}\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\t\/\/ cache key\n\tstore.keys[getZoneKeyFilename(id)] = keypair.Private.Value\n\treturn id, keypair.Public.Value, nil\n}\n\nfunc (store *FilesystemKeyStore) getPrivateKeyFilePath(filename string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", store.privateKeyDirectory, string(os.PathSeparator), filename)\n}\n\nfunc (store *FilesystemKeyStore) getPublicKeyFilePath(filename string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", store.publicKeyDirectory, string(os.PathSeparator), filename)\n}\n\nfunc (store *FilesystemKeyStore) GetZonePrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getZoneKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) HasZonePrivateKey(id []byte) bool {\n\tif !ValidateId(id) {\n\t\treturn false\n\t}\n\t\/\/ add caching false answers. now if key doesn't exists than always checks on fs\n\t\/\/ it's system call and slow.\n\tif len(id) == 0 {\n\t\treturn false\n\t}\n\tfname := getZoneKeyFilename(id)\n\tstore.lock.RLock()\n\tdefer store.lock.RUnlock()\n\t_, ok := store.keys[fname]\n\tif ok {\n\t\treturn true\n\t}\n\texists, _ := utils.FileExists(store.getPrivateKeyFilePath(fname))\n\treturn exists\n}\n\nfunc (store *FilesystemKeyStore) GetPeerPublicKey(id []byte) (*keys.PublicKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getPublicKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PublicKey{Value: key}, nil\n\t}\n\tpublicKey, err := utils.LoadPublicKey(store.getPublicKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = publicKey.Value\n\treturn publicKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GetPrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getServerKeyFilename(id)\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GetServerDecryptionPrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tif !ValidateId(id) {\n\t\treturn nil, ErrInvalidClientId\n\t}\n\tfname := getServerDecryptionKeyFilename(id)\n\tstore.lock.Lock()\n\tdefer store.lock.Unlock()\n\tkey, ok := store.keys[fname]\n\tif ok {\n\t\tlog.Debugf(\"load cached key: %s\", fname)\n\t\treturn &keys.PrivateKey{Value: key}, nil\n\t}\n\tprivateKey, err := utils.LoadPrivateKey(store.getPrivateKeyFilePath(fname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateKey.Value, err = store.encryptor.Decrypt(privateKey.Value, id); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"load key from fs: %s\", fname)\n\tstore.keys[fname] = privateKey.Value\n\treturn privateKey, nil\n}\n\nfunc (store *FilesystemKeyStore) GenerateProxyKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\tfilename := getProxyKeyFilename(id)\n\n\t_, err := store.generateKeyPair(filename, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\nfunc (store *FilesystemKeyStore) GenerateServerKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\tfilename := getServerKeyFilename(id)\n\t_, err := store.generateKeyPair(filename, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ generate key pair for data encryption\/decryption\nfunc (store *FilesystemKeyStore) GenerateDataEncryptionKeys(id []byte) error {\n\tif !ValidateId(id) {\n\t\treturn ErrInvalidClientId\n\t}\n\t_, err := store.generateKeyPair(getServerDecryptionKeyFilename(id), id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ clear all cached keys\nfunc (store *FilesystemKeyStore) Reset() {\n\tstore.keys = make(map[string][]byte)\n}\n\nfunc (store *FilesystemKeyStore) GetPoisonKeyPair() (*keys.Keypair, error) {\n\tprivatePath := store.getPrivateKeyFilePath(POISON_KEY_FILENAME)\n\tpublicPath := store.getPublicKeyFilePath(fmt.Sprintf(\"%s.pub\", POISON_KEY_FILENAME))\n\tprivateExists, err := utils.FileExists(privatePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublicExists, err := utils.FileExists(publicPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif privateExists && publicExists {\n\t\tprivate, err := utils.LoadPrivateKey(privatePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif private.Value, err = store.encryptor.Decrypt(private.Value, []byte(POISON_KEY_FILENAME)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpublic, err := utils.LoadPublicKey(publicPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &keys.Keypair{Public: public, Private: private}, nil\n\t}\n\tlog.Infoln(\"Generate poison key pair\")\n\treturn store.generateKeyPair(POISON_KEY_FILENAME, []byte(POISON_KEY_FILENAME))\n}\n\nfunc (store *FilesystemKeyStore) GetAuthKey(remove bool) ([]byte, error) {\n\tkeyPath := store.getPrivateKeyFilePath(BASIC_AUTH_KEY_FILENAME)\n\tkeyExists, err := utils.FileExists(keyPath)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tif keyExists && !remove {\n\t\tkey, err := utils.ReadFile(keyPath)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\treturn key, nil\n\t}\n\tlog.Infof(\"Generate basic auth key for AcraConfigUI to %v\", keyPath)\n\treturn store.generateKey(BASIC_AUTH_KEY_FILENAME, BASIC_AUTH_KEY_LENGTH)\n}\n<|endoftext|>"} {"text":"package indicators\n\nimport (\n\t\"errors\"\n\t\"github.com\/thetruetrade\/gotrade\"\n)\n\n\/\/ A Relative Strength Indicator (Rsi), no storage, for use in other indicators\ntype RsiWithoutStorage struct {\n\t*baseIndicator\n\t*baseFloatBounds\n\n\t\/\/ private variables\n\tvalueAvailableAction ValueAvailableActionFloat\n\tperiodCounter int\n\tpreviousClose float64\n\tpreviousGain float64\n\tpreviousLoss float64\n\ttimePeriod int\n}\n\n\/\/ NewRsiWithoutStorage creates a Relative Strength Indicator (Rsi) without storage\nfunc NewRsiWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *RsiWithoutStorage, err error) {\n\n\t\/\/ an indicator without storage MUST have a value available action\n\tif valueAvailableAction == nil {\n\t\treturn nil, ErrValueAvailableActionIsNil\n\t}\n\n\t\/\/ the minimum timeperiod for this indicator is 2\n\tif timePeriod < 2 {\n\t\treturn nil, errors.New(\"timePeriod is less than the minimum (2)\")\n\t}\n\n\t\/\/ check the maximum timeperiod\n\tif timePeriod > MaximumLookbackPeriod {\n\t\treturn nil, errors.New(\"timePeriod is greater than the maximum (100000)\")\n\t}\n\n\tlookback := timePeriod\n\tind := RsiWithoutStorage{\n\t\tbaseIndicator: newBaseIndicator(lookback),\n\t\tbaseFloatBounds: newBaseFloatBounds(),\n\t\tperiodCounter: (timePeriod * -1) - 1,\n\t\tpreviousClose: 0.0,\n\t\tpreviousGain: 0.0,\n\t\tpreviousLoss: 0.0,\n\t\tvalueAvailableAction: valueAvailableAction,\n\t\ttimePeriod: timePeriod,\n\t}\n\n\treturn &ind, err\n}\n\n\/\/ A Relative Strength Indicator (Rsi)\ntype Rsi struct {\n\t*RsiWithoutStorage\n\tselectData gotrade.DataSelectionFunc\n\n\t\/\/ public variables\n\tData []float64\n}\n\n\/\/ NewRsi creates a Relative Strength Indicator (Rsi) for online usage\nfunc NewRsi(timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind := Rsi{selectData: selectData}\n\tind.RsiWithoutStorage, err = NewRsiWithoutStorage(timePeriod,\n\t\tfunc(dataItem float64, streamBarIndex int) {\n\t\t\tind.Data = append(ind.Data, dataItem)\n\t\t})\n\n\treturn &ind, err\n}\n\n\/\/ NewDefaultRsi creates a Relative Strength Indicator (Rsi) for online usage with default parameters\n\/\/\t- timePeriod: 14\nfunc NewDefaultRsi() (indicator *Rsi, err error) {\n\ttimePeriod := 14\n\treturn NewRsi(timePeriod, gotrade.UseClosePrice)\n}\n\n\/\/ NewRsiWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage\nfunc NewRsiWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsi(timePeriod, selectData)\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with default parameters\nfunc NewDefaultRsiWithSrcLen(sourceLength uint) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsi()\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewRsiForStream creates a Relative Strength Indicator (Rsi) for online usage with a source data stream\nfunc NewRsiForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsi(timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiForStream creates a Relative Strength Indicator (Rsi) for online usage with a source data stream\nfunc NewDefaultRsiForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsi()\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewRsiForStreamWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with a source data stream\nfunc NewRsiForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsiWithSrcLen(sourceLength, timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiForStreamWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with a source data stream\nfunc NewDefaultRsiForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsiWithSrcLen(sourceLength)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ ReceiveDOHLCVTick consumes a source data DOHLCV price tick\nfunc (ind *Rsi) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) {\n\tvar selectedData = ind.selectData(tickData)\n\tind.ReceiveTick(selectedData, streamBarIndex)\n}\n\nfunc (ind *RsiWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) {\n\tind.periodCounter += 1\n\n\tif ind.periodCounter > ind.timePeriod*-1 {\n\n\t\tif ind.periodCounter <= 0 {\n\n\t\t\tif tickData > ind.previousClose {\n\t\t\t\tind.previousGain += (tickData - ind.previousClose)\n\t\t\t} else {\n\t\t\t\tind.previousLoss -= (tickData - ind.previousClose)\n\t\t\t}\n\t\t}\n\n\t\tif ind.periodCounter == 0 {\n\t\t\tind.previousGain \/= float64(ind.timePeriod)\n\t\t\tind.previousLoss \/= float64(ind.timePeriod)\n\n\t\t\t\/\/ increment the number of results this indicator can be expected to return\n\t\t\tind.dataLength += 1\n\t\t\tif ind.validFromBar == -1 {\n\t\t\t\t\/\/ set the streamBarIndex from which this indicator returns valid results\n\t\t\t\tind.validFromBar = streamBarIndex\n\t\t\t}\n\n\t\t\tvar result float64\n\t\t\t\/\/ Rsi = 100 * (prevGain\/(prevGain+prevLoss))\n\t\t\tif ind.previousGain+ind.previousLoss == 0.0 {\n\t\t\t\tresult = 0.0\n\t\t\t} else {\n\t\t\t\tresult = 100.0 * (ind.previousGain \/ (ind.previousGain + ind.previousLoss))\n\t\t\t}\n\n\t\t\t\/\/ update the maximum result value\n\t\t\tif result > ind.maxValue {\n\t\t\t\tind.maxValue = result\n\t\t\t}\n\n\t\t\t\/\/ update the minimum result value\n\t\t\tif result < ind.minValue {\n\t\t\t\tind.minValue = result\n\t\t\t}\n\n\t\t\t\/\/ notify of a new result value though the value available action\n\t\t\tind.valueAvailableAction(result, streamBarIndex)\n\t\t}\n\n\t\tif ind.periodCounter > 0 {\n\t\t\tind.previousGain *= float64(ind.timePeriod - 1)\n\t\t\tind.previousLoss *= float64(ind.timePeriod - 1)\n\n\t\t\tif tickData > ind.previousClose {\n\t\t\t\tind.previousGain += (tickData - ind.previousClose)\n\t\t\t} else {\n\t\t\t\tind.previousLoss -= (tickData - ind.previousClose)\n\t\t\t}\n\n\t\t\tind.previousGain \/= float64(ind.timePeriod)\n\t\t\tind.previousLoss \/= float64(ind.timePeriod)\n\n\t\t\t\/\/ increment the number of results this indicator can be expected to return\n\t\t\tind.dataLength += 1\n\n\t\t\tvar result float64\n\t\t\t\/\/ Rsi = 100 * (prevGain\/(prevGain+prevLoss))\n\t\t\tif ind.previousGain+ind.previousLoss == 0.0 {\n\t\t\t\tresult = 0.0\n\t\t\t} else {\n\t\t\t\tresult = 100.0 * (ind.previousGain \/ (ind.previousGain + ind.previousLoss))\n\t\t\t}\n\n\t\t\t\/\/ update the maximum result value\n\t\t\tif result > ind.maxValue {\n\t\t\t\tind.maxValue = result\n\t\t\t}\n\n\t\t\t\/\/ update the minimum result value\n\t\t\tif result < ind.minValue {\n\t\t\t\tind.minValue = result\n\t\t\t}\n\n\t\t\t\/\/ notify of a new result value though the value available action\n\t\t\tind.valueAvailableAction(result, streamBarIndex)\n\t\t}\n\t}\n\tind.previousClose = tickData\n}\n#76 Remove duplication - rsipackage indicators\n\nimport (\n\t\"errors\"\n\t\"github.com\/thetruetrade\/gotrade\"\n)\n\n\/\/ A Relative Strength Indicator (Rsi), no storage, for use in other indicators\ntype RsiWithoutStorage struct {\n\t*baseIndicatorWithFloatBounds\n\n\t\/\/ private variables\n\tperiodCounter int\n\tpreviousClose float64\n\tpreviousGain float64\n\tpreviousLoss float64\n\ttimePeriod int\n}\n\n\/\/ NewRsiWithoutStorage creates a Relative Strength Indicator (Rsi) without storage\nfunc NewRsiWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *RsiWithoutStorage, err error) {\n\n\t\/\/ an indicator without storage MUST have a value available action\n\tif valueAvailableAction == nil {\n\t\treturn nil, ErrValueAvailableActionIsNil\n\t}\n\n\t\/\/ the minimum timeperiod for this indicator is 2\n\tif timePeriod < 2 {\n\t\treturn nil, errors.New(\"timePeriod is less than the minimum (2)\")\n\t}\n\n\t\/\/ check the maximum timeperiod\n\tif timePeriod > MaximumLookbackPeriod {\n\t\treturn nil, errors.New(\"timePeriod is greater than the maximum (100000)\")\n\t}\n\n\tlookback := timePeriod\n\tind := RsiWithoutStorage{\n\t\tbaseIndicatorWithFloatBounds: newBaseIndicatorWithFloatBounds(lookback, valueAvailableAction),\n\t\tperiodCounter: (timePeriod * -1) - 1,\n\t\tpreviousClose: 0.0,\n\t\tpreviousGain: 0.0,\n\t\tpreviousLoss: 0.0,\n\t\ttimePeriod: timePeriod,\n\t}\n\n\treturn &ind, err\n}\n\n\/\/ A Relative Strength Indicator (Rsi)\ntype Rsi struct {\n\t*RsiWithoutStorage\n\tselectData gotrade.DataSelectionFunc\n\n\t\/\/ public variables\n\tData []float64\n}\n\n\/\/ NewRsi creates a Relative Strength Indicator (Rsi) for online usage\nfunc NewRsi(timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind := Rsi{selectData: selectData}\n\tind.RsiWithoutStorage, err = NewRsiWithoutStorage(timePeriod,\n\t\tfunc(dataItem float64, streamBarIndex int) {\n\t\t\tind.Data = append(ind.Data, dataItem)\n\t\t})\n\n\treturn &ind, err\n}\n\n\/\/ NewDefaultRsi creates a Relative Strength Indicator (Rsi) for online usage with default parameters\n\/\/\t- timePeriod: 14\nfunc NewDefaultRsi() (indicator *Rsi, err error) {\n\ttimePeriod := 14\n\treturn NewRsi(timePeriod, gotrade.UseClosePrice)\n}\n\n\/\/ NewRsiWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage\nfunc NewRsiWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsi(timePeriod, selectData)\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with default parameters\nfunc NewDefaultRsiWithSrcLen(sourceLength uint) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsi()\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewRsiForStream creates a Relative Strength Indicator (Rsi) for online usage with a source data stream\nfunc NewRsiForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsi(timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiForStream creates a Relative Strength Indicator (Rsi) for online usage with a source data stream\nfunc NewDefaultRsiForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsi()\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewRsiForStreamWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with a source data stream\nfunc NewRsiForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Rsi, err error) {\n\tind, err := NewRsiWithSrcLen(sourceLength, timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRsiForStreamWithSrcLen creates a Relative Strength Indicator (Rsi) for offline usage with a source data stream\nfunc NewDefaultRsiForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Rsi, err error) {\n\tind, err := NewDefaultRsiWithSrcLen(sourceLength)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ ReceiveDOHLCVTick consumes a source data DOHLCV price tick\nfunc (ind *Rsi) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) {\n\tvar selectedData = ind.selectData(tickData)\n\tind.ReceiveTick(selectedData, streamBarIndex)\n}\n\nfunc (ind *RsiWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) {\n\tind.periodCounter += 1\n\n\tif ind.periodCounter > ind.timePeriod*-1 {\n\n\t\tif ind.periodCounter <= 0 {\n\n\t\t\tif tickData > ind.previousClose {\n\t\t\t\tind.previousGain += (tickData - ind.previousClose)\n\t\t\t} else {\n\t\t\t\tind.previousLoss -= (tickData - ind.previousClose)\n\t\t\t}\n\t\t}\n\n\t\tif ind.periodCounter == 0 {\n\t\t\tind.previousGain \/= float64(ind.timePeriod)\n\t\t\tind.previousLoss \/= float64(ind.timePeriod)\n\n\t\t\tvar result float64\n\t\t\t\/\/ Rsi = 100 * (prevGain\/(prevGain+prevLoss))\n\t\t\tif ind.previousGain+ind.previousLoss == 0.0 {\n\t\t\t\tresult = 0.0\n\t\t\t} else {\n\t\t\t\tresult = 100.0 * (ind.previousGain \/ (ind.previousGain + ind.previousLoss))\n\t\t\t}\n\n\t\t\tind.UpdateIndicatorWithNewValue(result, streamBarIndex)\n\t\t}\n\n\t\tif ind.periodCounter > 0 {\n\t\t\tind.previousGain *= float64(ind.timePeriod - 1)\n\t\t\tind.previousLoss *= float64(ind.timePeriod - 1)\n\n\t\t\tif tickData > ind.previousClose {\n\t\t\t\tind.previousGain += (tickData - ind.previousClose)\n\t\t\t} else {\n\t\t\t\tind.previousLoss -= (tickData - ind.previousClose)\n\t\t\t}\n\n\t\t\tind.previousGain \/= float64(ind.timePeriod)\n\t\t\tind.previousLoss \/= float64(ind.timePeriod)\n\n\t\t\tvar result float64\n\t\t\t\/\/ Rsi = 100 * (prevGain\/(prevGain+prevLoss))\n\t\t\tif ind.previousGain+ind.previousLoss == 0.0 {\n\t\t\t\tresult = 0.0\n\t\t\t} else {\n\t\t\t\tresult = 100.0 * (ind.previousGain \/ (ind.previousGain + ind.previousLoss))\n\t\t\t}\n\n\t\t\tind.UpdateIndicatorWithNewValue(result, streamBarIndex)\n\t\t}\n\t}\n\tind.previousClose = tickData\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n)\n\n\/\/ Message to send to other nodes\ntype BinaryTransportMessage struct {\n\tVersion uint32 \/\/ Message format (e.g. 1)\n\tType BinaryTransportMessageType \/\/ Sort message\n\tLen uint32 \/\/ Length of data\n\tData []byte \/\/ Actual data\n}\n\n\/\/ This version\nconst BINARY_TRANSPORT_MESSAGE_VERSION uint32 = 1\n\n\/\/ Message type\ntype BinaryTransportMessageType uint32\n\n\/\/ Message types\nconst (\n\tEmptyBinaryTransportMessageType BinaryTransportMessageType = iota \/\/ 0 = not set\n\tShardIdxBinaryTransportMessageType \/\/ 1 = shard index\n\tFileBinaryTransportMessageType \/\/ 2 = file\n\tCreateShardBinaryTransportMessageType \/\/ 3 = create shard (replication)\n)\n\n\/\/ To bytes\nfunc (this *BinaryTransportMessage) Bytes() []byte {\n\tif this.Type < 1 || this.Len < 1 {\n\t\tpanic(\"Can not convert empty message to bytes\")\n\t}\n\tbuf := new(bytes.Buffer)\n\tbinary.Write(buf, binary.BigEndian, this.Version) \/\/ meta version\n\tbinary.Write(buf, binary.BigEndian, this.Type) \/\/ type\n\tbinary.Write(buf, binary.BigEndian, this.Len) \/\/ data length\n\tif this.Data != nil {\n\t\tbuf.Write(this.Data)\n\t}\n\treturn buf.Bytes()\n}\n\n\/\/ From bytes\nfunc (this *BinaryTransportMessage) FromBytes(b []byte) {\n\tbuf := bytes.NewReader(b)\n\tvar err error\n\terr = binary.Read(buf, binary.BigEndian, &this.Version) \/\/ meta version\n\tpanicErr(err)\n\terr = binary.Read(buf, binary.BigEndian, &this.Type) \/\/ type\n\tpanicErr(err)\n\terr = binary.Read(buf, binary.BigEndian, &this.Len) \/\/ length\n\tpanicErr(err)\n\n\t\/\/ Read data\n\tthis.Data = make([]byte, this.Len)\n\tbuf.Read(this.Data)\n}\n\n\/\/ New message\nfunc newBinaryTransportMessage(t BinaryTransportMessageType, data []byte) *BinaryTransportMessage {\n\tvar l uint32 = 0\n\tif data != nil {\n\t\tl = uint32(len(data))\n\t}\n\treturn &BinaryTransportMessage{\n\t\tVersion: BINARY_TRANSPORT_MESSAGE_VERSION,\n\t\tType: t,\n\t\tLen: l,\n\t\tData: data,\n\t}\n}\nUpdate commentpackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n)\n\n\/\/ Message to send to other nodes\ntype BinaryTransportMessage struct {\n\tVersion uint32 \/\/ Message format (e.g. 1)\n\tType BinaryTransportMessageType \/\/ Sort message\n\tLen uint32 \/\/ Length of data\n\tData []byte \/\/ Actual data\n}\n\n\/\/ This version\nconst BINARY_TRANSPORT_MESSAGE_VERSION uint32 = 1\n\n\/\/ Message type\ntype BinaryTransportMessageType uint32\n\n\/\/ Message types\nconst (\n\tEmptyBinaryTransportMessageType BinaryTransportMessageType = iota \/\/ 0 = not set\n\tShardIdxBinaryTransportMessageType \/\/ 1 = shard index\n\tFileBinaryTransportMessageType \/\/ 2 = file binary transport\n\tCreateShardBinaryTransportMessageType \/\/ 3 = create shard (replication)\n)\n\n\/\/ To bytes\nfunc (this *BinaryTransportMessage) Bytes() []byte {\n\tif this.Type < 1 || this.Len < 1 {\n\t\tpanic(\"Can not convert empty message to bytes\")\n\t}\n\tbuf := new(bytes.Buffer)\n\tbinary.Write(buf, binary.BigEndian, this.Version) \/\/ meta version\n\tbinary.Write(buf, binary.BigEndian, this.Type) \/\/ type\n\tbinary.Write(buf, binary.BigEndian, this.Len) \/\/ data length\n\tif this.Data != nil {\n\t\tbuf.Write(this.Data)\n\t}\n\treturn buf.Bytes()\n}\n\n\/\/ From bytes\nfunc (this *BinaryTransportMessage) FromBytes(b []byte) {\n\tbuf := bytes.NewReader(b)\n\tvar err error\n\terr = binary.Read(buf, binary.BigEndian, &this.Version) \/\/ meta version\n\tpanicErr(err)\n\terr = binary.Read(buf, binary.BigEndian, &this.Type) \/\/ type\n\tpanicErr(err)\n\terr = binary.Read(buf, binary.BigEndian, &this.Len) \/\/ length\n\tpanicErr(err)\n\n\t\/\/ Read data\n\tthis.Data = make([]byte, this.Len)\n\tbuf.Read(this.Data)\n}\n\n\/\/ New message\nfunc newBinaryTransportMessage(t BinaryTransportMessageType, data []byte) *BinaryTransportMessage {\n\tvar l uint32 = 0\n\tif data != nil {\n\t\tl = uint32(len(data))\n\t}\n\treturn &BinaryTransportMessage{\n\t\tVersion: BINARY_TRANSPORT_MESSAGE_VERSION,\n\t\tType: t,\n\t\tLen: l,\n\t\tData: data,\n\t}\n}\n<|endoftext|>"} {"text":"package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsSpotInstanceRequest() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSpotInstanceRequestCreate,\n\t\tRead: resourceAwsSpotInstanceRequestRead,\n\t\tDelete: resourceAwsSpotInstanceRequestDelete,\n\t\tUpdate: resourceAwsSpotInstanceRequestUpdate,\n\n\t\tSchema: func() map[string]*schema.Schema {\n\t\t\t\/\/ The Spot Instance Request Schema is based on the AWS Instance schema.\n\t\t\ts := resourceAwsInstance().Schema\n\n\t\t\t\/\/ Everything on a spot instance is ForceNew except tags\n\t\t\tfor k, v := range s {\n\t\t\t\tif k == \"tags\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tv.ForceNew = true\n\t\t\t}\n\n\t\t\ts[\"spot_price\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t}\n\t\t\ts[\"spot_type\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"persistent\",\n\t\t\t}\n\t\t\ts[\"wait_for_fulfillment\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: false,\n\t\t\t}\n\t\t\ts[\"spot_bid_status\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\t\t\ts[\"spot_request_state\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\t\t\ts[\"spot_instance_id\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\n\t\t\treturn s\n\t\t}(),\n\t}\n}\n\nfunc resourceAwsSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tinstanceOpts, err := buildAwsInstanceOpts(d, meta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspotOpts := &ec2.RequestSpotInstancesInput{\n\t\tSpotPrice: aws.String(d.Get(\"spot_price\").(string)),\n\t\tType: aws.String(d.Get(\"spot_type\").(string)),\n\n\t\t\/\/ Though the AWS API supports creating spot instance requests for multiple\n\t\t\/\/ instances, for TF purposes we fix this to one instance per request.\n\t\t\/\/ Users can get equivalent behavior out of TF's \"count\" meta-parameter.\n\t\tInstanceCount: aws.Int64(1),\n\n\t\tLaunchSpecification: &ec2.RequestSpotLaunchSpecification{\n\t\t\tBlockDeviceMappings: instanceOpts.BlockDeviceMappings,\n\t\t\tEbsOptimized: instanceOpts.EBSOptimized,\n\t\t\tMonitoring: instanceOpts.Monitoring,\n\t\t\tIamInstanceProfile: instanceOpts.IAMInstanceProfile,\n\t\t\tImageId: instanceOpts.ImageID,\n\t\t\tInstanceType: instanceOpts.InstanceType,\n\t\t\tKeyName: instanceOpts.KeyName,\n\t\t\tPlacement: instanceOpts.SpotPlacement,\n\t\t\tSecurityGroupIds: instanceOpts.SecurityGroupIDs,\n\t\t\tSecurityGroups: instanceOpts.SecurityGroups,\n\t\t\tSubnetId: instanceOpts.SubnetID,\n\t\t\tUserData: instanceOpts.UserData64,\n\t\t},\n\t}\n\n\t\/\/ If the instance is configured with a Network Interface (a subnet, has\n\t\/\/ public IP, etc), then the instanceOpts.SecurityGroupIds and SubnetId will\n\t\/\/ be nil\n\tif len(instanceOpts.NetworkInterfaces) > 0 {\n\t\tspotOpts.LaunchSpecification.SecurityGroupIds = instanceOpts.NetworkInterfaces[0].Groups\n\t\tspotOpts.LaunchSpecification.SubnetId = instanceOpts.NetworkInterfaces[0].SubnetId\n\t}\n\n\t\/\/ Make the spot instance request\n\tlog.Printf(\"[DEBUG] Requesting spot bid opts: %s\", spotOpts)\n\tresp, err := conn.RequestSpotInstances(spotOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error requesting spot instances: %s\", err)\n\t}\n\tif len(resp.SpotInstanceRequests) != 1 {\n\t\treturn fmt.Errorf(\n\t\t\t\"Expected response with length 1, got: %s\", resp)\n\t}\n\n\tsir := *resp.SpotInstanceRequests[0]\n\td.SetId(*sir.SpotInstanceRequestId)\n\n\tif d.Get(\"wait_for_fulfillment\").(bool) {\n\t\tspotStateConf := &resource.StateChangeConf{\n\t\t\t\/\/ http:\/\/docs.aws.amazon.com\/AWSEC2\/latest\/UserGuide\/spot-bid-status.html\n\t\t\tPending: []string{\"start\", \"pending-evaluation\", \"pending-fulfillment\"},\n\t\t\tTarget: \"fulfilled\",\n\t\t\tRefresh: SpotInstanceStateRefreshFunc(conn, sir),\n\t\t\tTimeout: 10 * time.Minute,\n\t\t\tDelay: 10 * time.Second,\n\t\t\tMinTimeout: 3 * time.Second,\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] waiting for spot bid to resolve... this may take several minutes.\")\n\t\t_, err = spotStateConf.WaitForState()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while waiting for spot request (%s) to resolve: %s\", sir, err)\n\t\t}\n\t}\n\n\treturn resourceAwsSpotInstanceRequestUpdate(d, meta)\n}\n\n\/\/ Update spot state, etc\nfunc resourceAwsSpotInstanceRequestRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\treq := &ec2.DescribeSpotInstanceRequestsInput{\n\t\tSpotInstanceRequestIds: []*string{aws.String(d.Id())},\n\t}\n\tresp, err := conn.DescribeSpotInstanceRequests(req)\n\n\tif err != nil {\n\t\t\/\/ If the spot request was not found, return nil so that we can show\n\t\t\/\/ that it is gone.\n\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidSpotInstanceRequestID.NotFound\" {\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.SpotInstanceRequests) == 0 {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\trequest := resp.SpotInstanceRequests[0]\n\n\t\/\/ if the request is cancelled, then it is gone\n\tif *request.State == \"cancelled\" {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\td.Set(\"spot_bid_status\", *request.Status.Code)\n\t\/\/ Instance ID is not set if the request is still pending\n\tif request.InstanceId != nil {\n\t\td.Set(\"spot_instance_id\", *request.InstanceId)\n\t\tif err := readInstance(d, meta); err != nil {\n\t\t\treturn fmt.Errorf(\"[ERR] Error reading Spot Instance Data: %s\", err)\n\t\t}\n\t}\n\td.Set(\"spot_request_state\", *request.State)\n\td.Set(\"tags\", tagsToMap(request.Tags))\n\n\t\/\/ return nil\n\t\/\/ let's read the instance data...\n\treturn readInstance(d, meta)\n}\n\nfunc readInstance(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tresp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{aws.String(d.Get(\"spot_instance_id\").(string))},\n\t})\n\tif err != nil {\n\t\t\/\/ If the instance was not found, return nil so that we can show\n\t\t\/\/ that the instance is gone.\n\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidInstanceID.NotFound\" {\n\t\t\treturn fmt.Errorf(\"no instance found\")\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.Reservations) == 0 {\n\t\treturn fmt.Errorf(\"no instances found\")\n\t}\n\n\tinstance := resp.Reservations[0].Instances[0]\n\n\t\/\/ Set these fields for connection information\n\tif instance != nil {\n\t\td.Set(\"public_dns\", instance.PublicDnsName)\n\t\td.Set(\"public_ip\", instance.PublicIpAddress)\n\t\td.Set(\"private_dns\", instance.PrivateDnsName)\n\t\td.Set(\"private_ip\", instance.PrivateIpAddress)\n\t}\n\n\t\/\/ set connection information\n\tif instance.PublicIpAddress != nil {\n\t\td.SetConnInfo(map[string]string{\n\t\t\t\"type\": \"ssh\",\n\t\t\t\"host\": *instance.PublicIpAddress,\n\t\t})\n\t} else if instance.PrivateIpAddress != nil {\n\t\td.SetConnInfo(map[string]string{\n\t\t\t\"type\": \"ssh\",\n\t\t\t\"host\": *instance.PrivateIpAddress,\n\t\t})\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSpotInstanceRequestUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\td.Partial(true)\n\tif err := setTags(conn, d); err != nil {\n\t\treturn err\n\t} else {\n\t\td.SetPartial(\"tags\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsSpotInstanceRequestRead(d, meta)\n}\n\nfunc resourceAwsSpotInstanceRequestDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tlog.Printf(\"[INFO] Cancelling spot request: %s\", d.Id())\n\t_, err := conn.CancelSpotInstanceRequests(&ec2.CancelSpotInstanceRequestsInput{\n\t\tSpotInstanceRequestIds: []*string{aws.String(d.Id())},\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error cancelling spot request (%s): %s\", d.Id(), err)\n\t}\n\n\tif instanceId := d.Get(\"spot_instance_id\").(string); instanceId != \"\" {\n\t\tlog.Printf(\"[INFO] Terminating instance: %s\", instanceId)\n\t\tif err := awsTerminateInstance(conn, instanceId); err != nil {\n\t\t\treturn fmt.Errorf(\"Error terminating spot instance: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SpotInstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch\n\/\/ an EC2 spot instance request\nfunc SpotInstanceStateRefreshFunc(\n\tconn *ec2.EC2, sir ec2.SpotInstanceRequest) resource.StateRefreshFunc {\n\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.DescribeSpotInstanceRequests(&ec2.DescribeSpotInstanceRequestsInput{\n\t\t\tSpotInstanceRequestIds: []*string{sir.SpotInstanceRequestId},\n\t\t})\n\n\t\tif err != nil {\n\t\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidSpotInstanceRequestID.NotFound\" {\n\t\t\t\t\/\/ Set this to nil as if we didn't find anything.\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on StateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil || len(resp.SpotInstanceRequests) == 0 {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our request yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\treq := resp.SpotInstanceRequests[0]\n\t\treturn req, *req.Status.Code, nil\n\t}\n}\nminor tweaks to connection info setuppackage aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsSpotInstanceRequest() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSpotInstanceRequestCreate,\n\t\tRead: resourceAwsSpotInstanceRequestRead,\n\t\tDelete: resourceAwsSpotInstanceRequestDelete,\n\t\tUpdate: resourceAwsSpotInstanceRequestUpdate,\n\n\t\tSchema: func() map[string]*schema.Schema {\n\t\t\t\/\/ The Spot Instance Request Schema is based on the AWS Instance schema.\n\t\t\ts := resourceAwsInstance().Schema\n\n\t\t\t\/\/ Everything on a spot instance is ForceNew except tags\n\t\t\tfor k, v := range s {\n\t\t\t\tif k == \"tags\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tv.ForceNew = true\n\t\t\t}\n\n\t\t\ts[\"spot_price\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t}\n\t\t\ts[\"spot_type\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"persistent\",\n\t\t\t}\n\t\t\ts[\"wait_for_fulfillment\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: false,\n\t\t\t}\n\t\t\ts[\"spot_bid_status\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\t\t\ts[\"spot_request_state\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\t\t\ts[\"spot_instance_id\"] = &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t}\n\n\t\t\treturn s\n\t\t}(),\n\t}\n}\n\nfunc resourceAwsSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tinstanceOpts, err := buildAwsInstanceOpts(d, meta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspotOpts := &ec2.RequestSpotInstancesInput{\n\t\tSpotPrice: aws.String(d.Get(\"spot_price\").(string)),\n\t\tType: aws.String(d.Get(\"spot_type\").(string)),\n\n\t\t\/\/ Though the AWS API supports creating spot instance requests for multiple\n\t\t\/\/ instances, for TF purposes we fix this to one instance per request.\n\t\t\/\/ Users can get equivalent behavior out of TF's \"count\" meta-parameter.\n\t\tInstanceCount: aws.Int64(1),\n\n\t\tLaunchSpecification: &ec2.RequestSpotLaunchSpecification{\n\t\t\tBlockDeviceMappings: instanceOpts.BlockDeviceMappings,\n\t\t\tEbsOptimized: instanceOpts.EBSOptimized,\n\t\t\tMonitoring: instanceOpts.Monitoring,\n\t\t\tIamInstanceProfile: instanceOpts.IAMInstanceProfile,\n\t\t\tImageId: instanceOpts.ImageID,\n\t\t\tInstanceType: instanceOpts.InstanceType,\n\t\t\tKeyName: instanceOpts.KeyName,\n\t\t\tPlacement: instanceOpts.SpotPlacement,\n\t\t\tSecurityGroupIds: instanceOpts.SecurityGroupIDs,\n\t\t\tSecurityGroups: instanceOpts.SecurityGroups,\n\t\t\tSubnetId: instanceOpts.SubnetID,\n\t\t\tUserData: instanceOpts.UserData64,\n\t\t},\n\t}\n\n\t\/\/ If the instance is configured with a Network Interface (a subnet, has\n\t\/\/ public IP, etc), then the instanceOpts.SecurityGroupIds and SubnetId will\n\t\/\/ be nil\n\tif len(instanceOpts.NetworkInterfaces) > 0 {\n\t\tspotOpts.LaunchSpecification.SecurityGroupIds = instanceOpts.NetworkInterfaces[0].Groups\n\t\tspotOpts.LaunchSpecification.SubnetId = instanceOpts.NetworkInterfaces[0].SubnetId\n\t}\n\n\t\/\/ Make the spot instance request\n\tlog.Printf(\"[DEBUG] Requesting spot bid opts: %s\", spotOpts)\n\tresp, err := conn.RequestSpotInstances(spotOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error requesting spot instances: %s\", err)\n\t}\n\tif len(resp.SpotInstanceRequests) != 1 {\n\t\treturn fmt.Errorf(\n\t\t\t\"Expected response with length 1, got: %s\", resp)\n\t}\n\n\tsir := *resp.SpotInstanceRequests[0]\n\td.SetId(*sir.SpotInstanceRequestId)\n\n\tif d.Get(\"wait_for_fulfillment\").(bool) {\n\t\tspotStateConf := &resource.StateChangeConf{\n\t\t\t\/\/ http:\/\/docs.aws.amazon.com\/AWSEC2\/latest\/UserGuide\/spot-bid-status.html\n\t\t\tPending: []string{\"start\", \"pending-evaluation\", \"pending-fulfillment\"},\n\t\t\tTarget: \"fulfilled\",\n\t\t\tRefresh: SpotInstanceStateRefreshFunc(conn, sir),\n\t\t\tTimeout: 10 * time.Minute,\n\t\t\tDelay: 10 * time.Second,\n\t\t\tMinTimeout: 3 * time.Second,\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] waiting for spot bid to resolve... this may take several minutes.\")\n\t\t_, err = spotStateConf.WaitForState()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while waiting for spot request (%s) to resolve: %s\", sir, err)\n\t\t}\n\t}\n\n\treturn resourceAwsSpotInstanceRequestUpdate(d, meta)\n}\n\n\/\/ Update spot state, etc\nfunc resourceAwsSpotInstanceRequestRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\treq := &ec2.DescribeSpotInstanceRequestsInput{\n\t\tSpotInstanceRequestIds: []*string{aws.String(d.Id())},\n\t}\n\tresp, err := conn.DescribeSpotInstanceRequests(req)\n\n\tif err != nil {\n\t\t\/\/ If the spot request was not found, return nil so that we can show\n\t\t\/\/ that it is gone.\n\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidSpotInstanceRequestID.NotFound\" {\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.SpotInstanceRequests) == 0 {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\trequest := resp.SpotInstanceRequests[0]\n\n\t\/\/ if the request is cancelled, then it is gone\n\tif *request.State == \"cancelled\" {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\td.Set(\"spot_bid_status\", *request.Status.Code)\n\t\/\/ Instance ID is not set if the request is still pending\n\tif request.InstanceId != nil {\n\t\td.Set(\"spot_instance_id\", *request.InstanceId)\n\t\tif err := readInstance(d, meta); err != nil {\n\t\t\treturn fmt.Errorf(\"[ERR] Error reading Spot Instance Data: %s\", err)\n\t\t}\n\t}\n\td.Set(\"spot_request_state\", *request.State)\n\td.Set(\"tags\", tagsToMap(request.Tags))\n\n\t\/\/ Read the instance data, setting up connection information\n\treturn readInstance(d, meta)\n}\n\nfunc readInstance(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tresp, err := conn.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{aws.String(d.Get(\"spot_instance_id\").(string))},\n\t})\n\tif err != nil {\n\t\t\/\/ If the instance was not found, return nil so that we can show\n\t\t\/\/ that the instance is gone.\n\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidInstanceID.NotFound\" {\n\t\t\treturn fmt.Errorf(\"no instance found\")\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.Reservations) == 0 {\n\t\treturn fmt.Errorf(\"no instances found\")\n\t}\n\n\tinstance := resp.Reservations[0].Instances[0]\n\n\t\/\/ Set these fields for connection information\n\tif instance != nil {\n\t\td.Set(\"public_dns\", instance.PublicDnsName)\n\t\td.Set(\"public_ip\", instance.PublicIpAddress)\n\t\td.Set(\"private_dns\", instance.PrivateDnsName)\n\t\td.Set(\"private_ip\", instance.PrivateIpAddress)\n\n\t\t\/\/ set connection information\n\t\tif instance.PublicIpAddress != nil {\n\t\t\td.SetConnInfo(map[string]string{\n\t\t\t\t\"type\": \"ssh\",\n\t\t\t\t\"host\": *instance.PublicIpAddress,\n\t\t\t})\n\t\t} else if instance.PrivateIpAddress != nil {\n\t\t\td.SetConnInfo(map[string]string{\n\t\t\t\t\"type\": \"ssh\",\n\t\t\t\t\"host\": *instance.PrivateIpAddress,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSpotInstanceRequestUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\td.Partial(true)\n\tif err := setTags(conn, d); err != nil {\n\t\treturn err\n\t} else {\n\t\td.SetPartial(\"tags\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsSpotInstanceRequestRead(d, meta)\n}\n\nfunc resourceAwsSpotInstanceRequestDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tlog.Printf(\"[INFO] Cancelling spot request: %s\", d.Id())\n\t_, err := conn.CancelSpotInstanceRequests(&ec2.CancelSpotInstanceRequestsInput{\n\t\tSpotInstanceRequestIds: []*string{aws.String(d.Id())},\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error cancelling spot request (%s): %s\", d.Id(), err)\n\t}\n\n\tif instanceId := d.Get(\"spot_instance_id\").(string); instanceId != \"\" {\n\t\tlog.Printf(\"[INFO] Terminating instance: %s\", instanceId)\n\t\tif err := awsTerminateInstance(conn, instanceId); err != nil {\n\t\t\treturn fmt.Errorf(\"Error terminating spot instance: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SpotInstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch\n\/\/ an EC2 spot instance request\nfunc SpotInstanceStateRefreshFunc(\n\tconn *ec2.EC2, sir ec2.SpotInstanceRequest) resource.StateRefreshFunc {\n\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.DescribeSpotInstanceRequests(&ec2.DescribeSpotInstanceRequestsInput{\n\t\t\tSpotInstanceRequestIds: []*string{sir.SpotInstanceRequestId},\n\t\t})\n\n\t\tif err != nil {\n\t\t\tif ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == \"InvalidSpotInstanceRequestID.NotFound\" {\n\t\t\t\t\/\/ Set this to nil as if we didn't find anything.\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on StateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil || len(resp.SpotInstanceRequests) == 0 {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our request yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\treq := resp.SpotInstanceRequests[0]\n\t\treturn req, *req.Status.Code, nil\n\t}\n}\n<|endoftext|>"} {"text":"package repair\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"koding\/klient\/remote\/req\"\n\t\"time\"\n\n\t\"github.com\/koding\/logging\"\n)\n\ntype KontrolRepair struct {\n\tLog logging.Logger\n\n\t\/\/ The klient we will be communicating with.\n\tKlient interface {\n\t\tRemoteStatus(req.Status) error\n\t}\n\n\t\/\/ The options that this repairer will use.\n\tRetryOptions RetryOptions\n\n\t\/\/ The way\n\tStdout io.Writer\n\n\t\/\/ A struct that runs the given command.\n\tExec interface {\n\t\tRun(string, ...string) error\n\t}\n}\n\nfunc (r *KontrolRepair) String() string {\n\treturn \"kontrolrepair\"\n}\n\nfunc (r *KontrolRepair) Status() error {\n\tvar (\n\t\tneedNewline bool\n\t\terr error\n\t)\n\n\tfor i := uint(0); i <= r.RetryOptions.StatusRetries; i++ {\n\t\terr = r.status()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\tneedNewline = true\n\t\t\tfmt.Fprint(r.Stdout, \"Kontrol not connected. Waiting for reconnect.\")\n\t\tdefault:\n\t\t\tfmt.Fprint(r.Stdout, \" .\")\n\t\t}\n\n\t\ttime.Sleep(r.RetryOptions.StatusDelay)\n\t}\n\n\tif needNewline {\n\t\tfmt.Fprint(r.Stdout, \"\\n\")\n\t}\n\n\treturn err\n}\n\nfunc (r *KontrolRepair) status() error {\n\treturn r.Klient.RemoteStatus(req.Status{\n\t\tItem: req.KontrolStatus,\n\t})\n}\n\nfunc (r *KontrolRepair) Repair() error {\n\tfmt.Fprintln(r.Stdout, \"Kontrol has not reconnected in expected time. Restarting.\")\n\n\tif err := r.Exec.Run(\"sudo\", \"kd\", \"restart\"); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Subprocess kd failed to start. err:%s\", err,\n\t\t)\n\t}\n\n\t\/\/ Run status again, to confirm it's running as best we can. If not, we've\n\t\/\/ tried and failed.\n\tif err := r.status(); err != nil {\n\t\tfmt.Fprintln(r.Stdout, \"Unable to reconnect to kontrol.\")\n\t}\n\n\treturn nil\n}\nklientctl: Added a retry on the final kontrol status checkpackage repair\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"koding\/klient\/remote\/req\"\n\t\"time\"\n\n\t\"github.com\/koding\/logging\"\n)\n\ntype KontrolRepair struct {\n\tLog logging.Logger\n\n\t\/\/ The klient we will be communicating with.\n\tKlient interface {\n\t\tRemoteStatus(req.Status) error\n\t}\n\n\t\/\/ The options that this repairer will use.\n\tRetryOptions RetryOptions\n\n\t\/\/ The way\n\tStdout io.Writer\n\n\t\/\/ A struct that runs the given command.\n\tExec interface {\n\t\tRun(string, ...string) error\n\t}\n}\n\nfunc (r *KontrolRepair) String() string {\n\treturn \"kontrolrepair\"\n}\n\nfunc (r *KontrolRepair) Status() error {\n\tif err := r.remoteStatus(); err == nil {\n\t\treturn nil\n\t}\n\n\tfmt.Fprint(r.Stdout, \"Kontrol not connected. Waiting for reconnect.\")\n\n\treturn r.statusLoop()\n}\n\n\/\/ statusLoop runs the status loop, optionally printing a dot to indicate progress.\nfunc (r *KontrolRepair) statusLoop() error {\n\tvar err error\n\n\tfor i := uint(0); i <= r.RetryOptions.StatusRetries; i++ {\n\t\tif err = r.remoteStatus(); err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Fprint(r.Stdout, \".\")\n\n\t\ttime.Sleep(r.RetryOptions.StatusDelay)\n\t}\n\n\treturn err\n}\n\nfunc (r *KontrolRepair) remoteStatus() error {\n\treturn r.Klient.RemoteStatus(req.Status{\n\t\tItem: req.KontrolStatus,\n\t})\n}\n\nfunc (r *KontrolRepair) Repair() error {\n\tfmt.Fprintln(r.Stdout, \"Kontrol has not reconnected in expected time. Restarting.\")\n\n\tif err := r.Exec.Run(\"sudo\", \"kd\", \"restart\"); err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Subprocess kd failed to start. err:%s\", err,\n\t\t)\n\t}\n\n\t\/\/ Run status again, to confirm it's running as best we can. If not, we've\n\t\/\/ tried and failed.\n\tfmt.Fprint(r.Stdout, \"Waiting for reconnect.\")\n\n\tif err := r.statusLoop(); err != nil {\n\t\tfmt.Fprintln(r.Stdout, \"Unable to reconnect to kontrol.\")\n\t\treturn err\n\t}\n\n\tfmt.Fprint(r.Stdout, \"\\nReconnected to kontrol.\")\n\treturn nil\n}\n<|endoftext|>"} {"text":"package checks\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/armon\/circbuf\"\n\t\"github.com\/docker\/go-connections\/sockets\"\n)\n\n\/\/ DockerClient is a simplified client for the Docker Engine API\n\/\/ to execute the health checks and avoid significant dependencies.\n\/\/ It also consumes all data returned from the Docker API through\n\/\/ a ring buffer with a fixed limit to avoid excessive resource\n\/\/ consumption.\ntype DockerClient struct {\n\thost string\n\tscheme string\n\tproto string\n\taddr string\n\tbasepath string\n\tmaxbuf int64\n\tclient *http.Client\n}\n\nfunc NewDockerClient(host string, maxbuf int64) (*DockerClient, error) {\n\tif host == \"\" {\n\t\thost = DefaultDockerHost\n\t}\n\n\tproto, addr, basepath, err := ParseHost(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttransport := new(http.Transport)\n\tsockets.ConfigureTransport(transport, proto, addr)\n\tclient := &http.Client{Transport: transport}\n\n\treturn &DockerClient{\n\t\thost: host,\n\t\tscheme: \"http\",\n\t\tproto: proto,\n\t\taddr: addr,\n\t\tbasepath: basepath,\n\t\tmaxbuf: maxbuf,\n\t\tclient: client,\n\t}, nil\n}\n\nfunc (c *DockerClient) Host() string {\n\treturn c.host\n}\n\n\/\/ ParseHost verifies that the given host strings is valid.\n\/\/ copied from github.com\/docker\/docker\/client.go\nfunc ParseHost(host string) (string, string, string, error) {\n\tprotoAddrParts := strings.SplitN(host, \":\/\/\", 2)\n\tif len(protoAddrParts) == 1 {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"unable to parse docker host `%s`\", host)\n\t}\n\n\tvar basePath string\n\tproto, addr := protoAddrParts[0], protoAddrParts[1]\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\treturn proto, addr, basePath, nil\n}\n\nfunc (c *DockerClient) call(method, uri string, v interface{}) (*circbuf.Buffer, int, error) {\n\treq, err := http.NewRequest(method, uri, nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif c.proto == \"unix\" || c.proto == \"npipe\" {\n\t\t\/\/ For local communications, it doesn't matter what the host is. We just\n\t\t\/\/ need a valid and meaningful host name. (See #189)\n\t\treq.Host = \"docker\"\n\t}\n\n\treq.URL.Host = c.addr\n\treq.URL.Scheme = c.scheme\n\n\tif v != nil {\n\t\tvar b bytes.Buffer\n\t\tif err := json.NewEncoder(&b).Encode(v); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\treq.Body = ioutil.NopCloser(&b)\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tb, err := circbuf.NewBuffer(c.maxbuf)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\t_, err = io.Copy(b, resp.Body)\n\treturn b, resp.StatusCode, err\n}\n\nfunc (c *DockerClient) CreateExec(containerID string, cmd []string) (string, error) {\n\tdata := struct {\n\t\tAttachStdin bool\n\t\tAttachStdout bool\n\t\tAttachStderr bool\n\t\tTty bool\n\t\tCmd []string\n\t}{\n\t\tAttachStderr: true,\n\t\tAttachStdout: true,\n\t\tCmd: cmd,\n\t}\n\n\turi := fmt.Sprintf(\"\/containers\/%s\/exec\", url.QueryEscape(containerID))\n\tb, code, err := c.call(\"POST\", uri, data)\n\tswitch {\n\tcase err != nil:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for container %s: %s\", containerID, err)\n\tcase code == 201:\n\t\tvar resp struct{ Id string }\n\t\tif err = json.NewDecoder(bytes.NewReader(b.Bytes())).Decode(&resp); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"create exec response for container %s cannot be parsed: %s\", containerID, err)\n\t\t}\n\t\treturn resp.Id, nil\n\tcase code == 404:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for unknown container %s\", containerID)\n\tcase code == 409:\n\t\treturn \"\", fmt.Errorf(\"create exec failed since container %s is paused or stopped\", containerID)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for container %s with status %d: %s\", containerID, code, b)\n\t}\n}\n\nfunc (c *DockerClient) StartExec(containerID, execID string) (*circbuf.Buffer, error) {\n\tdata := struct{ Detach, Tty bool }{Detach: false, Tty: true}\n\turi := fmt.Sprintf(\"\/exec\/%s\/start\", execID)\n\tb, code, err := c.call(\"POST\", uri, data)\n\tswitch {\n\tcase err != nil && !strings.Contains(err.Error(), \"connection reset by peer\"):\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s: %s\", containerID, err)\n\tcase code == 200:\n\t\treturn b, nil\n\tcase code == 404:\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s: invalid exec id %s\", containerID, execID)\n\tcase code == 409:\n\t\treturn nil, fmt.Errorf(\"start exec failed since container %s is paused or stopped\", containerID)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s with status %d: body: %s err: %s\", containerID, code, b, err)\n\t}\n}\n\nfunc (c *DockerClient) InspectExec(containerID, execID string) (int, error) {\n\turi := fmt.Sprintf(\"\/exec\/%s\/json\", execID)\n\tb, code, err := c.call(\"GET\", uri, nil)\n\tswitch {\n\tcase err != nil:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s: %s\", containerID, err)\n\tcase code == 200:\n\t\tvar resp struct{ ExitCode int }\n\t\tif err := json.NewDecoder(bytes.NewReader(b.Bytes())).Decode(&resp); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"inspect exec response for container %s cannot be parsed: %s\", containerID, err)\n\t\t}\n\t\treturn resp.ExitCode, nil\n\tcase code == 404:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s: invalid exec id %s\", containerID, execID)\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s with status %d: %s\", containerID, code, b)\n\t}\n}\ndocker: do not alloc a tty since this is not interactivepackage checks\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/armon\/circbuf\"\n\t\"github.com\/docker\/go-connections\/sockets\"\n)\n\n\/\/ DockerClient is a simplified client for the Docker Engine API\n\/\/ to execute the health checks and avoid significant dependencies.\n\/\/ It also consumes all data returned from the Docker API through\n\/\/ a ring buffer with a fixed limit to avoid excessive resource\n\/\/ consumption.\ntype DockerClient struct {\n\thost string\n\tscheme string\n\tproto string\n\taddr string\n\tbasepath string\n\tmaxbuf int64\n\tclient *http.Client\n}\n\nfunc NewDockerClient(host string, maxbuf int64) (*DockerClient, error) {\n\tif host == \"\" {\n\t\thost = DefaultDockerHost\n\t}\n\n\tproto, addr, basepath, err := ParseHost(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttransport := new(http.Transport)\n\tsockets.ConfigureTransport(transport, proto, addr)\n\tclient := &http.Client{Transport: transport}\n\n\treturn &DockerClient{\n\t\thost: host,\n\t\tscheme: \"http\",\n\t\tproto: proto,\n\t\taddr: addr,\n\t\tbasepath: basepath,\n\t\tmaxbuf: maxbuf,\n\t\tclient: client,\n\t}, nil\n}\n\nfunc (c *DockerClient) Host() string {\n\treturn c.host\n}\n\n\/\/ ParseHost verifies that the given host strings is valid.\n\/\/ copied from github.com\/docker\/docker\/client.go\nfunc ParseHost(host string) (string, string, string, error) {\n\tprotoAddrParts := strings.SplitN(host, \":\/\/\", 2)\n\tif len(protoAddrParts) == 1 {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"unable to parse docker host `%s`\", host)\n\t}\n\n\tvar basePath string\n\tproto, addr := protoAddrParts[0], protoAddrParts[1]\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\treturn proto, addr, basePath, nil\n}\n\nfunc (c *DockerClient) call(method, uri string, v interface{}) (*circbuf.Buffer, int, error) {\n\treq, err := http.NewRequest(method, uri, nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif c.proto == \"unix\" || c.proto == \"npipe\" {\n\t\t\/\/ For local communications, it doesn't matter what the host is. We just\n\t\t\/\/ need a valid and meaningful host name. (See #189)\n\t\treq.Host = \"docker\"\n\t}\n\n\treq.URL.Host = c.addr\n\treq.URL.Scheme = c.scheme\n\n\tif v != nil {\n\t\tvar b bytes.Buffer\n\t\tif err := json.NewEncoder(&b).Encode(v); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\treq.Body = ioutil.NopCloser(&b)\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tb, err := circbuf.NewBuffer(c.maxbuf)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\t_, err = io.Copy(b, resp.Body)\n\treturn b, resp.StatusCode, err\n}\n\nfunc (c *DockerClient) CreateExec(containerID string, cmd []string) (string, error) {\n\tdata := struct {\n\t\tAttachStdin bool\n\t\tAttachStdout bool\n\t\tAttachStderr bool\n\t\tTty bool\n\t\tCmd []string\n\t}{\n\t\tAttachStderr: true,\n\t\tAttachStdout: true,\n\t\tCmd: cmd,\n\t}\n\n\turi := fmt.Sprintf(\"\/containers\/%s\/exec\", url.QueryEscape(containerID))\n\tb, code, err := c.call(\"POST\", uri, data)\n\tswitch {\n\tcase err != nil:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for container %s: %s\", containerID, err)\n\tcase code == 201:\n\t\tvar resp struct{ Id string }\n\t\tif err = json.NewDecoder(bytes.NewReader(b.Bytes())).Decode(&resp); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"create exec response for container %s cannot be parsed: %s\", containerID, err)\n\t\t}\n\t\treturn resp.Id, nil\n\tcase code == 404:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for unknown container %s\", containerID)\n\tcase code == 409:\n\t\treturn \"\", fmt.Errorf(\"create exec failed since container %s is paused or stopped\", containerID)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"create exec failed for container %s with status %d: %s\", containerID, code, b)\n\t}\n}\n\nfunc (c *DockerClient) StartExec(containerID, execID string) (*circbuf.Buffer, error) {\n\tdata := struct{ Detach, Tty bool }{Detach: false, Tty: false}\n\turi := fmt.Sprintf(\"\/exec\/%s\/start\", execID)\n\tb, code, err := c.call(\"POST\", uri, data)\n\tswitch {\n\tcase err != nil && !strings.Contains(err.Error(), \"connection reset by peer\"):\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s: %s\", containerID, err)\n\tcase code == 200:\n\t\treturn b, nil\n\tcase code == 404:\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s: invalid exec id %s\", containerID, execID)\n\tcase code == 409:\n\t\treturn nil, fmt.Errorf(\"start exec failed since container %s is paused or stopped\", containerID)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"start exec failed for container %s with status %d: body: %s err: %s\", containerID, code, b, err)\n\t}\n}\n\nfunc (c *DockerClient) InspectExec(containerID, execID string) (int, error) {\n\turi := fmt.Sprintf(\"\/exec\/%s\/json\", execID)\n\tb, code, err := c.call(\"GET\", uri, nil)\n\tswitch {\n\tcase err != nil:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s: %s\", containerID, err)\n\tcase code == 200:\n\t\tvar resp struct{ ExitCode int }\n\t\tif err := json.NewDecoder(bytes.NewReader(b.Bytes())).Decode(&resp); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"inspect exec response for container %s cannot be parsed: %s\", containerID, err)\n\t\t}\n\t\treturn resp.ExitCode, nil\n\tcase code == 404:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s: invalid exec id %s\", containerID, execID)\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"inspect exec failed for container %s with status %d: %s\", containerID, code, b)\n\t}\n}\n<|endoftext|>"} {"text":"package hwaflib\n\nfunc (ctx *Context) Version() string {\n\tversion := \"20131204\"\n\treturn version\n}\n\nfunc (ctx *Context) Revision() string {\n\trevision := \"6dc9a4b\"\n\treturn revision\n}\n\n\/\/ EOF\n\n\nversion: 20131206package hwaflib\n\nfunc (ctx *Context) Version() string {\n\tversion := \"20131206\"\n\treturn version\n}\n\nfunc (ctx *Context) Revision() string {\n\trevision := \"76b771a\"\n\treturn revision\n}\n\n\/\/ EOF\n\n\n<|endoftext|>"} {"text":"\/\/ Tinkering with go, zmq, and Jupyter\npackage main\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\tzmq \"github.com\/pebbe\/zmq4\"\n)\n\n\/\/ MessageHeader is a Jupyter message header\n\/\/ See: http:\/\/jupyter-client.readthedocs.org\/en\/latest\/messaging.html\ntype MessageHeader struct {\n\tMessageID string `json:\"msg_id\"`\n\tUsername string `json:\"username\"`\n\tSession string `json:\"session\"`\n\tMessageType string `json:\"msg_type\"`\n\tVersion string `json:\"version\"`\n}\n\n\/\/ Message is a generic Jupyter message (not a wire message)\ntype Message struct {\n\tHeader MessageHeader `json:\"header\"`\n\tParentHeader MessageHeader `json:\"parent_header\"`\n\tMetadata map[string]interface{} `json:\"metadata\"`\n\tContent map[string]interface{} `json:\"content\"`\n}\n\n\/\/ ConnectionInfo represents the runtime connection data used by Jupyter kernels\ntype ConnectionInfo struct {\n\tIOPubPort int `json:\"iopub_port\"`\n\tStdinPort int `json:\"stdin_port\"`\n\tIP string `json:\"ip\"`\n\tTransport string `json:\"transport\"`\n\tHBPort int `json:\"hb_port\"`\n\tSignatureScheme string `json:\"signature_scheme\"`\n\tShellPort int `json:\"shell_port\"`\n\tControlPort int `json:\"control_port\"`\n\tKey string `json:\"key\"`\n}\n\n\/\/ DELIMITER denotes the Jupyter multipart message\nvar DELIMITER = \"\"\n\n\/\/ ParseWireProtocol fills a Message with all the juicy Jupyter bits\nfunc (m *Message) ParseWireProtocol(wireMessage [][]byte, key []byte) (err error) {\n\tvar i int\n\tvar el []byte\n\n\t\/\/ Wire protocol\n\t\/**\n\t\t[\n\t \t\tb'u-u-i-d', # zmq identity(ies)\n\t \t\tb'', # delimiter\n\t \t\tb'baddad42', # HMAC signature\n\t\t\tb'{header}', # serialized header dict\n\t\t\tb'{parent_header}', # serialized parent header dict\n\t\t\tb'{metadata}', # serialized metadata dict\n\t\t\tb'{content}', # serialized content dict\n\t\t\tb'blob', # extra raw data buffer(s)\n\t \t\t...\n\t\t]\n\t*\/\n\t\/\/ Determine where the delimiter is\n\tfor i, el = range wireMessage {\n\t\tif string(el) == DELIMITER {\n\t\t\tbreak \/\/ Found our delimiter\n\t\t}\n\t}\n\n\tif string(wireMessage[i]) != DELIMITER {\n\t\treturn errors.New(\"Couldn't find delimeter\")\n\t}\n\n\t\/\/ Extract the zmq identiti(es)\n\t\/\/identities := wireMessage[:delimiterLocation]\n\n\t\/\/ If the message was signed\n\tif len(key) != 0 {\n\t\tmac := hmac.New(sha256.New, key)\n\t\tfor _, msgpart := range wireMessage[i+2 : i+6] {\n\t\t\tmac.Write(msgpart)\n\t\t}\n\t\tsignature := make([]byte, hex.DecodedLen(len(wireMessage[i+1])))\n\t\thex.Decode(signature, wireMessage[i+1])\n\t\tif !hmac.Equal(mac.Sum(nil), signature) {\n\t\t\treturn errors.New(\"Invalid signature\")\n\t\t}\n\t}\n\n\tjson.Unmarshal(wireMessage[i+2], &m.Header)\n\tjson.Unmarshal(wireMessage[i+3], &m.ParentHeader)\n\tjson.Unmarshal(wireMessage[i+4], &m.Metadata)\n\tjson.Unmarshal(wireMessage[i+5], &m.Content)\n\n\treturn nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tlog.Fatalln(\"Need a command line argument for the connection file.\")\n\t}\n\n\tconnFile, err := os.Open(flag.Arg(0))\n\tif err != nil {\n\t\tfmt.Errorf(\"Couldn't open connection file: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tjsonParser := json.NewDecoder(connFile)\n\n\tvar connInfo ConnectionInfo\n\n\tif err = jsonParser.Decode(&connInfo); err != nil {\n\t\tfmt.Errorf(\"Couldn't parse connection file: %v\", err)\n\t\tos.Exit(2)\n\t}\n\n\tiopubSocket, err := zmq.NewSocket(zmq.SUB)\n\tif err != nil {\n\t\tfmt.Errorf(\"Couldn't start the iopub socket: %v\", err)\n\t}\n\n\tdefer iopubSocket.Close()\n\n\tconnectionString := fmt.Sprintf(\"%s:\/\/%s:%d\",\n\t\tconnInfo.Transport,\n\t\tconnInfo.IP,\n\t\tconnInfo.IOPubPort)\n\n\tiopubSocket.Connect(connectionString)\n\tiopubSocket.SetSubscribe(\"\")\n\n\tfmt.Println(\"Connected to\")\n\tfmt.Println(connInfo)\n\n\tfor {\n\t\twireMessage, err := iopubSocket.RecvMessageBytes(0)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error on receive: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar message Message\n\t\tmessage.ParseWireProtocol(wireMessage, []byte(connInfo.Key))\n\n\t\tfmt.Println(message.Content)\n\n\t}\n\n}\nFlesh out the mimebundle\/\/ Tinkering with go, zmq, and Jupyter\npackage main\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\tzmq \"github.com\/pebbe\/zmq4\"\n)\n\n\/\/ MessageHeader is a Jupyter message header\n\/\/ See: http:\/\/jupyter-client.readthedocs.org\/en\/latest\/messaging.html\ntype MessageHeader struct {\n\tMessageID string `json:\"msg_id\"`\n\tUsername string `json:\"username\"`\n\tSession string `json:\"session\"`\n\tMessageType string `json:\"msg_type\"`\n\tVersion string `json:\"version\"`\n}\n\n\/\/ Message is a generic Jupyter message (not a wire message)\ntype Message struct {\n\tHeader MessageHeader `json:\"header\"`\n\tParentHeader MessageHeader `json:\"parent_header\"`\n\tMetadata map[string]interface{} `json:\"metadata\"`\n\tContent map[string]interface{} `json:\"content\"`\n}\n\n\/\/ MimeBundle is a collection of mimetypes -> data\n\/\/ Example:\n\/\/ 'text\/html' -> '

Hey!<\/h1>'\n\/\/ 'image\/png' -> 'R0lGODlhAQABAIAAAAAAAP\/\/\/yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'\ntype MimeBundle map[string]string\n\n\/\/ ConnectionInfo represents the runtime connection data used by Jupyter kernels\ntype ConnectionInfo struct {\n\tIOPubPort int `json:\"iopub_port\"`\n\tStdinPort int `json:\"stdin_port\"`\n\tIP string `json:\"ip\"`\n\tTransport string `json:\"transport\"`\n\tHBPort int `json:\"hb_port\"`\n\tSignatureScheme string `json:\"signature_scheme\"`\n\tShellPort int `json:\"shell_port\"`\n\tControlPort int `json:\"control_port\"`\n\tKey string `json:\"key\"`\n}\n\n\/\/ DELIMITER denotes the Jupyter multipart message\nvar DELIMITER = \"\"\n\n\/\/ ParseWireProtocol fills a Message with all the juicy Jupyter bits\nfunc (m *Message) ParseWireProtocol(wireMessage [][]byte, key []byte) (err error) {\n\tvar i int\n\tvar el []byte\n\n\t\/\/ Wire protocol\n\t\/**\n\t\t[\n\t \t\tb'u-u-i-d', # zmq identity(ies)\n\t \t\tb'', # delimiter\n\t \t\tb'baddad42', # HMAC signature\n\t\t\tb'{header}', # serialized header dict\n\t\t\tb'{parent_header}', # serialized parent header dict\n\t\t\tb'{metadata}', # serialized metadata dict\n\t\t\tb'{content}', # serialized content dict\n\t\t\tb'blob', # extra raw data buffer(s)\n\t \t\t...\n\t\t]\n\t*\/\n\t\/\/ Determine where the delimiter is\n\tfor i, el = range wireMessage {\n\t\tif string(el) == DELIMITER {\n\t\t\tbreak \/\/ Found our delimiter\n\t\t}\n\t}\n\n\tif string(wireMessage[i]) != DELIMITER {\n\t\treturn errors.New(\"Couldn't find delimeter\")\n\t}\n\n\t\/\/ Extract the zmq identiti(es)\n\t\/\/identities := wireMessage[:delimiterLocation]\n\n\t\/\/ If the message was signed\n\tif len(key) != 0 {\n\t\t\/\/ TODO: Programmatic selection of scheme\n\t\tmac := hmac.New(sha256.New, key)\n\t\tfor _, msgpart := range wireMessage[i+2 : i+6] {\n\t\t\tmac.Write(msgpart)\n\t\t}\n\t\tsignature := make([]byte, hex.DecodedLen(len(wireMessage[i+1])))\n\t\thex.Decode(signature, wireMessage[i+1])\n\t\tif !hmac.Equal(mac.Sum(nil), signature) {\n\t\t\treturn errors.New(\"Invalid signature\")\n\t\t}\n\t}\n\n\tjson.Unmarshal(wireMessage[i+2], &m.Header)\n\tjson.Unmarshal(wireMessage[i+3], &m.ParentHeader)\n\tjson.Unmarshal(wireMessage[i+4], &m.Metadata)\n\tjson.Unmarshal(wireMessage[i+5], &m.Content)\n\n\treturn nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tlog.Fatalln(\"Need a command line argument for the connection file.\")\n\t}\n\n\tconnFile, err := os.Open(flag.Arg(0))\n\tif err != nil {\n\t\tfmt.Errorf(\"Couldn't open connection file: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tjsonParser := json.NewDecoder(connFile)\n\n\tvar connInfo ConnectionInfo\n\n\tif err = jsonParser.Decode(&connInfo); err != nil {\n\t\tfmt.Errorf(\"Couldn't parse connection file: %v\", err)\n\t\tos.Exit(2)\n\t}\n\n\tiopubSocket, err := zmq.NewSocket(zmq.SUB)\n\tif err != nil {\n\t\tfmt.Errorf(\"Couldn't start the iopub socket: %v\", err)\n\t}\n\n\tdefer iopubSocket.Close()\n\n\tconnectionString := fmt.Sprintf(\"%s:\/\/%s:%d\",\n\t\tconnInfo.Transport,\n\t\tconnInfo.IP,\n\t\tconnInfo.IOPubPort)\n\n\tiopubSocket.Connect(connectionString)\n\tiopubSocket.SetSubscribe(\"\")\n\n\tfmt.Printf(\"Connected to %v\\n\", connectionString)\n\n\tfor {\n\t\twireMessage, err := iopubSocket.RecvMessageBytes(0)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error on receive: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar message Message\n\t\tmessage.ParseWireProtocol(wireMessage, []byte(connInfo.Key))\n\n\t\t_, ok := message.Content[\"data\"]\n\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tmimeBundle := (message.Content[\"data\"]).(map[string]interface{})\n\n\t\tfmt.Println(mimeBundle)\n\n\t}\n\n}\n<|endoftext|>"} {"text":"package api\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/gorilla\/mux\"\n\n\t\"github.com\/hoffie\/larasync\/helpers\/bincontainer\"\n\trepositoryModule \"github.com\/hoffie\/larasync\/repository\"\n)\n\n\/\/ nibGet returns the NIB data for a given repository and a given UUID.\nfunc (s *Server) nibGet(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorJSON(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tnibID := vars[\"nibID\"]\n\n\treader, err := repository.GetNIBReader(nibID)\n\n\tif err != nil {\n\t\trw.Header().Set(\"Content-Type\", \"plain\/text\")\n\t\tif os.IsNotExist(err) {\n\t\t\terrorText(rw, \"Not found\", http.StatusNotFound)\n\t\t} else {\n\t\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\trw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\trw.WriteHeader(http.StatusOK)\n\tio.Copy(rw, reader)\n}\n\n\/\/ nibPut is the handler which adds a NIB to the repository.\nfunc (s *Server) nibPut(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorJSON(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tnibID := vars[\"nibID\"]\n\n\tsuccessReturnStatus := http.StatusOK\n\tif !repository.HasNIB(nibID) {\n\t\tsuccessReturnStatus = http.StatusCreated\n\t}\n\n\terr = repository.AddNIBContent(nibID, req.Body)\n\n\tif err != nil {\n\t\tif err == repositoryModule.ErrSignatureVerification {\n\t\t\terrorText(rw, \"Signature could not be verified\", http.StatusUnauthorized)\n\t\t} else if err == repositoryModule.ErrUnMarshalling {\n\t\t\terrorText(rw, \"Could not extract NIB\", http.StatusBadRequest)\n\t\t} else {\n\t\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\trw.Header().Set(\"Location\", req.URL.String())\n\trw.WriteHeader(successReturnStatus)\n}\n\nfunc (s *Server) nibList(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvalues := req.URL.Query()\n\tfromRepositoryIDString, ok := values[\"from-transaction-id\"]\n\n\tvar nibChannel <-chan []byte\n\tif !ok {\n\t\tnibChannel, err = repository.GetAllNIBBytes()\n\t} else {\n\t\tfromRepositoryID, err := strconv.ParseInt(fromRepositoryIDString[0], 10, 64)\n\t\tif err != nil {\n\t\t\terrorText(\n\t\t\t\trw,\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"from-transaction-id %s is not a valid transaction id\",\n\t\t\t\t\tfromRepositoryIDString,\n\t\t\t\t),\n\t\t\t\thttp.StatusBadRequest,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tnibChannel, err = repository.GetNIBBytesFrom(fromRepositoryID)\n\t}\n\n\tif err != nil {\n\t\terrorText(rw, \"Could not extract data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\theader := rw.Header()\n\theader.Set(\"Content-Type\", \"application\/octet-stream\")\n\tcurrentTransaction, err := repository.CurrentTransaction()\n\tif err != nil && err != repositoryModule.ErrTransactionNotExists {\n\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t} else if currentTransaction != nil {\n\t\theader.Set(\"X-Current-Transaction-Id\", currentTransaction.IDString())\n\t}\n\n\trw.WriteHeader(http.StatusOK)\n\n\tencoder := bincontainer.NewEncoder(rw)\n\tfor nibData := range nibChannel {\n\t\tencoder.WriteChunk(nibData)\n\t}\n}\napi: All NIB endpoints now return the X-Current-Transaction-Id Header.package api\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/gorilla\/mux\"\n\n\t\"github.com\/hoffie\/larasync\/helpers\/bincontainer\"\n\trepositoryModule \"github.com\/hoffie\/larasync\/repository\"\n)\n\nfunc attachCurrentTransactionHeader(r *repositoryModule.Repository, rw http.ResponseWriter) {\n\theader := rw.Header()\n\tcurrentTransaction, err := repository.CurrentTransaction()\n\tif err != nil && err != repositoryModule.ErrTransactionNotExists {\n\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t} else if currentTransaction != nil {\n\t\theader.Set(\"X-Current-Transaction-Id\", currentTransaction.IDString())\n\t}\n}\n\n\/\/ nibGet returns the NIB data for a given repository and a given UUID.\nfunc (s *Server) nibGet(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorJSON(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tnibID := vars[\"nibID\"]\n\n\treader, err := repository.GetNIBReader(nibID)\n\n\tif err != nil {\n\t\trw.Header().Set(\"Content-Type\", \"plain\/text\")\n\t\tif os.IsNotExist(err) {\n\t\t\terrorText(rw, \"Not found\", http.StatusNotFound)\n\t\t} else {\n\t\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\trw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\tattachCurrentTransactionHeader(repository, rw)\n\trw.WriteHeader(http.StatusOK)\n\tio.Copy(rw, reader)\n}\n\n\/\/ nibPut is the handler which adds a NIB to the repository.\nfunc (s *Server) nibPut(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorJSON(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tnibID := vars[\"nibID\"]\n\n\tsuccessReturnStatus := http.StatusOK\n\tif !repository.HasNIB(nibID) {\n\t\tsuccessReturnStatus = http.StatusCreated\n\t}\n\n\terr = repository.AddNIBContent(nibID, req.Body)\n\n\tif err != nil {\n\t\tif err == repositoryModule.ErrSignatureVerification {\n\t\t\terrorText(rw, \"Signature could not be verified\", http.StatusUnauthorized)\n\t\t} else if err == repositoryModule.ErrUnMarshalling {\n\t\t\terrorText(rw, \"Could not extract NIB\", http.StatusBadRequest)\n\t\t} else {\n\t\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\trw.Header().Set(\"Location\", req.URL.String())\n\tattachCurrentTransactionHeader(repository, rw)\n\trw.WriteHeader(successReturnStatus)\n}\n\nfunc (s *Server) nibList(rw http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\trepositoryName := vars[\"repository\"]\n\n\trepository, err := s.rm.Open(repositoryName)\n\tif err != nil {\n\t\terrorText(rw, \"Internal Error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvalues := req.URL.Query()\n\tfromRepositoryIDString, ok := values[\"from-transaction-id\"]\n\n\tvar nibChannel <-chan []byte\n\tif !ok {\n\t\tnibChannel, err = repository.GetAllNIBBytes()\n\t} else {\n\t\tfromRepositoryID, err := strconv.ParseInt(fromRepositoryIDString[0], 10, 64)\n\t\tif err != nil {\n\t\t\terrorText(\n\t\t\t\trw,\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"from-transaction-id %s is not a valid transaction id\",\n\t\t\t\t\tfromRepositoryIDString,\n\t\t\t\t),\n\t\t\t\thttp.StatusBadRequest,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tnibChannel, err = repository.GetNIBBytesFrom(fromRepositoryID)\n\t}\n\n\tif err != nil {\n\t\terrorText(rw, \"Could not extract data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\theader := rw.Header()\n\theader.Set(\"Content-Type\", \"application\/octet-stream\")\n\tattachCurrentTransactionHeader(repository, rw)\n\n\trw.WriteHeader(http.StatusOK)\n\n\tencoder := bincontainer.NewEncoder(rw)\n\tfor nibData := range nibChannel {\n\t\tencoder.WriteChunk(nibData)\n\t}\n}\n<|endoftext|>"} {"text":"package msgpack\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/vmihailenco\/msgpack\/v5\/msgpcode\"\n)\n\nvar timeExtID int8 = -1\n\nfunc init() {\n\tRegisterExtEncoder(timeExtID, time.Time{}, timeEncoder)\n\tRegisterExtDecoder(timeExtID, time.Time{}, timeDecoder)\n}\n\nfunc timeEncoder(e *Encoder, v reflect.Value) ([]byte, error) {\n\treturn e.encodeTime(v.Interface().(time.Time)), nil\n}\n\nfunc timeDecoder(d *Decoder, v reflect.Value, extLen int) error {\n\ttm, err := d.decodeTime(extLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tptr := v.Addr().Interface().(*time.Time)\n\t*ptr = tm\n\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeTime(tm time.Time) error {\n\tb := e.encodeTime(tm)\n\tif err := e.encodeExtLen(len(b)); err != nil {\n\t\treturn err\n\t}\n\tif err := e.w.WriteByte(byte(timeExtID)); err != nil {\n\t\treturn err\n\t}\n\treturn e.write(b)\n}\n\nfunc (e *Encoder) encodeTime(tm time.Time) []byte {\n\tif e.timeBuf == nil {\n\t\te.timeBuf = make([]byte, 12)\n\t}\n\n\tsecs := uint64(tm.Unix())\n\tif secs>>34 == 0 {\n\t\tdata := uint64(tm.Nanosecond())<<34 | secs\n\n\t\tif data&0xffffffff00000000 == 0 {\n\t\t\tb := e.timeBuf[:4]\n\t\t\tbinary.BigEndian.PutUint32(b, uint32(data))\n\t\t\treturn b\n\t\t}\n\n\t\tb := e.timeBuf[:8]\n\t\tbinary.BigEndian.PutUint64(b, data)\n\t\treturn b\n\t}\n\n\tb := e.timeBuf[:12]\n\tbinary.BigEndian.PutUint32(b, uint32(tm.Nanosecond()))\n\tbinary.BigEndian.PutUint64(b[4:], secs)\n\treturn b\n}\n\nfunc (d *Decoder) DecodeTime() (time.Time, error) {\n\tc, err := d.readCode()\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\t\/\/ Legacy format.\n\tif c == msgpcode.FixedArrayLow|2 {\n\t\tsec, err := d.DecodeInt64()\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\n\t\tnsec, err := d.DecodeInt64()\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\n\t\treturn time.Unix(sec, nsec), nil\n\t}\n\n\tif msgpcode.IsString(c) {\n\t\ts, err := d.string(c)\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\treturn time.Parse(time.RFC3339Nano, s)\n\t}\n\n\textID, extLen, err := d.extHeader(c)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\tif extID != timeExtID {\n\t\treturn time.Time{}, fmt.Errorf(\"msgpack: invalid time ext id=%d\", extID)\n\t}\n\n\ttm, err := d.decodeTime(extLen)\n\tif err != nil {\n\t\treturn tm, err\n\t}\n\n\tif tm.IsZero() {\n\t\t\/\/ Zero time does not have timezone information.\n\t\treturn tm.UTC(), nil\n\t}\n\treturn tm, nil\n}\n\nfunc (d *Decoder) decodeTime(extLen int) (time.Time, error) {\n\tb, err := d.readN(extLen)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\tswitch len(b) {\n\tcase 4:\n\t\tsec := binary.BigEndian.Uint32(b)\n\t\treturn time.Unix(int64(sec), 0), nil\n\tcase 8:\n\t\tsec := binary.BigEndian.Uint64(b)\n\t\tnsec := int64(sec >> 34)\n\t\tsec &= 0x00000003ffffffff\n\t\treturn time.Unix(int64(sec), nsec), nil\n\tcase 12:\n\t\tnsec := binary.BigEndian.Uint32(b)\n\t\tsec := binary.BigEndian.Uint64(b[4:])\n\t\treturn time.Unix(int64(sec), int64(nsec)), nil\n\tdefault:\n\t\terr = fmt.Errorf(\"msgpack: invalid ext len=%d decoding time\", extLen)\n\t\treturn time.Time{}, err\n\t}\n}\nfeat: allow overwriting time.Time parsing from extID 13 (for NodeJS Date)package msgpack\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/vmihailenco\/msgpack\/v5\/msgpcode\"\n)\n\nvar timeExtID int8 = -1\n\nfunc init() {\n\tRegisterExtEncoder(timeExtID, time.Time{}, timeEncoder)\n\tRegisterExtDecoder(timeExtID, time.Time{}, timeDecoder)\n}\n\nfunc timeEncoder(e *Encoder, v reflect.Value) ([]byte, error) {\n\treturn e.encodeTime(v.Interface().(time.Time)), nil\n}\n\nfunc timeDecoder(d *Decoder, v reflect.Value, extLen int) error {\n\ttm, err := d.decodeTime(extLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tptr := v.Addr().Interface().(*time.Time)\n\t*ptr = tm\n\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeTime(tm time.Time) error {\n\tb := e.encodeTime(tm)\n\tif err := e.encodeExtLen(len(b)); err != nil {\n\t\treturn err\n\t}\n\tif err := e.w.WriteByte(byte(timeExtID)); err != nil {\n\t\treturn err\n\t}\n\treturn e.write(b)\n}\n\nfunc (e *Encoder) encodeTime(tm time.Time) []byte {\n\tif e.timeBuf == nil {\n\t\te.timeBuf = make([]byte, 12)\n\t}\n\n\tsecs := uint64(tm.Unix())\n\tif secs>>34 == 0 {\n\t\tdata := uint64(tm.Nanosecond())<<34 | secs\n\n\t\tif data&0xffffffff00000000 == 0 {\n\t\t\tb := e.timeBuf[:4]\n\t\t\tbinary.BigEndian.PutUint32(b, uint32(data))\n\t\t\treturn b\n\t\t}\n\n\t\tb := e.timeBuf[:8]\n\t\tbinary.BigEndian.PutUint64(b, data)\n\t\treturn b\n\t}\n\n\tb := e.timeBuf[:12]\n\tbinary.BigEndian.PutUint32(b, uint32(tm.Nanosecond()))\n\tbinary.BigEndian.PutUint64(b[4:], secs)\n\treturn b\n}\n\nfunc (d *Decoder) DecodeTime() (time.Time, error) {\n\tc, err := d.readCode()\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\t\/\/ Legacy format.\n\tif c == msgpcode.FixedArrayLow|2 {\n\t\tsec, err := d.DecodeInt64()\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\n\t\tnsec, err := d.DecodeInt64()\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\n\t\treturn time.Unix(sec, nsec), nil\n\t}\n\n\tif msgpcode.IsString(c) {\n\t\ts, err := d.string(c)\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t\treturn time.Parse(time.RFC3339Nano, s)\n\t}\n\n\textID, extLen, err := d.extHeader(c)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\t\/\/ NodeJS seems to use extID 13.\n\tif extID != timeExtID && extID != 13 {\n\t\treturn time.Time{}, fmt.Errorf(\"msgpack: invalid time ext id=%d\", extID)\n\t}\n\n\ttm, err := d.decodeTime(extLen)\n\tif err != nil {\n\t\treturn tm, err\n\t}\n\n\tif tm.IsZero() {\n\t\t\/\/ Zero time does not have timezone information.\n\t\treturn tm.UTC(), nil\n\t}\n\treturn tm, nil\n}\n\nfunc (d *Decoder) decodeTime(extLen int) (time.Time, error) {\n\tb, err := d.readN(extLen)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\tswitch len(b) {\n\tcase 4:\n\t\tsec := binary.BigEndian.Uint32(b)\n\t\treturn time.Unix(int64(sec), 0), nil\n\tcase 8:\n\t\tsec := binary.BigEndian.Uint64(b)\n\t\tnsec := int64(sec >> 34)\n\t\tsec &= 0x00000003ffffffff\n\t\treturn time.Unix(int64(sec), nsec), nil\n\tcase 12:\n\t\tnsec := binary.BigEndian.Uint32(b)\n\t\tsec := binary.BigEndian.Uint64(b[4:])\n\t\treturn time.Unix(int64(sec), int64(nsec)), nil\n\tdefault:\n\t\terr = fmt.Errorf(\"msgpack: invalid ext len=%d decoding time\", extLen)\n\t\treturn time.Time{}, err\n\t}\n}\n<|endoftext|>"} {"text":"package api\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jkomoros\/boardgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/users\"\n\t\"log\"\n\t\"strconv\"\n)\n\nconst (\n\tctxGameKey = \"ctxGame\"\n\tctxAdminAllowedKey = \"ctxAdminAllowed\"\n\tctxViewingPlayerAsKey = \"ctxViewingPlayerAs\"\n\tctxUserKey = \"ctxUser\"\n\tctxHasEmptySlots = \"ctxHasEmptySlots\"\n)\n\nconst (\n\tqryAdminKey = \"admin\"\n\tqryPlayerKey = \"player\"\n\tqryAutoCurrentPlayerKey = \"current\"\n\tqryGameIdKey = \"id\"\n\tqryGameNameKey = \"name\"\n\tqryManagerKey = \"manager\"\n\tqryNumPlayersKey = \"numplayers\"\n\tqryAgentKey = \"agent-player-\"\n\tqryGameVersion = \"version\"\n\tqryOpen = \"open\"\n\tqryVisible = \"visible\"\n)\n\nconst (\n\tinvalidPlayerIndex = boardgame.PlayerIndex(-10)\n)\n\nfunc (s *Server) getRequestManager(c *gin.Context) string {\n\treturn c.PostForm(qryManagerKey)\n}\n\nfunc (s *Server) getRequestNumPlayers(c *gin.Context) int {\n\trawValue := c.PostForm(qryNumPlayersKey)\n\n\tif rawValue == \"\" {\n\t\trawValue = \"0\"\n\t}\n\n\tnumPlayers, err := strconv.Atoi(rawValue)\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn numPlayers\n\n}\n\nfunc (s *Server) getRequestAgents(c *gin.Context, expectedNum int) []string {\n\tvar result []string\n\tfor i := 0; i < expectedNum; i++ {\n\t\tresult = append(result, c.PostForm(qryAgentKey+strconv.Itoa(i)))\n\t}\n\treturn result\n}\n\nfunc (s *Server) getRequestGameVersion(c *gin.Context) int {\n\trawVal := c.Param(qryGameVersion)\n\n\tresult, _ := strconv.Atoi(rawVal)\n\n\treturn result\n}\n\nfunc (s *Server) getRequestOpen(c *gin.Context) bool {\n\topen := c.Query(qryOpen)\n\n\tif open == \"\" {\n\n\t\topen = c.PostForm(qryOpen)\n\n\t\tif open == \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\topenInt, err := strconv.Atoi(open)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn openInt > 0\n}\n\nfunc (s *Server) getRequestVisible(c *gin.Context) bool {\n\tvisible := c.Query(qryVisible)\n\n\tif visible == \"\" {\n\n\t\tvisible = c.PostForm(qryVisible)\n\n\t\tif visible == \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tvisibleInt, err := strconv.Atoi(visible)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn visibleInt > 0\n}\n\nfunc (s *Server) getRequestGameId(c *gin.Context) string {\n\treturn c.Param(qryGameIdKey)\n}\n\nfunc (s *Server) getRequestGameName(c *gin.Context) string {\n\tresult := c.Param(qryGameNameKey)\n\tif result != \"\" {\n\t\treturn result\n\t}\n\treturn c.Query(qryGameNameKey)\n}\n\nfunc (s *Server) getRequestCookie(c *gin.Context) string {\n\tresult, err := c.Cookie(cookieName)\n\n\tif err != nil {\n\t\tlog.Println(\"Couldnt' get cookie:\", err)\n\t\treturn \"\"\n\t}\n\n\treturn result\n}\n\nfunc (s *Server) setUser(c *gin.Context, user *users.StorageRecord) {\n\tc.Set(ctxUserKey, user)\n}\n\nfunc (s *Server) getUser(c *gin.Context) *users.StorageRecord {\n\tobj, ok := c.Get(ctxUserKey)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tuser, ok := obj.(*users.StorageRecord)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn user\n}\n\nfunc (s *Server) setGame(c *gin.Context, game *boardgame.Game) {\n\tc.Set(ctxGameKey, game)\n}\n\nfunc (s *Server) getGame(c *gin.Context) *boardgame.Game {\n\tobj, ok := c.Get(ctxGameKey)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tgame, ok := obj.(*boardgame.Game)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn game\n}\n\nfunc (s *Server) setViewingAsPlayer(c *gin.Context, playerIndex boardgame.PlayerIndex) {\n\tc.Set(ctxViewingPlayerAsKey, playerIndex)\n}\n\nfunc (s *Server) getViewingAsPlayer(c *gin.Context) boardgame.PlayerIndex {\n\tobj, ok := c.Get(ctxViewingPlayerAsKey)\n\n\tif !ok {\n\t\treturn invalidPlayerIndex\n\t}\n\n\tplayerIndex, ok := obj.(boardgame.PlayerIndex)\n\n\tif !ok {\n\t\treturn invalidPlayerIndex\n\t}\n\n\treturn playerIndex\n}\n\nfunc (s *Server) setHasEmptySlots(c *gin.Context, hasEmptySlots bool) {\n\tc.Set(ctxHasEmptySlots, hasEmptySlots)\n}\n\nfunc (s *Server) getHasEmptySlots(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxHasEmptySlots)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\temptySlots, ok := obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn emptySlots\n}\n\nfunc (s *Server) calcViewingAsPlayerAndEmptySlots(userIds []string, user *users.StorageRecord, agents []string) (player boardgame.PlayerIndex, emptySlots []boardgame.PlayerIndex) {\n\n\tresult := boardgame.ObserverPlayerIndex\n\n\tif len(userIds) != len(agents) {\n\t\tpanic(\"Agents and UserIds were different sizes\")\n\t}\n\n\tfor i, userId := range userIds {\n\t\tif userId == \"\" && agents[i] == \"\" {\n\t\t\temptySlots = append(emptySlots, boardgame.PlayerIndex(i))\n\t\t}\n\t\tif user != nil && userId == user.Id {\n\t\t\t\/\/We're here!\n\t\t\tresult = boardgame.PlayerIndex(i)\n\t\t}\n\t}\n\n\treturn result, emptySlots\n}\n\nfunc (s *Server) getRequestPlayerIndex(c *gin.Context) boardgame.PlayerIndex {\n\tplayer := c.Query(qryPlayerKey)\n\n\tif player == \"\" {\n\n\t\tplayer = c.PostForm(qryPlayerKey)\n\n\t\tif player == \"\" {\n\t\t\treturn invalidPlayerIndex\n\t\t}\n\t}\n\n\tplayerIndexInt, err := strconv.Atoi(player)\n\n\tif err != nil {\n\t\treturn invalidPlayerIndex\n\t}\n\n\treturn boardgame.PlayerIndex(playerIndexInt)\n}\n\nfunc (s *Server) effectivePlayerIndex(c *gin.Context) boardgame.PlayerIndex {\n\n\tadminAllowed := s.getAdminAllowed(c)\n\trequestAdmin := s.getRequestAdmin(c)\n\n\tisAdmin := s.calcIsAdmin(adminAllowed, requestAdmin)\n\n\trequestPlayerIndex := s.getRequestPlayerIndex(c)\n\tviewingAsPlayer := s.getViewingAsPlayer(c)\n\n\treturn s.calcEffectivePlayerIndex(isAdmin, requestPlayerIndex, viewingAsPlayer)\n}\n\nfunc (s *Server) effectiveAutoCurrentPlayer(c *gin.Context) bool {\n\tadminAllowed := s.getAdminAllowed(c)\n\trequestAdmin := s.getRequestAdmin(c)\n\n\tisAdmin := s.calcIsAdmin(adminAllowed, requestAdmin)\n\n\tif !isAdmin {\n\t\treturn false\n\t}\n\n\treturn s.getRequestAutoCurrentPlayer(c)\n}\n\nfunc (s *Server) calcEffectivePlayerIndex(isAdmin bool, requestPlayerIndex boardgame.PlayerIndex, viewingAsPlayer boardgame.PlayerIndex) boardgame.PlayerIndex {\n\n\tresult := requestPlayerIndex\n\n\tif !isAdmin {\n\t\tresult = viewingAsPlayer\n\n\t\tif result == invalidPlayerIndex {\n\t\t\tresult = boardgame.ObserverPlayerIndex\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (s *Server) calcAdminAllowed(user *users.StorageRecord) bool {\n\tadminAllowed := true\n\n\tif user == nil {\n\t\treturn false\n\t}\n\n\tif !s.config.DisableAdminChecking {\n\n\t\t\/\/Are they allowed to be admin or not?\n\n\t\tmatchedAdmin := false\n\n\t\tfor _, userId := range s.config.AdminUserIds {\n\t\t\tif user.Id == userId {\n\t\t\t\tmatchedAdmin = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !matchedAdmin {\n\t\t\t\/\/Nope, you weren't an admin. Sorry!\n\t\t\tadminAllowed = false\n\t\t}\n\n\t}\n\n\treturn adminAllowed\n\n}\n\nfunc (s *Server) setAdminAllowed(c *gin.Context, allowed bool) {\n\tc.Set(ctxAdminAllowedKey, allowed)\n}\n\nfunc (s *Server) calcIsAdmin(adminAllowed bool, requestAdmin bool) bool {\n\treturn adminAllowed && requestAdmin\n}\n\nfunc (s *Server) getRequestAdmin(c *gin.Context) bool {\n\n\tresult := c.Query(qryAdminKey) == \"1\"\n\n\tif result {\n\t\treturn result\n\t}\n\n\treturn c.PostForm(qryAdminKey) == \"1\"\n}\n\nfunc (s *Server) getRequestAutoCurrentPlayer(c *gin.Context) bool {\n\n\tresult := c.Query(qryAutoCurrentPlayerKey) == \"1\"\n\n\tif result {\n\t\treturn result\n\t}\n\n\treturn c.PostForm(qryAutoCurrentPlayerKey) == \"1\"\n}\n\n\/\/returns true if the request asserts the user is an admin, and the user is\n\/\/allowed to be an admin.\nfunc (s *Server) getAdminAllowed(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxAdminAllowedKey)\n\n\tadminAllowed := false\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tadminAllowed, ok = obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn adminAllowed\n\n}\n\nfunc (s *Server) getMoveFromForm(c *gin.Context, game *boardgame.Game) (boardgame.Move, error) {\n\n\tmove := game.PlayerMoveByName(c.PostForm(\"MoveType\"))\n\n\tif move == nil {\n\t\treturn nil, errors.New(\"Invalid MoveType\")\n\t}\n\n\t\/\/TODO: should we use gin's Binding to do this instead?\n\n\tfor _, field := range formFields(move) {\n\n\t\trawVal := c.PostForm(field.Name)\n\n\t\tswitch field.Type {\n\t\tcase boardgame.TypeInt:\n\t\t\tif rawVal == \"\" {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"An int field had no value\", field.Name))\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"Couldn't set field\", field.Name, err))\n\t\t\t}\n\t\t\tmove.ReadSetter().SetProp(field.Name, num)\n\t\tcase boardgame.TypePlayerIndex:\n\t\t\tif rawVal == \"\" {\n\t\t\t\treturn nil, errors.New(\"An int field had no value \" + field.Name)\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"Couldn't set field \" + field.Name + \" \" + err.Error())\n\t\t\t}\n\t\t\tmove.ReadSetter().SetProp(field.Name, boardgame.PlayerIndex(num))\n\t\tcase boardgame.TypeBool:\n\t\t\tif rawVal == \"\" {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, false)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"Couldn't set field\", field.Name, err))\n\t\t\t}\n\t\t\tif num == 1 {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, true)\n\t\t\t} else {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, false)\n\t\t\t}\n\t\tcase boardgame.TypeEnumVar:\n\t\t\teVar, err := move.ReadSetter().EnumVarProp(field.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"Invalid field name: \" + err.Error())\n\t\t\t}\n\t\t\tif err := eVar.SetStringValue(rawVal); err != nil {\n\t\t\t\treturn nil, errors.New(\"Couldn't set field value: \" + err.Error())\n\t\t\t}\n\t\tcase boardgame.TypeIllegal:\n\t\t\treturn nil, errors.New(fmt.Sprint(\"Field\", field.Name, \"was an unknown value type\"))\n\t\t}\n\t}\n\n\treturn move, nil\n}\nMake it so that server will accept the int or string version of an enum.Var. Part of #457.package api\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jkomoros\/boardgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/users\"\n\t\"log\"\n\t\"strconv\"\n)\n\nconst (\n\tctxGameKey = \"ctxGame\"\n\tctxAdminAllowedKey = \"ctxAdminAllowed\"\n\tctxViewingPlayerAsKey = \"ctxViewingPlayerAs\"\n\tctxUserKey = \"ctxUser\"\n\tctxHasEmptySlots = \"ctxHasEmptySlots\"\n)\n\nconst (\n\tqryAdminKey = \"admin\"\n\tqryPlayerKey = \"player\"\n\tqryAutoCurrentPlayerKey = \"current\"\n\tqryGameIdKey = \"id\"\n\tqryGameNameKey = \"name\"\n\tqryManagerKey = \"manager\"\n\tqryNumPlayersKey = \"numplayers\"\n\tqryAgentKey = \"agent-player-\"\n\tqryGameVersion = \"version\"\n\tqryOpen = \"open\"\n\tqryVisible = \"visible\"\n)\n\nconst (\n\tinvalidPlayerIndex = boardgame.PlayerIndex(-10)\n)\n\nfunc (s *Server) getRequestManager(c *gin.Context) string {\n\treturn c.PostForm(qryManagerKey)\n}\n\nfunc (s *Server) getRequestNumPlayers(c *gin.Context) int {\n\trawValue := c.PostForm(qryNumPlayersKey)\n\n\tif rawValue == \"\" {\n\t\trawValue = \"0\"\n\t}\n\n\tnumPlayers, err := strconv.Atoi(rawValue)\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn numPlayers\n\n}\n\nfunc (s *Server) getRequestAgents(c *gin.Context, expectedNum int) []string {\n\tvar result []string\n\tfor i := 0; i < expectedNum; i++ {\n\t\tresult = append(result, c.PostForm(qryAgentKey+strconv.Itoa(i)))\n\t}\n\treturn result\n}\n\nfunc (s *Server) getRequestGameVersion(c *gin.Context) int {\n\trawVal := c.Param(qryGameVersion)\n\n\tresult, _ := strconv.Atoi(rawVal)\n\n\treturn result\n}\n\nfunc (s *Server) getRequestOpen(c *gin.Context) bool {\n\topen := c.Query(qryOpen)\n\n\tif open == \"\" {\n\n\t\topen = c.PostForm(qryOpen)\n\n\t\tif open == \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\topenInt, err := strconv.Atoi(open)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn openInt > 0\n}\n\nfunc (s *Server) getRequestVisible(c *gin.Context) bool {\n\tvisible := c.Query(qryVisible)\n\n\tif visible == \"\" {\n\n\t\tvisible = c.PostForm(qryVisible)\n\n\t\tif visible == \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tvisibleInt, err := strconv.Atoi(visible)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn visibleInt > 0\n}\n\nfunc (s *Server) getRequestGameId(c *gin.Context) string {\n\treturn c.Param(qryGameIdKey)\n}\n\nfunc (s *Server) getRequestGameName(c *gin.Context) string {\n\tresult := c.Param(qryGameNameKey)\n\tif result != \"\" {\n\t\treturn result\n\t}\n\treturn c.Query(qryGameNameKey)\n}\n\nfunc (s *Server) getRequestCookie(c *gin.Context) string {\n\tresult, err := c.Cookie(cookieName)\n\n\tif err != nil {\n\t\tlog.Println(\"Couldnt' get cookie:\", err)\n\t\treturn \"\"\n\t}\n\n\treturn result\n}\n\nfunc (s *Server) setUser(c *gin.Context, user *users.StorageRecord) {\n\tc.Set(ctxUserKey, user)\n}\n\nfunc (s *Server) getUser(c *gin.Context) *users.StorageRecord {\n\tobj, ok := c.Get(ctxUserKey)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tuser, ok := obj.(*users.StorageRecord)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn user\n}\n\nfunc (s *Server) setGame(c *gin.Context, game *boardgame.Game) {\n\tc.Set(ctxGameKey, game)\n}\n\nfunc (s *Server) getGame(c *gin.Context) *boardgame.Game {\n\tobj, ok := c.Get(ctxGameKey)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tgame, ok := obj.(*boardgame.Game)\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn game\n}\n\nfunc (s *Server) setViewingAsPlayer(c *gin.Context, playerIndex boardgame.PlayerIndex) {\n\tc.Set(ctxViewingPlayerAsKey, playerIndex)\n}\n\nfunc (s *Server) getViewingAsPlayer(c *gin.Context) boardgame.PlayerIndex {\n\tobj, ok := c.Get(ctxViewingPlayerAsKey)\n\n\tif !ok {\n\t\treturn invalidPlayerIndex\n\t}\n\n\tplayerIndex, ok := obj.(boardgame.PlayerIndex)\n\n\tif !ok {\n\t\treturn invalidPlayerIndex\n\t}\n\n\treturn playerIndex\n}\n\nfunc (s *Server) setHasEmptySlots(c *gin.Context, hasEmptySlots bool) {\n\tc.Set(ctxHasEmptySlots, hasEmptySlots)\n}\n\nfunc (s *Server) getHasEmptySlots(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxHasEmptySlots)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\temptySlots, ok := obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn emptySlots\n}\n\nfunc (s *Server) calcViewingAsPlayerAndEmptySlots(userIds []string, user *users.StorageRecord, agents []string) (player boardgame.PlayerIndex, emptySlots []boardgame.PlayerIndex) {\n\n\tresult := boardgame.ObserverPlayerIndex\n\n\tif len(userIds) != len(agents) {\n\t\tpanic(\"Agents and UserIds were different sizes\")\n\t}\n\n\tfor i, userId := range userIds {\n\t\tif userId == \"\" && agents[i] == \"\" {\n\t\t\temptySlots = append(emptySlots, boardgame.PlayerIndex(i))\n\t\t}\n\t\tif user != nil && userId == user.Id {\n\t\t\t\/\/We're here!\n\t\t\tresult = boardgame.PlayerIndex(i)\n\t\t}\n\t}\n\n\treturn result, emptySlots\n}\n\nfunc (s *Server) getRequestPlayerIndex(c *gin.Context) boardgame.PlayerIndex {\n\tplayer := c.Query(qryPlayerKey)\n\n\tif player == \"\" {\n\n\t\tplayer = c.PostForm(qryPlayerKey)\n\n\t\tif player == \"\" {\n\t\t\treturn invalidPlayerIndex\n\t\t}\n\t}\n\n\tplayerIndexInt, err := strconv.Atoi(player)\n\n\tif err != nil {\n\t\treturn invalidPlayerIndex\n\t}\n\n\treturn boardgame.PlayerIndex(playerIndexInt)\n}\n\nfunc (s *Server) effectivePlayerIndex(c *gin.Context) boardgame.PlayerIndex {\n\n\tadminAllowed := s.getAdminAllowed(c)\n\trequestAdmin := s.getRequestAdmin(c)\n\n\tisAdmin := s.calcIsAdmin(adminAllowed, requestAdmin)\n\n\trequestPlayerIndex := s.getRequestPlayerIndex(c)\n\tviewingAsPlayer := s.getViewingAsPlayer(c)\n\n\treturn s.calcEffectivePlayerIndex(isAdmin, requestPlayerIndex, viewingAsPlayer)\n}\n\nfunc (s *Server) effectiveAutoCurrentPlayer(c *gin.Context) bool {\n\tadminAllowed := s.getAdminAllowed(c)\n\trequestAdmin := s.getRequestAdmin(c)\n\n\tisAdmin := s.calcIsAdmin(adminAllowed, requestAdmin)\n\n\tif !isAdmin {\n\t\treturn false\n\t}\n\n\treturn s.getRequestAutoCurrentPlayer(c)\n}\n\nfunc (s *Server) calcEffectivePlayerIndex(isAdmin bool, requestPlayerIndex boardgame.PlayerIndex, viewingAsPlayer boardgame.PlayerIndex) boardgame.PlayerIndex {\n\n\tresult := requestPlayerIndex\n\n\tif !isAdmin {\n\t\tresult = viewingAsPlayer\n\n\t\tif result == invalidPlayerIndex {\n\t\t\tresult = boardgame.ObserverPlayerIndex\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (s *Server) calcAdminAllowed(user *users.StorageRecord) bool {\n\tadminAllowed := true\n\n\tif user == nil {\n\t\treturn false\n\t}\n\n\tif !s.config.DisableAdminChecking {\n\n\t\t\/\/Are they allowed to be admin or not?\n\n\t\tmatchedAdmin := false\n\n\t\tfor _, userId := range s.config.AdminUserIds {\n\t\t\tif user.Id == userId {\n\t\t\t\tmatchedAdmin = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !matchedAdmin {\n\t\t\t\/\/Nope, you weren't an admin. Sorry!\n\t\t\tadminAllowed = false\n\t\t}\n\n\t}\n\n\treturn adminAllowed\n\n}\n\nfunc (s *Server) setAdminAllowed(c *gin.Context, allowed bool) {\n\tc.Set(ctxAdminAllowedKey, allowed)\n}\n\nfunc (s *Server) calcIsAdmin(adminAllowed bool, requestAdmin bool) bool {\n\treturn adminAllowed && requestAdmin\n}\n\nfunc (s *Server) getRequestAdmin(c *gin.Context) bool {\n\n\tresult := c.Query(qryAdminKey) == \"1\"\n\n\tif result {\n\t\treturn result\n\t}\n\n\treturn c.PostForm(qryAdminKey) == \"1\"\n}\n\nfunc (s *Server) getRequestAutoCurrentPlayer(c *gin.Context) bool {\n\n\tresult := c.Query(qryAutoCurrentPlayerKey) == \"1\"\n\n\tif result {\n\t\treturn result\n\t}\n\n\treturn c.PostForm(qryAutoCurrentPlayerKey) == \"1\"\n}\n\n\/\/returns true if the request asserts the user is an admin, and the user is\n\/\/allowed to be an admin.\nfunc (s *Server) getAdminAllowed(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxAdminAllowedKey)\n\n\tadminAllowed := false\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tadminAllowed, ok = obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn adminAllowed\n\n}\n\nfunc (s *Server) getMoveFromForm(c *gin.Context, game *boardgame.Game) (boardgame.Move, error) {\n\n\tmove := game.PlayerMoveByName(c.PostForm(\"MoveType\"))\n\n\tif move == nil {\n\t\treturn nil, errors.New(\"Invalid MoveType\")\n\t}\n\n\t\/\/TODO: should we use gin's Binding to do this instead?\n\n\tfor _, field := range formFields(move) {\n\n\t\trawVal := c.PostForm(field.Name)\n\n\t\tswitch field.Type {\n\t\tcase boardgame.TypeInt:\n\t\t\tif rawVal == \"\" {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"An int field had no value\", field.Name))\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"Couldn't set field\", field.Name, err))\n\t\t\t}\n\t\t\tmove.ReadSetter().SetProp(field.Name, num)\n\t\tcase boardgame.TypePlayerIndex:\n\t\t\tif rawVal == \"\" {\n\t\t\t\treturn nil, errors.New(\"An int field had no value \" + field.Name)\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"Couldn't set field \" + field.Name + \" \" + err.Error())\n\t\t\t}\n\t\t\tmove.ReadSetter().SetProp(field.Name, boardgame.PlayerIndex(num))\n\t\tcase boardgame.TypeBool:\n\t\t\tif rawVal == \"\" {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, false)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprint(\"Couldn't set field\", field.Name, err))\n\t\t\t}\n\t\t\tif num == 1 {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, true)\n\t\t\t} else {\n\t\t\t\tmove.ReadSetter().SetProp(field.Name, false)\n\t\t\t}\n\t\tcase boardgame.TypeEnumVar:\n\t\t\teVar, err := move.ReadSetter().EnumVarProp(field.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"Invalid field name: \" + err.Error())\n\t\t\t}\n\n\t\t\tnum, err := strconv.Atoi(rawVal)\n\t\t\tif err == nil {\n\t\t\t\tif err := eVar.SetValue(num); err != nil {\n\t\t\t\t\treturn nil, errors.New(\"Couldn't set number value: \" + err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/Guess it was a string value\n\t\t\t\tif err := eVar.SetStringValue(rawVal); err != nil {\n\t\t\t\t\treturn nil, errors.New(\"Couldn't set field value: \" + err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase boardgame.TypeIllegal:\n\t\t\treturn nil, errors.New(fmt.Sprint(\"Field\", field.Name, \"was an unknown value type\"))\n\t\t}\n\t}\n\n\treturn move, nil\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n)\n\n\/\/ VtctlClientProcess is a generic handle for a running vtctlclient command .\n\/\/ It can be spawned manually\ntype VtctlClientProcess struct {\n\tName string\n\tBinary string\n\tServer string\n\tTempDirectory string\n\tZoneName string\n}\n\n\/\/ InitShardMaster executes vtctlclient command to make one of tablet as master\nfunc (vtctlclient *VtctlClientProcess) InitShardMaster(Keyspace string, Shard string, Cell string, TabletUID int) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"InitShardMaster\",\n\t\t\"-force\",\n\t\tfmt.Sprintf(\"%s\/%s\", Keyspace, Shard),\n\t\tfmt.Sprintf(\"%s-%d\", Cell, TabletUID))\n}\n\n\/\/ ApplySchema applies SQL schema to the keyspace\nfunc (vtctlclient *VtctlClientProcess) ApplySchema(Keyspace string, SQL string) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"ApplySchema\",\n\t\t\"-sql\", SQL,\n\t\tKeyspace)\n}\n\n\/\/ ApplyVSchema applies vitess schema (JSON format) to the keyspace\nfunc (vtctlclient *VtctlClientProcess) ApplyVSchema(Keyspace string, JSON string) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"ApplyVSchema\",\n\t\t\"-vschema\", JSON,\n\t\tKeyspace,\n\t)\n}\n\n\/\/ ExecuteCommand executes any vtctlclient command\nfunc (vtctlclient *VtctlClientProcess) ExecuteCommand(args ...string) (err error) {\n\tpArgs := []string{\"-server\", vtctlclient.Server}\n\n\tif *isCoverage {\n\t\tpArgs = append(pArgs, \"-test.coverprofile=\"+getCoveragePath(\"vtctlclient-\"+args[0]+\".out\"), \"-test.v\")\n\t}\n\tpArgs = append(pArgs, args...)\n\ttmpProcess := exec.Command(\n\t\tvtctlclient.Binary,\n\t\tpArgs...,\n\t)\n\tlog.Infof(\"Executing vtctlclient with command: %v\", strings.Join(tmpProcess.Args, \" \"))\n\treturn tmpProcess.Run()\n}\n\n\/\/ ExecuteCommandWithOutput executes any vtctlclient command and returns output\nfunc (vtctlclient *VtctlClientProcess) ExecuteCommandWithOutput(args ...string) (result string, err error) {\n\tpArgs := []string{\"-server\", vtctlclient.Server}\n\tif *isCoverage {\n\t\tpArgs = append(pArgs, \"-test.coverprofile=\"+getCoveragePath(\"vtctlclient-\"+args[0]+\".out\"), \"-test.v\")\n\t}\n\tpArgs = append(pArgs, args...)\n\ttmpProcess := exec.Command(\n\t\tvtctlclient.Binary,\n\t\tpArgs...,\n\t)\n\tlog.Infof(\"Executing vtctlclient with command: %v\", strings.Join(tmpProcess.Args, \" \"))\n\tresultByte, err := tmpProcess.CombinedOutput()\n\treturn filterResultWhenRunsForCoverage(string(resultByte)), err\n}\n\n\/\/ VtctlClientProcessInstance returns a VtctlProcess handle for vtctlclient process\n\/\/ configured with the given Config.\nfunc VtctlClientProcessInstance(hostname string, grpcPort int, tmpDirectory string) *VtctlClientProcess {\n\tvtctlclient := &VtctlClientProcess{\n\t\tName: \"vtctlclient\",\n\t\tBinary: \"vtctlclient\",\n\t\tServer: fmt.Sprintf(\"%s:%d\", hostname, grpcPort),\n\t\tTempDirectory: tmpDirectory,\n\t}\n\treturn vtctlclient\n}\n\n\/\/ InitTablet initializes a tablet\nfunc (vtctlclient *VtctlClientProcess) InitTablet(tablet *Vttablet, cell string, keyspaceName string, hostname string, shardName string) error {\n\ttabletType := \"replica\"\n\tif tablet.Type == \"rdonly\" {\n\t\ttabletType = \"rdonly\"\n\t}\n\targs := []string{\"InitTablet\", \"-hostname\", hostname,\n\t\t\"-port\", fmt.Sprintf(\"%d\", tablet.HTTPPort), \"-allow_update\", \"-parent\",\n\t\t\"-keyspace\", keyspaceName,\n\t\t\"-shard\", shardName}\n\tif tablet.MySQLPort > 0 {\n\t\targs = append(args, \"-mysql_port\", fmt.Sprintf(\"%d\", tablet.MySQLPort))\n\t}\n\tif tablet.GrpcPort > 0 {\n\t\targs = append(args, \"-grpc_port\", fmt.Sprintf(\"%d\", tablet.GrpcPort))\n\t}\n\targs = append(args, fmt.Sprintf(\"%s-%010d\", cell, tablet.TabletUID), tabletType)\n\treturn vtctlclient.ExecuteCommand(args...)\n}\nInitial schema: log output if vtctlclient errors out, for debugging CI errors\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n)\n\n\/\/ VtctlClientProcess is a generic handle for a running vtctlclient command .\n\/\/ It can be spawned manually\ntype VtctlClientProcess struct {\n\tName string\n\tBinary string\n\tServer string\n\tTempDirectory string\n\tZoneName string\n}\n\n\/\/ InitShardMaster executes vtctlclient command to make one of tablet as master\nfunc (vtctlclient *VtctlClientProcess) InitShardMaster(Keyspace string, Shard string, Cell string, TabletUID int) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"InitShardMaster\",\n\t\t\"-force\",\n\t\tfmt.Sprintf(\"%s\/%s\", Keyspace, Shard),\n\t\tfmt.Sprintf(\"%s-%d\", Cell, TabletUID))\n}\n\n\/\/ ApplySchema applies SQL schema to the keyspace\nfunc (vtctlclient *VtctlClientProcess) ApplySchema(Keyspace string, SQL string) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"ApplySchema\",\n\t\t\"-sql\", SQL,\n\t\tKeyspace)\n}\n\n\/\/ ApplyVSchema applies vitess schema (JSON format) to the keyspace\nfunc (vtctlclient *VtctlClientProcess) ApplyVSchema(Keyspace string, JSON string) (err error) {\n\treturn vtctlclient.ExecuteCommand(\n\t\t\"ApplyVSchema\",\n\t\t\"-vschema\", JSON,\n\t\tKeyspace,\n\t)\n}\n\n\/\/ ExecuteCommand executes any vtctlclient command\nfunc (vtctlclient *VtctlClientProcess) ExecuteCommand(args ...string) (err error) {\n\tpArgs := []string{\"-server\", vtctlclient.Server}\n\n\tif *isCoverage {\n\t\tpArgs = append(pArgs, \"-test.coverprofile=\"+getCoveragePath(\"vtctlclient-\"+args[0]+\".out\"), \"-test.v\")\n\t}\n\tpArgs = append(pArgs, args...)\n\ttmpProcess := exec.Command(\n\t\tvtctlclient.Binary,\n\t\tpArgs...,\n\t)\n\tlog.Infof(\"Executing vtctlclient with command: %v\", strings.Join(tmpProcess.Args, \" \"))\n\toutput, err := tmpProcess.Output()\n\tif err != nil {\n\t\tlog.Errorf(\"Error executing %s: output %s, err %v\", strings.Join(tmpProcess.Args, \" \"), output, err)\n\t}\n\treturn err\n}\n\n\/\/ ExecuteCommandWithOutput executes any vtctlclient command and returns output\nfunc (vtctlclient *VtctlClientProcess) ExecuteCommandWithOutput(args ...string) (result string, err error) {\n\tpArgs := []string{\"-server\", vtctlclient.Server}\n\tif *isCoverage {\n\t\tpArgs = append(pArgs, \"-test.coverprofile=\"+getCoveragePath(\"vtctlclient-\"+args[0]+\".out\"), \"-test.v\")\n\t}\n\tpArgs = append(pArgs, args...)\n\ttmpProcess := exec.Command(\n\t\tvtctlclient.Binary,\n\t\tpArgs...,\n\t)\n\tlog.Infof(\"Executing vtctlclient with command: %v\", strings.Join(tmpProcess.Args, \" \"))\n\tresultByte, err := tmpProcess.CombinedOutput()\n\treturn filterResultWhenRunsForCoverage(string(resultByte)), err\n}\n\n\/\/ VtctlClientProcessInstance returns a VtctlProcess handle for vtctlclient process\n\/\/ configured with the given Config.\nfunc VtctlClientProcessInstance(hostname string, grpcPort int, tmpDirectory string) *VtctlClientProcess {\n\tvtctlclient := &VtctlClientProcess{\n\t\tName: \"vtctlclient\",\n\t\tBinary: \"vtctlclient\",\n\t\tServer: fmt.Sprintf(\"%s:%d\", hostname, grpcPort),\n\t\tTempDirectory: tmpDirectory,\n\t}\n\treturn vtctlclient\n}\n\n\/\/ InitTablet initializes a tablet\nfunc (vtctlclient *VtctlClientProcess) InitTablet(tablet *Vttablet, cell string, keyspaceName string, hostname string, shardName string) error {\n\ttabletType := \"replica\"\n\tif tablet.Type == \"rdonly\" {\n\t\ttabletType = \"rdonly\"\n\t}\n\targs := []string{\"InitTablet\", \"-hostname\", hostname,\n\t\t\"-port\", fmt.Sprintf(\"%d\", tablet.HTTPPort), \"-allow_update\", \"-parent\",\n\t\t\"-keyspace\", keyspaceName,\n\t\t\"-shard\", shardName}\n\tif tablet.MySQLPort > 0 {\n\t\targs = append(args, \"-mysql_port\", fmt.Sprintf(\"%d\", tablet.MySQLPort))\n\t}\n\tif tablet.GrpcPort > 0 {\n\t\targs = append(args, \"-grpc_port\", fmt.Sprintf(\"%d\", tablet.GrpcPort))\n\t}\n\targs = append(args, fmt.Sprintf(\"%s-%010d\", cell, tablet.TabletUID), tabletType)\n\treturn vtctlclient.ExecuteCommand(args...)\n}\n<|endoftext|>"} {"text":"package proxy\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/asciimoo\/filtron\/rule\"\n)\n\nvar transport *http.Transport = &http.Transport{\n\t\/\/ TODO without this sometimes uwsgi closes connection\n\tDisableKeepAlives: true,\n}\n\nvar client *http.Client = &http.Client{Transport: transport}\n\ntype Proxy struct {\n\tNumberOfRequests uint\n\ttarget string\n\ttransport *http.Transport\n\trules *[]*rule.Rule\n}\n\nfunc Listen(address, target string, rules *[]*rule.Rule) *Proxy {\n\tlog.Println(\"Proxy listens on\", address)\n\tp := &Proxy{0, target, &http.Transport{}, rules}\n\ts := http.NewServeMux()\n\ts.HandleFunc(\"\/\", p.Handler)\n\tgo func(address string, s *http.ServeMux) {\n\t\thttp.ListenAndServe(address, s)\n\t}(address, s)\n\treturn p\n}\n\nfunc (p *Proxy) Handler(w http.ResponseWriter, r *http.Request) {\n\turi, err := url.Parse(p.target)\n\tfatal(err)\n\terr = r.ParseForm()\n\turi.Path = path.Join(uri.Path, r.URL.Path)\n\turi.RawQuery = r.URL.RawQuery\n\n\tfatal(err)\n\n\texceeded := false\n\tfor _, rule := range *p.rules {\n\t\tif rule.IsLimitExceeded(r) {\n\t\t\texceeded = true\n\t\t}\n\t}\n\tif exceeded {\n\t\tw.WriteHeader(429)\n\t\tw.Write([]byte(\"Rate limit exceeded\"))\n\t\tlog.Println(\"Blocked:\", uri.String())\n\t\treturn\n\t}\n\n\tlog.Println(r.Method, uri.String(), r.PostForm.Encode())\n\n\trr, err := http.NewRequest(r.Method, uri.String(), bytes.NewBufferString(r.PostForm.Encode()))\n\tfatal(err)\n\tcopyHeaders(r.Header, &rr.Header)\n\n\tresp, err := client.Do(rr)\n\tif err != nil {\n\t\tlog.Println(\"Response error:\", err, resp)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tfatal(err)\n\n\tdH := w.Header()\n\tcopyHeaders(resp.Header, &dH)\n\tw.WriteHeader(resp.StatusCode)\n\n\tw.Write(body)\n}\n\nfunc (p *Proxy) ReloadRules(filename string) error {\n\trules, err := rule.ParseJSON(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.rules = &rules\n\treturn nil\n}\n\nfunc fatal(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc copyHeaders(source http.Header, dest *http.Header) {\n\tfor n, v := range source {\n\t\tfor _, vv := range v {\n\t\t\tdest.Add(n, vv)\n\t\t}\n\t}\n}\n[fix] connection closepackage proxy\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/asciimoo\/filtron\/rule\"\n)\n\nvar transport *http.Transport = &http.Transport{\n\tDisableKeepAlives: false,\n}\n\nvar client *http.Client = &http.Client{Transport: transport}\n\ntype Proxy struct {\n\tNumberOfRequests uint\n\ttarget string\n\ttransport *http.Transport\n\trules *[]*rule.Rule\n}\n\nfunc Listen(address, target string, rules *[]*rule.Rule) *Proxy {\n\tlog.Println(\"Proxy listens on\", address)\n\tp := &Proxy{0, target, &http.Transport{}, rules}\n\ts := http.NewServeMux()\n\ts.HandleFunc(\"\/\", p.Handler)\n\tgo func(address string, s *http.ServeMux) {\n\t\thttp.ListenAndServe(address, s)\n\t}(address, s)\n\treturn p\n}\n\nfunc (p *Proxy) Handler(w http.ResponseWriter, r *http.Request) {\n\turi, err := url.Parse(p.target)\n\tfatal(err)\n\terr = r.ParseForm()\n\turi.Path = path.Join(uri.Path, r.URL.Path)\n\turi.RawQuery = r.URL.RawQuery\n\n\tfatal(err)\n\n\texceeded := false\n\tfor _, rule := range *p.rules {\n\t\tif rule.IsLimitExceeded(r) {\n\t\t\texceeded = true\n\t\t}\n\t}\n\tif exceeded {\n\t\tw.WriteHeader(429)\n\t\tw.Write([]byte(\"Rate limit exceeded\"))\n\t\tlog.Println(\"Blocked:\", uri.String())\n\t\treturn\n\t}\n\n\tvar appRequest *http.Request\n\tif r.Method == \"POST\" || r.Method == \"PUT\" {\n\t\tappRequest, err = http.NewRequest(r.Method, uri.String(), bytes.NewBufferString(r.PostForm.Encode()))\n\t} else {\n\t\tappRequest, err = http.NewRequest(r.Method, uri.String(), nil)\n\t}\n\tfatal(err)\n\tcopyHeaders(r.Header, &appRequest.Header)\n\n\tresp, err := client.Do(appRequest)\n\tif err != nil {\n\t\tlog.Println(\"Response error:\", err, resp)\n\t\tw.WriteHeader(429)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tfatal(err)\n\n\tdH := w.Header()\n\tcopyHeaders(resp.Header, &dH)\n\tw.WriteHeader(resp.StatusCode)\n\n\tw.Write(body)\n}\n\nfunc (p *Proxy) ReloadRules(filename string) error {\n\trules, err := rule.ParseJSON(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.rules = &rules\n\treturn nil\n}\n\nfunc fatal(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc copyHeaders(source http.Header, dest *http.Header) {\n\tfor n, v := range source {\n\t\tif n == \"Connection\" || n == \"Accept-Encoding\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, vv := range v {\n\t\t\tdest.Add(n, vv)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schema\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\tbinlogdatapb \"vitess.io\/vitess\/go\/vt\/proto\/binlogdata\"\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tabletserver\/tabletenv\"\n\t\"vitess.io\/vitess\/go\/vt\/withddl\"\n)\n\nconst createSchemaTrackingTable = `CREATE TABLE IF NOT EXISTS _vt.schema_version (\n\t\t id INT AUTO_INCREMENT,\n\t\t pos VARBINARY(10000) NOT NULL,\n\t\t time_updated BIGINT(20) NOT NULL,\n\t\t ddl VARBINARY(1000) DEFAULT NULL,\n\t\t schemax BLOB NOT NULL,\n\t\t PRIMARY KEY (id)\n\t\t) ENGINE=InnoDB`\nconst alterSchemaTrackingTable = \"alter table _vt.schema_version modify column ddl BLOB NOT NULL\"\n\nvar withDDL = withddl.New([]string{createSchemaTrackingTable, alterSchemaTrackingTable})\n\n\/\/ VStreamer defines the functions of VStreamer\n\/\/ that the replicationWatcher needs.\ntype VStreamer interface {\n\tStream(ctx context.Context, startPos string, tablePKs []*binlogdatapb.TableLastPK, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error\n}\n\n\/\/ Tracker watches the replication and saves the latest schema into _vt.schema_version when a DDL is encountered.\ntype Tracker struct {\n\tenabled bool\n\n\tmu sync.Mutex\n\tcancel context.CancelFunc\n\twg sync.WaitGroup\n\n\tenv tabletenv.Env\n\tvs VStreamer\n\tengine *Engine\n}\n\n\/\/ NewTracker creates a Tracker, needs an Open SchemaEngine (which implements the trackerEngine interface)\nfunc NewTracker(env tabletenv.Env, vs VStreamer, engine *Engine) *Tracker {\n\treturn &Tracker{\n\t\tenabled: env.Config().TrackSchemaVersions,\n\t\tenv: env,\n\t\tvs: vs,\n\t\tengine: engine,\n\t}\n}\n\n\/\/ Open enables the tracker functionality\nfunc (tr *Tracker) Open() {\n\tif !tr.enabled {\n\t\tlog.Info(\"Schema tracker is not enabled.\")\n\t\treturn\n\t}\n\n\ttr.mu.Lock()\n\tdefer tr.mu.Unlock()\n\tif tr.cancel != nil {\n\t\treturn\n\t}\n\n\tctx, cancel := context.WithCancel(tabletenv.LocalContext())\n\ttr.cancel = cancel\n\ttr.wg.Add(1)\n\tlog.Info(\"Schema tracker enabled.\")\n\tgo tr.process(ctx)\n}\n\n\/\/ Close disables the tracker functionality\nfunc (tr *Tracker) Close() {\n\ttr.mu.Lock()\n\tdefer tr.mu.Unlock()\n\tif tr.cancel == nil {\n\t\treturn\n\t}\n\n\tlog.Info(\"Schema tracker stopped.\")\n\ttr.cancel()\n\ttr.cancel = nil\n\ttr.wg.Wait()\n}\n\n\/\/ Enable forces tracking to be on or off.\n\/\/ Only used for testing.\nfunc (tr *Tracker) Enable(enabled bool) {\n\ttr.mu.Lock()\n\ttr.enabled = enabled\n\ttr.mu.Unlock()\n\tif enabled {\n\t\ttr.Open()\n\t} else {\n\t\ttr.Close()\n\t}\n}\n\nfunc (tr *Tracker) process(ctx context.Context) {\n\tdefer tr.env.LogError()\n\tdefer tr.wg.Done()\n\n\tfilter := &binlogdatapb.Filter{\n\t\tRules: []*binlogdatapb.Rule{{\n\t\t\tMatch: \"\/.*\",\n\t\t}},\n\t}\n\n\tvar gtid string\n\tfor {\n\t\terr := tr.vs.Stream(ctx, \"current\", nil, filter, func(events []*binlogdatapb.VEvent) error {\n\t\t\tfor _, event := range events {\n\t\t\t\tif event.Type == binlogdatapb.VEventType_GTID {\n\t\t\t\t\tgtid = event.Gtid\n\t\t\t\t}\n\t\t\t\tif event.Type == binlogdatapb.VEventType_DDL {\n\t\t\t\t\tif err := tr.schemaUpdated(gtid, event.Ddl, event.Timestamp); err != nil {\n\t\t\t\t\t\ttr.env.Stats().ErrorCounters.Add(vtrpcpb.Code_INTERNAL.String(), 1)\n\t\t\t\t\t\tlog.Errorf(\"Error updating schema: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t\tlog.Infof(\"Tracker's vStream ended: %v, retrying in 5 seconds\", err)\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\nfunc (tr *Tracker) schemaUpdated(gtid string, ddl string, timestamp int64) error {\n\tlog.Infof(\"Processing schemaUpdated event for gtid %s, ddl %s\", gtid, ddl)\n\tif gtid == \"\" || ddl == \"\" {\n\t\treturn fmt.Errorf(\"got invalid gtid or ddl in schemaUpdated\")\n\t}\n\tctx := context.Background()\n\n\t\/\/ Engine will have reloaded the schema because vstream will reload it on a DDL\n\ttables := tr.engine.GetSchema()\n\tdbSchema := &binlogdatapb.MinimalSchema{\n\t\tTables: []*binlogdatapb.MinimalTable{},\n\t}\n\tfor _, table := range tables {\n\t\tdbSchema.Tables = append(dbSchema.Tables, newMinimalTable(table))\n\t}\n\tblob, _ := proto.Marshal(dbSchema)\n\n\tconn, err := tr.engine.GetConnection(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Recycle()\n\n\tquery := fmt.Sprintf(\"insert into _vt.schema_version \"+\n\t\t\"(pos, ddl, schemax, time_updated) \"+\n\t\t\"values (%v, %v, %v, %d)\", encodeString(gtid), encodeString(ddl), encodeString(string(blob)), timestamp)\n\t_, err = withDDL.Exec(ctx, query, conn.Exec)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newMinimalTable(st *Table) *binlogdatapb.MinimalTable {\n\ttable := &binlogdatapb.MinimalTable{\n\t\tName: st.Name.String(),\n\t\tFields: st.Fields,\n\t}\n\tvar pkc []int64\n\tfor _, pk := range st.PKColumns {\n\t\tpkc = append(pkc, int64(pk))\n\t}\n\ttable.PKColumns = pkc\n\treturn table\n}\n\nfunc encodeString(in string) string {\n\tbuf := bytes.NewBuffer(nil)\n\tsqltypes.NewVarChar(in).EncodeSQL(buf)\n\treturn buf.String()\n}\nschema_version table: change schemax to longblob\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schema\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"vitess.io\/vitess\/go\/vt\/sqlparser\"\n\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\tbinlogdatapb \"vitess.io\/vitess\/go\/vt\/proto\/binlogdata\"\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tabletserver\/tabletenv\"\n\t\"vitess.io\/vitess\/go\/vt\/withddl\"\n)\n\nconst createSchemaTrackingTable = `CREATE TABLE IF NOT EXISTS _vt.schema_version (\n\t\t id INT AUTO_INCREMENT,\n\t\t pos VARBINARY(10000) NOT NULL,\n\t\t time_updated BIGINT(20) NOT NULL,\n\t\t ddl VARBINARY(1000) DEFAULT NULL,\n\t\t schemax BLOB NOT NULL,\n\t\t PRIMARY KEY (id)\n\t\t) ENGINE=InnoDB`\nconst alterSchemaTrackingTableDDLBlob = \"alter table _vt.schema_version modify column ddl BLOB NOT NULL\"\nconst alterSchemaTrackingTableSchemaxBlob = \"alter table _vt.schema_version modify column schemax LONGBLOB NOT NULL\"\n\nvar withDDL = withddl.New([]string{\n\tcreateSchemaTrackingTable,\n\talterSchemaTrackingTableDDLBlob,\n\talterSchemaTrackingTableSchemaxBlob,\n})\n\n\/\/ VStreamer defines the functions of VStreamer\n\/\/ that the replicationWatcher needs.\ntype VStreamer interface {\n\tStream(ctx context.Context, startPos string, tablePKs []*binlogdatapb.TableLastPK, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error\n}\n\n\/\/ Tracker watches the replication and saves the latest schema into _vt.schema_version when a DDL is encountered.\ntype Tracker struct {\n\tenabled bool\n\n\tmu sync.Mutex\n\tcancel context.CancelFunc\n\twg sync.WaitGroup\n\n\tenv tabletenv.Env\n\tvs VStreamer\n\tengine *Engine\n}\n\n\/\/ NewTracker creates a Tracker, needs an Open SchemaEngine (which implements the trackerEngine interface)\nfunc NewTracker(env tabletenv.Env, vs VStreamer, engine *Engine) *Tracker {\n\treturn &Tracker{\n\t\tenabled: env.Config().TrackSchemaVersions,\n\t\tenv: env,\n\t\tvs: vs,\n\t\tengine: engine,\n\t}\n}\n\n\/\/ Open enables the tracker functionality\nfunc (tr *Tracker) Open() {\n\tif !tr.enabled {\n\t\tlog.Info(\"Schema tracker is not enabled.\")\n\t\treturn\n\t}\n\n\ttr.mu.Lock()\n\tdefer tr.mu.Unlock()\n\tif tr.cancel != nil {\n\t\treturn\n\t}\n\n\tctx, cancel := context.WithCancel(tabletenv.LocalContext())\n\ttr.cancel = cancel\n\ttr.wg.Add(1)\n\tlog.Info(\"Schema tracker enabled.\")\n\tgo tr.process(ctx)\n}\n\n\/\/ Close disables the tracker functionality\nfunc (tr *Tracker) Close() {\n\ttr.mu.Lock()\n\tdefer tr.mu.Unlock()\n\tif tr.cancel == nil {\n\t\treturn\n\t}\n\n\tlog.Info(\"Schema tracker stopped.\")\n\ttr.cancel()\n\ttr.cancel = nil\n\ttr.wg.Wait()\n}\n\n\/\/ Enable forces tracking to be on or off.\n\/\/ Only used for testing.\nfunc (tr *Tracker) Enable(enabled bool) {\n\ttr.mu.Lock()\n\ttr.enabled = enabled\n\ttr.mu.Unlock()\n\tif enabled {\n\t\ttr.Open()\n\t} else {\n\t\ttr.Close()\n\t}\n}\n\nfunc (tr *Tracker) process(ctx context.Context) {\n\tdefer tr.env.LogError()\n\tdefer tr.wg.Done()\n\n\tfilter := &binlogdatapb.Filter{\n\t\tRules: []*binlogdatapb.Rule{{\n\t\t\tMatch: \"\/.*\",\n\t\t}},\n\t}\n\n\tvar gtid string\n\tfor {\n\t\terr := tr.vs.Stream(ctx, \"current\", nil, filter, func(events []*binlogdatapb.VEvent) error {\n\t\t\tfor _, event := range events {\n\t\t\t\tif event.Type == binlogdatapb.VEventType_GTID {\n\t\t\t\t\tgtid = event.Gtid\n\t\t\t\t}\n\t\t\t\tif event.Type == binlogdatapb.VEventType_DDL {\n\t\t\t\t\tif err := tr.schemaUpdated(gtid, event.Ddl, event.Timestamp); err != nil {\n\t\t\t\t\t\ttr.env.Stats().ErrorCounters.Add(vtrpcpb.Code_INTERNAL.String(), 1)\n\t\t\t\t\t\tlog.Errorf(\"Error updating schema: %s\", sqlparser.TruncateForLog(err.Error()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-time.After(5 * time.Second):\n\t\t}\n\t\tlog.Infof(\"Tracker's vStream ended: %v, retrying in 5 seconds\", err)\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\nfunc (tr *Tracker) schemaUpdated(gtid string, ddl string, timestamp int64) error {\n\tlog.Infof(\"Processing schemaUpdated event for gtid %s, ddl %s\", gtid, ddl)\n\tif gtid == \"\" || ddl == \"\" {\n\t\treturn fmt.Errorf(\"got invalid gtid or ddl in schemaUpdated\")\n\t}\n\tctx := context.Background()\n\n\t\/\/ Engine will have reloaded the schema because vstream will reload it on a DDL\n\ttables := tr.engine.GetSchema()\n\tdbSchema := &binlogdatapb.MinimalSchema{\n\t\tTables: []*binlogdatapb.MinimalTable{},\n\t}\n\tfor _, table := range tables {\n\t\tdbSchema.Tables = append(dbSchema.Tables, newMinimalTable(table))\n\t}\n\tblob, _ := proto.Marshal(dbSchema)\n\n\tconn, err := tr.engine.GetConnection(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Recycle()\n\n\tquery := fmt.Sprintf(\"insert into _vt.schema_version \"+\n\t\t\"(pos, ddl, schemax, time_updated) \"+\n\t\t\"values (%v, %v, %v, %d)\", encodeString(gtid), encodeString(ddl), encodeString(string(blob)), timestamp)\n\t_, err = withDDL.Exec(ctx, query, conn.Exec)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newMinimalTable(st *Table) *binlogdatapb.MinimalTable {\n\ttable := &binlogdatapb.MinimalTable{\n\t\tName: st.Name.String(),\n\t\tFields: st.Fields,\n\t}\n\tvar pkc []int64\n\tfor _, pk := range st.PKColumns {\n\t\tpkc = append(pkc, int64(pk))\n\t}\n\ttable.PKColumns = pkc\n\treturn table\n}\n\nfunc encodeString(in string) string {\n\tbuf := bytes.NewBuffer(nil)\n\tsqltypes.NewVarChar(in).EncodeSQL(buf)\n\treturn buf.String()\n}\n<|endoftext|>"} {"text":"package gorequest\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestGetRequest(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"GET\", req.Method, \"Should equal request method\")\n\n\t\tresp.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(resp, \"Hello World\")\n\t}))\n\n\tr := NewRequestBuilder().WithUrl(ts.URL).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n\tassert.Equal(t, \"Hello World\", string(r.Body()), \"Should equal response body\")\n}\n\nfunc TestPostRequestWithTextBody(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method, \"Should equal request method\")\n\t\tassert.Equal(t, \"text\/plain\", req.Header.Get(\"Content-Type\"), \"Should equal Content-Type header\")\n\n\t\tdefer req.Body.Close()\n\n\t\tif b, err := ioutil.ReadAll(req.Body); err != nil {\n\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(resp, err.Error())\n\t\t} else {\n\t\t\tresp.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintf(resp, string(b))\n\t\t}\n\t}))\n\n\tr := NewRequestBuilder().WithMethod(\"POST\").WithUrl(ts.URL).WithTextBody(\"Hello World\").Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n\tassert.Equal(t, \"Hello World\", string(r.Body()), \"Should equal request body\")\n}\n\nfunc TestPostJsonRequest(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method, \"Should equal request method\")\n\t\tassert.Equal(t, \"application\/json\", req.Header.Get(\"Content-Type\"), \"Should equal Content-Type header\")\n\n\t\tvar s *testJsonStruct\n\n\t\tdecoder := json.NewDecoder(req.Body)\n\n\t\tif err := decoder.Decode(&s); err != nil {\n\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(resp, err.Error())\n\t\t} else {\n\t\t\tassert.Equal(t, 10, s.IntField, \"Should equal IntField\")\n\t\t\tassert.Equal(t, \"Hello World\", s.StringField, \"Should equal StringField\")\n\t\t\tassert.True(t, s.BoolField, \"Should be true\")\n\n\t\t\tresp.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintf(resp, \"OK\")\n\t\t}\n\t}))\n\n\ttestJsonData := &testJsonStruct{\n\t\tIntField: 10,\n\t\tStringField: \"Hello World\",\n\t\tBoolField: true,\n\t}\n\n\tr := NewRequestBuilder().WithMethod(\"POST\").WithUrl(ts.URL).WithJsonBody(testJsonData).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\n\n\/\/func TestPutRequest(t *testing.T) {\n\/\/\tassert.True(t, false, \"Not Implemented\")\n\/\/}\n\n\/\/func TestDeleteRequest(t *testing.T) {\n\/\/\tassert.True(t, false, \"Not Implemented\")\n\/\/}\n\nfunc TestBasicAuthentication(t *testing.T) {\n\tr := NewRequestBuilder().WithMethod(\"GET\").WithUrl(POSTMAN_ECHO_BASIC_AUTH_ENDPOINT).WithBasicAuth(\"postman\", \"password\").Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\n\nfunc TestBasicAuthenticationWithRFC1738(t *testing.T) {\n\tbasicAuthEndpoint := \"https:\/\/postman:password@postman-echo.com\/basic-auth\"\n\tr := NewRequestBuilder().WithMethod(\"GET\").WithRFC1738(basicAuthEndpoint).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\nFixed issue in which the testserver was not being closed.package gorequest\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestGetRequest(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"GET\", req.Method, \"Should equal request method\")\n\n\t\tresp.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(resp, \"Hello World\")\n\t}))\n\tdefer ts.Close()\n\n\tr := NewRequestBuilder().WithUrl(ts.URL).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n\tassert.Equal(t, \"Hello World\", string(r.Body()), \"Should equal response body\")\n}\n\nfunc TestPostRequestWithTextBody(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method, \"Should equal request method\")\n\t\tassert.Equal(t, \"text\/plain\", req.Header.Get(\"Content-Type\"), \"Should equal Content-Type header\")\n\n\t\tdefer req.Body.Close()\n\n\t\tif b, err := ioutil.ReadAll(req.Body); err != nil {\n\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(resp, err.Error())\n\t\t} else {\n\t\t\tresp.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintf(resp, string(b))\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tr := NewRequestBuilder().WithMethod(\"POST\").WithUrl(ts.URL).WithTextBody(\"Hello World\").Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n\tassert.Equal(t, \"Hello World\", string(r.Body()), \"Should equal request body\")\n}\n\nfunc TestPostJsonRequest(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, \"POST\", req.Method, \"Should equal request method\")\n\t\tassert.Equal(t, \"application\/json\", req.Header.Get(\"Content-Type\"), \"Should equal Content-Type header\")\n\n\t\tvar s *testJsonStruct\n\n\t\tdecoder := json.NewDecoder(req.Body)\n\n\t\tif err := decoder.Decode(&s); err != nil {\n\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(resp, err.Error())\n\t\t} else {\n\t\t\tassert.Equal(t, 10, s.IntField, \"Should equal IntField\")\n\t\t\tassert.Equal(t, \"Hello World\", s.StringField, \"Should equal StringField\")\n\t\t\tassert.True(t, s.BoolField, \"Should be true\")\n\n\t\t\tresp.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprintf(resp, \"OK\")\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\ttestJsonData := &testJsonStruct{\n\t\tIntField: 10,\n\t\tStringField: \"Hello World\",\n\t\tBoolField: true,\n\t}\n\n\tr := NewRequestBuilder().WithMethod(\"POST\").WithUrl(ts.URL).WithJsonBody(testJsonData).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\n\n\/\/func TestPutRequest(t *testing.T) {\n\/\/\tassert.True(t, false, \"Not Implemented\")\n\/\/}\n\n\/\/func TestDeleteRequest(t *testing.T) {\n\/\/\tassert.True(t, false, \"Not Implemented\")\n\/\/}\n\nfunc TestBasicAuthentication(t *testing.T) {\n\tr := NewRequestBuilder().WithMethod(\"GET\").WithUrl(POSTMAN_ECHO_BASIC_AUTH_ENDPOINT).WithBasicAuth(\"postman\", \"password\").Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\n\nfunc TestBasicAuthenticationWithRFC1738(t *testing.T) {\n\tbasicAuthEndpoint := \"https:\/\/postman:password@postman-echo.com\/basic-auth\"\n\tr := NewRequestBuilder().WithMethod(\"GET\").WithRFC1738(basicAuthEndpoint).Build().Do()\n\n\tassert.NotNil(t, r, \"Should not be nil\")\n\tassert.Equal(t, http.StatusOK, r.Response().StatusCode, \"Should equal HTTP Status 200 (OK)\")\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package menu displays a Terminal UI based text menu to choose boot options\n\/\/ from.\npackage menu\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/u-root\/u-root\/pkg\/boot\"\n\t\"github.com\/u-root\/u-root\/pkg\/sh\"\n\t\"golang.org\/x\/sys\/unix\"\n\t\"golang.org\/x\/term\"\n)\n\nvar (\n\tinitialTimeout = 10 * time.Second\n\tsubsequentTimeout = 60 * time.Second\n)\n\n\/\/ Entry is a menu entry.\ntype Entry interface {\n\t\/\/ Label is the string displayed to the user in the menu.\n\tLabel() string\n\n\t\/\/ Edit the kernel command line if possible. Must be called prior to\n\t\/\/ Load.\n\tEdit(func(cmdline string) string)\n\n\t\/\/ Load is called when the entry is chosen, but does not transfer\n\t\/\/ execution to another process or kernel.\n\tLoad() error\n\n\t\/\/ Exec transfers execution to another process or kernel.\n\t\/\/\n\t\/\/ Exec either returns an error or does not return at all.\n\tExec() error\n\n\t\/\/ IsDefault indicates that this action should be run by default if the\n\t\/\/ user didn't make an entry choice.\n\tIsDefault() bool\n}\n\nfunc parseBootNum(choice string, entries []Entry) (int, error) {\n\tnum, err := strconv.Atoi(choice)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"%s is not a valid entry number: %v\", choice, err)\n\t}\n\tif num < 1 || num > len(entries) {\n\t\treturn -1, fmt.Errorf(\"%s is not a valid entry number\", choice)\n\t}\n\treturn num, nil\n}\n\n\/\/ SetInitialTimeout sets the initial timeout of the menu to the provided duration\nfunc SetInitialTimeout(timeout time.Duration) {\n\tinitialTimeout = timeout\n}\n\n\/\/ Choose presents the user a menu on input to choose an entry from and returns that entry.\nfunc Choose(input *os.File, entries ...Entry) Entry {\n\tfmt.Println(\"\")\n\tfor i, e := range entries {\n\t\tfmt.Printf(\"%02d. %s\\n\\n\", i+1, e.Label())\n\t}\n\tfmt.Println(\"\\r\")\n\n\toldState, err := term.MakeRaw(int(input.Fd()))\n\tif err != nil {\n\t\tlog.Printf(\"BUG: Please report: We cannot actually let you choose from menu (MakeRaw failed): %v\", err)\n\t\treturn nil\n\t}\n\tdefer term.Restore(int(input.Fd()), oldState)\n\n\t\/\/ TODO(chrisko): reduce this timeout a la GRUB. 3 seconds, and hitting\n\t\/\/ any button resets the timeout. We could save 7 seconds here.\n\tt := time.NewTimer(initialTimeout)\n\n\tboot := make(chan Entry, 1)\n\n\tgo func() {\n\t\t\/\/ Note that term is in raw mode. Write \\r\\n whenever you would\n\t\t\/\/ write a \\n. When testing in qemu, it might look fine because\n\t\t\/\/ there might be another tty cooking the newlines. In for\n\t\t\/\/ example minicom, the behavior is different. And you would\n\t\t\/\/ see something like:\n\t\t\/\/\n\t\t\/\/ Select a boot option to edit:\n\t\t\/\/ >\n\t\t\/\/\n\t\t\/\/ Instead of:\n\t\t\/\/\n\t\t\/\/ Select a boot option to edit:\n\t\t\/\/ >\n\t\tterm := term.NewTerminal(input, \"\")\n\n\t\tterm.AutoCompleteCallback = func(line string, pos int, key rune) (string, int, bool) {\n\t\t\t\/\/ We ain't gonna autocomplete, but we'll reset the countdown timer when you press a key.\n\t\t\tt.Reset(subsequentTimeout)\n\t\t\treturn \"\", 0, false\n\t\t}\n\n\t\tfor {\n\t\t\tterm.SetPrompt(\"Enter an option ('01' is the default, 'e' to edit kernel cmdline):\\r\\n > \")\n\t\t\tchoice, err := term.ReadLine()\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tfmt.Printf(\"BUG: Please report: Terminal read error: %v.\\n\", err)\n\t\t\t\t}\n\t\t\t\tboot <- nil\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif choice == \"e\" {\n\t\t\t\t\/\/ Edit command line.\n\t\t\t\tterm.SetPrompt(\"Select a boot option to edit:\\r\\n > \")\n\t\t\t\tchoice, err := term.ReadLine()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnum, err := parseBootNum(choice, entries)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tentries[num-1].Edit(func(cmdline string) string {\n\t\t\t\t\tfmt.Fprintf(term, \"The current quoted cmdline for option %d is:\\r\\n > %q\\r\\n\", num, cmdline)\n\t\t\t\t\tfmt.Fprintln(term, ` * Note the cmdline is c-style quoted. Ex: \\n => newline, \\\\ => \\`)\n\t\t\t\t\tterm.SetPrompt(\"Enter an option:\\r\\n * (a)ppend, (o)verwrite, (r)eturn to main menu\\r\\n > \")\n\t\t\t\t\tchoice, err := term.ReadLine()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t}\n\t\t\t\t\tswitch choice {\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tterm.SetPrompt(\"Enter unquoted cmdline to append:\\r\\n > \")\n\t\t\t\t\t\tappendCmdline, err := term.ReadLine()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif appendCmdline != \"\" {\n\t\t\t\t\t\t\tcmdline += \" \" + appendCmdline\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"o\":\n\t\t\t\t\t\tterm.SetPrompt(\"Enter new unquoted cmdline:\\r\\n > \")\n\t\t\t\t\t\tnewCmdline, err := term.ReadLine()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcmdline = newCmdline\n\t\t\t\t\tcase \"r\":\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfmt.Fprintf(term, \"Unrecognized choice %q\", choice)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(term, \"The new quoted cmdline for option %d is:\\r\\n > %q\\r\\n\", num, cmdline)\n\t\t\t\t\treturn cmdline\n\t\t\t\t})\n\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif choice == \"\" {\n\t\t\t\t\/\/ nil will result in the default order.\n\t\t\t\tboot <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnum, err := parseBootNum(choice, entries)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tboot <- entries[num-1]\n\t\t\treturn\n\t\t}\n\t}()\n\n\tselect {\n\tcase entry := <-boot:\n\t\tif entry != nil {\n\t\t\tfmt.Printf(\"Chosen option %s.\\r\\n\\r\\n\", entry.Label())\n\t\t}\n\t\treturn entry\n\n\tcase <-t.C:\n\t\treturn nil\n\t}\n}\n\n\/\/ ShowMenuAndLoad lets the user choose one of entries and loads it. If no\n\/\/ entry is chosen by the user, an entry whose IsDefault() is true will be\n\/\/ returned.\n\/\/\n\/\/ The user is left to call Entry.Exec when this function returns.\nfunc ShowMenuAndLoad(input *os.File, entries ...Entry) Entry {\n\t\/\/ Clear the screen (ANSI terminal escape code for screen clear).\n\tfmt.Printf(\"\\033[1;1H\\033[2J\\n\\n\")\n\tfmt.Printf(\"Welcome to LinuxBoot's Menu\\n\\n\")\n\tfmt.Printf(\"Enter a number to boot a kernel:\\n\")\n\n\tfor {\n\t\t\/\/ Allow the user to choose.\n\t\tentry := Choose(input, entries...)\n\t\tif entry == nil {\n\t\t\t\/\/ This only returns something if the user explicitly\n\t\t\t\/\/ entered something.\n\t\t\t\/\/\n\t\t\t\/\/ If nothing was entered, fall back to default.\n\t\t\tbreak\n\t\t}\n\t\tif err := entry.Load(); err != nil {\n\t\t\tlog.Printf(\"Failed to load %s: %v\", entry.Label(), err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Entry was successfully loaded. Leave it to the caller to\n\t\t\/\/ exec, so the caller can clean up the OS before rebooting or\n\t\t\/\/ kexecing (e.g. unmount file systems).\n\t\treturn entry\n\t}\n\n\tfmt.Println(\"\")\n\n\t\/\/ We only get one shot at actually booting, so boot the first kernel\n\t\/\/ that can be loaded correctly.\n\tfor _, e := range entries {\n\t\t\/\/ Only perform actions that are default actions. I.e. don't\n\t\t\/\/ drop to shell.\n\t\tif e.IsDefault() {\n\t\t\tfmt.Printf(\"Attempting to boot %s.\\n\\n\", e)\n\n\t\t\tif err := e.Load(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to load %s: %v\", e.Label(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Entry was successfully loaded. Leave it to the\n\t\t\t\/\/ caller to exec, so the caller can clean up the OS\n\t\t\t\/\/ before rebooting or kexecing (e.g. unmount file\n\t\t\t\/\/ systems).\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ OSImages returns menu entries for the given OSImages.\nfunc OSImages(verbose bool, imgs ...boot.OSImage) []Entry {\n\tvar menu []Entry\n\tfor _, img := range imgs {\n\t\tmenu = append(menu, &OSImageAction{\n\t\t\tOSImage: img,\n\t\t\tVerbose: verbose,\n\t\t})\n\t}\n\treturn menu\n}\n\n\/\/ OSImageAction is a menu.Entry that boots an OSImage.\ntype OSImageAction struct {\n\tboot.OSImage\n\tVerbose bool\n}\n\n\/\/ Load implements Entry.Load by loading the OS image into memory.\nfunc (oia OSImageAction) Load() error {\n\tif err := oia.OSImage.Load(oia.Verbose); err != nil {\n\t\treturn fmt.Errorf(\"could not load image %s: %v\", oia.OSImage, err)\n\t}\n\treturn nil\n}\n\n\/\/ Exec executes the loaded image.\nfunc (oia OSImageAction) Exec() error {\n\treturn boot.Execute()\n}\n\n\/\/ IsDefault returns true -- this action should be performed in order by\n\/\/ default if the user did not choose a boot entry.\nfunc (OSImageAction) IsDefault() bool { return true }\n\n\/\/ StartShell is a menu.Entry that starts a LinuxBoot shell.\ntype StartShell struct{}\n\n\/\/ Label is the label to show to the user.\nfunc (StartShell) Label() string {\n\treturn \"Enter a LinuxBoot shell\"\n}\n\n\/\/ Edit does nothing.\nfunc (StartShell) Edit(func(cmdline string) string) {\n}\n\n\/\/ Load does nothing.\nfunc (StartShell) Load() error {\n\treturn nil\n}\n\n\/\/ Exec implements Entry.Exec by running \/bin\/defaultsh.\nfunc (StartShell) Exec() error {\n\t\/\/ Reset signal handler for SIGINT to enable user interrupts again\n\tsignal.Reset(syscall.SIGINT)\n\treturn sh.RunWithLogs(\"\/bin\/defaultsh\")\n}\n\n\/\/ IsDefault indicates that this should not be run as a default action.\nfunc (StartShell) IsDefault() bool { return false }\n\n\/\/ Reboot is a menu.Entry that reboots the machine.\ntype Reboot struct{}\n\n\/\/ Label is the label to show to the user.\nfunc (Reboot) Label() string {\n\treturn \"Reboot\"\n}\n\n\/\/ Edit does nothing.\nfunc (Reboot) Edit(func(cmdline string) string) {\n}\n\n\/\/ Load does nothing.\nfunc (Reboot) Load() error {\n\treturn nil\n}\n\n\/\/ Exec reboots the machine using sys_reboot.\nfunc (Reboot) Exec() error {\n\tunix.Sync()\n\treturn unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)\n}\n\n\/\/ IsDefault indicates that this should not be run as a default action.\nfunc (Reboot) IsDefault() bool { return false }\nClean up error return on kernel selection\/\/ Copyright 2020 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package menu displays a Terminal UI based text menu to choose boot options\n\/\/ from.\npackage menu\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/u-root\/u-root\/pkg\/boot\"\n\t\"github.com\/u-root\/u-root\/pkg\/sh\"\n\t\"golang.org\/x\/sys\/unix\"\n\t\"golang.org\/x\/term\"\n)\n\nvar (\n\tinitialTimeout = 10 * time.Second\n\tsubsequentTimeout = 60 * time.Second\n)\n\n\/\/ Entry is a menu entry.\ntype Entry interface {\n\t\/\/ Label is the string displayed to the user in the menu.\n\tLabel() string\n\n\t\/\/ Edit the kernel command line if possible. Must be called prior to\n\t\/\/ Load.\n\tEdit(func(cmdline string) string)\n\n\t\/\/ Load is called when the entry is chosen, but does not transfer\n\t\/\/ execution to another process or kernel.\n\tLoad() error\n\n\t\/\/ Exec transfers execution to another process or kernel.\n\t\/\/\n\t\/\/ Exec either returns an error or does not return at all.\n\tExec() error\n\n\t\/\/ IsDefault indicates that this action should be run by default if the\n\t\/\/ user didn't make an entry choice.\n\tIsDefault() bool\n}\n\nfunc parseBootNum(choice string, entries []Entry) (int, error) {\n\tnum, err := strconv.Atoi(strings.TrimSpace(choice))\n\tif err != nil || num < 1 || num > len(entries) {\n\t\treturn -1, fmt.Errorf(\"%q is not a valid entry number\", choice)\n\t}\n\treturn num, nil\n}\n\n\/\/ SetInitialTimeout sets the initial timeout of the menu to the provided duration\nfunc SetInitialTimeout(timeout time.Duration) {\n\tinitialTimeout = timeout\n}\n\n\/\/ Choose presents the user a menu on input to choose an entry from and returns that entry.\nfunc Choose(input *os.File, entries ...Entry) Entry {\n\tfmt.Println(\"\")\n\tfor i, e := range entries {\n\t\tfmt.Printf(\"%02d. %s\\n\\n\", i+1, e.Label())\n\t}\n\tfmt.Println(\"\\r\")\n\n\toldState, err := term.MakeRaw(int(input.Fd()))\n\tif err != nil {\n\t\tlog.Printf(\"BUG: Please report: We cannot actually let you choose from menu (MakeRaw failed): %v\", err)\n\t\treturn nil\n\t}\n\tdefer term.Restore(int(input.Fd()), oldState)\n\n\t\/\/ TODO(chrisko): reduce this timeout a la GRUB. 3 seconds, and hitting\n\t\/\/ any button resets the timeout. We could save 7 seconds here.\n\tt := time.NewTimer(initialTimeout)\n\n\tboot := make(chan Entry, 1)\n\n\tgo func() {\n\t\t\/\/ Note that term is in raw mode. Write \\r\\n whenever you would\n\t\t\/\/ write a \\n. When testing in qemu, it might look fine because\n\t\t\/\/ there might be another tty cooking the newlines. In for\n\t\t\/\/ example minicom, the behavior is different. And you would\n\t\t\/\/ see something like:\n\t\t\/\/\n\t\t\/\/ Select a boot option to edit:\n\t\t\/\/ >\n\t\t\/\/\n\t\t\/\/ Instead of:\n\t\t\/\/\n\t\t\/\/ Select a boot option to edit:\n\t\t\/\/ >\n\t\tterm := term.NewTerminal(input, \"\")\n\n\t\tterm.AutoCompleteCallback = func(line string, pos int, key rune) (string, int, bool) {\n\t\t\t\/\/ We ain't gonna autocomplete, but we'll reset the countdown timer when you press a key.\n\t\t\tt.Reset(subsequentTimeout)\n\t\t\treturn \"\", 0, false\n\t\t}\n\n\t\tfor {\n\t\t\tterm.SetPrompt(\"Enter an option ('01' is the default, 'e' to edit kernel cmdline):\\r\\n > \")\n\t\t\tchoice, err := term.ReadLine()\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tfmt.Printf(\"BUG: Please report: Terminal read error: %v.\\n\", err)\n\t\t\t\t}\n\t\t\t\tboot <- nil\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif choice == \"e\" {\n\t\t\t\t\/\/ Edit command line.\n\t\t\t\tterm.SetPrompt(\"Select a boot option to edit:\\r\\n > \")\n\t\t\t\tchoice, err := term.ReadLine()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnum, err := parseBootNum(choice, entries)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tentries[num-1].Edit(func(cmdline string) string {\n\t\t\t\t\tfmt.Fprintf(term, \"The current quoted cmdline for option %d is:\\r\\n > %q\\r\\n\", num, cmdline)\n\t\t\t\t\tfmt.Fprintln(term, ` * Note the cmdline is c-style quoted. Ex: \\n => newline, \\\\ => \\`)\n\t\t\t\t\tterm.SetPrompt(\"Enter an option:\\r\\n * (a)ppend, (o)verwrite, (r)eturn to main menu\\r\\n > \")\n\t\t\t\t\tchoice, err := term.ReadLine()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t}\n\t\t\t\t\tswitch choice {\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tterm.SetPrompt(\"Enter unquoted cmdline to append:\\r\\n > \")\n\t\t\t\t\t\tappendCmdline, err := term.ReadLine()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif appendCmdline != \"\" {\n\t\t\t\t\t\t\tcmdline += \" \" + appendCmdline\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"o\":\n\t\t\t\t\t\tterm.SetPrompt(\"Enter new unquoted cmdline:\\r\\n > \")\n\t\t\t\t\t\tnewCmdline, err := term.ReadLine()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\t\t\t\treturn cmdline\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcmdline = newCmdline\n\t\t\t\t\tcase \"r\":\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfmt.Fprintf(term, \"Unrecognized choice %q\", choice)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(term, \"The new quoted cmdline for option %d is:\\r\\n > %q\\r\\n\", num, cmdline)\n\t\t\t\t\treturn cmdline\n\t\t\t\t})\n\t\t\t\tfmt.Fprintln(term, \"Returning to main menu...\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif choice == \"\" {\n\t\t\t\t\/\/ nil will result in the default order.\n\t\t\t\tboot <- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnum, err := parseBootNum(choice, entries)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(term, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tboot <- entries[num-1]\n\t\t\treturn\n\t\t}\n\t}()\n\n\tselect {\n\tcase entry := <-boot:\n\t\tif entry != nil {\n\t\t\tfmt.Printf(\"Chosen option %s.\\r\\n\\r\\n\", entry.Label())\n\t\t}\n\t\treturn entry\n\n\tcase <-t.C:\n\t\treturn nil\n\t}\n}\n\n\/\/ ShowMenuAndLoad lets the user choose one of entries and loads it. If no\n\/\/ entry is chosen by the user, an entry whose IsDefault() is true will be\n\/\/ returned.\n\/\/\n\/\/ The user is left to call Entry.Exec when this function returns.\nfunc ShowMenuAndLoad(input *os.File, entries ...Entry) Entry {\n\t\/\/ Clear the screen (ANSI terminal escape code for screen clear).\n\tfmt.Printf(\"\\033[1;1H\\033[2J\\n\\n\")\n\tfmt.Printf(\"Welcome to LinuxBoot's Menu\\n\\n\")\n\tfmt.Printf(\"Enter a number to boot a kernel:\\n\")\n\n\tfor {\n\t\t\/\/ Allow the user to choose.\n\t\tentry := Choose(input, entries...)\n\t\tif entry == nil {\n\t\t\t\/\/ This only returns something if the user explicitly\n\t\t\t\/\/ entered something.\n\t\t\t\/\/\n\t\t\t\/\/ If nothing was entered, fall back to default.\n\t\t\tbreak\n\t\t}\n\t\tif err := entry.Load(); err != nil {\n\t\t\tlog.Printf(\"Failed to load %s: %v\", entry.Label(), err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Entry was successfully loaded. Leave it to the caller to\n\t\t\/\/ exec, so the caller can clean up the OS before rebooting or\n\t\t\/\/ kexecing (e.g. unmount file systems).\n\t\treturn entry\n\t}\n\n\tfmt.Println(\"\")\n\n\t\/\/ We only get one shot at actually booting, so boot the first kernel\n\t\/\/ that can be loaded correctly.\n\tfor _, e := range entries {\n\t\t\/\/ Only perform actions that are default actions. I.e. don't\n\t\t\/\/ drop to shell.\n\t\tif e.IsDefault() {\n\t\t\tfmt.Printf(\"Attempting to boot %s.\\n\\n\", e)\n\n\t\t\tif err := e.Load(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to load %s: %v\", e.Label(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Entry was successfully loaded. Leave it to the\n\t\t\t\/\/ caller to exec, so the caller can clean up the OS\n\t\t\t\/\/ before rebooting or kexecing (e.g. unmount file\n\t\t\t\/\/ systems).\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ OSImages returns menu entries for the given OSImages.\nfunc OSImages(verbose bool, imgs ...boot.OSImage) []Entry {\n\tvar menu []Entry\n\tfor _, img := range imgs {\n\t\tmenu = append(menu, &OSImageAction{\n\t\t\tOSImage: img,\n\t\t\tVerbose: verbose,\n\t\t})\n\t}\n\treturn menu\n}\n\n\/\/ OSImageAction is a menu.Entry that boots an OSImage.\ntype OSImageAction struct {\n\tboot.OSImage\n\tVerbose bool\n}\n\n\/\/ Load implements Entry.Load by loading the OS image into memory.\nfunc (oia OSImageAction) Load() error {\n\tif err := oia.OSImage.Load(oia.Verbose); err != nil {\n\t\treturn fmt.Errorf(\"could not load image %s: %v\", oia.OSImage, err)\n\t}\n\treturn nil\n}\n\n\/\/ Exec executes the loaded image.\nfunc (oia OSImageAction) Exec() error {\n\treturn boot.Execute()\n}\n\n\/\/ IsDefault returns true -- this action should be performed in order by\n\/\/ default if the user did not choose a boot entry.\nfunc (OSImageAction) IsDefault() bool { return true }\n\n\/\/ StartShell is a menu.Entry that starts a LinuxBoot shell.\ntype StartShell struct{}\n\n\/\/ Label is the label to show to the user.\nfunc (StartShell) Label() string {\n\treturn \"Enter a LinuxBoot shell\"\n}\n\n\/\/ Edit does nothing.\nfunc (StartShell) Edit(func(cmdline string) string) {\n}\n\n\/\/ Load does nothing.\nfunc (StartShell) Load() error {\n\treturn nil\n}\n\n\/\/ Exec implements Entry.Exec by running \/bin\/defaultsh.\nfunc (StartShell) Exec() error {\n\t\/\/ Reset signal handler for SIGINT to enable user interrupts again\n\tsignal.Reset(syscall.SIGINT)\n\treturn sh.RunWithLogs(\"\/bin\/defaultsh\")\n}\n\n\/\/ IsDefault indicates that this should not be run as a default action.\nfunc (StartShell) IsDefault() bool { return false }\n\n\/\/ Reboot is a menu.Entry that reboots the machine.\ntype Reboot struct{}\n\n\/\/ Label is the label to show to the user.\nfunc (Reboot) Label() string {\n\treturn \"Reboot\"\n}\n\n\/\/ Edit does nothing.\nfunc (Reboot) Edit(func(cmdline string) string) {\n}\n\n\/\/ Load does nothing.\nfunc (Reboot) Load() error {\n\treturn nil\n}\n\n\/\/ Exec reboots the machine using sys_reboot.\nfunc (Reboot) Exec() error {\n\tunix.Sync()\n\treturn unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)\n}\n\n\/\/ IsDefault indicates that this should not be run as a default action.\nfunc (Reboot) IsDefault() bool { return false }\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"internal\/testenv\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc loadSyms(t *testing.T) map[string]string {\n\tcmd := testenv.Command(t, testenv.GoToolPath(t), \"tool\", \"nm\", os.Args[0])\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go tool nm %v: %v\\n%s\", os.Args[0], err, string(out))\n\t}\n\tsyms := make(map[string]string)\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tf := strings.Fields(scanner.Text())\n\t\tif len(f) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tsyms[f[2]] = f[0]\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tt.Fatalf(\"error reading symbols: %v\", err)\n\t}\n\treturn syms\n}\n\nfunc runAddr2Line(t *testing.T, exepath, addr string) (funcname, path, lineno string) {\n\tcmd := testenv.Command(t, exepath, os.Args[0])\n\tcmd.Stdin = strings.NewReader(addr)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go tool addr2line %v: %v\\n%s\", os.Args[0], err, string(out))\n\t}\n\tf := strings.Split(string(out), \"\\n\")\n\tif len(f) < 3 && f[2] == \"\" {\n\t\tt.Fatal(\"addr2line output must have 2 lines\")\n\t}\n\tfuncname = f[0]\n\tpathAndLineNo := f[1]\n\tf = strings.Split(pathAndLineNo, \":\")\n\tif runtime.GOOS == \"windows\" && len(f) == 3 {\n\t\t\/\/ Reattach drive letter.\n\t\tf = []string{f[0] + \":\" + f[1], f[2]}\n\t}\n\tif len(f) != 2 {\n\t\tt.Fatalf(\"no line number found in %q\", pathAndLineNo)\n\t}\n\treturn funcname, f[0], f[1]\n}\n\nconst symName = \"cmd\/addr2line.TestAddr2Line\"\n\nfunc testAddr2Line(t *testing.T, exepath, addr string) {\n\tfuncName, srcPath, srcLineNo := runAddr2Line(t, exepath, addr)\n\tif symName != funcName {\n\t\tt.Fatalf(\"expected function name %v; got %v\", symName, funcName)\n\t}\n\tfi1, err := os.Stat(\"addr2line_test.go\")\n\tif err != nil {\n\t\tt.Fatalf(\"Stat failed: %v\", err)\n\t}\n\n\t\/\/ Debug paths are stored slash-separated, so convert to system-native.\n\tsrcPath = filepath.FromSlash(srcPath)\n\tfi2, err := os.Stat(srcPath)\n\n\t\/\/ If GOROOT_FINAL is set and srcPath is not the file we expect, perhaps\n\t\/\/ srcPath has had GOROOT_FINAL substituted for GOROOT and GOROOT hasn't been\n\t\/\/ moved to its final location yet. If so, try the original location instead.\n\tif gorootFinal := os.Getenv(\"GOROOT_FINAL\"); gorootFinal != \"\" &&\n\t\t(os.IsNotExist(err) || (err == nil && !os.SameFile(fi1, fi2))) {\n\t\t\/\/ srcPath is clean, but GOROOT_FINAL itself might not be.\n\t\t\/\/ (See https:\/\/golang.org\/issue\/41447.)\n\t\tgorootFinal = filepath.Clean(gorootFinal)\n\n\t\tif strings.HasPrefix(srcPath, gorootFinal) {\n\t\t\tfi2, err = os.Stat(runtime.GOROOT() + strings.TrimPrefix(srcPath, gorootFinal))\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"Stat failed: %v\", err)\n\t}\n\tif !os.SameFile(fi1, fi2) {\n\t\tt.Fatalf(\"addr2line_test.go and %s are not same file\", srcPath)\n\t}\n\tif srcLineNo != \"105\" {\n\t\tt.Fatalf(\"line number = %v; want 105\", srcLineNo)\n\t}\n}\n\n\/\/ This is line 104. The test depends on that.\nfunc TestAddr2Line(t *testing.T) {\n\ttestenv.MustHaveGoBuild(t)\n\n\ttmpDir, err := os.MkdirTemp(\"\", \"TestAddr2Line\")\n\tif err != nil {\n\t\tt.Fatal(\"TempDir failed: \", err)\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\t\/\/ Build copy of test binary with debug symbols,\n\t\/\/ since the one running now may not have them.\n\texepath := filepath.Join(tmpDir, \"testaddr2line_test.exe\")\n\tout, err := testenv.Command(t, testenv.GoToolPath(t), \"test\", \"-c\", \"-o\", exepath, \"cmd\/addr2line\").CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go test -c -o %v cmd\/addr2line: %v\\n%s\", exepath, err, string(out))\n\t}\n\tos.Args[0] = exepath\n\n\tsyms := loadSyms(t)\n\n\texepath = filepath.Join(tmpDir, \"testaddr2line.exe\")\n\tout, err = testenv.Command(t, testenv.GoToolPath(t), \"build\", \"-o\", exepath, \"cmd\/addr2line\").CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go build -o %v cmd\/addr2line: %v\\n%s\", exepath, err, string(out))\n\t}\n\n\ttestAddr2Line(t, exepath, syms[symName])\n\ttestAddr2Line(t, exepath, \"0x\"+syms[symName])\n}\ncmd\/addr2line: use the test binary as 'addr2line' instead of rebuilding it twice\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"internal\/testenv\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n)\n\n\/\/ TestMain executes the test binary as the addr2line command if\n\/\/ GO_ADDR2LINETEST_IS_ADDR2LINE is set, and runs the tests otherwise.\nfunc TestMain(m *testing.M) {\n\tif os.Getenv(\"GO_ADDR2LINETEST_IS_ADDR2LINE\") != \"\" {\n\t\tmain()\n\t\tos.Exit(0)\n\t}\n\n\tos.Setenv(\"GO_ADDR2LINETEST_IS_ADDR2LINE\", \"1\") \/\/ Set for subprocesses to inherit.\n\tos.Exit(m.Run())\n}\n\n\/\/ addr2linePath returns the path to the \"addr2line\" binary to run.\nfunc addr2linePath(t testing.TB) string {\n\tt.Helper()\n\ttestenv.MustHaveExec(t)\n\n\taddr2linePathOnce.Do(func() {\n\t\taddr2lineExePath, addr2linePathErr = os.Executable()\n\t})\n\tif addr2linePathErr != nil {\n\t\tt.Fatal(addr2linePathErr)\n\t}\n\treturn addr2lineExePath\n}\n\nvar (\n\taddr2linePathOnce sync.Once\n\taddr2lineExePath string\n\taddr2linePathErr error\n)\n\nfunc loadSyms(t *testing.T, dbgExePath string) map[string]string {\n\tcmd := testenv.Command(t, testenv.GoToolPath(t), \"tool\", \"nm\", dbgExePath)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"%v: %v\\n%s\", cmd, err, string(out))\n\t}\n\tsyms := make(map[string]string)\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tf := strings.Fields(scanner.Text())\n\t\tif len(f) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tsyms[f[2]] = f[0]\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tt.Fatalf(\"error reading symbols: %v\", err)\n\t}\n\treturn syms\n}\n\nfunc runAddr2Line(t *testing.T, dbgExePath, addr string) (funcname, path, lineno string) {\n\tcmd := testenv.Command(t, addr2linePath(t), dbgExePath)\n\tcmd.Stdin = strings.NewReader(addr)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go tool addr2line %v: %v\\n%s\", os.Args[0], err, string(out))\n\t}\n\tf := strings.Split(string(out), \"\\n\")\n\tif len(f) < 3 && f[2] == \"\" {\n\t\tt.Fatal(\"addr2line output must have 2 lines\")\n\t}\n\tfuncname = f[0]\n\tpathAndLineNo := f[1]\n\tf = strings.Split(pathAndLineNo, \":\")\n\tif runtime.GOOS == \"windows\" && len(f) == 3 {\n\t\t\/\/ Reattach drive letter.\n\t\tf = []string{f[0] + \":\" + f[1], f[2]}\n\t}\n\tif len(f) != 2 {\n\t\tt.Fatalf(\"no line number found in %q\", pathAndLineNo)\n\t}\n\treturn funcname, f[0], f[1]\n}\n\nconst symName = \"cmd\/addr2line.TestAddr2Line\"\n\nfunc testAddr2Line(t *testing.T, dbgExePath, addr string) {\n\tfuncName, srcPath, srcLineNo := runAddr2Line(t, dbgExePath, addr)\n\tif symName != funcName {\n\t\tt.Fatalf(\"expected function name %v; got %v\", symName, funcName)\n\t}\n\tfi1, err := os.Stat(\"addr2line_test.go\")\n\tif err != nil {\n\t\tt.Fatalf(\"Stat failed: %v\", err)\n\t}\n\n\t\/\/ Debug paths are stored slash-separated, so convert to system-native.\n\tsrcPath = filepath.FromSlash(srcPath)\n\tfi2, err := os.Stat(srcPath)\n\n\t\/\/ If GOROOT_FINAL is set and srcPath is not the file we expect, perhaps\n\t\/\/ srcPath has had GOROOT_FINAL substituted for GOROOT and GOROOT hasn't been\n\t\/\/ moved to its final location yet. If so, try the original location instead.\n\tif gorootFinal := os.Getenv(\"GOROOT_FINAL\"); gorootFinal != \"\" &&\n\t\t(os.IsNotExist(err) || (err == nil && !os.SameFile(fi1, fi2))) {\n\t\t\/\/ srcPath is clean, but GOROOT_FINAL itself might not be.\n\t\t\/\/ (See https:\/\/golang.org\/issue\/41447.)\n\t\tgorootFinal = filepath.Clean(gorootFinal)\n\n\t\tif strings.HasPrefix(srcPath, gorootFinal) {\n\t\t\tfi2, err = os.Stat(runtime.GOROOT() + strings.TrimPrefix(srcPath, gorootFinal))\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"Stat failed: %v\", err)\n\t}\n\tif !os.SameFile(fi1, fi2) {\n\t\tt.Fatalf(\"addr2line_test.go and %s are not same file\", srcPath)\n\t}\n\tif srcLineNo != \"138\" {\n\t\tt.Fatalf(\"line number = %v; want 138\", srcLineNo)\n\t}\n}\n\n\/\/ This is line 137. The test depends on that.\nfunc TestAddr2Line(t *testing.T) {\n\ttestenv.MustHaveGoBuild(t)\n\n\ttmpDir, err := os.MkdirTemp(\"\", \"TestAddr2Line\")\n\tif err != nil {\n\t\tt.Fatal(\"TempDir failed: \", err)\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\t\/\/ Build copy of test binary with debug symbols,\n\t\/\/ since the one running now may not have them.\n\texepath := filepath.Join(tmpDir, \"testaddr2line_test.exe\")\n\tout, err := testenv.Command(t, testenv.GoToolPath(t), \"test\", \"-c\", \"-o\", exepath, \"cmd\/addr2line\").CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go test -c -o %v cmd\/addr2line: %v\\n%s\", exepath, err, string(out))\n\t}\n\n\tsyms := loadSyms(t, exepath)\n\n\ttestAddr2Line(t, exepath, syms[symName])\n\ttestAddr2Line(t, exepath, \"0x\"+syms[symName])\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/rockneurotiko\/go-tgbot\"\n)\n\ntype usersAnsweringStruct struct {\n\t*sync.RWMutex\n\tUsers map[int]string\n}\n\nvar usersAnswering = usersAnsweringStruct{&sync.RWMutex{}, make(map[int]string)}\n\nfunc (users *usersAnsweringStruct) get(user int) (string, bool) {\n\tusers.RLock()\n\ts, ok := users.Users[user]\n\tusers.RUnlock()\n\treturn s, ok\n}\n\nfunc (users *usersAnsweringStruct) set(user int, value string) {\n\tusers.Lock()\n\tusers.Users[user] = value\n\tusers.Unlock()\n}\n\nfunc (users *usersAnsweringStruct) del(user int) {\n\tusers.Lock()\n\tdelete(users.Users, user)\n\tusers.Unlock()\n}\n\nfunc main() {\n\tcfg, _ := getConfig()\n\tbot := tgbot.NewTgBot(cfg.Telegram.Token)\n\tbot.CommandFn(`echo (.+)`, echoHandler)\n\tbot.SimpleCommandFn(`learninig`, learnHandler)\n\tbot.NotCalledFn(answerHandler)\n\tbot.SimpleStart()\n}\n\nfunc learnHandler(bot tgbot.TgBot, msg tgbot.Message, text string) *string {\n\tkey := \"understand\" \/\/ TODO: must be random\n\tusersAnswering.set(msg.Chat.ID, key)\n\tbot.Answer(msg).Text(key).ReplyToMessage(msg.ID).End()\n\treturn nil\n}\n\nfunc answerHandler(bot tgbot.TgBot, msg tgbot.Message) {\n\tif msg.Text == nil {\n\t\treturn\n\t}\n\ts, ok := usersAnswering.get(msg.Chat.ID)\n\tusersAnswering.del(msg.Chat.ID)\n\tif !ok {\n\t\tbot.Answer(msg).Text(\"You need to start \/learninig first\").End()\n\t\treturn\n\t}\n\tverbs := getAllVerbs()\n\t\/\/ TODO: Check answer\n\tbot.Answer(msg).Text(fmt.Sprintf(\"%s %s\", verbs[s][0], verbs[s][1])).End()\n}\n\nfunc echoHandler(bot tgbot.TgBot, msg tgbot.Message, vals []string, kvals map[string]string) *string {\n\tfmt.Println(vals, kvals)\n\tnewmsg := fmt.Sprintf(\"[Echoed]: %s\", vals[1])\n\treturn &newmsg\n}\n\nfunc getAllVerbs() map[string][]string {\n\treturn GetEnglishVerbs()\n}\nThe main part is donepackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/rockneurotiko\/go-tgbot\"\n)\n\ntype usersAnsweringStruct struct {\n\t*sync.RWMutex\n\tUsers map[int]string\n}\n\nvar usersAnswering = usersAnsweringStruct{&sync.RWMutex{}, make(map[int]string)}\n\nfunc (users *usersAnsweringStruct) get(user int) (string, bool) {\n\tusers.RLock()\n\ts, ok := users.Users[user]\n\tusers.RUnlock()\n\treturn s, ok\n}\n\nfunc (users *usersAnsweringStruct) set(user int, value string) {\n\tusers.Lock()\n\tusers.Users[user] = value\n\tusers.Unlock()\n}\n\nfunc (users *usersAnsweringStruct) del(user int) {\n\tusers.Lock()\n\tdelete(users.Users, user)\n\tusers.Unlock()\n}\n\nfunc main() {\n\tcfg, _ := getConfig()\n\tbot := tgbot.NewTgBot(cfg.Telegram.Token)\n\tbot.CommandFn(`echo (.+)`, echoHandler)\n\tbot.SimpleCommandFn(`learninig`, startLearningHandler)\n\tbot.NotCalledFn(answerHandler)\n\tbot.SimpleStart()\n}\n\nfunc getRandomVerb() string {\n\tfor key := range getAllVerbs() {\n\t\treturn key\n\t}\n\treturn \"cut\"\n}\n\nfunc startLearningHandler(bot tgbot.TgBot, msg tgbot.Message, text string) *string {\n\tverb := getRandomVerb()\n\tusersAnswering.set(msg.Chat.ID, verb)\n\tbot.Answer(msg).Text(verb).End()\n\treturn nil\n}\n\nfunc answerHandler(bot tgbot.TgBot, msg tgbot.Message) {\n\tif msg.Text == nil {\n\t\treturn\n\t}\n\ts, ok := usersAnswering.get(msg.Chat.ID)\n\tif *msg.Text == \"\/stop\" {\n\t\tusersAnswering.del(msg.Chat.ID)\n\t\treturn\n\t}\n\tif !ok {\n\t\tbot.Answer(msg).Text(\"You need to start \/learninig first\").End()\n\t\treturn\n\t}\n\tverbs := getAllVerbs()\n\tuserVerbs := strings.Split(*msg.Text, \" \")\n\tif len(userVerbs) != 2 {\n\t\tbot.Answer(msg).Text(\"Answer should be two verbs separated by space\").End()\n\t}\n\tv2, v3 := verbs[s][0], verbs[s][1]\n\tif strings.ToLower(userVerbs[0]) == v2 && strings.ToLower(userVerbs[1]) == v3 {\n\t\tbot.Answer(msg).Text(\"Correct!\").End()\n\t} else {\n\t\tbot.Answer(msg).Text(fmt.Sprintf(\"Incorrect. The right answer is %s %s\", v2, v3)).End()\n\t}\n\tverb := getRandomVerb()\n\tusersAnswering.set(msg.Chat.ID, verb)\n\tbot.Answer(msg).Text(verb).End()\n}\n\nfunc echoHandler(bot tgbot.TgBot, msg tgbot.Message, vals []string, kvals map[string]string) *string {\n\tfmt.Println(vals, kvals)\n\tnewmsg := fmt.Sprintf(\"[Echoed]: %s\", vals[1])\n\treturn &newmsg\n}\n\nfunc getAllVerbs() map[string][]string {\n\treturn GetEnglishVerbs()\n}\n<|endoftext|>"} {"text":"package RethinkDBStorage\n\nimport (\n\t\"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/github.com\/RangelReale\/osin\"\n\t\"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/github.com\/mitchellh\/mapstructure\"\n\tr \"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/gopkg.in\/dancannon\/gorethink.v1\"\n)\n\nconst (\n\tclientsTable = \"oauth_clients\"\n\tauthorizeTable = \"oauth_authorize_data\"\n\taccessTable = \"oauth_access_data\"\n\taccessTokenField = \"AccessToken\"\n\trefreshTokenField = \"RefreshToken\"\n)\n\n\/\/ RethinkDBStorage implements storage for osin\ntype RethinkDBStorage struct {\n\tdbName string\n\tsession *r.Session\n}\n\n\/\/ New initializes and returns a new RethinkDBStorage\nfunc New(session *r.Session, dbName string) *RethinkDBStorage {\n\tstorage := &RethinkDBStorage{dbName, session}\n\treturn storage\n}\n\n\/\/ CreateClient inserts a new client\nfunc (s *RethinkDBStorage) CreateClient(c osin.Client) error {\n\t_, err := r.Table(clientsTable).Insert(c).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ GetClient returns client with given ID\nfunc (s *RethinkDBStorage) GetClient(clientID string) (*osin.DefaultClient, error) {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(clientID)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clientStruct osin.DefaultClient\n\terr = mapstructure.Decode(clientMap, &clientStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &clientStruct, nil\n}\n\n\/\/ UpdateClient updates given client\nfunc (s *RethinkDBStorage) UpdateClient(c osin.Client) error {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(c.GetId())).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(clientsTable).Get(clientMap[\"id\"]).Update(c).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ DeleteClient deletes given client\nfunc (s *RethinkDBStorage) DeleteClient(c osin.Client) error {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(c.GetId())).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(clientsTable).Get(clientMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\n\n\/\/ SaveAuthorize creates a new authorization\nfunc (s *RethinkDBStorage) SaveAuthorize(data *osin.AuthorizeData) error {\n\t_, err := r.Table(authorizeTable).Insert(data).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ LoadAuthorize gets authorization data with given code\nfunc (s *RethinkDBStorage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {\n\tresult, err := r.Table(authorizeTable).Filter(r.Row.Field(\"Code\").Eq(code)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client *osin.DefaultClient\n\tclientID := dataMap[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tclient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"Client\"] = client\n\n\tvar dataStruct osin.AuthorizeData\n\terr = mapstructure.Decode(dataMap, &dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dataStruct, nil\n}\n\n\/\/ RemoveAuthorize deletes given authorization\nfunc (s *RethinkDBStorage) RemoveAuthorize(code string) error {\n\tresult, err := r.Table(authorizeTable).Filter(r.Row.Field(\"Code\").Eq(code)).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(authorizeTable).Get(dataMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\n\n\/\/ SaveAccess creates a new access data\nfunc (s *RethinkDBStorage) SaveAccess(data *osin.AccessData) error {\n\t_, err := r.Table(accessTable).Insert(data).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ LoadAccess gets access data with given access token\nfunc (s *RethinkDBStorage) LoadAccess(accessToken string) (*osin.AccessData, error) {\n\treturn s.getAccessData(accessTokenField, accessToken)\n}\n\n\/\/ RemoveAccess deletes AccessData with given access token\nfunc (s *RethinkDBStorage) RemoveAccess(accessToken string) error {\n\treturn s.removeAccessData(accessTokenField, accessToken)\n}\n\n\/\/ LoadRefresh gets access data with given refresh token\nfunc (s *RethinkDBStorage) LoadRefresh(refreshToken string) (*osin.AccessData, error) {\n\treturn s.getAccessData(refreshTokenField, refreshToken)\n}\n\n\/\/ RemoveRefresh deletes AccessData with given refresh token\nfunc (s *RethinkDBStorage) RemoveRefresh(refreshToken string) error {\n\treturn s.removeAccessData(refreshTokenField, refreshToken)\n}\n\n\/\/ getAccessData is a common function to get AccessData by field\nfunc (s *RethinkDBStorage) getAccessData(fieldName, token string) (*osin.AccessData, error) {\n\tresult, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client *osin.DefaultClient\n\tclientID := dataMap[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tclient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"Client\"] = client\n\n\tvar authorizeDataClient *osin.DefaultClient\n\tclientID = dataMap[\"AuthorizeData\"].(map[string]interface{})[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tauthorizeDataClient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"AuthorizeData\"].(map[string]interface{})[\"Client\"] = authorizeDataClient\n\n\tvar dataStruct osin.AccessData\n\terr = mapstructure.Decode(dataMap, &dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dataStruct, nil\n}\n\n\/\/ removeAccessData is a common function to remove AccessData by field\nfunc (s *RethinkDBStorage) removeAccessData(fieldName, token string) error {\n\tresult, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(accessTable).Get(dataMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\nRemove obsolete variable.package RethinkDBStorage\n\nimport (\n\t\"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/github.com\/RangelReale\/osin\"\n\t\"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/github.com\/mitchellh\/mapstructure\"\n\tr \"github.com\/ahmet\/osin-rethinkdb\/Godeps\/_workspace\/src\/gopkg.in\/dancannon\/gorethink.v1\"\n)\n\nconst (\n\tclientsTable = \"oauth_clients\"\n\tauthorizeTable = \"oauth_authorize_data\"\n\taccessTable = \"oauth_access_data\"\n\taccessTokenField = \"AccessToken\"\n\trefreshTokenField = \"RefreshToken\"\n)\n\n\/\/ RethinkDBStorage implements storage for osin\ntype RethinkDBStorage struct {\n\tsession *r.Session\n}\n\n\/\/ New initializes and returns a new RethinkDBStorage\nfunc New(session *r.Session) *RethinkDBStorage {\n\tstorage := &RethinkDBStorage{session}\n\treturn storage\n}\n\n\/\/ CreateClient inserts a new client\nfunc (s *RethinkDBStorage) CreateClient(c osin.Client) error {\n\t_, err := r.Table(clientsTable).Insert(c).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ GetClient returns client with given ID\nfunc (s *RethinkDBStorage) GetClient(clientID string) (*osin.DefaultClient, error) {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(clientID)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clientStruct osin.DefaultClient\n\terr = mapstructure.Decode(clientMap, &clientStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &clientStruct, nil\n}\n\n\/\/ UpdateClient updates given client\nfunc (s *RethinkDBStorage) UpdateClient(c osin.Client) error {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(c.GetId())).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(clientsTable).Get(clientMap[\"id\"]).Update(c).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ DeleteClient deletes given client\nfunc (s *RethinkDBStorage) DeleteClient(c osin.Client) error {\n\tresult, err := r.Table(clientsTable).Filter(r.Row.Field(\"Id\").Eq(c.GetId())).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar clientMap map[string]interface{}\n\terr = result.One(&clientMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(clientsTable).Get(clientMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\n\n\/\/ SaveAuthorize creates a new authorization\nfunc (s *RethinkDBStorage) SaveAuthorize(data *osin.AuthorizeData) error {\n\t_, err := r.Table(authorizeTable).Insert(data).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ LoadAuthorize gets authorization data with given code\nfunc (s *RethinkDBStorage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {\n\tresult, err := r.Table(authorizeTable).Filter(r.Row.Field(\"Code\").Eq(code)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client *osin.DefaultClient\n\tclientID := dataMap[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tclient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"Client\"] = client\n\n\tvar dataStruct osin.AuthorizeData\n\terr = mapstructure.Decode(dataMap, &dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dataStruct, nil\n}\n\n\/\/ RemoveAuthorize deletes given authorization\nfunc (s *RethinkDBStorage) RemoveAuthorize(code string) error {\n\tresult, err := r.Table(authorizeTable).Filter(r.Row.Field(\"Code\").Eq(code)).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(authorizeTable).Get(dataMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\n\n\/\/ SaveAccess creates a new access data\nfunc (s *RethinkDBStorage) SaveAccess(data *osin.AccessData) error {\n\t_, err := r.Table(accessTable).Insert(data).RunWrite(s.session)\n\treturn err\n}\n\n\/\/ LoadAccess gets access data with given access token\nfunc (s *RethinkDBStorage) LoadAccess(accessToken string) (*osin.AccessData, error) {\n\treturn s.getAccessData(accessTokenField, accessToken)\n}\n\n\/\/ RemoveAccess deletes AccessData with given access token\nfunc (s *RethinkDBStorage) RemoveAccess(accessToken string) error {\n\treturn s.removeAccessData(accessTokenField, accessToken)\n}\n\n\/\/ LoadRefresh gets access data with given refresh token\nfunc (s *RethinkDBStorage) LoadRefresh(refreshToken string) (*osin.AccessData, error) {\n\treturn s.getAccessData(refreshTokenField, refreshToken)\n}\n\n\/\/ RemoveRefresh deletes AccessData with given refresh token\nfunc (s *RethinkDBStorage) RemoveRefresh(refreshToken string) error {\n\treturn s.removeAccessData(refreshTokenField, refreshToken)\n}\n\n\/\/ getAccessData is a common function to get AccessData by field\nfunc (s *RethinkDBStorage) getAccessData(fieldName, token string) (*osin.AccessData, error) {\n\tresult, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client *osin.DefaultClient\n\tclientID := dataMap[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tclient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"Client\"] = client\n\n\tvar authorizeDataClient *osin.DefaultClient\n\tclientID = dataMap[\"AuthorizeData\"].(map[string]interface{})[\"Client\"].(map[string]interface{})[\"Id\"].(string)\n\tauthorizeDataClient, err = s.GetClient(clientID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdataMap[\"AuthorizeData\"].(map[string]interface{})[\"Client\"] = authorizeDataClient\n\n\tvar dataStruct osin.AccessData\n\terr = mapstructure.Decode(dataMap, &dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dataStruct, nil\n}\n\n\/\/ removeAccessData is a common function to remove AccessData by field\nfunc (s *RethinkDBStorage) removeAccessData(fieldName, token string) error {\n\tresult, err := r.Table(accessTable).Filter(r.Row.Field(fieldName).Eq(token)).Run(s.session)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer result.Close()\n\n\tvar dataMap map[string]interface{}\n\terr = result.One(&dataMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Table(accessTable).Get(dataMap[\"id\"]).Delete().RunWrite(s.session)\n\treturn err\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT\n\/\/ file at the top-level directory of this distribution and at\n\/\/ https:\/\/github.com\/go-vgo\/robotgo\/blob\/master\/LICENSE\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 or the MIT license\n\/\/ , at your\n\/\/ option. This file may not be copied, modified, or distributed\n\/\/ except according to those terms.\n\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/go-vgo\/robotgo\"\n\t\/\/ \"go-vgo\/robotgo\"\n)\n\nfunc addEvent() {\n\tfmt.Println(\"--- Please press ctrl + shift + q ---\")\n\tok := robotgo.AddEvents(\"q\", \"ctrl\", \"shift\")\n\tif ok {\n\t\tfmt.Println(\"add events...\")\n\t}\n\n\tfmt.Println(\"--- Please press w---\")\n\tok = robotgo.AddEvents(\"w\")\n\tif ok {\n\t\tfmt.Println(\"add events\")\n\t}\n\n\ts := robotgo.Start()\n\tdefer robotgo.End()\n\n\tfor ev := range s {\n\t\tfmt.Println(ev)\n\t}\n}\n\nfunc add() {\n\tfmt.Println(\"--- Please press v---\")\n\teve := robotgo.AddEvent(\"v\")\n\n\tif eve {\n\t\tfmt.Println(\"--- You press v---\", \"v\")\n\t}\n\n\tfmt.Println(\"--- Please press k---\")\n\tkeve := robotgo.AddEvent(\"k\")\n\tif keve {\n\t\tfmt.Println(\"--- You press k---\", \"k\")\n\t}\n\n\tfmt.Println(\"--- Please press f1---\")\n\tfeve := robotgo.AddEvent(\"f1\")\n\tif feve {\n\t\tfmt.Println(\"You press...\", \"f1\")\n\t}\n}\n\nfunc event() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Global event listener\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tadd()\n\n\tfmt.Println(\"--- Please press left mouse button---\")\n\tmleft := robotgo.AddEvent(\"mleft\")\n\tif mleft {\n\t\tfmt.Println(\"--- You press left mouse button---\", \"mleft\")\n\t}\n\n\tmright := robotgo.AddEvent(\"mright\")\n\tif mright {\n\t\tfmt.Println(\"--- You press right mouse button---\", \"mright\")\n\t}\n\n\t\/\/ stop AddEvent\n\t\/\/ robotgo.StopEvent()\n}\n\nfunc main() {\n\tfmt.Println(\"test begin...\")\n\n\taddEvent()\n\n\tevent()\n}\nupdate example, add godoc\/\/ Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT\n\/\/ file at the top-level directory of this distribution and at\n\/\/ https:\/\/github.com\/go-vgo\/robotgo\/blob\/master\/LICENSE\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 or the MIT license\n\/\/ , at your\n\/\/ option. This file may not be copied, modified, or distributed\n\/\/ except according to those terms.\n\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/go-vgo\/robotgo\"\n\t\/\/ \"go-vgo\/robotgo\"\n)\n\nfunc addEvent() {\n\tfmt.Println(\"--- Please press ctrl + shift + q ---\")\n\tok := robotgo.AddEvents(\"q\", \"ctrl\", \"shift\")\n\tif ok {\n\t\tfmt.Println(\"add events...\")\n\t}\n\n\tfmt.Println(\"--- Please press w---\")\n\tok = robotgo.AddEvents(\"w\")\n\tif ok {\n\t\tfmt.Println(\"add events\")\n\t}\n\n\t\/\/ start hook\n\ts := robotgo.Start()\n\t\/\/ end hook\n\tdefer robotgo.End()\n\n\tfor ev := range s {\n\t\tfmt.Println(ev)\n\t}\n}\n\nfunc add() {\n\tfmt.Println(\"--- Please press v---\")\n\teve := robotgo.AddEvent(\"v\")\n\n\tif eve {\n\t\tfmt.Println(\"--- You press v---\", \"v\")\n\t}\n\n\tfmt.Println(\"--- Please press k---\")\n\tkeve := robotgo.AddEvent(\"k\")\n\tif keve {\n\t\tfmt.Println(\"--- You press k---\", \"k\")\n\t}\n\n\tfmt.Println(\"--- Please press f1---\")\n\tfeve := robotgo.AddEvent(\"f1\")\n\tif feve {\n\t\tfmt.Println(\"You press...\", \"f1\")\n\t}\n}\n\nfunc event() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Global event listener\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tadd()\n\n\tfmt.Println(\"--- Please press left mouse button---\")\n\tmleft := robotgo.AddEvent(\"mleft\")\n\tif mleft {\n\t\tfmt.Println(\"--- You press left mouse button---\", \"mleft\")\n\t}\n\n\tmright := robotgo.AddEvent(\"mright\")\n\tif mright {\n\t\tfmt.Println(\"--- You press right mouse button---\", \"mright\")\n\t}\n\n\t\/\/ stop AddEvent\n\t\/\/ robotgo.StopEvent()\n}\n\nfunc main() {\n\tfmt.Println(\"test begin...\")\n\n\taddEvent()\n\n\tevent()\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"koding\/db\/models\"\n\tmm \"koding\/db\/mongodb\"\n\thelper \"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/tools\/config\"\n\t\"koding\/tools\/logger\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar log = logger.New(\"post truncator\")\n\ntype strToInf map[string]interface{}\n\nvar (\n\tMAX_ITERATION_COUNT = 50\n\tconf *config.Config\n\tSLEEPING_TIME = 10 * time.Millisecond\n\toneMonthAgo = time.Now().Add(-time.Hour * 24 * 30).UTC()\n\tflagProfile = flag.String(\"c\", \"vagrant\", \"Configuration profile from file\")\n\tflagSkip = flag.Int(\"s\", 0, \"Configuration profile from file\")\n\tflagLimit = flag.Int(\"l\", 1000, \"Configuration profile from file\")\n\tmongodb *mm.MongoDB\n\tdeletedItems = 0\n)\n\nfunc main() {\n\tlog.SetLevel(logger.DEBUG)\n\tflag.Parse()\n\tif *flagProfile == \"\" {\n\t\tlog.Fatal(\"Please specify profile via -c. Aborting.\")\n\t}\n\n\tconf = config.MustConfig(*flagProfile)\n\thelper.Initialize(conf.Mongo)\n\tlog.Info(\"Sync worker started\")\n\tmongodb = helper.Mongo\n\tfor _, coll := range ToBeDTruncatedNames {\n\t\tcollName := coll\n\t\terr := mongodb.Run(collName, createQuery(collName))\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Connecting to Mongo: %v\", err)\n\t\t}\n\t}\n\n}\n\nfunc createQuery(collectionName string) func(coll *mgo.Collection) error {\n\treturn func(coll *mgo.Collection) error {\n\n\t\tquery := coll.Find(helper.Selector{})\n\t\ttotalCount, err := query.Count()\n\t\tif err != nil {\n\t\t\tlog.Error(\"While getting count, exiting: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tif totalCount == 0 {\n\t\t\tfmt.Println(\"Collection is empty \", collectionName)\n\t\t\tlog.Info(\"deleted item count %v\", deletedItems)\n\t\t\treturn nil\n\t\t}\n\n\t\tskip := *flagSkip\n\t\t\/\/ this is a starting point\n\t\tindex := skip\n\t\t\/\/ this is the item count to be processed\n\t\tlimit := *flagLimit\n\t\t\/\/ this will be the ending point\n\t\tcount := index + limit\n\n\t\tvar result map[string]interface{}\n\n\t\titeration := 0\n\t\tfor {\n\t\t\t\/\/ if we reach to the end of the all collection, exit\n\t\t\tif index >= totalCount {\n\t\t\t\tlog.Info(\"All items are processed, exiting\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ this is the max re-iterating count\n\t\t\tif iteration == MAX_ITERATION_COUNT {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ if we processed all items then exit\n\t\t\tif index == count {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\titer := query.Skip(index).Limit(count - index).Iter()\n\t\t\tfor iter.Next(&result) {\n\t\t\t\ttime.Sleep(SLEEPING_TIME)\n\n\t\t\t\tdeleteDoc(result, collectionName)\n\n\t\t\t\tindex++\n\t\t\t\tlog.Info(\"Index: %v\", index)\n\t\t\t}\n\n\t\t\tif err := iter.Close(); err != nil {\n\t\t\t\tlog.Error(\"Iteration failed: %v\", err)\n\t\t\t}\n\n\t\t\tif iter.Timeout() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Info(\"iter existed, starting over from %v -- %v item(s) are processsed on this iter\", index+1, index-skip)\n\t\t\titeration++\n\t\t}\n\n\t\tif iteration == MAX_ITERATION_COUNT {\n\t\t\tlog.Info(\"Max iteration count %v reached, exiting\", iteration)\n\t\t}\n\t\tlog.Info(\"%v entries on this process\", index-skip)\n\t\tlog.Info(\"deleted item count %v\", deletedItems)\n\n\t\treturn nil\n\t}\n}\n\nfunc deleteDoc(result map[string]interface{}, collectionName string) {\n\n\tid, ok := result[\"_id\"]\n\tif !ok {\n\t\tlog.Error(\"result doesnt have _id %v\", result)\n\t\treturn\n\t}\n\tvar collectionId bson.ObjectId\n\n\tcollectionId = (id.(bson.ObjectId))\n\n\tif !collectionId.Valid() {\n\t\tlog.Info(\"result id is not valid %v\", collectionId)\n\t\treturn\n\t}\n\n\tif collectionId.Time().UTC().UnixNano() > oneMonthAgo.UnixNano() {\n\t\tlog.Info(\"not deleting docuemnt %v\", collectionId.Time())\n\t\treturn\n\t}\n\n\tdeleteRel(collectionId)\n\n\tlog.Info(\"removing collectionId: %v from collectionName: %v \", collectionId.Hex(), collectionName)\n\n\tif err := mongodb.Run(collectionName, func(coll *mgo.Collection) error {\n\t\treturn coll.RemoveId(collectionId)\n\t}); err != nil {\n\t\tlog.Error(\"couldnt remove collectionId: %v from collectionName: %v \", collectionId.Hex(), collectionName)\n\t}\n\tdeletedItems++\n}\n\nfunc deleteRel(id bson.ObjectId) {\n\tvar rels []models.Relationship\n\tif err := mongodb.Run(\"relationships\", func(coll *mgo.Collection) error {\n\t\tselector := helper.Selector{\"$or\": []helper.Selector{\n\t\t\thelper.Selector{\"sourceId\": id},\n\t\t\thelper.Selector{\"targetId\": id},\n\t\t}}\n\t\treturn coll.Find(selector).All(&rels)\n\t}); err != nil {\n\t\tlog.Error(\"couldnt fetch collectionId: %v from relationships \", id.Hex())\n\t\treturn\n\t}\n\n\tdeleteDocumentsFromRelationships(rels)\n}\n\nfunc deleteDocumentsFromRelationships(rels []models.Relationship) {\n\tif len(rels) == 0 {\n\t\tlog.Info(\"document has no relationship\")\n\t\treturn\n\t}\n\n\tfor _, rel := range rels {\n\t\tif err := mongodb.Run(\"relationships\", func(coll *mgo.Collection) error {\n\t\t\treturn coll.RemoveId(rel.Id)\n\t\t}); err != nil {\n\t\t\tlog.Error(\"couldnt remove collectionId: %v from relationships \", rel.Id.Hex())\n\t\t}\n\t\tdeletedItems++\n\t}\n}\n\nvar ToBeDTruncatedNames = []string{\n\t\"cActivities\",\n\t\"cFolloweeBuckets\",\n\t\"cLikeeBuckets\",\n\t\"cLikerBuckets\",\n\t\"cNewMemberBuckets\",\n\t\"cReplieeBuckets\",\n\t\"jEmailConfirmations\",\n\t\"jEmailNotifications\",\n\t\"jInvitationRequests\",\n\t\"jInvitations\",\n\t\"jLogs\",\n\t\"jMailNotifications\",\n\t\"jMails\",\n\t\"jOldUsers\",\n\t\"jPasswordRecoveries\",\n\t\"jVerificationTokens\",\n}\nTruncator: switch using Iter helperpackage main\n\nimport (\n\t\"flag\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\"\n\n\thelper \"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/helpers\"\n\t\"koding\/tools\/config\"\n\t\"koding\/tools\/logger\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar log = logger.New(\"post truncator\")\n\ntype strToInf map[string]interface{}\n\nvar (\n\tconf *config.Config\n\tflagProfile = flag.String(\"c\", \"vagrant\", \"Configuration profile from file\")\n\tflagDirection = flag.String(\"direction\", \"targetName\", \"direction name \")\n\tflagSkip = flag.Int(\"s\", 0, \"Configuration profile from file\")\n\tflagLimit = flag.Int(\"l\", 1000, \"Configuration profile from file\")\n\tmongo *mongodb.MongoDB\n\tdeletedItems = 0\n\toneMonthAgo = time.Now().Add(-time.Minute * 60 * 24 * 30).UTC()\n)\n\nfunc initialize() {\n\tflag.Parse()\n\tlog.SetLevel(logger.INFO)\n\tif *flagProfile == \"\" {\n\t\tlog.Fatal(\"Please specify profile via -c. Aborting.\")\n\t}\n\n\tconf = config.MustConfig(*flagProfile)\n\thelper.Initialize(conf.Mongo)\n\tmongo = helper.Mongo\n}\n\nfunc main() {\n\n\t\/\/ init the package\n\tinitialize()\n\tlog.Info(\"Truncater worker started\")\n\n\tvar resultDataType map[string]interface{}\n\n\titerOptions := helpers.NewIterOptions()\n\titerOptions.Filter = helper.Selector{}\n\titerOptions.DataType = &resultDataType\n\titerOptions.Limit = *flagLimit\n\titerOptions.Skip = *flagSkip\n\titerOptions.Log = log\n\n\tlog.SetLevel(logger.DEBUG)\n\n\tfor _, coll := range ToBeDTruncatedNames {\n\t\titerOptions.CollectionName = coll\n\t\titerOptions.F = truncateItems(coll)\n\t\terr := helpers.Iter(mongo, iterOptions)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error while iter: %v\", err)\n\t\t}\n\t}\n\n\tlog.Info(\"Truncator worker finished\")\n\n}\n\nfunc truncateItems(collectionName string) func(doc interface{}) {\n\treturn func(doc interface{}) {\n\t\tresult := *(doc.(*map[string]interface{}))\n\n\t\tid, ok := result[\"_id\"]\n\t\tif !ok {\n\t\t\tlog.Error(\"result doesnt have _id %v\", result)\n\t\t\treturn\n\t\t}\n\t\tvar collectionId bson.ObjectId\n\n\t\tcollectionId = (id.(bson.ObjectId))\n\n\t\tif !collectionId.Valid() {\n\t\t\tlog.Info(\"result id is not valid %v\", collectionId)\n\t\t\treturn\n\t\t}\n\n\t\tif collectionId.Time().UTC().UnixNano() > oneMonthAgo.UnixNano() {\n\t\t\tlog.Info(\"not deleting docuemnt %v\", collectionId.Time())\n\t\t\treturn\n\t\t}\n\n\t\tdeleteRel(collectionId)\n\n\t\tlog.Info(\"removing collectionId: %v from collectionName: %v \", collectionId.Hex(), collectionName)\n\n\t\tif err := mongo.Run(collectionName, func(coll *mgo.Collection) error {\n\t\t\treturn coll.RemoveId(collectionId)\n\t\t}); err != nil {\n\t\t\tlog.Error(\"couldnt remove collectionId: %v from collectionName: %v \", collectionId.Hex(), collectionName)\n\t\t}\n\t\tdeletedItems++\n\t}\n}\n\nfunc deleteRel(id bson.ObjectId) {\n\tvar rels []models.Relationship\n\tif err := mongo.Run(\"relationships\", func(coll *mgo.Collection) error {\n\t\tselector := helper.Selector{\"$or\": []helper.Selector{\n\t\t\thelper.Selector{\"sourceId\": id},\n\t\t\thelper.Selector{\"targetId\": id},\n\t\t}}\n\t\treturn coll.Find(selector).All(&rels)\n\t}); err != nil {\n\t\tlog.Error(\"couldnt fetch collectionId: %v from relationships \", id.Hex())\n\t\treturn\n\t}\n\n\tdeleteDocumentsFromRelationships(rels)\n}\n\nfunc deleteDocumentsFromRelationships(rels []models.Relationship) {\n\tif len(rels) == 0 {\n\t\tlog.Info(\"document has no relationship\")\n\t\treturn\n\t}\n\n\tfor _, rel := range rels {\n\t\tif err := mongo.Run(\"relationships\", func(coll *mgo.Collection) error {\n\t\t\treturn coll.RemoveId(rel.Id)\n\t\t}); err != nil {\n\t\t\tlog.Error(\"couldnt remove collectionId: %v from relationships \", rel.Id.Hex())\n\t\t}\n\t\tdeletedItems++\n\t}\n}\n\nvar ToBeDTruncatedNames = []string{\n\t\"cActivities\",\n\t\"cFolloweeBuckets\",\n\t\"cLikeeBuckets\",\n\t\"cLikerBuckets\",\n\t\"cNewMemberBuckets\",\n\t\"cReplieeBuckets\",\n\t\"jEmailConfirmations\",\n\t\"jEmailNotifications\",\n\t\"jInvitationRequests\",\n\t\"jInvitations\",\n\t\"jLogs\",\n\t\"jMailNotifications\",\n\t\"jMails\",\n\t\"jOldUsers\",\n\t\"jPasswordRecoveries\",\n\t\"jVerificationTokens\",\n}\n<|endoftext|>"} {"text":"package inflector_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/tangzero\/inflector\"\n)\n\nvar SingularToPlural = map[string]string{\n\t\"search\": \"searches\",\n\t\"switch\": \"switches\",\n\t\"fix\": \"fixes\",\n\t\"box\": \"boxes\",\n\t\"process\": \"processes\",\n\t\"address\": \"addresses\",\n\t\"case\": \"cases\",\n\t\"stack\": \"stacks\",\n\t\"wish\": \"wishes\",\n\t\"fish\": \"fish\",\n\t\"jeans\": \"jeans\",\n\t\"funky jeans\": \"funky jeans\",\n\t\"my money\": \"my money\",\n\t\"category\": \"categories\",\n\t\"query\": \"queries\",\n\t\"ability\": \"abilities\",\n\t\"agency\": \"agencies\",\n\t\"movie\": \"movies\",\n\t\"archive\": \"archives\",\n\t\"index\": \"indices\",\n\t\"wife\": \"wives\",\n\t\"safe\": \"saves\",\n\t\"half\": \"halves\",\n\t\"move\": \"moves\",\n\t\"salesperson\": \"salespeople\",\n\t\"person\": \"people\",\n\t\"spokesman\": \"spokesmen\",\n\t\"man\": \"men\",\n\t\"woman\": \"women\",\n\t\"basis\": \"bases\",\n\t\"diagnosis\": \"diagnoses\",\n\t\"diagnosis_a\": \"diagnosis_as\",\n\t\"datum\": \"data\",\n\t\"medium\": \"media\",\n\t\"stadium\": \"stadia\",\n\t\"analysis\": \"analyses\",\n\t\"my_analysis\": \"my_analyses\",\n\t\"node_child\": \"node_children\",\n\t\"child\": \"children\",\n\t\"experience\": \"experiences\",\n\t\"day\": \"days\",\n\t\"comment\": \"comments\",\n\t\"foobar\": \"foobars\",\n\t\"newsletter\": \"newsletters\",\n\t\"old_news\": \"old_news\",\n\t\"news\": \"news\",\n\t\"series\": \"series\",\n\t\"miniseries\": \"miniseries\",\n\t\"species\": \"species\",\n\t\"quiz\": \"quizzes\",\n\t\"perspective\": \"perspectives\",\n\t\"ox\": \"oxen\",\n\t\"photo\": \"photos\",\n\t\"buffalo\": \"buffaloes\",\n\t\"tomato\": \"tomatoes\",\n\t\"dwarf\": \"dwarves\",\n\t\"elf\": \"elves\",\n\t\"information\": \"information\",\n\t\"equipment\": \"equipment\",\n\t\"bus\": \"buses\",\n\t\"status\": \"statuses\",\n\t\"status_code\": \"status_codes\",\n\t\"mouse\": \"mice\",\n\t\"louse\": \"lice\",\n\t\"house\": \"houses\",\n\t\"octopus\": \"octopi\",\n\t\"virus\": \"viri\",\n\t\"alias\": \"aliases\",\n\t\"portfolio\": \"portfolios\",\n\t\"vertex\": \"vertices\",\n\t\"matrix\": \"matrices\",\n\t\"matrix_fu\": \"matrix_fus\",\n\t\"axis\": \"axes\",\n\t\"taxi\": \"taxis\",\n\t\"testis\": \"testes\",\n\t\"crisis\": \"crises\",\n\t\"rice\": \"rice\",\n\t\"shoe\": \"shoes\",\n\t\"horse\": \"horses\",\n\t\"prize\": \"prizes\",\n\t\"edge\": \"edges\",\n\t\"database\": \"databases\",\n}\n\nvar CamelToUnderscore = map[string]string{\n\t\"Product\": \"product\",\n\t\"SpecialGuest\": \"special_guest\",\n\t\"ApplicationController\": \"application_controller\",\n\t\"Area51Controller\": \"area51_controller\",\n}\n\nvar CamelToDashes = map[string]string{\n\t\"Product\": \"product\",\n\t\"SpecialGuest\": \"special-guest\",\n\t\"ApplicationController\": \"application-controller\",\n\t\"Area51Controller\": \"area51-controller\",\n}\n\nvar ToTables = map[string]string{\n\t\"Product\": \"products\",\n\t\"AdminUser\": \"admin_users\",\n\t\"user-account\": \"user_accounts\",\n\t\"specialOrder\": \"special_orders\",\n}\nvar ToForeignKey = map[string]string{\n\t\"Product\": \"product_id\",\n\t\"AdminUser\": \"admin_user_id\",\n\t\"user-account\": \"user_account_id\",\n\t\"specialOrder\": \"special_order_id\",\n}\n\nfunc TestPluralize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = false\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, plural, inflector.Pluralize(singular))\n\t}\n}\n\nfunc TestCachedPluralize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = true\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, plural, inflector.Pluralize(singular))\n\t}\n}\n\nfunc TestSingularize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = false\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, singular, inflector.Singularize(plural))\n\t}\n}\n\nfunc TestCachedSingularize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = true\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, singular, inflector.Singularize(plural))\n\t}\n}\n\nfunc TestCamelize(t *testing.T) {\n\tfor camel, underscore := range CamelToUnderscore {\n\t\tassert.Equal(t, camel, inflector.Camelize(underscore))\n\t}\n}\n\nfunc TestUnderscorize(t *testing.T) {\n\tfor camel, underscore := range CamelToUnderscore {\n\t\tassert.Equal(t, underscore, inflector.Underscorize(camel))\n\t}\n}\n\nfunc TestDasherize(t *testing.T) {\n\tfor camel, dash := range CamelToDashes {\n\t\tassert.Equal(t, dash, inflector.Dasherize(camel))\n\t}\n}\n\nfunc TestTableize(t *testing.T) {\n\tfor term, table := range ToTables {\n\t\tassert.Equal(t, table, inflector.Tableize(term))\n\t}\n}\nfunc TestForeignKey(t *testing.T) {\n\tfor term, key := range ToForeignKey {\n\t\tassert.Equal(t, key, inflector.ForeignKey(term))\n\t}\n}\nadded missing empty line :Ppackage inflector_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/tangzero\/inflector\"\n)\n\nvar SingularToPlural = map[string]string{\n\t\"search\": \"searches\",\n\t\"switch\": \"switches\",\n\t\"fix\": \"fixes\",\n\t\"box\": \"boxes\",\n\t\"process\": \"processes\",\n\t\"address\": \"addresses\",\n\t\"case\": \"cases\",\n\t\"stack\": \"stacks\",\n\t\"wish\": \"wishes\",\n\t\"fish\": \"fish\",\n\t\"jeans\": \"jeans\",\n\t\"funky jeans\": \"funky jeans\",\n\t\"my money\": \"my money\",\n\t\"category\": \"categories\",\n\t\"query\": \"queries\",\n\t\"ability\": \"abilities\",\n\t\"agency\": \"agencies\",\n\t\"movie\": \"movies\",\n\t\"archive\": \"archives\",\n\t\"index\": \"indices\",\n\t\"wife\": \"wives\",\n\t\"safe\": \"saves\",\n\t\"half\": \"halves\",\n\t\"move\": \"moves\",\n\t\"salesperson\": \"salespeople\",\n\t\"person\": \"people\",\n\t\"spokesman\": \"spokesmen\",\n\t\"man\": \"men\",\n\t\"woman\": \"women\",\n\t\"basis\": \"bases\",\n\t\"diagnosis\": \"diagnoses\",\n\t\"diagnosis_a\": \"diagnosis_as\",\n\t\"datum\": \"data\",\n\t\"medium\": \"media\",\n\t\"stadium\": \"stadia\",\n\t\"analysis\": \"analyses\",\n\t\"my_analysis\": \"my_analyses\",\n\t\"node_child\": \"node_children\",\n\t\"child\": \"children\",\n\t\"experience\": \"experiences\",\n\t\"day\": \"days\",\n\t\"comment\": \"comments\",\n\t\"foobar\": \"foobars\",\n\t\"newsletter\": \"newsletters\",\n\t\"old_news\": \"old_news\",\n\t\"news\": \"news\",\n\t\"series\": \"series\",\n\t\"miniseries\": \"miniseries\",\n\t\"species\": \"species\",\n\t\"quiz\": \"quizzes\",\n\t\"perspective\": \"perspectives\",\n\t\"ox\": \"oxen\",\n\t\"photo\": \"photos\",\n\t\"buffalo\": \"buffaloes\",\n\t\"tomato\": \"tomatoes\",\n\t\"dwarf\": \"dwarves\",\n\t\"elf\": \"elves\",\n\t\"information\": \"information\",\n\t\"equipment\": \"equipment\",\n\t\"bus\": \"buses\",\n\t\"status\": \"statuses\",\n\t\"status_code\": \"status_codes\",\n\t\"mouse\": \"mice\",\n\t\"louse\": \"lice\",\n\t\"house\": \"houses\",\n\t\"octopus\": \"octopi\",\n\t\"virus\": \"viri\",\n\t\"alias\": \"aliases\",\n\t\"portfolio\": \"portfolios\",\n\t\"vertex\": \"vertices\",\n\t\"matrix\": \"matrices\",\n\t\"matrix_fu\": \"matrix_fus\",\n\t\"axis\": \"axes\",\n\t\"taxi\": \"taxis\",\n\t\"testis\": \"testes\",\n\t\"crisis\": \"crises\",\n\t\"rice\": \"rice\",\n\t\"shoe\": \"shoes\",\n\t\"horse\": \"horses\",\n\t\"prize\": \"prizes\",\n\t\"edge\": \"edges\",\n\t\"database\": \"databases\",\n}\n\nvar CamelToUnderscore = map[string]string{\n\t\"Product\": \"product\",\n\t\"SpecialGuest\": \"special_guest\",\n\t\"ApplicationController\": \"application_controller\",\n\t\"Area51Controller\": \"area51_controller\",\n}\n\nvar CamelToDashes = map[string]string{\n\t\"Product\": \"product\",\n\t\"SpecialGuest\": \"special-guest\",\n\t\"ApplicationController\": \"application-controller\",\n\t\"Area51Controller\": \"area51-controller\",\n}\n\nvar ToTables = map[string]string{\n\t\"Product\": \"products\",\n\t\"AdminUser\": \"admin_users\",\n\t\"user-account\": \"user_accounts\",\n\t\"specialOrder\": \"special_orders\",\n}\nvar ToForeignKey = map[string]string{\n\t\"Product\": \"product_id\",\n\t\"AdminUser\": \"admin_user_id\",\n\t\"user-account\": \"user_account_id\",\n\t\"specialOrder\": \"special_order_id\",\n}\n\nfunc TestPluralize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = false\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, plural, inflector.Pluralize(singular))\n\t}\n}\n\nfunc TestCachedPluralize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = true\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, plural, inflector.Pluralize(singular))\n\t}\n}\n\nfunc TestSingularize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = false\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, singular, inflector.Singularize(plural))\n\t}\n}\n\nfunc TestCachedSingularize(t *testing.T) {\n\tinflector.ClearCache()\n\tinflector.ShouldCache = true\n\tfor singular, plural := range SingularToPlural {\n\t\tassert.Equal(t, singular, inflector.Singularize(plural))\n\t}\n}\n\nfunc TestCamelize(t *testing.T) {\n\tfor camel, underscore := range CamelToUnderscore {\n\t\tassert.Equal(t, camel, inflector.Camelize(underscore))\n\t}\n}\n\nfunc TestUnderscorize(t *testing.T) {\n\tfor camel, underscore := range CamelToUnderscore {\n\t\tassert.Equal(t, underscore, inflector.Underscorize(camel))\n\t}\n}\n\nfunc TestDasherize(t *testing.T) {\n\tfor camel, dash := range CamelToDashes {\n\t\tassert.Equal(t, dash, inflector.Dasherize(camel))\n\t}\n}\n\nfunc TestTableize(t *testing.T) {\n\tfor term, table := range ToTables {\n\t\tassert.Equal(t, table, inflector.Tableize(term))\n\t}\n}\n\nfunc TestForeignKey(t *testing.T) {\n\tfor term, key := range ToForeignKey {\n\t\tassert.Equal(t, key, inflector.ForeignKey(term))\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graphics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\/opengl\"\n)\n\nfunc glMatrix(m *[4][4]float64) []float32 {\n\treturn []float32{\n\t\tfloat32(m[0][0]), float32(m[1][0]), float32(m[2][0]), float32(m[3][0]),\n\t\tfloat32(m[0][1]), float32(m[1][1]), float32(m[2][1]), float32(m[3][1]),\n\t\tfloat32(m[0][2]), float32(m[1][2]), float32(m[2][2]), float32(m[3][2]),\n\t\tfloat32(m[0][3]), float32(m[1][3]), float32(m[2][3]), float32(m[3][3]),\n\t}\n}\n\ntype Matrix interface {\n\tElement(i, j int) float64\n}\n\nvar vertices = make([]int16, 16*quadsMaxNum)\n\nvar shadersInitialized = false\n\nfunc drawTexture(c *opengl.Context, texture opengl.Texture, projectionMatrix *[4][4]float64, quads TextureQuads, geo Matrix, color Matrix) error {\n\t\/\/ NOTE: WebGL doesn't seem to have Check gl.MAX_ELEMENTS_VERTICES or gl.MAX_ELEMENTS_INDICES so far.\n\t\/\/ Let's use them to compare to len(quads) in the future.\n\n\tif !shadersInitialized {\n\t\tif err := initialize(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tshadersInitialized = true\n\t}\n\n\tl := quads.Len()\n\tif l == 0 {\n\t\treturn nil\n\t}\n\tif quadsMaxNum < l {\n\t\treturn errors.New(fmt.Sprintf(\"len(quads) must be equal to or less than %d\", quadsMaxNum))\n\t}\n\n\tp := programContext{\n\t\tprogram: programTexture,\n\t\tcontext: c,\n\t\tprojectionMatrix: glMatrix(projectionMatrix),\n\t\ttexture: texture,\n\t\tgeoM: geo,\n\t\tcolorM: color,\n\t}\n\tp.begin()\n\tdefer p.end()\n\n\tfor i := 0; i < l; i++ {\n\t\tx0, y0, x1, y1 := quads.Vertex(i)\n\t\tu0, v0, u1, v1 := quads.Texture(i)\n\t\tvertices[16*i] = int16(x0)\n\t\tvertices[16*i+1] = int16(y0)\n\t\tvertices[16*i+2] = int16(u0)\n\t\tvertices[16*i+3] = int16(v0)\n\t\tvertices[16*i+4] = int16(x1)\n\t\tvertices[16*i+5] = int16(y0)\n\t\tvertices[16*i+6] = int16(u1)\n\t\tvertices[16*i+7] = int16(v0)\n\t\tvertices[16*i+8] = int16(x0)\n\t\tvertices[16*i+9] = int16(y1)\n\t\tvertices[16*i+10] = int16(u0)\n\t\tvertices[16*i+11] = int16(v1)\n\t\tvertices[16*i+12] = int16(x1)\n\t\tvertices[16*i+13] = int16(y1)\n\t\tvertices[16*i+14] = int16(u1)\n\t\tvertices[16*i+15] = int16(v1)\n\t}\n\tif len(vertices) == 0 {\n\t\treturn nil\n\t}\n\tc.BufferSubData(c.ArrayBuffer, vertices[:16*quads.Len()])\n\tc.DrawElements(c.Triangles, 6*quads.Len())\n\treturn nil\n}\ngraphics: Remove unneeded 'if'\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graphics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\/opengl\"\n)\n\nfunc glMatrix(m *[4][4]float64) []float32 {\n\treturn []float32{\n\t\tfloat32(m[0][0]), float32(m[1][0]), float32(m[2][0]), float32(m[3][0]),\n\t\tfloat32(m[0][1]), float32(m[1][1]), float32(m[2][1]), float32(m[3][1]),\n\t\tfloat32(m[0][2]), float32(m[1][2]), float32(m[2][2]), float32(m[3][2]),\n\t\tfloat32(m[0][3]), float32(m[1][3]), float32(m[2][3]), float32(m[3][3]),\n\t}\n}\n\ntype Matrix interface {\n\tElement(i, j int) float64\n}\n\nvar vertices = make([]int16, 16*quadsMaxNum)\n\nvar shadersInitialized = false\n\nfunc drawTexture(c *opengl.Context, texture opengl.Texture, projectionMatrix *[4][4]float64, quads TextureQuads, geo Matrix, color Matrix) error {\n\t\/\/ NOTE: WebGL doesn't seem to have Check gl.MAX_ELEMENTS_VERTICES or gl.MAX_ELEMENTS_INDICES so far.\n\t\/\/ Let's use them to compare to len(quads) in the future.\n\n\tif !shadersInitialized {\n\t\tif err := initialize(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tshadersInitialized = true\n\t}\n\n\tl := quads.Len()\n\tif l == 0 {\n\t\treturn nil\n\t}\n\tif quadsMaxNum < l {\n\t\treturn errors.New(fmt.Sprintf(\"len(quads) must be equal to or less than %d\", quadsMaxNum))\n\t}\n\n\tp := programContext{\n\t\tprogram: programTexture,\n\t\tcontext: c,\n\t\tprojectionMatrix: glMatrix(projectionMatrix),\n\t\ttexture: texture,\n\t\tgeoM: geo,\n\t\tcolorM: color,\n\t}\n\tp.begin()\n\tdefer p.end()\n\n\tfor i := 0; i < l; i++ {\n\t\tx0, y0, x1, y1 := quads.Vertex(i)\n\t\tu0, v0, u1, v1 := quads.Texture(i)\n\t\tvertices[16*i] = int16(x0)\n\t\tvertices[16*i+1] = int16(y0)\n\t\tvertices[16*i+2] = int16(u0)\n\t\tvertices[16*i+3] = int16(v0)\n\t\tvertices[16*i+4] = int16(x1)\n\t\tvertices[16*i+5] = int16(y0)\n\t\tvertices[16*i+6] = int16(u1)\n\t\tvertices[16*i+7] = int16(v0)\n\t\tvertices[16*i+8] = int16(x0)\n\t\tvertices[16*i+9] = int16(y1)\n\t\tvertices[16*i+10] = int16(u0)\n\t\tvertices[16*i+11] = int16(v1)\n\t\tvertices[16*i+12] = int16(x1)\n\t\tvertices[16*i+13] = int16(y1)\n\t\tvertices[16*i+14] = int16(u1)\n\t\tvertices[16*i+15] = int16(v1)\n\t}\n\tc.BufferSubData(c.ArrayBuffer, vertices[:16*quads.Len()])\n\tc.DrawElements(c.Triangles, 6*quads.Len())\n\treturn nil\n}\n<|endoftext|>"} {"text":"package kite\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ Test 2 way communication between kites.\nfunc TestKite(t *testing.T) {\n\tmathKite := New(\"mathworker\", \"0.0.1\")\n\tmathKite.HandleFunc(\"square\", Square)\n\tmathKite.HandleFunc(\"squareCB\", SquareCB)\n\tmathKite.Config.DisableAuthentication = true\n\tgo http.ListenAndServe(\"127.0.0.1:3636\", mathKite)\n\n\texp2Kite := New(\"exp2\", \"0.0.1\")\n\tgo http.ListenAndServe(\"127.0.0.1:3637\", exp2Kite)\n\n\t\/\/ Wait until they start serving\n\ttime.Sleep(time.Second)\n\n\tfooChan := make(chan string)\n\thandleFoo := func(r *Request) (interface{}, error) {\n\t\ts := r.Args.One().MustString()\n\t\tfmt.Printf(\"Message received: %s\\n\", s)\n\t\tfooChan <- s\n\t\treturn nil, nil\n\t}\n\n\texp2Kite.HandleFunc(\"foo\", handleFoo)\n\n\t\/\/ exp2 connects to mathworker\n\tremote := exp2Kite.NewRemoteKiteString(\"ws:\/\/127.0.0.1:3636\")\n\terr := remote.Dial()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t\treturn\n\t}\n\n\tresult, err := remote.Tell(\"square\", 2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t\treturn\n\t}\n\n\tnumber := result.MustFloat64()\n\n\tfmt.Printf(\"rpc result: %f\\n\", number)\n\n\tif number != 4 {\n\t\tt.Errorf(\"Invalid result: %f\", number)\n\t}\n\n\tselect {\n\tcase s := <-fooChan:\n\t\tif s != \"bar\" {\n\t\t\tt.Errorf(\"Invalid message: %s\", s)\n\t\t\treturn\n\t\t}\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Errorf(\"Did not get the message\")\n\t\treturn\n\t}\n\n\tresultChan := make(chan float64, 1)\n\tresultCallback := func(r *Request) {\n\t\tfmt.Printf(\"Request: %#v\\n\", r)\n\t\tn := r.Args.One().MustFloat64()\n\t\tresultChan <- n\n\t}\n\n\tresult, err = remote.Tell(\"squareCB\", 3, Callback(resultCallback))\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tselect {\n\tcase n := <-resultChan:\n\t\tif n != 9.0 {\n\t\t\tt.Errorf(\"Unexpected result: %f\", n)\n\t\t\treturn\n\t\t}\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Errorf(\"Did not get the message\")\n\t\treturn\n\t}\n}\n\n\/\/ Returns the result. Also tests reverse call.\nfunc Square(r *Request) (interface{}, error) {\n\ta := r.Args[0].MustFloat64()\n\tresult := a * a\n\n\tfmt.Printf(\"Kite call, sending result '%f' back\\n\", result)\n\n\t\/\/ Reverse method call\n\tr.RemoteKite.Go(\"foo\", \"bar\")\n\n\treturn result, nil\n}\n\n\/\/ Calls the callback with the result. For testing requests with Callback.\nfunc SquareCB(r *Request) (interface{}, error) {\n\targs := r.Args.MustSliceOfLength(2)\n\ta := args[0].MustFloat64()\n\tcb := args[1].MustFunction()\n\n\tresult := a * a\n\n\tfmt.Printf(\"Kite call, sending result '%f' back\\n\", result)\n\n\t\/\/ Send the result.\n\terr := cb(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\nrefactor kite testpackage kite\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ Test 2 way communication between kites.\nfunc TestKite(t *testing.T) {\n\tmathKite := New(\"mathworker\", \"0.0.1\")\n\tmathKite.HandleFunc(\"square\", Square)\n\tmathKite.HandleFunc(\"squareCB\", SquareCB)\n\tmathKite.Config.DisableAuthentication = true\n\tgo http.ListenAndServe(\"127.0.0.1:3636\", mathKite)\n\n\texp2Kite := New(\"exp2\", \"0.0.1\")\n\tgo http.ListenAndServe(\"127.0.0.1:3637\", exp2Kite)\n\n\t\/\/ Wait until they start serving\n\ttime.Sleep(time.Second)\n\n\tfooChan := make(chan string)\n\thandleFoo := func(r *Request) (interface{}, error) {\n\t\ts := r.Args.One().MustString()\n\t\tfmt.Printf(\"Message received: %s\\n\", s)\n\t\tfooChan <- s\n\t\treturn nil, nil\n\t}\n\n\texp2Kite.HandleFunc(\"foo\", handleFoo)\n\n\t\/\/ exp2 connects to mathworker\n\tremote := exp2Kite.NewRemoteKiteString(\"ws:\/\/127.0.0.1:3636\")\n\terr := remote.Dial()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tresult, err := remote.Tell(\"square\", 2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tnumber := result.MustFloat64()\n\n\tfmt.Printf(\"rpc result: %f\\n\", number)\n\n\tif number != 4 {\n\t\tt.Fatalf(\"Invalid result: %f\", number)\n\t}\n\n\tselect {\n\tcase s := <-fooChan:\n\t\tif s != \"bar\" {\n\t\t\tt.Fatalf(\"Invalid message: %s\", s)\n\t\t}\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Did not get the message\")\n\t}\n\n\tresultChan := make(chan float64, 1)\n\tresultCallback := func(r *Request) {\n\t\tfmt.Printf(\"Request: %#v\\n\", r)\n\t\tn := r.Args.One().MustFloat64()\n\t\tresultChan <- n\n\t}\n\n\tresult, err = remote.Tell(\"squareCB\", 3, Callback(resultCallback))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tselect {\n\tcase n := <-resultChan:\n\t\tif n != 9.0 {\n\t\t\tt.Fatalf(\"Unexpected result: %f\", n)\n\t\t}\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"Did not get the message\")\n\t}\n}\n\n\/\/ Returns the result. Also tests reverse call.\nfunc Square(r *Request) (interface{}, error) {\n\ta := r.Args[0].MustFloat64()\n\tresult := a * a\n\n\tfmt.Printf(\"Kite call, sending result '%f' back\\n\", result)\n\n\t\/\/ Reverse method call\n\tr.RemoteKite.Go(\"foo\", \"bar\")\n\n\treturn result, nil\n}\n\n\/\/ Calls the callback with the result. For testing requests with Callback.\nfunc SquareCB(r *Request) (interface{}, error) {\n\targs := r.Args.MustSliceOfLength(2)\n\ta := args[0].MustFloat64()\n\tcb := args[1].MustFunction()\n\n\tresult := a * a\n\n\tfmt.Printf(\"Kite call, sending result '%f' back\\n\", result)\n\n\t\/\/ Send the result.\n\terr := cb(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n<|endoftext|>"} {"text":"\/*\n\n Copyright 2013 Niklas Voss\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\npackage golem\n\nimport (\n\t\"errors\"\n\t\"github.com\/garyburd\/go-websocket\/websocket\"\n\t\"log\"\n\t\"net\/http\"\n\t\"reflect\"\n)\n\n\/\/ Router handles multiplexing of incoming messenges by typenames\/events.\n\/\/ Initially a router uses heartbeats and the default protocol.\ntype Router struct {\n\t\/\/ Map of callbacks for event types.\n\tcallbacks map[string]func(*Connection, interface{})\n\t\/\/ Protocol extensions\n\textensions map[reflect.Type]reflect.Value\n\t\/\/ Function being called if connection is closed.\n\tcloseFunc func(*Connection)\n\t\/\/ Function verifying handshake.\n\thandshakeFunc func(http.ResponseWriter, *http.Request) bool\n\t\/\/ Active protocol\n\tprotocol Protocol\n\t\/\/ Flag to enable or disable heartbeats\n\tuseHeartbeats bool\n\t\/\/\n\tconnExtensionConstructor reflect.Value\n}\n\n\/\/ NewRouter intialises a new instance and returns the pointer.\nfunc NewRouter() *Router {\n\t\/\/ Tries to run hub, if already running nothing will happen.\n\thub.run()\n\t\/\/ Returns pointer to instance.\n\treturn &Router{\n\t\tcallbacks: make(map[string]func(*Connection, interface{})),\n\t\textensions: make(map[reflect.Type]reflect.Value),\n\t\tcloseFunc: func(*Connection) {}, \/\/ Empty placeholder close function.\n\t\thandshakeFunc: func(http.ResponseWriter, *http.Request) bool { return true }, \/\/ Handshake always allowed.\n\t\tprotocol: initialProtocol,\n\t\tuseHeartbeats: true,\n\t\tconnExtensionConstructor: defaultConnectionExtension,\n\t}\n}\n\n\/\/ Handler creates a handler function for this router, that can be used with the\n\/\/ http-package to handle WebSocket-Connections.\nfunc (router *Router) Handler() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Check if method used was GET.\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Disallow cross-origin connections.\n\t\tif r.Header.Get(\"Origin\") != \"http:\/\/\"+r.Host {\n\t\t\thttp.Error(w, \"Origin not allowed\", 403)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Check if handshake callback verifies upgrade.\n\t\tif !router.handshakeFunc(w, r) {\n\t\t\thttp.Error(w, \"Authorization failed\", 403)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Upgrade websocket connection.\n\t\tsocket, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)\n\t\t\/\/ Check if handshake was successful\n\t\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Create the connection.\n\t\tconn := newConnection(socket, router)\n\t\t\/\/\n\t\tif router.connExtensionConstructor.IsValid() {\n\t\t\tconn.extend(router.connExtensionConstructor.Call([]reflect.Value{reflect.ValueOf(conn)})[0].Interface())\n\t\t}\n\t\t\/\/ And start reading and writing routines.\n\t\tconn.run()\n\t}\n}\n\n\/\/ The On-function adds callbacks by name of the event, that should be handled.\n\/\/ For type T the callback would be of type:\n\/\/ func (*golem.Connection, *T)\n\/\/ Type T can be any type. By default golem tries to unmarshal json into the\n\/\/ specified type. If a custom protocol is used, it will be used instead to process the data.\n\/\/ If type T is registered to use a protocol extension, it will be used instead.\n\/\/ If type T is interface{} the interstage data of the active protocol will be directly forwarded!\n\/\/ (Note: the golem wiki has a whole page about this function)\nfunc (router *Router) On(name string, callback interface{}) {\n\n\tcallbackValue := reflect.ValueOf(callback)\n\tcallbackType := reflect.TypeOf(callback)\n\tif router.connExtensionConstructor.IsValid() {\n\t\textType := router.connExtensionConstructor.Type().Out(0)\n\t\tif callbackType.In(0) == extType {\n\t\t\t\/\/ EXTENSION TYPE\n\n\t\t\t\/\/ NO DATA\n\t\t\tif callbackType.NumIn() == 1 {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension)}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ INTERFACE\n\t\t\tif callbackType.In(1).Kind() == reflect.Interface {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), reflect.ValueOf(data)}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ PROTOCOL EXTENSION\n\t\t\tif parser, ok := router.extensions[callbackType.In(1)]; ok {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\tif result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() {\n\t\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), result[0]}\n\t\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ PROTOCOL\n\t\t\tcallbackDataElem := callbackType.In(1).Elem()\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tresult := reflect.New(callbackDataElem)\n\n\t\t\t\terr := router.protocol.Unmarshal(data, result.Interface())\n\t\t\t\tif err == nil {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), result}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: Proper debug output!\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t\/\/ DEFAULT TYPE\n\n\t\t\/\/ NO DATA\n\t\tif reflect.TypeOf(callback).NumIn() == 1 {\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tcallback.(func(*Connection))(conn)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ INTERFACE\n\t\tif cb, ok := callback.(func(*Connection, interface{})); ok {\n\t\t\trouter.callbacks[name] = cb\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ PROTOCOL EXTENSION\n\t\tif parser, ok := router.extensions[callbackType.In(1)]; ok {\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tif result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn), result[0]}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ PROTOCOL\n\t\tcallbackDataElem := callbackType.In(1).Elem()\n\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\tresult := reflect.New(callbackDataElem)\n\n\t\t\terr := router.protocol.Unmarshal(data, result.Interface())\n\t\t\tif err == nil {\n\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn), result}\n\t\t\t\tcallbackValue.Call(args)\n\t\t\t} else {\n\t\t\t\t\/\/ TODO: Proper debug output!\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n}\n\n\/\/ Unpacks incoming data and forwards it to callback.\nfunc (router *Router) processMessage(conn *Connection, in []byte) {\n\tif name, data, err := router.protocol.Unpack(in); err == nil {\n\t\tif callback, ok := router.callbacks[name]; ok {\n\t\t\tcallback(conn, data)\n\t\t}\n\t} \/\/ TODO: else error logging?\n\n\tdefer recover()\n}\n\n\/\/ OnClose sets the callback for connection closes.\nfunc (router *Router) OnClose(callback func(*Connection)) {\n\trouter.closeFunc = callback\n}\n\n\/\/ OnHandshake sets the callback for handshake verfication.\n\/\/ If the handshake function returns false the request will not be upgraded.\nfunc (router *Router) OnHandshake(callback func(http.ResponseWriter, *http.Request) bool) {\n\trouter.handshakeFunc = callback\n}\n\n\/\/ The AddProtocolExtension-function allows adding of custom parsers for custom types. For any Type T\n\/\/ the parser function would look like this:\n\/\/ func (interface{}) (T, bool)\n\/\/ The interface's type is depending on the interstage product of the active protocol, by default\n\/\/ for the JSON-based protocol it is []byte and therefore the function could be simplified to:\n\/\/ func ([]byte) (T, bool)\n\/\/ Or in general if P is the interstage product:\n\/\/ func (*P) (T, bool)\n\/\/ The boolean return value is necessary to verify if parsing was successful.\n\/\/ All On-handling function accepting T as input data will now automatically use the custom\n\/\/ extension. For an example see the example_data.go file in the example repository.\nfunc (router *Router) AddProtocolExtension(extensionFunc interface{}) error {\n\textensionValue := reflect.ValueOf(extensionFunc)\n\textensionType := extensionValue.Type()\n\n\tif extensionType.NumIn() != 1 {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: To many arguments!\")\n\t}\n\tif extensionType.NumOut() != 2 {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: Wrong number of return values!\")\n\t}\n\tif extensionType.Out(1).Kind() != reflect.Bool {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: Second return value is not Bool!\")\n\t}\n\n\trouter.extensions[extensionType.Out(0)] = extensionValue\n\n\treturn nil\n}\n\n\/\/ SetConnectionExtension sets the extension for this router. A connection extension is an extended connection structure, that afterwards can be\n\/\/ used by On-handlers as well (use-cases: add persistent storage to connection, additional methods et cetera).\n\/\/ The SetConnectionExtension function takes the constructor of the custom format to be able to use and create it on\n\/\/ connection to the router.\n\/\/ For type E the constructor needs to fulfil the following requirements:\n\/\/ func NewE(conn *Connection) *E\n\/\/ Afterwards On-handler can us this extended type:\n\/\/ router.On(func (extendedConn E, data Datatype) { ... })\n\/\/ For an example have a look at the example repository and have a look at the 'example_connection_extension.go'.\nfunc (router *Router) SetConnectionExtension(constructor interface{}) {\n\trouter.connExtensionConstructor = reflect.ValueOf(constructor)\n}\n\n\/\/ SetProtocol sets the protocol of the router to the supplied implementation of the Protocol interface.\nfunc (router *Router) SetProtocol(protocol Protocol) {\n\trouter.protocol = protocol\n}\n\n\/\/\n\n\/\/ SetHeartbeat activates or deactivates the heartbeat depending on the flag parameter. By default heartbeats are activated.\nfunc (router *Router) SetHeartbeat(flag bool) {\n\trouter.useHeartbeats = flag\n}\nOnClose function extended to accept callbacks with extended connections.\/*\n\n Copyright 2013 Niklas Voss\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\npackage golem\n\nimport (\n\t\"errors\"\n\t\"github.com\/garyburd\/go-websocket\/websocket\"\n\t\"log\"\n\t\"net\/http\"\n\t\"reflect\"\n)\n\n\/\/ Router handles multiplexing of incoming messenges by typenames\/events.\n\/\/ Initially a router uses heartbeats and the default protocol.\ntype Router struct {\n\t\/\/ Map of callbacks for event types.\n\tcallbacks map[string]func(*Connection, interface{})\n\t\/\/ Protocol extensions\n\textensions map[reflect.Type]reflect.Value\n\t\/\/ Function being called if connection is closed.\n\tcloseFunc func(*Connection)\n\t\/\/ Function verifying handshake.\n\thandshakeFunc func(http.ResponseWriter, *http.Request) bool\n\t\/\/ Active protocol\n\tprotocol Protocol\n\t\/\/ Flag to enable or disable heartbeats\n\tuseHeartbeats bool\n\t\/\/\n\tconnExtensionConstructor reflect.Value\n}\n\n\/\/ NewRouter intialises a new instance and returns the pointer.\nfunc NewRouter() *Router {\n\t\/\/ Tries to run hub, if already running nothing will happen.\n\thub.run()\n\t\/\/ Returns pointer to instance.\n\treturn &Router{\n\t\tcallbacks: make(map[string]func(*Connection, interface{})),\n\t\textensions: make(map[reflect.Type]reflect.Value),\n\t\tcloseFunc: func(*Connection) {}, \/\/ Empty placeholder close function.\n\t\thandshakeFunc: func(http.ResponseWriter, *http.Request) bool { return true }, \/\/ Handshake always allowed.\n\t\tprotocol: initialProtocol,\n\t\tuseHeartbeats: true,\n\t\tconnExtensionConstructor: defaultConnectionExtension,\n\t}\n}\n\n\/\/ Handler creates a handler function for this router, that can be used with the\n\/\/ http-package to handle WebSocket-Connections.\nfunc (router *Router) Handler() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Check if method used was GET.\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Disallow cross-origin connections.\n\t\tif r.Header.Get(\"Origin\") != \"http:\/\/\"+r.Host {\n\t\t\thttp.Error(w, \"Origin not allowed\", 403)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Check if handshake callback verifies upgrade.\n\t\tif !router.handshakeFunc(w, r) {\n\t\t\thttp.Error(w, \"Authorization failed\", 403)\n\t\t\treturn\n\t\t}\n\t\t\/\/ Upgrade websocket connection.\n\t\tsocket, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)\n\t\t\/\/ Check if handshake was successful\n\t\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Create the connection.\n\t\tconn := newConnection(socket, router)\n\t\t\/\/\n\t\tif router.connExtensionConstructor.IsValid() {\n\t\t\tconn.extend(router.connExtensionConstructor.Call([]reflect.Value{reflect.ValueOf(conn)})[0].Interface())\n\t\t}\n\t\t\/\/ And start reading and writing routines.\n\t\tconn.run()\n\t}\n}\n\n\/\/ The On-function adds callbacks by name of the event, that should be handled.\n\/\/ For type T the callback would be of type:\n\/\/ func (*golem.Connection, *T)\n\/\/ Type T can be any type. By default golem tries to unmarshal json into the\n\/\/ specified type. If a custom protocol is used, it will be used instead to process the data.\n\/\/ If type T is registered to use a protocol extension, it will be used instead.\n\/\/ If type T is interface{} the interstage data of the active protocol will be directly forwarded!\n\/\/ (Note: the golem wiki has a whole page about this function)\nfunc (router *Router) On(name string, callback interface{}) {\n\n\tcallbackValue := reflect.ValueOf(callback)\n\tcallbackType := reflect.TypeOf(callback)\n\tif router.connExtensionConstructor.IsValid() {\n\t\textType := router.connExtensionConstructor.Type().Out(0)\n\t\tif callbackType.In(0) == extType {\n\t\t\t\/\/ EXTENSION TYPE\n\n\t\t\t\/\/ NO DATA\n\t\t\tif callbackType.NumIn() == 1 {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension)}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ INTERFACE\n\t\t\tif callbackType.In(1).Kind() == reflect.Interface {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), reflect.ValueOf(data)}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ PROTOCOL EXTENSION\n\t\t\tif parser, ok := router.extensions[callbackType.In(1)]; ok {\n\t\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\t\tif result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() {\n\t\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), result[0]}\n\t\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ PROTOCOL\n\t\t\tcallbackDataElem := callbackType.In(1).Elem()\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tresult := reflect.New(callbackDataElem)\n\n\t\t\t\terr := router.protocol.Unmarshal(data, result.Interface())\n\t\t\t\tif err == nil {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn.extension), result}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: Proper debug output!\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t\/\/ DEFAULT TYPE\n\n\t\t\/\/ NO DATA\n\t\tif reflect.TypeOf(callback).NumIn() == 1 {\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tcallback.(func(*Connection))(conn)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ INTERFACE\n\t\tif cb, ok := callback.(func(*Connection, interface{})); ok {\n\t\t\trouter.callbacks[name] = cb\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ PROTOCOL EXTENSION\n\t\tif parser, ok := router.extensions[callbackType.In(1)]; ok {\n\t\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\t\tif result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() {\n\t\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn), result[0]}\n\t\t\t\t\tcallbackValue.Call(args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ PROTOCOL\n\t\tcallbackDataElem := callbackType.In(1).Elem()\n\t\trouter.callbacks[name] = func(conn *Connection, data interface{}) {\n\t\t\tresult := reflect.New(callbackDataElem)\n\n\t\t\terr := router.protocol.Unmarshal(data, result.Interface())\n\t\t\tif err == nil {\n\t\t\t\targs := []reflect.Value{reflect.ValueOf(conn), result}\n\t\t\t\tcallbackValue.Call(args)\n\t\t\t} else {\n\t\t\t\t\/\/ TODO: Proper debug output!\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n}\n\n\/\/ Unpacks incoming data and forwards it to callback.\nfunc (router *Router) processMessage(conn *Connection, in []byte) {\n\tif name, data, err := router.protocol.Unpack(in); err == nil {\n\t\tif callback, ok := router.callbacks[name]; ok {\n\t\t\tcallback(conn, data)\n\t\t}\n\t} \/\/ TODO: else error logging?\n\n\tdefer recover()\n}\n\n\/\/ OnClose sets the callback, that is called when the connection is closed.\n\/\/ It accept function of the type func(*Connection) by default or functions\n\/\/ taking extended connection types if previously registered.\nfunc (router *Router) OnClose(callback interface{}) error { \/\/func(*Connection)) {\n\tif cb, ok := callback.(func(*Connection)); ok {\n\t\trouter.closeFunc = cb\n\t} else {\n\t\tif router.connExtensionConstructor.IsValid() {\n\t\t\tcallbackValue := reflect.ValueOf(callback)\n\t\t\textType := router.connExtensionConstructor.Type().Out(0)\n\t\t\tif reflect.TypeOf(callback).In(0) == extType {\n\t\t\t\trouter.closeFunc = func(conn *Connection) {\n\t\t\t\t\tcallbackValue.Call([]reflect.Value{reflect.ValueOf(conn.extension)})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn errors.New(\"OnClose cannot accept a callback of the type \" + reflect.TypeOf(callback).String() + \".\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn errors.New(\"OnClose can only accept functions of the type func(*Connection), if no extension is registered.\")\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ OnHandshake sets the callback for handshake verfication.\n\/\/ If the handshake function returns false the request will not be upgraded.\nfunc (router *Router) OnHandshake(callback func(http.ResponseWriter, *http.Request) bool) {\n\trouter.handshakeFunc = callback\n}\n\n\/\/ The AddProtocolExtension-function allows adding of custom parsers for custom types. For any Type T\n\/\/ the parser function would look like this:\n\/\/ func (interface{}) (T, bool)\n\/\/ The interface's type is depending on the interstage product of the active protocol, by default\n\/\/ for the JSON-based protocol it is []byte and therefore the function could be simplified to:\n\/\/ func ([]byte) (T, bool)\n\/\/ Or in general if P is the interstage product:\n\/\/ func (*P) (T, bool)\n\/\/ The boolean return value is necessary to verify if parsing was successful.\n\/\/ All On-handling function accepting T as input data will now automatically use the custom\n\/\/ extension. For an example see the example_data.go file in the example repository.\nfunc (router *Router) AddProtocolExtension(extensionFunc interface{}) error {\n\textensionValue := reflect.ValueOf(extensionFunc)\n\textensionType := extensionValue.Type()\n\n\tif extensionType.NumIn() != 1 {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: To many arguments!\")\n\t}\n\tif extensionType.NumOut() != 2 {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: Wrong number of return values!\")\n\t}\n\tif extensionType.Out(1).Kind() != reflect.Bool {\n\t\treturn errors.New(\"Cannot add function(\" + extensionType.String() + \") as parser: Second return value is not Bool!\")\n\t}\n\n\trouter.extensions[extensionType.Out(0)] = extensionValue\n\n\treturn nil\n}\n\n\/\/ SetConnectionExtension sets the extension for this router. A connection extension is an extended connection structure, that afterwards can be\n\/\/ used by On-handlers as well (use-cases: add persistent storage to connection, additional methods et cetera).\n\/\/ The SetConnectionExtension function takes the constructor of the custom format to be able to use and create it on\n\/\/ connection to the router.\n\/\/ For type E the constructor needs to fulfil the following requirements:\n\/\/ func NewE(conn *Connection) *E\n\/\/ Afterwards On-handler can us this extended type:\n\/\/ router.On(func (extendedConn E, data Datatype) { ... })\n\/\/ For an example have a look at the example repository and have a look at the 'example_connection_extension.go'.\nfunc (router *Router) SetConnectionExtension(constructor interface{}) {\n\trouter.connExtensionConstructor = reflect.ValueOf(constructor)\n}\n\n\/\/ SetProtocol sets the protocol of the router to the supplied implementation of the Protocol interface.\nfunc (router *Router) SetProtocol(protocol Protocol) {\n\trouter.protocol = protocol\n}\n\n\/\/\n\n\/\/ SetHeartbeat activates or deactivates the heartbeat depending on the flag parameter. By default heartbeats are activated.\nfunc (router *Router) SetHeartbeat(flag bool) {\n\trouter.useHeartbeats = flag\n}\n<|endoftext|>"} {"text":"package plexgoslack\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nconst base_url string = \"http:\/\/api.themoviedb.org\/3\"\n\ntype TMDb struct {\n\tapi_key string\n}\n\nfunc New(api_key string) *TMDb {\n\treturn &TMDb{api_key: api_key}\n}\n\ntype Result struct {\n\tVoteCount int `json:\"vote_count\"`\n\tId int `json:\"id\"`\n\tVideo bool `json:\"video\"`\n\tVoteAverage float32 `json:\"vote_average\"`\n\tTitle string `json:\"title\"`\n\tPopularity float32 `json:\"popularity\"`\n\tPosterPath string `json:\"poster_path\"`\n\tOriginalLanguage string `json:\"original_language\"`\n\tOriginalTitle string `json:\"original_title\"`\n\tGenreIds []int `json:\"genre_ids\"`\n\tBackdropPath string `json:\"backdrop_path\"`\n\tAdult bool `json:\"adult\"`\n\tOverview string `json:\"overview\"`\n\tReleaseDate string `json:\"release_date\"`\n}\n\ntype SearchResult struct {\n\tPage int `json:\"page\"`\n\tTotalResults int `json:\"total_results\"`\n\tTotalPages int `json:\"total_pages\"`\n\tResults []Result `json:\"results\"`\n}\n\ntype MovieInfo struct {\n\tTitle string\n\tYear string\n\tTumbnail string\n\tSynopsis string\n}\n\nfunc (tmdb *TMDb) GetInfo(title string, year string) (MovieInfo, error) {\n\tvar resp MovieInfo\n\tresult, err := tmdb.SearchMovie(title, year)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tif result.TotalResults == 0 {\n\t\treturn resp, errors.New(\"Couldn't find \" + title + \" (\" + year + \") at TMDb\")\n\t}\n\treturn MovieInfo{Title: title, Year: year, Tumbnail: \"https:\/\/image.tmdb.org\/t\/p\/w92\" + result.Results[0].PosterPath, Synopsis: result.Results[0].Overview}, nil\n}\n\nfunc (tmdb *TMDb) SearchMovie(title string, year string) (SearchResult, error) {\n\tvar resp SearchResult\n\tres, err := http.Get(base_url + \"\/search\/movie?api_key=\" + tmdb.api_key + \"&query=\" + url.QueryEscape(title) + \"&year=\" + year)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tif res.StatusCode != 200 {\n\t\treturn resp, errors.New(fmt.Sprintf(\"HTTP Resposnse %s\", res.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn SearchResult{}, err\n\t}\n\tif err := json.Unmarshal(body, &resp); err != nil {\n\t\treturn SearchResult{}, err\n\t}\n\treturn resp, nil\n}\nmoved<|endoftext|>"} {"text":"package kontena\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/jakubknejzlik\/kontena-git-cli\/model\"\n\t\"github.com\/jakubknejzlik\/kontena-git-cli\/utils\"\n)\n\n\/\/ ServiceCreate ...\nfunc (c *Client) ServiceCreate(name string, service model.KontenaService) error {\n\tcmd := []string{`kontena service create`}\n\tif *service.Instances > 0 {\n\t\tcmd = append(cmd, `--instances `+string(*service.Instances))\n\t}\n\tif service.Command != \"\" {\n\t\tcmd = append(cmd, `--cmd `+service.Command)\n\t}\n\tfor _, value := range service.Environment {\n\t\tcmd = append(cmd, `-e \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Links {\n\t\tcmd = append(cmd, `-l \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Volumes {\n\t\tcmd = append(cmd, `-v \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Ports {\n\t\tcmd = append(cmd, `-p \"`+value+`\"`)\n\t}\n\tif service.Deploy.Strategy != \"\" {\n\t\tcmd = append(cmd, `--deploy `+service.Deploy.Strategy)\n\t}\n\tcmd = append(cmd, name)\n\tcmd = append(cmd, service.Image)\n\n\tutils.Log(\"creating service\", name)\n\treturn utils.RunInteractive(strings.Join(cmd, \" \"))\n}\n\n\/\/ ServiceDeploy ...\nfunc (c *Client) ServiceDeploy(service string) error {\n\tutils.Log(\"deploying service\", service)\n\treturn utils.RunInteractive(fmt.Sprintf(\"kontena service deploy %s\", service))\n}\n\n\/\/ ServiceInStackDeploy ...\nfunc (c *Client) ServiceInStackDeploy(stack, service string) error {\n\treturn c.ServiceDeploy(stack + \"\/\" + service)\n}\n\n\/\/ ServiceExec ...\nfunc (c *Client) ServiceExec(service, command string) ([]byte, error) {\n\treturn utils.Run(fmt.Sprintf(\"kontena service exec %s %s\", service, command))\n}\n\n\/\/ ServiceInStackExec ...\nfunc (c *Client) ServiceInStackExec(stack, service, command string) ([]byte, error) {\n\treturn c.ServiceExec(stack+\"\/\"+service, command)\n}\n\n\/\/ ServiceRemove ...\nfunc (c *Client) ServiceRemove(service string) error {\n\tutils.Log(\"removing service\", service)\n\treturn utils.RunInteractive(fmt.Sprintf(\"kontena service rm --force %s\", service))\n}\nFix service instances nil dereferencepackage kontena\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/jakubknejzlik\/kontena-git-cli\/model\"\n\t\"github.com\/jakubknejzlik\/kontena-git-cli\/utils\"\n)\n\n\/\/ ServiceCreate ...\nfunc (c *Client) ServiceCreate(name string, service model.KontenaService) error {\n\tcmd := []string{`kontena service create`}\n\tif service.Instances != nil && *service.Instances > 0 {\n\t\tcmd = append(cmd, `--instances `+string(*service.Instances))\n\t}\n\tif service.Command != \"\" {\n\t\tcmd = append(cmd, `--cmd `+service.Command)\n\t}\n\tfor _, value := range service.Environment {\n\t\tcmd = append(cmd, `-e \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Links {\n\t\tcmd = append(cmd, `-l \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Volumes {\n\t\tcmd = append(cmd, `-v \"`+value+`\"`)\n\t}\n\tfor _, value := range service.Ports {\n\t\tcmd = append(cmd, `-p \"`+value+`\"`)\n\t}\n\tif service.Deploy.Strategy != \"\" {\n\t\tcmd = append(cmd, `--deploy `+service.Deploy.Strategy)\n\t}\n\tcmd = append(cmd, name)\n\tcmd = append(cmd, service.Image)\n\n\tutils.Log(\"creating service\", name)\n\treturn utils.RunInteractive(strings.Join(cmd, \" \"))\n}\n\n\/\/ ServiceDeploy ...\nfunc (c *Client) ServiceDeploy(service string) error {\n\tutils.Log(\"deploying service\", service)\n\treturn utils.RunInteractive(fmt.Sprintf(\"kontena service deploy %s\", service))\n}\n\n\/\/ ServiceInStackDeploy ...\nfunc (c *Client) ServiceInStackDeploy(stack, service string) error {\n\treturn c.ServiceDeploy(stack + \"\/\" + service)\n}\n\n\/\/ ServiceExec ...\nfunc (c *Client) ServiceExec(service, command string) ([]byte, error) {\n\treturn utils.Run(fmt.Sprintf(\"kontena service exec %s %s\", service, command))\n}\n\n\/\/ ServiceInStackExec ...\nfunc (c *Client) ServiceInStackExec(stack, service, command string) ([]byte, error) {\n\treturn c.ServiceExec(stack+\"\/\"+service, command)\n}\n\n\/\/ ServiceRemove ...\nfunc (c *Client) ServiceRemove(service string) error {\n\tutils.Log(\"removing service\", service)\n\treturn utils.RunInteractive(fmt.Sprintf(\"kontena service rm --force %s\", service))\n}\n<|endoftext|>"} {"text":"package app\n\nimport (\n\t. \"github.com\/tendermint\/go-common\"\n\t\"github.com\/tendermint\/go-merkle\"\n\t\"github.com\/tendermint\/go-wire\"\n\ttmsp \"github.com\/tendermint\/tmsp\/types\"\n)\n\ntype MerkleEyesApp struct {\n\ttree merkle.Tree\n}\n\nfunc NewMerkleEyesApp() *MerkleEyesApp {\n\ttree := merkle.NewIAVLTree(\n\t\t0,\n\t\tnil,\n\t)\n\treturn &MerkleEyesApp{tree: tree}\n}\n\nfunc (app *MerkleEyesApp) Info() string {\n\treturn Fmt(\"size:%v\", app.tree.Size())\n}\n\nfunc (app *MerkleEyesApp) SetOption(key string, value string) (log string) {\n\treturn \"No options are supported yet\"\n}\n\nfunc (app *MerkleEyesApp) AppendTx(tx []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(tx) == 0 {\n\t\treturn tmsp.CodeType_EncodingError, nil, \"Tx length cannot be zero\"\n\t}\n\ttypeByte := tx[0]\n\ttx = tx[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Set\n\t\tkey, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tvalue, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting value: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\tapp.tree.Set(key, value)\n\tcase 0x02: \/\/ Remove\n\t\tkey, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\tapp.tree.Remove(key)\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n\treturn tmsp.CodeType_OK, nil, \"\"\n}\n\nfunc (app *MerkleEyesApp) CheckTx(tx []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(tx) == 0 {\n\t\treturn tmsp.CodeType_EncodingError, nil, \"Tx length cannot be zero\"\n\t}\n\ttypeByte := tx[0]\n\ttx = tx[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Set\n\t\t_, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\t_, n, err = wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting value: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t\/\/app.tree.Set(key, value)\n\tcase 0x02: \/\/ Remove\n\t\t_, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t\/\/app.tree.Remove(key)\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n\treturn tmsp.CodeType_OK, nil, \"\"\n}\n\nfunc (app *MerkleEyesApp) GetHash() (hash []byte, log string) {\n\tif app.tree.Size() == 0 {\n\t\treturn nil, \"Empty hash for empty tree\"\n\t}\n\thash = app.tree.Hash()\n\treturn hash, \"\"\n}\n\nfunc (app *MerkleEyesApp) Query(query []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(query) == 0 {\n\t\treturn tmsp.CodeType_OK, nil, \"Query length cannot be zero\"\n\t}\n\ttypeByte := query[0]\n\tquery = query[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Get\n\t\tkey, n, err := wire.GetByteSlice(query)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\tquery = query[n:]\n\t\tif len(query) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t_, value, _ := app.tree.Get(key)\n\t\tres := make([]byte, wire.ByteSliceSize(value))\n\t\tbuf := res\n\t\tn, err = wire.PutByteSlice(buf, value)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error putting value: %v\", err.Error())\n\t\t}\n\t\tbuf = buf[n:]\n\t\treturn tmsp.CodeType_OK, res, \"\"\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n}\nPrint SET for demopackage app\n\nimport (\n\t\"fmt\"\n\t. \"github.com\/tendermint\/go-common\"\n\t\"github.com\/tendermint\/go-merkle\"\n\t\"github.com\/tendermint\/go-wire\"\n\ttmsp \"github.com\/tendermint\/tmsp\/types\"\n)\n\ntype MerkleEyesApp struct {\n\ttree merkle.Tree\n}\n\nfunc NewMerkleEyesApp() *MerkleEyesApp {\n\ttree := merkle.NewIAVLTree(\n\t\t0,\n\t\tnil,\n\t)\n\treturn &MerkleEyesApp{tree: tree}\n}\n\nfunc (app *MerkleEyesApp) Info() string {\n\treturn Fmt(\"size:%v\", app.tree.Size())\n}\n\nfunc (app *MerkleEyesApp) SetOption(key string, value string) (log string) {\n\treturn \"No options are supported yet\"\n}\n\nfunc (app *MerkleEyesApp) AppendTx(tx []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(tx) == 0 {\n\t\treturn tmsp.CodeType_EncodingError, nil, \"Tx length cannot be zero\"\n\t}\n\ttypeByte := tx[0]\n\ttx = tx[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Set\n\t\tkey, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tvalue, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting value: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\tapp.tree.Set(key, value)\n\t\tfmt.Println(\"SET\", Fmt(\"%X\", key), Fmt(\"%X\", value))\n\tcase 0x02: \/\/ Remove\n\t\tkey, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\tapp.tree.Remove(key)\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n\treturn tmsp.CodeType_OK, nil, \"\"\n}\n\nfunc (app *MerkleEyesApp) CheckTx(tx []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(tx) == 0 {\n\t\treturn tmsp.CodeType_EncodingError, nil, \"Tx length cannot be zero\"\n\t}\n\ttypeByte := tx[0]\n\ttx = tx[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Set\n\t\t_, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\t_, n, err = wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting value: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t\/\/app.tree.Set(key, value)\n\tcase 0x02: \/\/ Remove\n\t\t_, n, err := wire.GetByteSlice(tx)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\ttx = tx[n:]\n\t\tif len(tx) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t\/\/app.tree.Remove(key)\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n\treturn tmsp.CodeType_OK, nil, \"\"\n}\n\nfunc (app *MerkleEyesApp) GetHash() (hash []byte, log string) {\n\tif app.tree.Size() == 0 {\n\t\treturn nil, \"Empty hash for empty tree\"\n\t}\n\thash = app.tree.Hash()\n\treturn hash, \"\"\n}\n\nfunc (app *MerkleEyesApp) Query(query []byte) (code tmsp.CodeType, result []byte, log string) {\n\tif len(query) == 0 {\n\t\treturn tmsp.CodeType_OK, nil, \"Query length cannot be zero\"\n\t}\n\ttypeByte := query[0]\n\tquery = query[1:]\n\tswitch typeByte {\n\tcase 0x01: \/\/ Get\n\t\tkey, n, err := wire.GetByteSlice(query)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error getting key: %v\", err.Error())\n\t\t}\n\t\tquery = query[n:]\n\t\tif len(query) != 0 {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Got bytes left over\")\n\t\t}\n\t\t_, value, _ := app.tree.Get(key)\n\t\tres := make([]byte, wire.ByteSliceSize(value))\n\t\tbuf := res\n\t\tn, err = wire.PutByteSlice(buf, value)\n\t\tif err != nil {\n\t\t\treturn tmsp.CodeType_EncodingError, nil, Fmt(\"Error putting value: %v\", err.Error())\n\t\t}\n\t\tbuf = buf[n:]\n\t\treturn tmsp.CodeType_OK, res, \"\"\n\tdefault:\n\t\treturn tmsp.CodeType_UnknownRequest, nil, Fmt(\"Unexpected type byte %X\", typeByte)\n\t}\n}\n<|endoftext|>"} {"text":"package pt\n\ntype Material struct {\n\tColor Color\n\tTexture Texture\n\tEmittance float64\n\tAttenuation Attenuation\n\tIndex float64 \/\/ refractive index\n\tGloss float64 \/\/ reflection cone angle in radians\n\tTint float64 \/\/ specular tinting\n\tTransparent bool\n}\n\nfunc DiffuseMaterial(color Color) Material {\n\treturn Material{color, nil, 0, NoAttenuation, 1, 0, 0, false}\n}\n\nfunc SpecularMaterial(color Color, index float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, 0, 0, false}\n}\n\nfunc GlossyMaterial(color Color, index, gloss float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, gloss, 0, false}\n}\n\nfunc TransparentMaterial(color Color, index, gloss, tint float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, gloss, tint, true}\n}\n\nfunc LightMaterial(color Color, emittance float64, attenuation Attenuation) Material {\n\treturn Material{color, nil, emittance, attenuation, 1, 0, 0, false}\n}\nClearMaterialpackage pt\n\ntype Material struct {\n\tColor Color\n\tTexture Texture\n\tEmittance float64\n\tAttenuation Attenuation\n\tIndex float64 \/\/ refractive index\n\tGloss float64 \/\/ reflection cone angle in radians\n\tTint float64 \/\/ specular tinting\n\tTransparent bool\n}\n\nfunc DiffuseMaterial(color Color) Material {\n\treturn Material{color, nil, 0, NoAttenuation, 1, 0, 0, false}\n}\n\nfunc SpecularMaterial(color Color, index float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, 0, 0, false}\n}\n\nfunc GlossyMaterial(color Color, index, gloss float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, gloss, 0, false}\n}\n\nfunc ClearMaterial(index, gloss float64) Material {\n\treturn Material{Color{}, nil, 0, NoAttenuation, index, gloss, 0, true}\n}\n\nfunc TransparentMaterial(color Color, index, gloss, tint float64) Material {\n\treturn Material{color, nil, 0, NoAttenuation, index, gloss, tint, true}\n}\n\nfunc LightMaterial(color Color, emittance float64, attenuation Attenuation) Material {\n\treturn Material{color, nil, emittance, attenuation, 1, 0, 0, false}\n}\n<|endoftext|>"} {"text":"package errs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrMissingObjectID = errors.New(\"objectID is missing or empty\")\n\tErrMissingKeyID = errors.New(\"key ID is not set in Key.Value\")\n\tErrNoMoreHostToTry = errors.New(\"all hosts have been contacted unsuccessfully, it can either be a network error or wrong appID\/key credentials were used\")\n\tErrIndexAlreadyExists = errors.New(\"destination index already exists, please delete it first as the CopyIndex cannot hold the responsibility of modifying the destination index\")\n\tErrSameAppID = errors.New(\"indices cannot target the same application ID, please use Client.CopyIndex for same-app index copy instead\")\n\tErrObjectNotFound = errors.New(\"object not found in with search responses' hits list\")\n\tErrEmptySecuredAPIKey = errors.New(\"secured API key cannot be empty\")\n\tErrInvalidSecuredAPIKey = errors.New(\"invalid secured API key, please check that the given key is a secured one\")\n\tErrValidUntilNotFound = errors.New(\"no validUntil parameter found, please make sure the secured API key has one\")\n)\n\nfunc ErrJSONDecode(data []byte, t string) error {\n\treturn fmt.Errorf(\"cannot decode value %s to type %s\", string(data), t)\n}\nrefactor(errors): improve error message for `errs.ErrValidUntilNotFound`package errs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrMissingObjectID = errors.New(\"objectID is missing or empty\")\n\tErrMissingKeyID = errors.New(\"key ID is not set in Key.Value\")\n\tErrNoMoreHostToTry = errors.New(\"all hosts have been contacted unsuccessfully, it can either be a network error or wrong appID\/key credentials were used\")\n\tErrIndexAlreadyExists = errors.New(\"destination index already exists, please delete it first as the CopyIndex cannot hold the responsibility of modifying the destination index\")\n\tErrSameAppID = errors.New(\"indices cannot target the same application ID, please use Client.CopyIndex for same-app index copy instead\")\n\tErrObjectNotFound = errors.New(\"object not found in with search responses' hits list\")\n\tErrEmptySecuredAPIKey = errors.New(\"secured API key cannot be empty\")\n\tErrInvalidSecuredAPIKey = errors.New(\"invalid secured API key, please check that the given key is a secured one\")\n\tErrValidUntilNotFound = errors.New(\"no valid `validUntil` parameter found, please make sure the secured API key has been generated correctly\")\n)\n\nfunc ErrJSONDecode(data []byte, t string) error {\n\treturn fmt.Errorf(\"cannot decode value %s to type %s\", string(data), t)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"femebe\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ Automatically chooses between unix sockets and tcp sockets for\n\/\/ listening\nfunc autoListen(place string) (net.Listener, error) {\n\tif strings.Contains(place, \"\/\") {\n\t\treturn net.Listen(\"unix\", place)\n\t}\n\n\treturn net.Listen(\"tcp\", place)\n}\n\n\/\/ Automatically chooses between unix sockets and tcp sockets for\n\/\/ dialing.\nfunc autoDial(place string) (net.Conn, error) {\n\tif strings.Contains(place, \"\/\") {\n\t\treturn net.Dial(\"unix\", place)\n\t}\n\n\treturn net.Dial(\"tcp\", place)\n}\n\ntype handlerFunc func(\n\tclient femebe.MessageStream,\n\tserver femebe.MessageStream,\n\terrch chan error)\n\ntype proxyBehavior struct {\n\ttoFrontend handlerFunc\n\ttoServer handlerFunc\n}\n\nfunc (pbh *proxyBehavior) start(\n\tclient femebe.MessageStream,\n\tserver femebe.MessageStream) (errch chan error) {\n\n\terrch = make(chan error)\n\n\tgo pbh.toFrontend(client, server, errch)\n\tgo pbh.toServer(client, server, errch)\n\treturn errch\n}\n\nvar simpleProxy = proxyBehavior{\n\ttoFrontend: func(client femebe.MessageStream,\n\t\tserver femebe.MessageStream, errch chan error) {\n\t\tfor {\n\t\t\tmsg, err := server.Next()\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = client.Send(msg)\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t},\n\ttoServer: func(client femebe.MessageStream,\n\t\tserver femebe.MessageStream, errch chan error) {\n\t\tfor {\n\t\t\tmsg, err := client.Next()\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = server.Send(msg)\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t},\n}\n\n\/\/ Generic connection handler\n\/\/\n\/\/ This redelegates to more specific proxy handlers that contain the\n\/\/ main proxy loop logic.\nfunc handleConnection(proxy proxyBehavior,\n\tclientConn net.Conn, serverAddr string) {\n\tvar err error\n\n\t\/\/ Log disconnections\n\tdefer func() {\n\t\tif err != nil && err != io.EOF {\n\t\t\tfmt.Printf(\"Session exits with error: %v\\n\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"Session exits cleanly\\n\")\n\t\t}\n\t}()\n\n\tdefer clientConn.Close()\n\n\tc := femebe.NewMessageStream(\"Client\", clientConn, clientConn)\n\n\tserverConn, err := autoDial(serverAddr)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not connect to server: %v\\n\", err)\n\t}\n\n\tb := femebe.NewMessageStream(\"Server\", serverConn, serverConn)\n\n\tdone := proxy.start(c, b)\n\terr = <-done\n}\n\n\/\/ Startup and main client acceptance loop\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tfmt.Printf(\"Usage: simpleproxy LISTENADDR SERVERADDR\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tln, err := autoListen(os.Args[1])\n\tif err != nil {\n\t\tfmt.Printf(\"Could not listen on address: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo handleConnection(simpleProxy, conn, os.Args[2])\n\t}\n\n\tfmt.Println(\"simpleproxy quits successfully\")\n\treturn\n}\nRemove proxyBehavior, in favor of \"session\" constructpackage main\n\nimport (\n\t\"femebe\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ Automatically chooses between unix sockets and tcp sockets for\n\/\/ listening\nfunc autoListen(place string) (net.Listener, error) {\n\tif strings.Contains(place, \"\/\") {\n\t\treturn net.Listen(\"unix\", place)\n\t}\n\n\treturn net.Listen(\"tcp\", place)\n}\n\n\/\/ Automatically chooses between unix sockets and tcp sockets for\n\/\/ dialing.\nfunc autoDial(place string) (net.Conn, error) {\n\tif strings.Contains(place, \"\/\") {\n\t\treturn net.Dial(\"unix\", place)\n\t}\n\n\treturn net.Dial(\"tcp\", place)\n}\n\ntype session struct {\n\tingress func()\n\tegress func()\n}\n\nfunc (s *session) start() {\n\tgo s.ingress()\n\tgo s.egress()\n}\n\nfunc NewSimpleProxySession(\n\terrch chan error,\n\tclient femebe.MessageStream,\n\tserver femebe.MessageStream) *session {\n\n\tingress := func() {\n\t\tfor {\n\t\t\tmsg, err := client.Next()\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = server.Send(msg)\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tegress := func() {\n\t\tfor {\n\t\t\tmsg, err := server.Next()\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = client.Send(msg)\n\t\t\tif err != nil {\n\t\t\t\terrch <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &session{ingress: ingress, egress: egress}\n}\n\n\/\/ Generic connection handler\n\/\/\n\/\/ This redelegates to more specific proxy handlers that contain the\n\/\/ main proxy loop logic.\nfunc handleConnection(clientConn net.Conn, serverAddr string) {\n\tvar err error\n\n\t\/\/ Log disconnections\n\tdefer func() {\n\t\tif err != nil && err != io.EOF {\n\t\t\tfmt.Printf(\"Session exits with error: %v\\n\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"Session exits cleanly\\n\")\n\t\t}\n\t}()\n\n\tdefer clientConn.Close()\n\n\tc := femebe.NewMessageStream(\"Client\", clientConn, clientConn)\n\n\tserverConn, err := autoDial(serverAddr)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not connect to server: %v\\n\", err)\n\t}\n\n\ts := femebe.NewMessageStream(\"Server\", serverConn, serverConn)\n\n\tdone := make(chan error)\n\tNewSimpleProxySession(done, c, s).start()\n\terr = <-done\n}\n\n\/\/ Startup and main client acceptance loop\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tfmt.Printf(\"Usage: simpleproxy LISTENADDR SERVERADDR\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tln, err := autoListen(os.Args[1])\n\tif err != nil {\n\t\tfmt.Printf(\"Could not listen on address: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo handleConnection(conn, os.Args[2])\n\t}\n\n\tfmt.Println(\"simpleproxy quits successfully\")\n\treturn\n}\n<|endoftext|>"} {"text":"package opencl\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/png\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/achilleasa\/go-pathtrace\/tracer\"\n)\n\n\/\/ Debug flags.\ntype DebugFlag uint16\n\nconst (\n\tOff DebugFlag = 0\n\tPrimaryRayIntersectionDepth = 1 << iota\n\tPrimaryRayIntersectionNormals\n\tAllEmissiveSamples\n\tVisibleEmissiveSamples\n\tOccludedEmissiveSamples\n\tThroughput\n\tAccumulator\n\tFrameBuffer\n)\n\n\/\/ An alias for functions that can be used as part of the rendering pipeline.\ntype PipelineStage func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error)\n\n\/\/ The list of pluggable of stages that are used to render the scene.\ntype Pipeline struct {\n\t\/\/ Reset the tracer state. This stage is executed whenever the camera\n\t\/\/ is moved or the sample counter is reset.\n\tReset PipelineStage\n\n\t\/\/ This stage is executed whenever the tracer generates a new set\n\t\/\/ of primary rays. Depending on the samples per pixel this stage\n\t\/\/ may be invoked more than once.\n\tPrimaryRayGenerator PipelineStage\n\n\t\/\/ This stage implements an integrator function to trace the primary\n\t\/\/ rays and add their contribution into the accumulation buffer.\n\tIntegrator PipelineStage\n\n\t\/\/ A set of post-processing stages that are executed prior to\n\t\/\/ rendering the final frame.\n\tPostProcess []PipelineStage\n}\n\nfunc DefaultPipeline(debugFlags DebugFlag, numBounces uint32, exposure float32) *Pipeline {\n\tpipeline := &Pipeline{\n\t\tReset: ClearAccumulator(),\n\t\tPrimaryRayGenerator: PerspectiveCamera(),\n\t\tIntegrator: MonteCarloIntegrator(debugFlags, numBounces),\n\t\tPostProcess: []PipelineStage{\n\t\t\tTonemapSimpleReinhard(exposure),\n\t\t},\n\t}\n\n\tif debugFlags&FrameBuffer == FrameBuffer {\n\t\tpipeline.PostProcess = append(pipeline.PostProcess, DebugFrameBuffer(\"debug-fb.png\"))\n\t}\n\n\treturn pipeline\n}\n\n\/\/ Clear the accumulator buffer.\nfunc ClearAccumulator() PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.ClearAccumulator(blockReq)\n\t}\n}\n\n\/\/ Use a perspective camera for the primary ray generation stage.\nfunc PerspectiveCamera() PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.GeneratePrimaryRays(blockReq, tr.cameraPosition, tr.cameraFrustrum)\n\t}\n}\n\n\/\/ Apply simple Reinhard tone-mapping.\nfunc TonemapSimpleReinhard(exposure float32) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.TonemapSimpleReinhard(blockReq, exposure)\n\t}\n}\n\n\/\/ Use a montecarlo pathtracer implementation.\nfunc MonteCarloIntegrator(debugFlags DebugFlag, numBounces uint32) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\tvar err error\n\n\t\tstart := time.Now()\n\t\tnumPixels := int(blockReq.FrameW * blockReq.BlockH)\n\t\tnumEmissives := uint32(len(tr.sceneData.EmissivePrimitives))\n\n\t\tvar activeRayBuf uint32 = 0\n\n\t\t\/\/ Intersect primary rays outside of the loop\n\t\t\/\/ TODO: Use packet query\n\t\t_, err = tr.resources.RayIntersectionQuery(activeRayBuf, numPixels)\n\t\tif err != nil {\n\t\t\treturn time.Since(start), err\n\t\t}\n\n\t\tif debugFlags&PrimaryRayIntersectionDepth == PrimaryRayIntersectionDepth {\n\t\t\t_, err = tr.resources.DebugPrimaryRayIntersectionDepth(blockReq)\n\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, \"debug-primary-intersection-depth.png\")\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\t\t}\n\n\t\tif debugFlags&PrimaryRayIntersectionNormals == PrimaryRayIntersectionNormals {\n\t\t\t_, err = tr.resources.DebugPrimaryRayIntersectionNormals(blockReq)\n\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, \"debug-primary-intersection-normals.png\")\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\t\t}\n\n\t\tvar bounce uint32\n\t\tfor bounce = 0; bounce < numBounces; bounce++ {\n\t\t\t\/\/ Shade misses\n\t\t\tif tr.sceneData.SceneDiffuseMatIndex != -1 {\n\t\t\t\tif bounce == 0 {\n\t\t\t\t\t_, err = tr.resources.ShadePrimaryRayMisses(uint32(tr.sceneData.SceneDiffuseMatIndex), activeRayBuf, numPixels)\n\t\t\t\t} else {\n\t\t\t\t\t_, err = tr.resources.ShadeIndirectRayMisses(uint32(tr.sceneData.SceneDiffuseMatIndex), activeRayBuf, numPixels)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Shade hits\n\t\t\t_, err = tr.resources.ShadeHits(bounce, rand.Uint32(), numEmissives, activeRayBuf, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\tif debugFlags&Throughput == Throughput {\n\t\t\t\t_, err = tr.resources.DebugThroughput(blockReq)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-throughput-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Process intersections for occlusion rays and accumulate emissive samples for non occluded paths\n\t\t\t_, err := tr.resources.RayIntersectionTest(2, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\t_, err = tr.resources.AccumulateEmissiveSamples(2, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\tif debugFlags&AllEmissiveSamples == AllEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 0, 0)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-all-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&VisibleEmissiveSamples == VisibleEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 1, 0)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-vis-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&OccludedEmissiveSamples == OccludedEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 0, 1)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-occ-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&Accumulator == Accumulator {\n\t\t\t\t_, err = tr.resources.DebugAccumulator(blockReq)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-accumulator-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Process intersections for indirect rays\n\t\t\tif bounce+1 < numBounces {\n\t\t\t\tactiveRayBuf = 1 - activeRayBuf\n\t\t\t\t_, err = tr.resources.RayIntersectionQuery(activeRayBuf, numPixels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn time.Since(start), nil\n\t}\n}\n\n\/\/ Dump a copy of the RGBA framebuffer.\nfunc DebugFrameBuffer(imgFile string) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\tstart := time.Now()\n\n\t\tf, err := os.Create(imgFile)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\tim := image.NewRGBA(image.Rect(0, 0, int(blockReq.FrameW), int(blockReq.FrameH)))\n\t\terr = tr.resources.buffers.FrameBuffer.ReadData(0, 0, tr.resources.buffers.FrameBuffer.Size(), im.Pix)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\treturn time.Since(start), png.Encode(f, im)\n\t}\n}\n\n\/\/ Dump debug buffer to png file.\nfunc dumpDebugBuffer(debugKernelError error, dr *deviceResources, frameW, frameH uint32, imgFile string) error {\n\tif debugKernelError != nil {\n\t\treturn debugKernelError\n\t}\n\tf, err := os.Create(imgFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tim := image.NewRGBA(image.Rect(0, 0, int(frameW), int(frameH)))\n\terr = dr.buffers.DebugOutput.ReadData(0, 0, dr.buffers.DebugOutput.Size(), im.Pix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn png.Encode(f, im)\n}\n\nfunc readCounter(dr *deviceResources, counterIndex uint32) uint32 {\n\tout := make([]uint32, 1)\n\tdr.buffers.RayCounters[counterIndex].ReadData(0, 0, 4, out)\n\treturn out[0]\n}\nUse packet intersector for primary rays on GPUspackage opencl\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/png\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/achilleasa\/go-pathtrace\/tracer\"\n\t\"github.com\/achilleasa\/go-pathtrace\/tracer\/opencl\/device\"\n)\n\n\/\/ Debug flags.\ntype DebugFlag uint16\n\nconst (\n\tOff DebugFlag = 0\n\tPrimaryRayIntersectionDepth = 1 << iota\n\tPrimaryRayIntersectionNormals\n\tAllEmissiveSamples\n\tVisibleEmissiveSamples\n\tOccludedEmissiveSamples\n\tThroughput\n\tAccumulator\n\tFrameBuffer\n)\n\n\/\/ An alias for functions that can be used as part of the rendering pipeline.\ntype PipelineStage func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error)\n\n\/\/ The list of pluggable of stages that are used to render the scene.\ntype Pipeline struct {\n\t\/\/ Reset the tracer state. This stage is executed whenever the camera\n\t\/\/ is moved or the sample counter is reset.\n\tReset PipelineStage\n\n\t\/\/ This stage is executed whenever the tracer generates a new set\n\t\/\/ of primary rays. Depending on the samples per pixel this stage\n\t\/\/ may be invoked more than once.\n\tPrimaryRayGenerator PipelineStage\n\n\t\/\/ This stage implements an integrator function to trace the primary\n\t\/\/ rays and add their contribution into the accumulation buffer.\n\tIntegrator PipelineStage\n\n\t\/\/ A set of post-processing stages that are executed prior to\n\t\/\/ rendering the final frame.\n\tPostProcess []PipelineStage\n}\n\nfunc DefaultPipeline(debugFlags DebugFlag, numBounces uint32, exposure float32) *Pipeline {\n\tpipeline := &Pipeline{\n\t\tReset: ClearAccumulator(),\n\t\tPrimaryRayGenerator: PerspectiveCamera(),\n\t\tIntegrator: MonteCarloIntegrator(debugFlags, numBounces),\n\t\tPostProcess: []PipelineStage{\n\t\t\tTonemapSimpleReinhard(exposure),\n\t\t},\n\t}\n\n\tif debugFlags&FrameBuffer == FrameBuffer {\n\t\tpipeline.PostProcess = append(pipeline.PostProcess, DebugFrameBuffer(\"debug-fb.png\"))\n\t}\n\n\treturn pipeline\n}\n\n\/\/ Clear the accumulator buffer.\nfunc ClearAccumulator() PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.ClearAccumulator(blockReq)\n\t}\n}\n\n\/\/ Use a perspective camera for the primary ray generation stage.\nfunc PerspectiveCamera() PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.GeneratePrimaryRays(blockReq, tr.cameraPosition, tr.cameraFrustrum)\n\t}\n}\n\n\/\/ Apply simple Reinhard tone-mapping.\nfunc TonemapSimpleReinhard(exposure float32) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\treturn tr.resources.TonemapSimpleReinhard(blockReq, exposure)\n\t}\n}\n\n\/\/ Use a montecarlo pathtracer implementation.\nfunc MonteCarloIntegrator(debugFlags DebugFlag, numBounces uint32) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\tvar err error\n\n\t\tstart := time.Now()\n\t\tnumPixels := int(blockReq.FrameW * blockReq.BlockH)\n\t\tnumEmissives := uint32(len(tr.sceneData.EmissivePrimitives))\n\n\t\tvar activeRayBuf uint32 = 0\n\n\t\t\/\/ Intersect primary rays outside of the loop\n\t\t\/\/ Use packet query intersector for GPUs as opencl forces CPU\n\t\t\/\/ to use a local workgroup size equal to 1\n\t\tif tr.device.Type == device.GpuDevice {\n\t\t\t_, err = tr.resources.RayPacketIntersectionQuery(activeRayBuf, numPixels)\n\t\t} else {\n\t\t\t_, err = tr.resources.RayIntersectionQuery(activeRayBuf, numPixels)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn time.Since(start), err\n\t\t}\n\n\t\tif debugFlags&PrimaryRayIntersectionDepth == PrimaryRayIntersectionDepth {\n\t\t\t_, err = tr.resources.DebugPrimaryRayIntersectionDepth(blockReq)\n\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, \"debug-primary-intersection-depth.png\")\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\t\t}\n\t\tif debugFlags&PrimaryRayIntersectionNormals == PrimaryRayIntersectionNormals {\n\t\t\t_, err = tr.resources.DebugPrimaryRayIntersectionNormals(blockReq)\n\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, \"debug-primary-intersection-normals.png\")\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\t\t}\n\n\t\tvar bounce uint32\n\t\tfor bounce = 0; bounce < numBounces; bounce++ {\n\t\t\t\/\/ Shade misses\n\t\t\tif tr.sceneData.SceneDiffuseMatIndex != -1 {\n\t\t\t\tif bounce == 0 {\n\t\t\t\t\t_, err = tr.resources.ShadePrimaryRayMisses(uint32(tr.sceneData.SceneDiffuseMatIndex), activeRayBuf, numPixels)\n\t\t\t\t} else {\n\t\t\t\t\t_, err = tr.resources.ShadeIndirectRayMisses(uint32(tr.sceneData.SceneDiffuseMatIndex), activeRayBuf, numPixels)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Shade hits\n\t\t\t_, err = tr.resources.ShadeHits(bounce, rand.Uint32(), numEmissives, activeRayBuf, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\tif debugFlags&Throughput == Throughput {\n\t\t\t\t_, err = tr.resources.DebugThroughput(blockReq)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-throughput-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Process intersections for occlusion rays and accumulate emissive samples for non occluded paths\n\t\t\t_, err := tr.resources.RayIntersectionTest(2, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\t_, err = tr.resources.AccumulateEmissiveSamples(2, numPixels)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Since(start), err\n\t\t\t}\n\n\t\t\tif debugFlags&AllEmissiveSamples == AllEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 0, 0)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-all-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&VisibleEmissiveSamples == VisibleEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 1, 0)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-vis-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&OccludedEmissiveSamples == OccludedEmissiveSamples {\n\t\t\t\t_, err = tr.resources.DebugEmissiveSamples(blockReq, 0, 1)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-emissive-occ-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif debugFlags&Accumulator == Accumulator {\n\t\t\t\t_, err = tr.resources.DebugAccumulator(blockReq)\n\t\t\t\terr = dumpDebugBuffer(err, tr.resources, blockReq.FrameW, blockReq.FrameH, fmt.Sprintf(\"debug-accumulator-%03d.png\", bounce))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Process intersections for indirect rays\n\t\t\tif bounce+1 < numBounces {\n\t\t\t\tactiveRayBuf = 1 - activeRayBuf\n\t\t\t\t_, err = tr.resources.RayIntersectionQuery(activeRayBuf, numPixels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn time.Since(start), err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn time.Since(start), nil\n\t}\n}\n\n\/\/ Dump a copy of the RGBA framebuffer.\nfunc DebugFrameBuffer(imgFile string) PipelineStage {\n\treturn func(tr *Tracer, blockReq *tracer.BlockRequest) (time.Duration, error) {\n\t\tstart := time.Now()\n\n\t\tf, err := os.Create(imgFile)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\tim := image.NewRGBA(image.Rect(0, 0, int(blockReq.FrameW), int(blockReq.FrameH)))\n\t\terr = tr.resources.buffers.FrameBuffer.ReadData(0, 0, tr.resources.buffers.FrameBuffer.Size(), im.Pix)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\treturn time.Since(start), png.Encode(f, im)\n\t}\n}\n\n\/\/ Dump debug buffer to png file.\nfunc dumpDebugBuffer(debugKernelError error, dr *deviceResources, frameW, frameH uint32, imgFile string) error {\n\tif debugKernelError != nil {\n\t\treturn debugKernelError\n\t}\n\tf, err := os.Create(imgFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tim := image.NewRGBA(image.Rect(0, 0, int(frameW), int(frameH)))\n\terr = dr.buffers.DebugOutput.ReadData(0, 0, dr.buffers.DebugOutput.Size(), im.Pix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn png.Encode(f, im)\n}\n\nfunc readCounter(dr *deviceResources, counterIndex uint32) uint32 {\n\tout := make([]uint32, 1)\n\tdr.buffers.RayCounters[counterIndex].ReadData(0, 0, 4, out)\n\treturn out[0]\n}\n<|endoftext|>"} {"text":"package subcmd\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\tTEST_DIR = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/ieee0824\/thor\/test\"\n)\n\nfunc TestReadExternalVariablesFromFile(t *testing.T) {\n\tvar EXTERNSL_DIR = TEST_DIR + \"\/readExternalVariablesFromFiles\"\n\tresult, err := readExternalVariablesFromFile(EXTERNSL_DIR)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if len(result) != 2 {\n\t\tt.Errorf(\"The number of elements is invalid. Originally it should be %v, but it is actually %v.\", 2, len(result))\n\t}\n}\n\nfunc TestReadExternalVariables(t *testing.T) {\n\tvar EXTERNSL_DIRS = []string{\n\t\t\"readExternalVariablesFiles\/dir1\",\n\t\t\"readExternalVariablesFiles\/dir2\",\n\t\t\"readExternalVariablesFiles\/dir3\",\n\t}\n\n\tresult, err := readExternalVariables(EXTERNSL_DIRS...)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if len(result) != 2 {\n\t\tt.Errorf(\"The number of elements is invalid. Originally it should be %v, but it is actually %v.\", 2, len(result))\n\t}\n}\ntest用にディレクトリを作るpackage subcmd\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nvar (\n\tTEST_DIR = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/ieee0824\/thor\/test\"\n)\n\nfunc TestReadExternalVariablesFromFile(t *testing.T) {\n\tvar EXTERNSL_DIR = TEST_DIR + \"\/readExternalVariablesFromFiles\"\n\tresult, err := readExternalVariablesFromFile(EXTERNSL_DIR)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if len(result) != 2 {\n\t\tt.Errorf(\"The number of elements is invalid. Originally it should be %v, but it is actually %v.\", 2, len(result))\n\t}\n}\n\nfunc TestReadExternalVariables(t *testing.T) {\n\tvar EXTERNSL_DIRS = []string{\n\t\tTEST_DIR + \"readExternalVariablesFiles\/dir1\",\n\t\tTEST_DIR + \"readExternalVariablesFiles\/dir2\",\n\t\tTEST_DIR + \"readExternalVariablesFiles\/dir3\",\n\t}\n\n\t\/\/ test用にディレクトリを作る\n\tif err := os.Mkdir(TEST_DIR+\"readExternalVariablesFiles\/dir3\", 0777); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresult, err := readExternalVariables(EXTERNSL_DIRS...)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if len(result) != 2 {\n\t\tt.Errorf(\"The number of elements is invalid. Originally it should be %v, but it is actually %v.\", 2, len(result))\n\t}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage entrypoint\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\t\/\/ InternalErrorCode is what we write to the marker file to\n\t\/\/ indicate that we failed to start the wrapped command\n\tInternalErrorCode = 127\n\t\/\/ AbortedErrorCode is what we write to the marker file to\n\t\/\/ indicate that we were terminated via a signal.\n\tAbortedErrorCode = 130\n\n\t\/\/ DefaultTimeout is the default timeout for the test\n\t\/\/ process before SIGINT is sent\n\tDefaultTimeout = 120 * time.Minute\n\n\t\/\/ DefaultGracePeriod is the default timeout for the test\n\t\/\/ process after SIGINT is sent before SIGKILL is sent\n\tDefaultGracePeriod = 15 * time.Second\n)\n\nvar (\n\t\/\/ errTimedOut is used as the command's error when the command\n\t\/\/ is terminated after the timeout is reached\n\terrTimedOut = errors.New(\"process timed out\")\n\t\/\/ errAborted is used as the command's error when the command\n\t\/\/ is shut down by an external signal\n\terrAborted = errors.New(\"process aborted\")\n)\n\n\/\/ Run executes the test process then writes the exit code to the marker file.\n\/\/ This function returns the status code that should be passed to os.Exit().\nfunc (o Options) Run() int {\n\tcode, err := o.ExecuteProcess()\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Error executing test process: %v.\", err)\n\t}\n\tif err := o.mark(code); err != nil {\n\t\tlogrus.WithError(err).Error(\"Error writing exit code to marker file: %v.\", err)\n\t\treturn InternalErrorCode\n\t}\n\treturn code\n}\n\n\/\/ ExecuteProcess creates the artifact directory then executes the process as\n\/\/ configured, writing the output to the process log.\nfunc (o Options) ExecuteProcess() (int, error) {\n\tif o.ArtifactDir != \"\" {\n\t\tif err := os.MkdirAll(o.ArtifactDir, os.ModePerm); err != nil {\n\t\t\treturn InternalErrorCode, fmt.Errorf(\"could not create artifact directory(%s): %v\", o.ArtifactDir, err)\n\t\t}\n\t}\n\tprocessLogFile, err := os.Create(o.ProcessLog)\n\tif err != nil {\n\t\treturn InternalErrorCode, fmt.Errorf(\"could not create process logfile(%s): %v\", o.ProcessLog, err)\n\t}\n\tdefer processLogFile.Close()\n\n\toutput := io.MultiWriter(os.Stdout, processLogFile)\n\tlogrus.SetOutput(output)\n\tdefer logrus.SetOutput(os.Stdout)\n\n\texecutable := o.Args[0]\n\tvar arguments []string\n\tif len(o.Args) > 1 {\n\t\targuments = o.Args[1:]\n\t}\n\tcommand := exec.Command(executable, arguments...)\n\tcommand.Stderr = output\n\tcommand.Stdout = output\n\tif err := command.Start(); err != nil {\n\t\treturn InternalErrorCode, fmt.Errorf(\"could not start the process: %v\", err)\n\t}\n\n\t\/\/ if we get asked to terminate we need to forward\n\t\/\/ that to the wrapped process as if it timed out\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)\n\n\ttimeout := optionOrDefault(o.Timeout, DefaultTimeout)\n\tgracePeriod := optionOrDefault(o.GracePeriod, DefaultGracePeriod)\n\tvar commandErr error\n\tcancelled, aborted := false, false\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- command.Wait()\n\t}()\n\tselect {\n\tcase err := <-done:\n\t\tcommandErr = err\n\tcase <-time.After(timeout):\n\t\tlogrus.Errorf(\"Process did not finish before %s timeout\", timeout)\n\t\tcancelled = true\n\t\tgracefullyTerminate(command, done, gracePeriod)\n\tcase s := <-interrupt:\n\t\tlogrus.Errorf(\"Entrypoint received interrupt: %v\", s)\n\t\tcancelled = true\n\t\taborted = true\n\t\tgracefullyTerminate(command, done, gracePeriod)\n\t}\n\n\tvar returnCode int\n\tif cancelled {\n\t\tif aborted {\n\t\t\tcommandErr = errAborted\n\t\t\treturnCode = AbortedErrorCode\n\t\t} else {\n\t\t\tcommandErr = errTimedOut\n\t\t\treturnCode = InternalErrorCode\n\t\t}\n\t} else {\n\t\tif status, ok := command.ProcessState.Sys().(syscall.WaitStatus); ok {\n\t\t\treturnCode = status.ExitStatus()\n\t\t} else if commandErr == nil {\n\t\t\treturnCode = 0\n\t\t} else {\n\t\t\treturnCode = 1\n\t\t}\n\n\t\tif returnCode != 0 {\n\t\t\tcommandErr = fmt.Errorf(\"wrapped process failed: %v\", commandErr)\n\t\t}\n\t}\n\treturn returnCode, commandErr\n}\n\nfunc (o *Options) mark(exitCode int) error {\n\tcontent := []byte(strconv.Itoa(exitCode))\n\n\t\/\/ create temp file in the same directory as the desired marker file\n\tdir := filepath.Dir(o.MarkerFile)\n\ttempFile, err := ioutil.TempFile(dir, \"temp-marker\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create temp marker file in %s: %v\", dir, err)\n\t}\n\t\/\/ write the exit code to the tempfile, sync to disk and close\n\tif _, err = tempFile.Write(content); err != nil {\n\t\treturn fmt.Errorf(\"could not write to temp marker file (%s): %v\", tempFile.Name(), err)\n\t}\n\tif err = tempFile.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"could not sync temp marker file (%s): %v\", tempFile.Name(), err)\n\t}\n\ttempFile.Close()\n\t\/\/ set desired permission bits, then rename to the desired file name\n\tif err = os.Chmod(tempFile.Name(), os.ModePerm); err != nil {\n\t\treturn fmt.Errorf(\"could not chmod (%x) temp marker file (%s): %v\", os.ModePerm, tempFile.Name(), err)\n\t}\n\tif err := os.Rename(tempFile.Name(), o.MarkerFile); err != nil {\n\t\treturn fmt.Errorf(\"could not move marker file to destination path (%s): %v\", o.MarkerFile, err)\n\t}\n\treturn nil\n}\n\n\/\/ optionOrDefault defaults to a value if option\n\/\/ is the zero value\nfunc optionOrDefault(option, defaultValue time.Duration) time.Duration {\n\tif option == 0 {\n\t\treturn defaultValue\n\t}\n\n\treturn option\n}\n\nfunc gracefullyTerminate(command *exec.Cmd, done <-chan error, gracePeriod time.Duration) {\n\tif err := command.Process.Signal(os.Interrupt); err != nil {\n\t\tlogrus.WithError(err).Error(\"Could not interrupt process after timeout\")\n\t}\n\tselect {\n\tcase <-done:\n\t\tlogrus.Errorf(\"Process gracefully exited before %s grace period\", gracePeriod)\n\t\t\/\/ but we ignore the output error as we will want errTimedOut\n\tcase <-time.After(gracePeriod):\n\t\tlogrus.Errorf(\"Process did not exit before %s grace period\", gracePeriod)\n\t\tif err := command.Process.Kill(); err != nil {\n\t\t\tlogrus.WithError(err).Error(\"Could not kill process after grace period\")\n\t\t}\n\t}\n}\nFormat errors in entrypoint correctly\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage entrypoint\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\t\/\/ InternalErrorCode is what we write to the marker file to\n\t\/\/ indicate that we failed to start the wrapped command\n\tInternalErrorCode = 127\n\t\/\/ AbortedErrorCode is what we write to the marker file to\n\t\/\/ indicate that we were terminated via a signal.\n\tAbortedErrorCode = 130\n\n\t\/\/ DefaultTimeout is the default timeout for the test\n\t\/\/ process before SIGINT is sent\n\tDefaultTimeout = 120 * time.Minute\n\n\t\/\/ DefaultGracePeriod is the default timeout for the test\n\t\/\/ process after SIGINT is sent before SIGKILL is sent\n\tDefaultGracePeriod = 15 * time.Second\n)\n\nvar (\n\t\/\/ errTimedOut is used as the command's error when the command\n\t\/\/ is terminated after the timeout is reached\n\terrTimedOut = errors.New(\"process timed out\")\n\t\/\/ errAborted is used as the command's error when the command\n\t\/\/ is shut down by an external signal\n\terrAborted = errors.New(\"process aborted\")\n)\n\n\/\/ Run executes the test process then writes the exit code to the marker file.\n\/\/ This function returns the status code that should be passed to os.Exit().\nfunc (o Options) Run() int {\n\tcode, err := o.ExecuteProcess()\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Error executing test process\")\n\t}\n\tif err := o.mark(code); err != nil {\n\t\tlogrus.WithError(err).Error(\"Error writing exit code to marker file\")\n\t\treturn InternalErrorCode\n\t}\n\treturn code\n}\n\n\/\/ ExecuteProcess creates the artifact directory then executes the process as\n\/\/ configured, writing the output to the process log.\nfunc (o Options) ExecuteProcess() (int, error) {\n\tif o.ArtifactDir != \"\" {\n\t\tif err := os.MkdirAll(o.ArtifactDir, os.ModePerm); err != nil {\n\t\t\treturn InternalErrorCode, fmt.Errorf(\"could not create artifact directory(%s): %v\", o.ArtifactDir, err)\n\t\t}\n\t}\n\tprocessLogFile, err := os.Create(o.ProcessLog)\n\tif err != nil {\n\t\treturn InternalErrorCode, fmt.Errorf(\"could not create process logfile(%s): %v\", o.ProcessLog, err)\n\t}\n\tdefer processLogFile.Close()\n\n\toutput := io.MultiWriter(os.Stdout, processLogFile)\n\tlogrus.SetOutput(output)\n\tdefer logrus.SetOutput(os.Stdout)\n\n\texecutable := o.Args[0]\n\tvar arguments []string\n\tif len(o.Args) > 1 {\n\t\targuments = o.Args[1:]\n\t}\n\tcommand := exec.Command(executable, arguments...)\n\tcommand.Stderr = output\n\tcommand.Stdout = output\n\tif err := command.Start(); err != nil {\n\t\treturn InternalErrorCode, fmt.Errorf(\"could not start the process: %v\", err)\n\t}\n\n\t\/\/ if we get asked to terminate we need to forward\n\t\/\/ that to the wrapped process as if it timed out\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)\n\n\ttimeout := optionOrDefault(o.Timeout, DefaultTimeout)\n\tgracePeriod := optionOrDefault(o.GracePeriod, DefaultGracePeriod)\n\tvar commandErr error\n\tcancelled, aborted := false, false\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- command.Wait()\n\t}()\n\tselect {\n\tcase err := <-done:\n\t\tcommandErr = err\n\tcase <-time.After(timeout):\n\t\tlogrus.Errorf(\"Process did not finish before %s timeout\", timeout)\n\t\tcancelled = true\n\t\tgracefullyTerminate(command, done, gracePeriod)\n\tcase s := <-interrupt:\n\t\tlogrus.Errorf(\"Entrypoint received interrupt: %v\", s)\n\t\tcancelled = true\n\t\taborted = true\n\t\tgracefullyTerminate(command, done, gracePeriod)\n\t}\n\n\tvar returnCode int\n\tif cancelled {\n\t\tif aborted {\n\t\t\tcommandErr = errAborted\n\t\t\treturnCode = AbortedErrorCode\n\t\t} else {\n\t\t\tcommandErr = errTimedOut\n\t\t\treturnCode = InternalErrorCode\n\t\t}\n\t} else {\n\t\tif status, ok := command.ProcessState.Sys().(syscall.WaitStatus); ok {\n\t\t\treturnCode = status.ExitStatus()\n\t\t} else if commandErr == nil {\n\t\t\treturnCode = 0\n\t\t} else {\n\t\t\treturnCode = 1\n\t\t}\n\n\t\tif returnCode != 0 {\n\t\t\tcommandErr = fmt.Errorf(\"wrapped process failed: %v\", commandErr)\n\t\t}\n\t}\n\treturn returnCode, commandErr\n}\n\nfunc (o *Options) mark(exitCode int) error {\n\tcontent := []byte(strconv.Itoa(exitCode))\n\n\t\/\/ create temp file in the same directory as the desired marker file\n\tdir := filepath.Dir(o.MarkerFile)\n\ttempFile, err := ioutil.TempFile(dir, \"temp-marker\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create temp marker file in %s: %v\", dir, err)\n\t}\n\t\/\/ write the exit code to the tempfile, sync to disk and close\n\tif _, err = tempFile.Write(content); err != nil {\n\t\treturn fmt.Errorf(\"could not write to temp marker file (%s): %v\", tempFile.Name(), err)\n\t}\n\tif err = tempFile.Sync(); err != nil {\n\t\treturn fmt.Errorf(\"could not sync temp marker file (%s): %v\", tempFile.Name(), err)\n\t}\n\ttempFile.Close()\n\t\/\/ set desired permission bits, then rename to the desired file name\n\tif err = os.Chmod(tempFile.Name(), os.ModePerm); err != nil {\n\t\treturn fmt.Errorf(\"could not chmod (%x) temp marker file (%s): %v\", os.ModePerm, tempFile.Name(), err)\n\t}\n\tif err := os.Rename(tempFile.Name(), o.MarkerFile); err != nil {\n\t\treturn fmt.Errorf(\"could not move marker file to destination path (%s): %v\", o.MarkerFile, err)\n\t}\n\treturn nil\n}\n\n\/\/ optionOrDefault defaults to a value if option\n\/\/ is the zero value\nfunc optionOrDefault(option, defaultValue time.Duration) time.Duration {\n\tif option == 0 {\n\t\treturn defaultValue\n\t}\n\n\treturn option\n}\n\nfunc gracefullyTerminate(command *exec.Cmd, done <-chan error, gracePeriod time.Duration) {\n\tif err := command.Process.Signal(os.Interrupt); err != nil {\n\t\tlogrus.WithError(err).Error(\"Could not interrupt process after timeout\")\n\t}\n\tselect {\n\tcase <-done:\n\t\tlogrus.Errorf(\"Process gracefully exited before %s grace period\", gracePeriod)\n\t\t\/\/ but we ignore the output error as we will want errTimedOut\n\tcase <-time.After(gracePeriod):\n\t\tlogrus.Errorf(\"Process did not exit before %s grace period\", gracePeriod)\n\t\tif err := command.Process.Kill(); err != nil {\n\t\t\tlogrus.WithError(err).Error(\"Could not kill process after grace period\")\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package pathutil_test\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/JaSei\/pathutil-go\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\ntype FileSource struct {\n\tPath string `json:\"path\"`\n\tSize int `json:\"size\"`\n}\n\ntype FileInfo struct {\n\tFileId string `json:\"file_id\"`\n\tSources []FileSource `json:\"sources\"`\n}\n\nvar expected = FileInfo{\n\tFileId: \"01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b\",\n\tSources: []FileSource{\n\t\tFileSource{Path: \"c:\\\\tmp\\\\empty_file\", Size: 0},\n\t\tFileSource{Path: \"\/tmp\/empty_file\", Size: 0},\n\t},\n}\n\nfunc TestLoadJsonViaReader(t *testing.T) {\n\tpath, err := pathutil.NewPath(\"example.json\")\n\tassert.Nil(t, err)\n\n\treader, file, err := path.OpenReader()\n\tassert.Nil(t, err)\n\tdefer func() {\n\t\tassert.Nil(t, file.Close())\n\t}()\n\tassert.NotNil(t, reader)\n\n\tdecodedJson := new(FileInfo)\n\n\terr = json.NewDecoder(reader).Decode(decodedJson)\n\tif !assert.Nil(t, err) {\n\t\tt.Log(err)\n\t}\n\n\tassert.Equal(t, &expected, decodedJson)\n}\n\nfunc TestLoadJsonViaSlurp(t *testing.T) {\n\tpath, err := pathutil.NewPath(\"example.json\")\n\tassert.Nil(t, err)\n\n\tjsonBytes, err := path.Slurp()\n\tassert.Nil(t, err)\n\n\tdecodedJson := new(FileInfo)\n\tjson.Unmarshal(jsonBytes, decodedJson)\n\n\tassert.Equal(t, &expected, decodedJson)\n\n}\nfix testpackage pathutil_test\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/JaSei\/pathutil-go\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\ntype FileSource struct {\n\tPath string `json:\"path\"`\n\tSize int `json:\"size\"`\n}\n\ntype FileInfo struct {\n\tFileId string `json:\"file_id\"`\n\tSources []FileSource `json:\"sources\"`\n}\n\nvar expected = FileInfo{\n\tFileId: \"01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b\",\n\tSources: []FileSource{\n\t\tFileSource{Path: \"c:\\\\tmp\\\\empty_file\", Size: 0},\n\t\tFileSource{Path: \"\/tmp\/empty_file\", Size: 0},\n\t},\n}\n\nfunc TestLoadJsonViaReader(t *testing.T) {\n\tpath, err := pathutil.NewPath(\"example.json\")\n\tassert.Nil(t, err)\n\n\treader, file, err := path.OpenReader()\n\tassert.Nil(t, err)\n\tdefer func() {\n\t\tassert.Nil(t, file.Close())\n\t}()\n\tassert.NotNil(t, reader)\n\n\tdecodedJson := new(FileInfo)\n\n\terr = json.NewDecoder(reader).Decode(decodedJson)\n\tif !assert.Nil(t, err) {\n\t\tt.Log(err)\n\t}\n\n\tassert.Equal(t, &expected, decodedJson)\n}\n\nfunc TestLoadJsonViaSlurp(t *testing.T) {\n\tpath, err := pathutil.NewPath(\"example.json\")\n\tassert.Nil(t, err)\n\n\tjsonBytes, err := path.SlurpBytes()\n\tassert.Nil(t, err)\n\n\tdecodedJson := new(FileInfo)\n\tjson.Unmarshal(jsonBytes, decodedJson)\n\n\tassert.Equal(t, &expected, decodedJson)\n\n}\n<|endoftext|>"} {"text":"package api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/models\"\n\t\"socialapi\/workers\/common\/response\"\n\n\t\"github.com\/codahale\/sneaker\"\n)\n\nvar (\n\tErrPathNotFound = errors.New(\"required a path name to store keys\")\n\tErrRequiredValuesNotFound = errors.New(\"required fields not found to store\")\n)\n\n\/\/ KeyValue holds the credentials whatever you want as key-value pair\ntype KeyValue map[string]interface{}\n\ntype Credentials struct {\n\tKeyValues []KeyValue `json:\"keyValue\"`\n}\n\ntype SneakerS3 struct {\n\t*sneaker.Manager\n}\n\n\/\/ Store stores the given credentials on s3\nfunc (s *SneakerS3) Store(u *url.URL, h http.Header, cr *Credentials, context *models.Context) (int, http.Header, interface{}, error) {\n\tpathName := u.Query().Get(\"pathName\")\n\tif pathName == \"\" {\n\t\treturn response.NewBadRequest(ErrPathNotFound)\n\t}\n\n\tif !context.IsLoggedIn() {\n\t\treturn response.NewBadRequest(models.ErrNotLoggedIn)\n\t}\n\n\tif cr.KeyValues == nil {\n\t\treturn response.NewBadRequest(ErrRequiredValuesNotFound)\n\t}\n\n\t\/\/ convert credentials to bytes\n\tbyt, err := json.Marshal(cr)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\t\/\/ bytes need to imlement io.Reader interface\n\t\/\/ then we can use struct as 2.parameter of manager.Upload function\n\taa := bytes.NewReader(byt)\n\n\t\/\/ if another requeest comes to same pathName, its data will be updated.\n\t\/\/ and new incoming data is gonna override the old data\n\terr = s.Manager.Upload(pathName, aa)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(nil)\n}\n\nfunc (s *SneakerS3) Get(u *url.URL, h http.Header, _ interface{}, context *models.Context) (int, http.Header, interface{}, error) {\n\tpathName := u.Query().Get(\"pathName\")\n\tif pathName == \"\" {\n\t\treturn response.NewBadRequest(ErrPathNotFound)\n\t}\n\n\tif !context.IsLoggedIn() {\n\t\treturn response.NewBadRequest(models.ErrNotLoggedIn)\n\t}\n\n\tdownArray := []string{pathName}\n\tdown, err := s.Manager.Download(downArray)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tx := &Credentials{}\n\n\tdownX := bytes.NewReader(down[pathName])\n\tif err := json.NewDecoder(downX).Decode(x); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(x)\n}\ngo: remove array keyvaluepackage api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/models\"\n\t\"socialapi\/workers\/common\/response\"\n\n\t\"github.com\/codahale\/sneaker\"\n)\n\nvar (\n\tErrPathNotFound = errors.New(\"required a path name to store keys\")\n\tErrRequiredValuesNotFound = errors.New(\"required fields not found to store\")\n)\n\n\/\/ KeyValue holds the credentials whatever you want as key-value pair\ntype KeyValue map[string]interface{}\n\ntype Credentials struct {\n\tKeyValue KeyValue `json:\"keyValue\"`\n}\n\ntype SneakerS3 struct {\n\t*sneaker.Manager\n}\n\n\/\/ Store stores the given credentials on s3\nfunc (s *SneakerS3) Store(u *url.URL, h http.Header, cr *Credentials, context *models.Context) (int, http.Header, interface{}, error) {\n\tpathName := u.Query().Get(\"pathName\")\n\tif pathName == \"\" {\n\t\treturn response.NewBadRequest(ErrPathNotFound)\n\t}\n\n\tif !context.IsLoggedIn() {\n\t\treturn response.NewBadRequest(models.ErrNotLoggedIn)\n\t}\n\n\tif cr.KeyValue == nil {\n\t\treturn response.NewBadRequest(ErrRequiredValuesNotFound)\n\t}\n\n\t\/\/ convert credentials to bytes\n\tbyt, err := json.Marshal(cr)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\t\/\/ bytes need to imlement io.Reader interface\n\t\/\/ then we can use struct as 2.parameter of manager.Upload function\n\taa := bytes.NewReader(byt)\n\n\t\/\/ if another requeest comes to same pathName, its data will be updated.\n\t\/\/ and new incoming data is gonna override the old data\n\terr = s.Manager.Upload(pathName, aa)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(nil)\n}\n\nfunc (s *SneakerS3) Get(u *url.URL, h http.Header, _ interface{}, context *models.Context) (int, http.Header, interface{}, error) {\n\tpathName := u.Query().Get(\"pathName\")\n\tif pathName == \"\" {\n\t\treturn response.NewBadRequest(ErrPathNotFound)\n\t}\n\n\tif !context.IsLoggedIn() {\n\t\treturn response.NewBadRequest(models.ErrNotLoggedIn)\n\t}\n\n\tdownArray := []string{pathName}\n\tdown, err := s.Manager.Download(downArray)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tx := &Credentials{}\n\n\tdownX := bytes.NewReader(down[pathName])\n\tif err := json.NewDecoder(downX).Decode(x); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(x)\n}\n<|endoftext|>"} {"text":"package errlist\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\/\/ Errors is a list of errors.\ntype Errors []error\n\n\/\/ New returns a list of errors optionally populated with the given errors.\nfunc New(errors ...error) Errors {\n\treturn Errors(errors)\n}\n\n\/\/ Append adds a non-nil error to the list and returns it.\nfunc (e Errors) Append(err error) Errors {\n\tif err == nil {\n\t\treturn e\n\t}\n\treturn append(e, err)\n}\n\n\/\/ ErrorOrNil returns the error list if it contains at least one error.\n\/\/ Otherwise nil is returned.\nfunc (e Errors) ErrorOrNil() error {\n\tif len(e) == 0 {\n\t\treturn nil\n\t}\n\treturn e\n}\n\n\/\/ Error implements the error interface.\n\/\/ A single error is formatted as usual.\n\/\/ Multiple errors are formatted per line with a summary of the error count.\nfunc (e Errors) Error() string {\n\tif len(e) == 1 {\n\t\treturn e[0].Error()\n\t}\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, \"%d errors occurred:\\n\", len(e))\n\tfor _, err := range e {\n\t\tfmt.Fprintf(buf, \"* %s\\n\", err.Error())\n\t}\n\treturn buf.String()\n}\nAdd Errors.HasErrorpackage errlist\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\/\/ Errors is a list of errors.\ntype Errors []error\n\n\/\/ New returns a list of errors optionally populated with the given errors.\nfunc New(errors ...error) Errors {\n\treturn Errors(errors)\n}\n\n\/\/ Append adds a non-nil error to the list and returns it.\nfunc (e Errors) Append(err error) Errors {\n\tif err == nil {\n\t\treturn e\n\t}\n\treturn append(e, err)\n}\n\n\/\/ ErrorOrNil returns the error list if it contains at least one error.\n\/\/ Otherwise nil is returned.\nfunc (e Errors) ErrorOrNil() error {\n\tif len(e) == 0 {\n\t\treturn nil\n\t}\n\treturn e\n}\n\n\/\/ HasError returns true if the list contains at least one error.\nfunc (e Errors) HasError() bool {\n\treturn len(e) > 0\n}\n\n\/\/ Error implements the error interface.\n\/\/ A single error is formatted as usual.\n\/\/ Multiple errors are formatted per line with a summary of the error count.\nfunc (e Errors) Error() string {\n\tif len(e) == 1 {\n\t\treturn e[0].Error()\n\t}\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, \"%d errors occurred:\\n\", len(e))\n\tfor _, err := range e {\n\t\tfmt.Fprintf(buf, \"* %s\\n\", err.Error())\n\t}\n\treturn buf.String()\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graphics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\/opengl\"\n)\n\nfunc glMatrix(m *[4][4]float64) []float32 {\n\treturn []float32{\n\t\tfloat32(m[0][0]), float32(m[1][0]), float32(m[2][0]), float32(m[3][0]),\n\t\tfloat32(m[0][1]), float32(m[1][1]), float32(m[2][1]), float32(m[3][1]),\n\t\tfloat32(m[0][2]), float32(m[1][2]), float32(m[2][2]), float32(m[3][2]),\n\t\tfloat32(m[0][3]), float32(m[1][3]), float32(m[2][3]), float32(m[3][3]),\n\t}\n}\n\ntype Matrix interface {\n\tElement(i, j int) float64\n}\n\nvar vertices = make([]int16, 16*quadsMaxNum)\n\nvar shadersInitialized = false\n\nfunc drawTexture(c *opengl.Context, texture opengl.Texture, projectionMatrix *[4][4]float64, quads TextureQuads, geo Matrix, color Matrix, mode opengl.CompositeMode) error {\n\tc.BlendFunc(mode)\n\n\t\/\/ NOTE: WebGL doesn't seem to have Check gl.MAX_ELEMENTS_VERTICES or gl.MAX_ELEMENTS_INDICES so far.\n\t\/\/ Let's use them to compare to len(quads) in the future.\n\n\tif !shadersInitialized {\n\t\tif err := initialize(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tshadersInitialized = true\n\t}\n\n\tl := quads.Len()\n\tif l == 0 {\n\t\treturn nil\n\t}\n\tif quadsMaxNum < l {\n\t\treturn errors.New(fmt.Sprintf(\"len(quads) must be equal to or less than %d\", quadsMaxNum))\n\t}\n\n\tp := programContext{\n\t\tprogram: programTexture,\n\t\tcontext: c,\n\t\tprojectionMatrix: glMatrix(projectionMatrix),\n\t\ttexture: texture,\n\t\tgeoM: geo,\n\t\tcolorM: color,\n\t}\n\tp.begin()\n\tdefer p.end()\n\tn := quads.SetVertices(vertices)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tc.BufferSubData(c.ArrayBuffer, vertices[:16*n])\n\tc.DrawElements(c.Triangles, 6*n)\n\treturn nil\n}\ngraphics: Early return when num of vertices is 0\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graphics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\/opengl\"\n)\n\nfunc glMatrix(m *[4][4]float64) []float32 {\n\treturn []float32{\n\t\tfloat32(m[0][0]), float32(m[1][0]), float32(m[2][0]), float32(m[3][0]),\n\t\tfloat32(m[0][1]), float32(m[1][1]), float32(m[2][1]), float32(m[3][1]),\n\t\tfloat32(m[0][2]), float32(m[1][2]), float32(m[2][2]), float32(m[3][2]),\n\t\tfloat32(m[0][3]), float32(m[1][3]), float32(m[2][3]), float32(m[3][3]),\n\t}\n}\n\ntype Matrix interface {\n\tElement(i, j int) float64\n}\n\nvar vertices = make([]int16, 16*quadsMaxNum)\n\nvar shadersInitialized = false\n\nfunc drawTexture(c *opengl.Context, texture opengl.Texture, projectionMatrix *[4][4]float64, quads TextureQuads, geo Matrix, color Matrix, mode opengl.CompositeMode) error {\n\tc.BlendFunc(mode)\n\n\t\/\/ NOTE: WebGL doesn't seem to have Check gl.MAX_ELEMENTS_VERTICES or gl.MAX_ELEMENTS_INDICES so far.\n\t\/\/ Let's use them to compare to len(quads) in the future.\n\n\tif !shadersInitialized {\n\t\tif err := initialize(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tshadersInitialized = true\n\t}\n\n\tl := quads.Len()\n\tif l == 0 {\n\t\treturn nil\n\t}\n\tif quadsMaxNum < l {\n\t\treturn errors.New(fmt.Sprintf(\"len(quads) must be equal to or less than %d\", quadsMaxNum))\n\t}\n\n\tp := programContext{\n\t\tprogram: programTexture,\n\t\tcontext: c,\n\t\tprojectionMatrix: glMatrix(projectionMatrix),\n\t\ttexture: texture,\n\t\tgeoM: geo,\n\t\tcolorM: color,\n\t}\n\tn := quads.SetVertices(vertices)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tp.begin()\n\tdefer p.end()\n\tc.BufferSubData(c.ArrayBuffer, vertices[:16*n])\n\tc.DrawElements(c.Triangles, 6*n)\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Alex Browne and Soroush Pour.\n\/\/ Allrights reserved. Use of this source code is\n\/\/ governed by the MIT license, which can be found\n\/\/ in the LICENSE file.\n\npackage router\n\nimport (\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/go-humble\/detect\"\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n\t\"honnef.co\/go\/js\/dom\"\n)\n\nvar (\n\t\/\/ browserSupportsPushState will be true if the current browser\n\t\/\/ supports history.pushState and the onpopstate event.\n\tbrowserSupportsPushState bool\n\tdocument dom.HTMLDocument\n)\n\nfunc init() {\n\tif detect.IsBrowser() {\n\t\t\/\/ We only want to initialize certain things if we are running\n\t\t\/\/ inside a browser. Otherwise, they will cause the program to\n\t\t\/\/ panic.\n\t\tvar ok bool\n\t\tdocument, ok = dom.GetWindow().Document().(dom.HTMLDocument)\n\t\tif !ok {\n\t\t\tpanic(\"Could not convert document to dom.HTMLDocument\")\n\t\t}\n\t\tbrowserSupportsPushState = (js.Global.Get(\"onpopstate\") != js.Undefined) &&\n\t\t\t(js.Global.Get(\"history\") != js.Undefined) &&\n\t\t\t(js.Global.Get(\"history\").Get(\"pushState\") != js.Undefined)\n\t}\n}\n\n\/\/ Router is responsible for handling routes. If history.pushState is\n\/\/ supported, it uses it to navigate from page to page and will listen\n\/\/ to the \"onpopstate\" event. Otherwise, it sets the hash component of the\n\/\/ url and listens to changes via the \"onhashchange\" event.\ntype Router struct {\n\t\/\/ routes is the set of routes for this router.\n\troutes []*route\n\t\/\/ ShouldInterceptLinks tells the router whether or not to intercept click events\n\t\/\/ on links and call the Navigate method instead of the default behavior.\n\t\/\/ If it is set to true, the router will automatically intercept links when\n\t\/\/ Start, Navigate, or Back are called, or when the onpopstate event is triggered.\n\tShouldInterceptLinks bool\n\t\/\/ ForceHashURL tells the router to use the hash component of the url to\n\t\/\/ represent different routes, even if history.pushState is supported.\n\tForceHashURL bool\n\t\/\/ Verbose determines whether or not the router will log to console.log.\n\t\/\/ If true, the router will log a message if, e.g., a match cannot be found for\n\t\/\/ a particular path.\n\tVerbose bool\n\t\/\/ listener is the js.Object representation of a listener callback.\n\t\/\/ It is required in order to use the RemoveEventListener method\n\tlistener func(*js.Object)\n}\n\n\/\/ Context is used as an argument to Handlers\ntype Context struct {\n\t\/\/ Params is the parameters from the url as a map of names to values.\n\tParams map[string]string\n\t\/\/ Path is the path that triggered this particular route. If the hash\n\t\/\/ fallback is being used, the value of path does not include the '#'\n\t\/\/ symbol.\n\tPath string\n\t\/\/ InitialLoad is true iff this route was triggered during the initial\n\t\/\/ page load. I.e. it is true if this is the first path that the browser\n\t\/\/ was visiting when the javascript finished loading.\n\tInitialLoad bool\n}\n\n\/\/ Handler is a function which is run in response to a specific\n\/\/ route. A Handler takes a Context as an argument, which gives\n\/\/ handler functions access to path parameters and other important\n\/\/ information.\ntype Handler func(context *Context)\n\n\/\/ New creates and returns a new router\nfunc New() *Router {\n\treturn &Router{\n\t\troutes: []*route{},\n\t}\n}\n\n\/\/ route is a representation of a specific route\ntype route struct {\n\t\/\/ regex is a regex pattern that matches route\n\tregex *regexp.Regexp\n\t\/\/ paramNames is an ordered list of parameters expected\n\t\/\/ by route handler\n\tparamNames []string\n\t\/\/ handler called when route is matched\n\thandler Handler\n}\n\n\/\/ HandleFunc will cause the router to call f whenever window.location.pathname\n\/\/ (or window.location.hash, if history.pushState is not supported) matches path.\n\/\/ path can contain any number of parameters which are denoted with curly brackets.\n\/\/ So, for example, a path argument of \"users\/{id}\" will be triggered when the user\n\/\/ visits users\/123 and will call the handler function with params[\"id\"] = \"123\".\nfunc (r *Router) HandleFunc(path string, handler Handler) {\n\tr.routes = append(r.routes, newRoute(path, handler))\n}\n\n\/\/ newRoute returns a route with the given arguments. paramNames and regex\n\/\/ are calculated from the path\nfunc newRoute(path string, handler Handler) *route {\n\troute := &route{\n\t\thandler: handler,\n\t}\n\tstrs := strings.Split(path, \"\/\")\n\tstrs = removeEmptyStrings(strs)\n\tpattern := `^`\n\tfor _, str := range strs {\n\t\tif str[0] == '{' && str[len(str)-1] == '}' {\n\t\t\tpattern += `\/`\n\t\t\tpattern += `([\\w+-]*)`\n\t\t\troute.paramNames = append(route.paramNames, str[1:(len(str)-1)])\n\t\t} else {\n\t\t\tpattern += `\/`\n\t\t\tpattern += str\n\t\t}\n\t}\n\tpattern += `\/?$`\n\troute.regex = regexp.MustCompile(pattern)\n\treturn route\n}\n\n\/\/ Start causes the router to listen for changes to window.location and\n\/\/ trigger the appropriate handler whenever there is a change.\nfunc (r *Router) Start() {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tr.pathChanged(getPath(), true)\n\t\tr.watchHistory()\n\t} else {\n\t\tr.setInitialHash()\n\t\tr.watchHash()\n\t}\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ Stop causes the router to stop listening for changes, and therefore\n\/\/ the router will not trigger any more router.Handler functions.\nfunc (r *Router) Stop() {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tjs.Global.Set(\"onpopstate\", nil)\n\t} else {\n\t\tjs.Global.Set(\"onhashchange\", nil)\n\t}\n}\n\n\/\/ Navigate will trigger the handler associated with the given path\n\/\/ and update window.location accordingly. If the browser supports\n\/\/ history.pushState, that will be used. Otherwise, Navigate will\n\/\/ set the hash component of window.location to the given path.\nfunc (r *Router) Navigate(path string) {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tpushState(path)\n\t\tr.pathChanged(path, false)\n\t} else {\n\t\tsetHash(path)\n\t}\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ CanNavigate returns true if the specified path can be navigated by the\n\/\/ router, and false otherwise\nfunc (r *Router) CanNavigate(path string) bool {\n\tif bestRoute, _ := r.findBestRoute(path); bestRoute != nil {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Back will cause the browser to go back to the previous page.\n\/\/ It has the same effect as the user pressing the back button,\n\/\/ and is just a wrapper around history.back()\nfunc (r *Router) Back() {\n\tjs.Global.Get(\"history\").Call(\"back\")\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ InterceptLinks intercepts click events on links of the form <\/a>\n\/\/ and calls router.Navigate(\"\/foo\") instead, which triggers the appropriate Handler\n\/\/ instead of requesting a new page from the server. Since InterceptLinks works by\n\/\/ setting event listeners in the DOM, you must call this function whenever the DOM\n\/\/ is changed. Alternatively, you can set r.ShouldInterceptLinks to true, which will\n\/\/ trigger this function whenever Start, Navigate, or Back are called, or when the\n\/\/ onpopstate event is triggered. Even with r.ShouldInterceptLinks set to true, you\n\/\/ may still need to call this function if you change the DOM manually without\n\/\/ triggering a route.\nfunc (r *Router) InterceptLinks() {\n\tfor _, link := range document.Links() {\n\t\thref := link.GetAttribute(\"href\")\n\t\tswitch {\n\t\tcase href == \"\":\n\t\t\treturn\n\t\tcase strings.HasPrefix(href, \"http:\/\/\"), strings.HasPrefix(href, \"https:\/\/\"), strings.HasPrefix(href, \"\/\/\"):\n\t\t\t\/\/ These are external links and should behave normally.\n\t\t\treturn\n\t\tcase strings.HasPrefix(href, \"#\"):\n\t\t\t\/\/ These are anchor links and should behave normally.\n\t\t\t\/\/ Recall that even when we are using the hash trick, href\n\t\t\t\/\/ attributes should be relative paths without the \"#\" and\n\t\t\t\/\/ router will handle them appropriately.\n\t\t\treturn\n\t\tcase strings.HasPrefix(href, \"\/\"):\n\t\t\t\/\/ These are relative links. The kind that we want to intercept.\n\t\t\tif r.listener != nil {\n\t\t\t\t\/\/ Remove the old listener (if any)\n\t\t\t\tlink.RemoveEventListener(\"click\", true, r.listener)\n\t\t\t}\n\t\t\tr.listener = link.AddEventListener(\"click\", true, r.interceptLink)\n\t\t}\n\t}\n}\n\n\/\/ interceptLink is intended to be used as a callback function. It stops\n\/\/ the default behavior of event and instead calls r.Navigate, passing through\n\/\/ the link's href property.\nfunc (r *Router) interceptLink(event dom.Event) {\n\tpath := event.CurrentTarget().GetAttribute(\"href\")\n\t\/\/ Only intercept the click event if we have a route which matches\n\t\/\/ Otherwise, just do the default.\n\tif bestRoute, _ := r.findBestRoute(path); bestRoute != nil {\n\t\tevent.PreventDefault()\n\t\tgo r.Navigate(path)\n\t}\n}\n\n\/\/ setInitialHash will set hash to \/ if there is currently no hash.\nfunc (r *Router) setInitialHash() {\n\tif getHash() == \"\" {\n\t\tsetHash(\"\/\")\n\t} else {\n\t\tr.pathChanged(getPathFromHash(getHash()), true)\n\t}\n}\n\n\/\/ pathChanged should be called whenever the path changes and will trigger\n\/\/ the appropriate handler. initial should be true iff this is the first\n\/\/ time the javascript is loaded on the page.\nfunc (r *Router) pathChanged(path string, initial bool) {\n\tbestRoute, tokens := r.findBestRoute(path)\n\t\/\/ If no routes match, we throw console error and no handlers are called\n\tif bestRoute == nil {\n\t\tif r.Verbose {\n\t\t\tlog.Println(\"Could not find route to match: \" + path)\n\t\t}\n\t\treturn\n\t}\n\t\/\/ Create the context and pass it through to the handler\n\tc := &Context{\n\t\tPath: path,\n\t\tInitialLoad: initial,\n\t\tParams: map[string]string{},\n\t}\n\tfor i, token := range tokens {\n\t\tc.Params[bestRoute.paramNames[i]] = token\n\t}\n\tbestRoute.handler(c)\n}\n\n\/\/ findBestRoute compares the given path against regex patterns of routes.\n\/\/ Preference given to routes with most literal (non-parameter) matches. For\n\/\/ example if we have the following:\n\/\/ Route 1: \/todos\/work\n\/\/ Route 2: \/todos\/{category}\n\/\/ And the path argument is \"\/todos\/work\", the bestRoute would be todos\/work\n\/\/ because the string \"work\" matches the literal in Route 1.\nfunc (r Router) findBestRoute(path string) (bestRoute *route, tokens []string) {\n\tleastParams := -1\n\tfor _, route := range r.routes {\n\t\tmatches := route.regex.FindStringSubmatch(path)\n\t\tif matches != nil {\n\t\t\tif (leastParams == -1) || (len(matches) < leastParams) {\n\t\t\t\tleastParams = len(matches)\n\t\t\t\tbestRoute = route\n\t\t\t\ttokens = matches[1:]\n\t\t\t}\n\t\t}\n\t}\n\treturn bestRoute, tokens\n}\n\n\/\/ removeEmptyStrings removes any empty strings from strings\nfunc removeEmptyStrings(strings []string) []string {\n\tresult := []string{}\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tresult = append(result, s)\n\t\t}\n\t}\n\treturn result\n}\n\n\/\/ watchHash listens to the onhashchange event and calls r.pathChanged when\n\/\/ it changes\nfunc (r *Router) watchHash() {\n\tjs.Global.Set(\"onhashchange\", func() {\n\t\tgo func() {\n\t\t\tpath := getPathFromHash(getHash())\n\t\t\tr.pathChanged(path, false)\n\t\t}()\n\t})\n}\n\n\/\/ watchHistory listens to the onpopstate event and calls r.pathChanged when\n\/\/ it changes\nfunc (r *Router) watchHistory() {\n\tjs.Global.Set(\"onpopstate\", func() {\n\t\tgo func() {\n\t\t\tr.pathChanged(getPath(), false)\n\t\t\tif r.ShouldInterceptLinks {\n\t\t\t\tr.InterceptLinks()\n\t\t\t}\n\t\t}()\n\t})\n}\n\n\/\/ getPathFromHash returns everything after the \"#\" character in hash.\nfunc getPathFromHash(hash string) string {\n\treturn strings.SplitN(hash, \"#\", 2)[1]\n}\n\n\/\/ getHash is an alias for js.Global.Get(\"location\").Get(\"hash\").String()\nfunc getHash() string {\n\treturn js.Global.Get(\"location\").Get(\"hash\").String()\n}\n\n\/\/ setHash is an alias for js.Global.Get(\"location\").Set(\"hash\", hash)\nfunc setHash(hash string) {\n\tjs.Global.Get(\"location\").Set(\"hash\", hash)\n}\n\n\/\/ getPath is an alias for js.Global.Get(\"location\").Get(\"pathname\").String()\nfunc getPath() string {\n\treturn js.Global.Get(\"location\").Get(\"pathname\").String()\n}\n\n\/\/ pushState is an alias for js.Global.Get(\"history\").Call(\"pushState\", nil, \"\", path)\nfunc pushState(path string) {\n\tjs.Global.Get(\"history\").Call(\"pushState\", nil, \"\", path)\n}\nInterceptLinks should iterate all links - don't abort iteration certain href are matched\/\/ Copyright 2015 Alex Browne and Soroush Pour.\n\/\/ Allrights reserved. Use of this source code is\n\/\/ governed by the MIT license, which can be found\n\/\/ in the LICENSE file.\n\npackage router\n\nimport (\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/go-humble\/detect\"\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n\t\"honnef.co\/go\/js\/dom\"\n)\n\nvar (\n\t\/\/ browserSupportsPushState will be true if the current browser\n\t\/\/ supports history.pushState and the onpopstate event.\n\tbrowserSupportsPushState bool\n\tdocument dom.HTMLDocument\n)\n\nfunc init() {\n\tif detect.IsBrowser() {\n\t\t\/\/ We only want to initialize certain things if we are running\n\t\t\/\/ inside a browser. Otherwise, they will cause the program to\n\t\t\/\/ panic.\n\t\tvar ok bool\n\t\tdocument, ok = dom.GetWindow().Document().(dom.HTMLDocument)\n\t\tif !ok {\n\t\t\tpanic(\"Could not convert document to dom.HTMLDocument\")\n\t\t}\n\t\tbrowserSupportsPushState = (js.Global.Get(\"onpopstate\") != js.Undefined) &&\n\t\t\t(js.Global.Get(\"history\") != js.Undefined) &&\n\t\t\t(js.Global.Get(\"history\").Get(\"pushState\") != js.Undefined)\n\t}\n}\n\n\/\/ Router is responsible for handling routes. If history.pushState is\n\/\/ supported, it uses it to navigate from page to page and will listen\n\/\/ to the \"onpopstate\" event. Otherwise, it sets the hash component of the\n\/\/ url and listens to changes via the \"onhashchange\" event.\ntype Router struct {\n\t\/\/ routes is the set of routes for this router.\n\troutes []*route\n\t\/\/ ShouldInterceptLinks tells the router whether or not to intercept click events\n\t\/\/ on links and call the Navigate method instead of the default behavior.\n\t\/\/ If it is set to true, the router will automatically intercept links when\n\t\/\/ Start, Navigate, or Back are called, or when the onpopstate event is triggered.\n\tShouldInterceptLinks bool\n\t\/\/ ForceHashURL tells the router to use the hash component of the url to\n\t\/\/ represent different routes, even if history.pushState is supported.\n\tForceHashURL bool\n\t\/\/ Verbose determines whether or not the router will log to console.log.\n\t\/\/ If true, the router will log a message if, e.g., a match cannot be found for\n\t\/\/ a particular path.\n\tVerbose bool\n\t\/\/ listener is the js.Object representation of a listener callback.\n\t\/\/ It is required in order to use the RemoveEventListener method\n\tlistener func(*js.Object)\n}\n\n\/\/ Context is used as an argument to Handlers\ntype Context struct {\n\t\/\/ Params is the parameters from the url as a map of names to values.\n\tParams map[string]string\n\t\/\/ Path is the path that triggered this particular route. If the hash\n\t\/\/ fallback is being used, the value of path does not include the '#'\n\t\/\/ symbol.\n\tPath string\n\t\/\/ InitialLoad is true iff this route was triggered during the initial\n\t\/\/ page load. I.e. it is true if this is the first path that the browser\n\t\/\/ was visiting when the javascript finished loading.\n\tInitialLoad bool\n}\n\n\/\/ Handler is a function which is run in response to a specific\n\/\/ route. A Handler takes a Context as an argument, which gives\n\/\/ handler functions access to path parameters and other important\n\/\/ information.\ntype Handler func(context *Context)\n\n\/\/ New creates and returns a new router\nfunc New() *Router {\n\treturn &Router{\n\t\troutes: []*route{},\n\t}\n}\n\n\/\/ route is a representation of a specific route\ntype route struct {\n\t\/\/ regex is a regex pattern that matches route\n\tregex *regexp.Regexp\n\t\/\/ paramNames is an ordered list of parameters expected\n\t\/\/ by route handler\n\tparamNames []string\n\t\/\/ handler called when route is matched\n\thandler Handler\n}\n\n\/\/ HandleFunc will cause the router to call f whenever window.location.pathname\n\/\/ (or window.location.hash, if history.pushState is not supported) matches path.\n\/\/ path can contain any number of parameters which are denoted with curly brackets.\n\/\/ So, for example, a path argument of \"users\/{id}\" will be triggered when the user\n\/\/ visits users\/123 and will call the handler function with params[\"id\"] = \"123\".\nfunc (r *Router) HandleFunc(path string, handler Handler) {\n\tr.routes = append(r.routes, newRoute(path, handler))\n}\n\n\/\/ newRoute returns a route with the given arguments. paramNames and regex\n\/\/ are calculated from the path\nfunc newRoute(path string, handler Handler) *route {\n\troute := &route{\n\t\thandler: handler,\n\t}\n\tstrs := strings.Split(path, \"\/\")\n\tstrs = removeEmptyStrings(strs)\n\tpattern := `^`\n\tfor _, str := range strs {\n\t\tif str[0] == '{' && str[len(str)-1] == '}' {\n\t\t\tpattern += `\/`\n\t\t\tpattern += `([\\w+-]*)`\n\t\t\troute.paramNames = append(route.paramNames, str[1:(len(str)-1)])\n\t\t} else {\n\t\t\tpattern += `\/`\n\t\t\tpattern += str\n\t\t}\n\t}\n\tpattern += `\/?$`\n\troute.regex = regexp.MustCompile(pattern)\n\treturn route\n}\n\n\/\/ Start causes the router to listen for changes to window.location and\n\/\/ trigger the appropriate handler whenever there is a change.\nfunc (r *Router) Start() {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tr.pathChanged(getPath(), true)\n\t\tr.watchHistory()\n\t} else {\n\t\tr.setInitialHash()\n\t\tr.watchHash()\n\t}\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ Stop causes the router to stop listening for changes, and therefore\n\/\/ the router will not trigger any more router.Handler functions.\nfunc (r *Router) Stop() {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tjs.Global.Set(\"onpopstate\", nil)\n\t} else {\n\t\tjs.Global.Set(\"onhashchange\", nil)\n\t}\n}\n\n\/\/ Navigate will trigger the handler associated with the given path\n\/\/ and update window.location accordingly. If the browser supports\n\/\/ history.pushState, that will be used. Otherwise, Navigate will\n\/\/ set the hash component of window.location to the given path.\nfunc (r *Router) Navigate(path string) {\n\tif browserSupportsPushState && !r.ForceHashURL {\n\t\tpushState(path)\n\t\tr.pathChanged(path, false)\n\t} else {\n\t\tsetHash(path)\n\t}\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ CanNavigate returns true if the specified path can be navigated by the\n\/\/ router, and false otherwise\nfunc (r *Router) CanNavigate(path string) bool {\n\tif bestRoute, _ := r.findBestRoute(path); bestRoute != nil {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Back will cause the browser to go back to the previous page.\n\/\/ It has the same effect as the user pressing the back button,\n\/\/ and is just a wrapper around history.back()\nfunc (r *Router) Back() {\n\tjs.Global.Get(\"history\").Call(\"back\")\n\tif r.ShouldInterceptLinks {\n\t\tr.InterceptLinks()\n\t}\n}\n\n\/\/ InterceptLinks intercepts click events on links of the form <\/a>\n\/\/ and calls router.Navigate(\"\/foo\") instead, which triggers the appropriate Handler\n\/\/ instead of requesting a new page from the server. Since InterceptLinks works by\n\/\/ setting event listeners in the DOM, you must call this function whenever the DOM\n\/\/ is changed. Alternatively, you can set r.ShouldInterceptLinks to true, which will\n\/\/ trigger this function whenever Start, Navigate, or Back are called, or when the\n\/\/ onpopstate event is triggered. Even with r.ShouldInterceptLinks set to true, you\n\/\/ may still need to call this function if you change the DOM manually without\n\/\/ triggering a route.\nfunc (r *Router) InterceptLinks() {\n\tfor _, link := range document.Links() {\n\t\thref := link.GetAttribute(\"href\")\n\t\tswitch {\n\t\tcase href == \"\":\n\n\t\tcase strings.HasPrefix(href, \"http:\/\/\"), strings.HasPrefix(href, \"https:\/\/\"), strings.HasPrefix(href, \"\/\/\"):\n\t\t\t\/\/ These are external links and should behave normally.\n\n\t\tcase strings.HasPrefix(href, \"#\"):\n\t\t\t\/\/ These are anchor links and should behave normally.\n\t\t\t\/\/ Recall that even when we are using the hash trick, href\n\t\t\t\/\/ attributes should be relative paths without the \"#\" and\n\t\t\t\/\/ router will handle them appropriately.\n\n\t\tcase strings.HasPrefix(href, \"\/\"):\n\t\t\t\/\/ These are relative links. The kind that we want to intercept.\n\t\t\tif r.listener != nil {\n\t\t\t\t\/\/ Remove the old listener (if any)\n\t\t\t\tlink.RemoveEventListener(\"click\", true, r.listener)\n\t\t\t}\n\t\t\tr.listener = link.AddEventListener(\"click\", true, r.interceptLink)\n\t\t}\n\t}\n}\n\n\/\/ interceptLink is intended to be used as a callback function. It stops\n\/\/ the default behavior of event and instead calls r.Navigate, passing through\n\/\/ the link's href property.\nfunc (r *Router) interceptLink(event dom.Event) {\n\tpath := event.CurrentTarget().GetAttribute(\"href\")\n\t\/\/ Only intercept the click event if we have a route which matches\n\t\/\/ Otherwise, just do the default.\n\tif bestRoute, _ := r.findBestRoute(path); bestRoute != nil {\n\t\tevent.PreventDefault()\n\t\tgo r.Navigate(path)\n\t}\n}\n\n\/\/ setInitialHash will set hash to \/ if there is currently no hash.\nfunc (r *Router) setInitialHash() {\n\tif getHash() == \"\" {\n\t\tsetHash(\"\/\")\n\t} else {\n\t\tr.pathChanged(getPathFromHash(getHash()), true)\n\t}\n}\n\n\/\/ pathChanged should be called whenever the path changes and will trigger\n\/\/ the appropriate handler. initial should be true iff this is the first\n\/\/ time the javascript is loaded on the page.\nfunc (r *Router) pathChanged(path string, initial bool) {\n\tbestRoute, tokens := r.findBestRoute(path)\n\t\/\/ If no routes match, we throw console error and no handlers are called\n\tif bestRoute == nil {\n\t\tif r.Verbose {\n\t\t\tlog.Println(\"Could not find route to match: \" + path)\n\t\t}\n\t\treturn\n\t}\n\t\/\/ Create the context and pass it through to the handler\n\tc := &Context{\n\t\tPath: path,\n\t\tInitialLoad: initial,\n\t\tParams: map[string]string{},\n\t}\n\tfor i, token := range tokens {\n\t\tc.Params[bestRoute.paramNames[i]] = token\n\t}\n\tbestRoute.handler(c)\n}\n\n\/\/ findBestRoute compares the given path against regex patterns of routes.\n\/\/ Preference given to routes with most literal (non-parameter) matches. For\n\/\/ example if we have the following:\n\/\/ Route 1: \/todos\/work\n\/\/ Route 2: \/todos\/{category}\n\/\/ And the path argument is \"\/todos\/work\", the bestRoute would be todos\/work\n\/\/ because the string \"work\" matches the literal in Route 1.\nfunc (r Router) findBestRoute(path string) (bestRoute *route, tokens []string) {\n\tleastParams := -1\n\tfor _, route := range r.routes {\n\t\tmatches := route.regex.FindStringSubmatch(path)\n\t\tif matches != nil {\n\t\t\tif (leastParams == -1) || (len(matches) < leastParams) {\n\t\t\t\tleastParams = len(matches)\n\t\t\t\tbestRoute = route\n\t\t\t\ttokens = matches[1:]\n\t\t\t}\n\t\t}\n\t}\n\treturn bestRoute, tokens\n}\n\n\/\/ removeEmptyStrings removes any empty strings from strings\nfunc removeEmptyStrings(strings []string) []string {\n\tresult := []string{}\n\tfor _, s := range strings {\n\t\tif s != \"\" {\n\t\t\tresult = append(result, s)\n\t\t}\n\t}\n\treturn result\n}\n\n\/\/ watchHash listens to the onhashchange event and calls r.pathChanged when\n\/\/ it changes\nfunc (r *Router) watchHash() {\n\tjs.Global.Set(\"onhashchange\", func() {\n\t\tgo func() {\n\t\t\tpath := getPathFromHash(getHash())\n\t\t\tr.pathChanged(path, false)\n\t\t}()\n\t})\n}\n\n\/\/ watchHistory listens to the onpopstate event and calls r.pathChanged when\n\/\/ it changes\nfunc (r *Router) watchHistory() {\n\tjs.Global.Set(\"onpopstate\", func() {\n\t\tgo func() {\n\t\t\tr.pathChanged(getPath(), false)\n\t\t\tif r.ShouldInterceptLinks {\n\t\t\t\tr.InterceptLinks()\n\t\t\t}\n\t\t}()\n\t})\n}\n\n\/\/ getPathFromHash returns everything after the \"#\" character in hash.\nfunc getPathFromHash(hash string) string {\n\treturn strings.SplitN(hash, \"#\", 2)[1]\n}\n\n\/\/ getHash is an alias for js.Global.Get(\"location\").Get(\"hash\").String()\nfunc getHash() string {\n\treturn js.Global.Get(\"location\").Get(\"hash\").String()\n}\n\n\/\/ setHash is an alias for js.Global.Get(\"location\").Set(\"hash\", hash)\nfunc setHash(hash string) {\n\tjs.Global.Get(\"location\").Set(\"hash\", hash)\n}\n\n\/\/ getPath is an alias for js.Global.Get(\"location\").Get(\"pathname\").String()\nfunc getPath() string {\n\treturn js.Global.Get(\"location\").Get(\"pathname\").String()\n}\n\n\/\/ pushState is an alias for js.Global.Get(\"history\").Call(\"pushState\", nil, \"\", path)\nfunc pushState(path string) {\n\tjs.Global.Get(\"history\").Call(\"pushState\", nil, \"\", path)\n}\n<|endoftext|>"} {"text":"package common\n\nimport (\n\t\"cgl.tideland.biz\/identifier\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n\t\"github.com\/mitchellh\/multistep\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"log\"\n\t\"time\"\n)\n\ntype StepSecurityGroup struct {\n\tSecurityGroupId string\n\tSSHPort int\n\tVpcId string\n\n\tcreatedGroupId string\n}\n\nfunc (s *StepSecurityGroup) Run(state map[string]interface{}) multistep.StepAction {\n\tec2conn := state[\"ec2\"].(*ec2.EC2)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tif s.SecurityGroupId != \"\" {\n\t\tlog.Printf(\"Using specified security group: %s\", s.SecurityGroupId)\n\t\tstate[\"securityGroupId\"] = s.SecurityGroupId\n\t\treturn multistep.ActionContinue\n\t}\n\n\tif s.SSHPort == 0 {\n\t\tpanic(\"SSHPort must be set to a non-zero value.\")\n\t}\n\n\t\/\/ Create the group\n\tui.Say(\"Creating temporary security group for this instance...\")\n\tgroupName := fmt.Sprintf(\"packer %s\", hex.EncodeToString(identifier.NewUUID().Raw()))\n\tlog.Printf(\"Temporary group name: %s\", groupName)\n\tgroup := ec2.SecurityGroup{\n\t\tName: groupName,\n\t\tDescription: \"Temporary group for Packer\",\n\t\tVpcId: s.VpcId,\n\t}\n\tgroupResp, err := ec2conn.CreateSecurityGroup(group)\n\tif err != nil {\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set the group ID so we can delete it later\n\ts.createdGroupId = groupResp.Id\n\n\t\/\/ Authorize the SSH access\n\tperms := []ec2.IPPerm{\n\t\tec2.IPPerm{\n\t\t\tProtocol: \"tcp\",\n\t\t\tFromPort: s.SSHPort,\n\t\t\tToPort: s.SSHPort,\n\t\t\tSourceIPs: []string{\"0.0.0.0\/0\"},\n\t\t},\n\t}\n\n\tui.Say(\"Authorizing SSH access on the temporary security group...\")\n\tif _, err := ec2conn.AuthorizeSecurityGroup(groupResp.SecurityGroup, perms); err != nil {\n\t\terr := fmt.Errorf(\"Error creating temporary security group: %s\", err)\n\t\tstate[\"error\"] = err\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set some state data for use in future steps\n\tstate[\"securityGroupId\"] = s.createdGroupId\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *StepSecurityGroup) Cleanup(state map[string]interface{}) {\n\tif s.createdGroupId == \"\" {\n\t\treturn\n\t}\n\n\tec2conn := state[\"ec2\"].(*ec2.EC2)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tui.Say(\"Deleting temporary security group...\")\n\n\tvar err error\n\tfor i := 0; i < 5; i++ {\n\t\t_, err = ec2conn.DeleteSecurityGroup(ec2.SecurityGroup{Id: s.createdGroupId})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error deleting security group: %s\", err)\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tui.Error(fmt.Sprintf(\n\t\t\t\"Error cleaning up security group. Please delete the group manually: %s\", s.createdGroupId))\n\t}\n}\nbuilder\/amazon\/common: correct logic in deleting secutiry grouppackage common\n\nimport (\n\t\"cgl.tideland.biz\/identifier\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n\t\"github.com\/mitchellh\/multistep\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"log\"\n\t\"time\"\n)\n\ntype StepSecurityGroup struct {\n\tSecurityGroupId string\n\tSSHPort int\n\tVpcId string\n\n\tcreatedGroupId string\n}\n\nfunc (s *StepSecurityGroup) Run(state map[string]interface{}) multistep.StepAction {\n\tec2conn := state[\"ec2\"].(*ec2.EC2)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tif s.SecurityGroupId != \"\" {\n\t\tlog.Printf(\"Using specified security group: %s\", s.SecurityGroupId)\n\t\tstate[\"securityGroupId\"] = s.SecurityGroupId\n\t\treturn multistep.ActionContinue\n\t}\n\n\tif s.SSHPort == 0 {\n\t\tpanic(\"SSHPort must be set to a non-zero value.\")\n\t}\n\n\t\/\/ Create the group\n\tui.Say(\"Creating temporary security group for this instance...\")\n\tgroupName := fmt.Sprintf(\"packer %s\", hex.EncodeToString(identifier.NewUUID().Raw()))\n\tlog.Printf(\"Temporary group name: %s\", groupName)\n\tgroup := ec2.SecurityGroup{\n\t\tName: groupName,\n\t\tDescription: \"Temporary group for Packer\",\n\t\tVpcId: s.VpcId,\n\t}\n\tgroupResp, err := ec2conn.CreateSecurityGroup(group)\n\tif err != nil {\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set the group ID so we can delete it later\n\ts.createdGroupId = groupResp.Id\n\n\t\/\/ Authorize the SSH access\n\tperms := []ec2.IPPerm{\n\t\tec2.IPPerm{\n\t\t\tProtocol: \"tcp\",\n\t\t\tFromPort: s.SSHPort,\n\t\t\tToPort: s.SSHPort,\n\t\t\tSourceIPs: []string{\"0.0.0.0\/0\"},\n\t\t},\n\t}\n\n\tui.Say(\"Authorizing SSH access on the temporary security group...\")\n\tif _, err := ec2conn.AuthorizeSecurityGroup(groupResp.SecurityGroup, perms); err != nil {\n\t\terr := fmt.Errorf(\"Error creating temporary security group: %s\", err)\n\t\tstate[\"error\"] = err\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set some state data for use in future steps\n\tstate[\"securityGroupId\"] = s.createdGroupId\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *StepSecurityGroup) Cleanup(state map[string]interface{}) {\n\tif s.createdGroupId == \"\" {\n\t\treturn\n\t}\n\n\tec2conn := state[\"ec2\"].(*ec2.EC2)\n\tui := state[\"ui\"].(packer.Ui)\n\n\tui.Say(\"Deleting temporary security group...\")\n\n\tvar err error\n\tfor i := 0; i < 5; i++ {\n\t\t_, err = ec2conn.DeleteSecurityGroup(ec2.SecurityGroup{Id: s.createdGroupId})\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tlog.Printf(\"Error deleting security group: %s\", err)\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\tif err != nil {\n\t\tui.Error(fmt.Sprintf(\n\t\t\t\"Error cleaning up security group. Please delete the group manually: %s\", s.createdGroupId))\n\t}\n}\n<|endoftext|>"} {"text":"package tradier\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar timesalesJSONSingle = []byte(`{\n\t\"series\": {\n\t\t\"data\": {\n \"price\": 4.32,\n \"time\": \"2017-01-27T09:30:00\",\n \"timestamp\": 1485527400,\n \"volume\": 125\n }\n\t}\n}`)\n\nvar timesalesJSONArray = []byte(`{\n\t\"series\": {\n\t\t\"data\": [\n {\n \"price\": 4.32,\n \"time\": \"2017-01-27T09:30:00\",\n \"timestamp\": 1485527400,\n \"volume\": 125\n },\n {\n \"price\": 4.34,\n \"time\": \"2017-01-27T09:31:20\",\n \"timestamp\": 1485527480,\n \"volume\": 100\n }\n ]\n\t}\n}`)\n\nvar timesaleJSONEmpty = []byte(`{\n\t\"series\": \"null\"\n}`)\n\nvar timesalesSingle = &Series{\n\tData: []*Data{\n\t\t&Data{\n\t\t\tPrice: Float64(4.32),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 30, 0, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527400),\n\t\t\tVolume: Int(125),\n\t\t},\n\t},\n}\n\nvar timesalesArray = &Series{\n\tData: []*Data{\n\t\t&Data{\n\t\t\tPrice: Float64(4.32),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 30, 0, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527400),\n\t\t\tVolume: Int(125),\n\t\t},\n\t\t&Data{\n\t\t\tPrice: Float64(4.34),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 31, 20, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527480),\n\t\t\tVolume: Int(100),\n\t\t},\n\t},\n}\n\nvar timesalesEmpty = &Series{}\n\nfunc TestTimesales_UnmarshalJSON_Single(t *testing.T) {\n\twant := timesalesSingle\n\n\tgot := &Series{}\n\terr := json.Unmarshal(timesalesJSONSingle, got)\n\tif err != nil {\n\t\tt.Errorf(\"Series.UnmarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\t}\n}\n\nfunc TestTimesales_MarshalJSON_Single(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\terr := json.Compact(buf, timesalesJSONSingle)\n\twant := buf.Bytes()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgot, err := json.Marshal(timesalesSingle)\n\tif err != nil {\n\t\tt.Errorf(\"Accounts.MarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %s want: %s\", got, want)\n\t}\n}\n\nfunc TestTimesales_UnmarshalJSON_Array(t *testing.T) {\n\twant := timesalesArray\n\n\tgot := &Series{}\n\terr := json.Unmarshal(timesalesJSONArray, got)\n\tif err != nil {\n\t\tt.Errorf(\"Accounts.UnmarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\t}\n}\n\nfunc TestTimesales_MarshalJSON_Array(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\terr := json.Compact(buf, timesalesJSONArray)\n\twant := buf.Bytes()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgot, err := json.Marshal(timesalesArray)\n\tif err != nil {\n\t\tt.Errorf(\"Accounts.MarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %s want: %s\", got, want)\n\t}\n}\n\n\/\/ func TestAccounts_UnmarshalJSON_Null(t *testing.T) {\n\/\/ \twant := accountsNull\n\/\/\n\/\/ \tgot := &Accounts{}\n\/\/ \terr := json.Unmarshal(accountsJSONNull, got)\n\/\/ \tif err != nil {\n\/\/ \t\tt.Errorf(\"Accounts.UnmarshalJSON error: %s\", err)\n\/\/ \t}\n\/\/\n\/\/ \tif !reflect.DeepEqual(got, want) {\n\/\/ \t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\/\/ \t}\n\/\/ }\n\/\/\n\/\/ func TestAccounts_MarshalJSON_Null(t *testing.T) {\n\/\/ \tbuf := &bytes.Buffer{}\n\/\/ \terr := json.Compact(buf, accountsJSONNull)\n\/\/ \twant := buf.Bytes()\n\/\/ \tif err != nil {\n\/\/ \t\tt.Error(err)\n\/\/ \t}\n\/\/\n\/\/ \tgot, err := json.Marshal(&accountsNull)\n\/\/ \tif err != nil {\n\/\/ \t\tt.Errorf(\"Accounts.MarshalJSON error: %s\", err)\n\/\/ \t}\n\/\/\n\/\/ \tif !reflect.DeepEqual(got, want) {\n\/\/ \t\tt.Errorf(\"got: %s want: %s\", got, want)\n\/\/ \t}\n\/\/ }\nAdd marshal and unmarshal tests for empty seriespackage tradier\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar timesalesJSONSingle = []byte(`{\n\t\"series\": {\n\t\t\"data\": {\n \"price\": 4.32,\n \"time\": \"2017-01-27T09:30:00\",\n \"timestamp\": 1485527400,\n \"volume\": 125\n }\n\t}\n}`)\n\nvar timesalesJSONArray = []byte(`{\n\t\"series\": {\n\t\t\"data\": [\n {\n \"price\": 4.32,\n \"time\": \"2017-01-27T09:30:00\",\n \"timestamp\": 1485527400,\n \"volume\": 125\n },\n {\n \"price\": 4.34,\n \"time\": \"2017-01-27T09:31:20\",\n \"timestamp\": 1485527480,\n \"volume\": 100\n }\n ]\n\t}\n}`)\n\nvar timesaleJSONEmpty = []byte(`{\n\t\"series\": \"null\"\n}`)\n\nvar timesalesSingle = &Series{\n\tData: []*Data{\n\t\t&Data{\n\t\t\tPrice: Float64(4.32),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 30, 0, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527400),\n\t\t\tVolume: Int(125),\n\t\t},\n\t},\n}\n\nvar timesalesArray = &Series{\n\tData: []*Data{\n\t\t&Data{\n\t\t\tPrice: Float64(4.32),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 30, 0, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527400),\n\t\t\tVolume: Int(125),\n\t\t},\n\t\t&Data{\n\t\t\tPrice: Float64(4.34),\n\t\t\tTime: &Time{time.Date(2017, 01, 27, 9, 31, 20, 0, time.UTC)},\n\t\t\tTimestamp: Int(1485527480),\n\t\t\tVolume: Int(100),\n\t\t},\n\t},\n}\n\nvar timesalesEmpty = &Series{}\n\nfunc TestTimesales_UnmarshalJSON_Single(t *testing.T) {\n\twant := timesalesSingle\n\n\tgot := &Series{}\n\terr := json.Unmarshal(timesalesJSONSingle, got)\n\tif err != nil {\n\t\tt.Errorf(\"Series.UnmarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\t}\n}\n\nfunc TestTimesales_MarshalJSON_Single(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\terr := json.Compact(buf, timesalesJSONSingle)\n\twant := buf.Bytes()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgot, err := json.Marshal(timesalesSingle)\n\tif err != nil {\n\t\tt.Errorf(\"Series.MarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %s want: %s\", got, want)\n\t}\n}\n\nfunc TestTimesales_UnmarshalJSON_Array(t *testing.T) {\n\twant := timesalesArray\n\n\tgot := &Series{}\n\terr := json.Unmarshal(timesalesJSONArray, got)\n\tif err != nil {\n\t\tt.Errorf(\"Series.UnmarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\t}\n}\n\nfunc TestTimesales_MarshalJSON_Array(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\terr := json.Compact(buf, timesalesJSONArray)\n\twant := buf.Bytes()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgot, err := json.Marshal(timesalesArray)\n\tif err != nil {\n\t\tt.Errorf(\"Series.MarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %s want: %s\", got, want)\n\t}\n}\n\nfunc TestTimesales_UnmarshalJSON_Null(t *testing.T) {\n\twant := timesalesEmpty\n\n\tgot := &Series{}\n\terr := json.Unmarshal(timesaleJSONEmpty, got)\n\tif err != nil {\n\t\tt.Errorf(\"Series.UnmarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %+v want: %+v\", got, want)\n\t}\n}\n\nfunc TestTimesales_MarshalJSON_Null(t *testing.T) {\n\tbuf := &bytes.Buffer{}\n\terr := json.Compact(buf, timesaleJSONEmpty)\n\twant := buf.Bytes()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgot, err := json.Marshal(×alesEmpty)\n\tif err != nil {\n\t\tt.Errorf(\"Series.MarshalJSON error: %s\", err)\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %s want: %s\", got, want)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017-2018 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage dhclient\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\n\t\"github.com\/u-root\/dhcp4\"\n\t\"github.com\/u-root\/dhcp4\/dhcp4opts\"\n)\n\n\/\/ Packet4 implements convenience functions for DHCPv4 packets.\ntype Packet4 struct {\n\tP *dhcp4.Packet\n}\n\n\/\/ NewPacket4 wraps a DHCPv4 packet with some convenience methods.\nfunc NewPacket4(p *dhcp4.Packet) *Packet4 {\n\treturn &Packet4{\n\t\tP: p,\n\t}\n}\n\n\/\/ Lease returns the IPNet assigned.\nfunc (p *Packet4) Lease() *net.IPNet {\n\tnetmask, err := dhcp4opts.GetSubnetMask(p.P.Options)\n\tif err != nil {\n\t\t\/\/ If they did not offer a subnet mask, we choose the most\n\t\t\/\/ restrictive option.\n\t\tnetmask = []byte{255, 255, 255, 255}\n\t}\n\n\treturn &net.IPNet{\n\t\tIP: p.P.YIAddr,\n\t\tMask: net.IPMask(netmask),\n\t}\n}\n\n\/\/ Gateway returns the gateway IP assigned.\n\/\/\n\/\/ OptionRouter is used as opposed to GIAddr, which seems unused by most DHCP\n\/\/ servers?\nfunc (p *Packet4) Gateway() net.IP {\n\tgw, err := dhcp4opts.GetRouters(p.P.Options)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn gw[0]\n}\n\n\/\/ DNS returns DNS IPs assigned.\nfunc (p *Packet4) DNS() []net.IP {\n\tips, err := dhcp4opts.GetDomainNameServers(p.P.Options)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn []net.IP(ips)\n}\n\n\/\/ Boot returns the boot file assigned.\nfunc (p *Packet4) Boot() (url.URL, error) {\n\t\/\/ TODO: This is not 100% right -- if a certain option is set, this\n\t\/\/ stuff is encoded in options instead of in the packet's BootFile and\n\t\/\/ ServerName fields.\n\n\t\/\/ While the default is tftp, servers may specify HTTP or FTP URIs.\n\tu, err := url.Parse(p.P.BootFile)\n\tif err != nil {\n\t\treturn url.URL{}, err\n\t}\n\n\tif len(u.Scheme) == 0 {\n\t\t\/\/ Defaults to tftp is not specified.\n\t\tu.Scheme = \"tftp\"\n\t\tu.Path = p.P.BootFile\n\t\tif len(p.P.ServerName) == 0 {\n\t\t\tserver, err := dhcp4opts.GetServerIdentifier(p.P.Options)\n\t\t\tif err != nil {\n\t\t\t\treturn url.URL{}, err\n\t\t\t}\n\t\t\tu.Host = net.IP(server).String()\n\t\t} else {\n\t\t\tu.Host = p.P.ServerName\n\t\t}\n\t}\n\treturn *u, nil\n}\ndhclient: Fix errors resulting from dep update\/\/ Copyright 2017-2018 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage dhclient\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\n\t\"github.com\/u-root\/dhcp4\"\n\t\"github.com\/u-root\/dhcp4\/dhcp4opts\"\n)\n\n\/\/ Packet4 implements convenience functions for DHCPv4 packets.\ntype Packet4 struct {\n\tP *dhcp4.Packet\n}\n\n\/\/ NewPacket4 wraps a DHCPv4 packet with some convenience methods.\nfunc NewPacket4(p *dhcp4.Packet) *Packet4 {\n\treturn &Packet4{\n\t\tP: p,\n\t}\n}\n\n\/\/ Lease returns the IPNet assigned.\nfunc (p *Packet4) Lease() *net.IPNet {\n\tnetmask := dhcp4opts.GetSubnetMask(p.P.Options)\n\tif netmask == nil {\n\t\t\/\/ If they did not offer a subnet mask, we choose the most\n\t\t\/\/ restrictive option.\n\t\tnetmask = []byte{255, 255, 255, 255}\n\t}\n\n\treturn &net.IPNet{\n\t\tIP: p.P.YIAddr,\n\t\tMask: net.IPMask(netmask),\n\t}\n}\n\n\/\/ Gateway returns the gateway IP assigned.\n\/\/\n\/\/ OptionRouter is used as opposed to GIAddr, which seems unused by most DHCP\n\/\/ servers?\nfunc (p *Packet4) Gateway() net.IP {\n\tgw := dhcp4opts.GetRouters(p.P.Options)\n\tif gw == nil {\n\t\treturn nil\n\t}\n\treturn gw[0]\n}\n\n\/\/ DNS returns DNS IPs assigned.\nfunc (p *Packet4) DNS() []net.IP {\n\tips := dhcp4opts.GetDomainNameServers(p.P.Options)\n\tif ips == nil {\n\t\treturn nil\n\t}\n\treturn []net.IP(ips)\n}\n\n\/\/ Boot returns the boot file assigned.\nfunc (p *Packet4) Boot() (url.URL, error) {\n\t\/\/ TODO: This is not 100% right -- if a certain option is set, this\n\t\/\/ stuff is encoded in options instead of in the packet's BootFile and\n\t\/\/ ServerName fields.\n\n\t\/\/ While the default is tftp, servers may specify HTTP or FTP URIs.\n\tu, err := url.Parse(p.P.BootFile)\n\tif err != nil {\n\t\treturn url.URL{}, err\n\t}\n\n\tif len(u.Scheme) == 0 {\n\t\t\/\/ Defaults to tftp is not specified.\n\t\tu.Scheme = \"tftp\"\n\t\tu.Path = p.P.BootFile\n\t\tif len(p.P.ServerName) == 0 {\n\t\t\tserver := dhcp4opts.GetServerIdentifier(p.P.Options)\n\t\t\tif server == nil {\n\t\t\t\treturn url.URL{}, err\n\t\t\t}\n\t\t\tu.Host = net.IP(server).String()\n\t\t} else {\n\t\t\tu.Host = p.P.ServerName\n\t\t}\n\t}\n\treturn *u, nil\n}\n<|endoftext|>"} {"text":"package logging\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/hashicorp\/go-hclog\"\n)\n\n\/\/ This output is shown if a panic happens.\nconst panicOutput = `\n!!!!!!!!!!!!!!!!!!!!!!!!!!! TERRAFORM CRASH !!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nTerraform crashed! This is always indicative of a bug within Terraform.\nPlease report the crash with Terraform[1] so that we can fix this.\n\nWhen reporting bugs, please include your terraform version, the stack trace\nshown below, and any additional information which may help replicate the issue.\n\n[1]: https:\/\/github.com\/hashicorp\/terraform\/issues\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!! TERRAFORM CRASH !!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n`\n\n\/\/ PanicHandler is called to recover from an internal panic in Terraform, and\n\/\/ augments the standard stack trace with a more user friendly error message.\n\/\/ PanicHandler must be called as a defered function.\nfunc PanicHandler() {\n\trecovered := recover()\n\tif recovered == nil {\n\t\treturn\n\t}\n\n\tfmt.Fprint(os.Stderr, panicOutput)\n\tfmt.Fprint(os.Stderr, recovered)\n\n\t\/\/ When called from a deferred function, debug.PrintStack will include the\n\t\/\/ full stack from the point of the pending panic.\n\tdebug.PrintStack()\n\tos.Exit(2)\n}\n\nconst pluginPanicOutput = `\nStack trace from the %[1]s plugin:\n\n%s\n\nError: The %[1]s plugin crashed!\n\nThis is always indicative of a bug within the plugin. It would be immensely\nhelpful if you could report the crash with the plugin's maintainers so that it\ncan be fixed. The output above should help diagnose the issue.\n`\n\n\/\/ PluginPanics returns a series of provider panics that were collected during\n\/\/ execution, and formatted for output.\nfunc PluginPanics() []string {\n\treturn panics.allPanics()\n}\n\n\/\/ panicRecorder provides a registry to check for plugin panics that may have\n\/\/ happened when a plugin suddenly terminates.\ntype panicRecorder struct {\n\tsync.Mutex\n\n\t\/\/ panics maps the plugin name to the panic output lines received from\n\t\/\/ the logger.\n\tpanics map[string][]string\n\n\t\/\/ maxLines is the max number of lines we'll record after seeing a\n\t\/\/ panic header. Since this is going to be printed in the UI output, we\n\t\/\/ don't want to destroy the scrollback. In most cases, the first few lines\n\t\/\/ of the stack trace is all that are required.\n\tmaxLines int\n}\n\n\/\/ registerPlugin returns an accumulator function which will accept lines of\n\/\/ a panic stack trace to collect into an error when requested.\nfunc (p *panicRecorder) registerPlugin(name string) func(string) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\t\/\/ In most cases we shouldn't be starting a plugin if it already\n\t\/\/ panicked, but clear out previous entries just in case.\n\tdelete(p.panics, name)\n\n\tcount := 0\n\n\t\/\/ this callback is used by the logger to store panic output\n\treturn func(line string) {\n\t\tp.Lock()\n\t\tdefer p.Unlock()\n\n\t\t\/\/ stop recording if there are too many lines.\n\t\tif count > p.maxLines {\n\t\t\treturn\n\t\t}\n\t\tcount++\n\n\t\tp.panics[name] = append(p.panics[name], line)\n\t}\n}\n\nfunc (p *panicRecorder) allPanics() []string {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar res []string\n\tfor name, lines := range p.panics {\n\t\tif len(lines) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tres = append(res, fmt.Sprintf(pluginPanicOutput, name, strings.Join(lines, \"\\n\")))\n\t}\n\treturn res\n}\n\n\/\/ logPanicWrapper wraps an hclog.Logger and intercepts and records any output\n\/\/ that appears to be a panic.\ntype logPanicWrapper struct {\n\thclog.Logger\n\tpanicRecorder func(string)\n\tinPanic bool\n}\n\n\/\/ go-plugin will create a new named logger for each plugin binary.\nfunc (l *logPanicWrapper) Named(name string) hclog.Logger {\n\treturn &logPanicWrapper{\n\t\tLogger: l.Logger.Named(name),\n\t\tpanicRecorder: panics.registerPlugin(name),\n\t}\n}\n\n\/\/ we only need to implement Debug, since that is the default output level used\n\/\/ by go-plugin when encountering unstructured output on stderr.\nfunc (l *logPanicWrapper) Debug(msg string, args ...interface{}) {\n\t\/\/ We don't have access to the binary itself, so guess based on the stderr\n\t\/\/ output if this is the start of the traceback. An occasional false\n\t\/\/ positive shouldn't be a big deal, since this is only retrieved after an\n\t\/\/ error of some sort.\n\n\tpanicPrefix := strings.HasPrefix(msg, \"panic: \") || strings.HasPrefix(msg, \"fatal error: \")\n\n\tl.inPanic = l.inPanic || panicPrefix\n\n\tif l.inPanic && l.panicRecorder != nil {\n\t\tl.panicRecorder(msg)\n\t}\n\n\tl.Logger.Debug(msg, args...)\n}\nadd note about calling PanicHandler firstpackage logging\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/hashicorp\/go-hclog\"\n)\n\n\/\/ This output is shown if a panic happens.\nconst panicOutput = `\n!!!!!!!!!!!!!!!!!!!!!!!!!!! TERRAFORM CRASH !!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nTerraform crashed! This is always indicative of a bug within Terraform.\nPlease report the crash with Terraform[1] so that we can fix this.\n\nWhen reporting bugs, please include your terraform version, the stack trace\nshown below, and any additional information which may help replicate the issue.\n\n[1]: https:\/\/github.com\/hashicorp\/terraform\/issues\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!! TERRAFORM CRASH !!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n`\n\n\/\/ PanicHandler is called to recover from an internal panic in Terraform, and\n\/\/ augments the standard stack trace with a more user friendly error message.\n\/\/ PanicHandler must be called as a defered function, and must be the first\n\/\/ defer called at the start of a new goroutine.\nfunc PanicHandler() {\n\trecovered := recover()\n\tif recovered == nil {\n\t\treturn\n\t}\n\n\tfmt.Fprint(os.Stderr, panicOutput)\n\tfmt.Fprint(os.Stderr, recovered)\n\n\t\/\/ When called from a deferred function, debug.PrintStack will include the\n\t\/\/ full stack from the point of the pending panic.\n\tdebug.PrintStack()\n\tos.Exit(2)\n}\n\nconst pluginPanicOutput = `\nStack trace from the %[1]s plugin:\n\n%s\n\nError: The %[1]s plugin crashed!\n\nThis is always indicative of a bug within the plugin. It would be immensely\nhelpful if you could report the crash with the plugin's maintainers so that it\ncan be fixed. The output above should help diagnose the issue.\n`\n\n\/\/ PluginPanics returns a series of provider panics that were collected during\n\/\/ execution, and formatted for output.\nfunc PluginPanics() []string {\n\treturn panics.allPanics()\n}\n\n\/\/ panicRecorder provides a registry to check for plugin panics that may have\n\/\/ happened when a plugin suddenly terminates.\ntype panicRecorder struct {\n\tsync.Mutex\n\n\t\/\/ panics maps the plugin name to the panic output lines received from\n\t\/\/ the logger.\n\tpanics map[string][]string\n\n\t\/\/ maxLines is the max number of lines we'll record after seeing a\n\t\/\/ panic header. Since this is going to be printed in the UI output, we\n\t\/\/ don't want to destroy the scrollback. In most cases, the first few lines\n\t\/\/ of the stack trace is all that are required.\n\tmaxLines int\n}\n\n\/\/ registerPlugin returns an accumulator function which will accept lines of\n\/\/ a panic stack trace to collect into an error when requested.\nfunc (p *panicRecorder) registerPlugin(name string) func(string) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\t\/\/ In most cases we shouldn't be starting a plugin if it already\n\t\/\/ panicked, but clear out previous entries just in case.\n\tdelete(p.panics, name)\n\n\tcount := 0\n\n\t\/\/ this callback is used by the logger to store panic output\n\treturn func(line string) {\n\t\tp.Lock()\n\t\tdefer p.Unlock()\n\n\t\t\/\/ stop recording if there are too many lines.\n\t\tif count > p.maxLines {\n\t\t\treturn\n\t\t}\n\t\tcount++\n\n\t\tp.panics[name] = append(p.panics[name], line)\n\t}\n}\n\nfunc (p *panicRecorder) allPanics() []string {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tvar res []string\n\tfor name, lines := range p.panics {\n\t\tif len(lines) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tres = append(res, fmt.Sprintf(pluginPanicOutput, name, strings.Join(lines, \"\\n\")))\n\t}\n\treturn res\n}\n\n\/\/ logPanicWrapper wraps an hclog.Logger and intercepts and records any output\n\/\/ that appears to be a panic.\ntype logPanicWrapper struct {\n\thclog.Logger\n\tpanicRecorder func(string)\n\tinPanic bool\n}\n\n\/\/ go-plugin will create a new named logger for each plugin binary.\nfunc (l *logPanicWrapper) Named(name string) hclog.Logger {\n\treturn &logPanicWrapper{\n\t\tLogger: l.Logger.Named(name),\n\t\tpanicRecorder: panics.registerPlugin(name),\n\t}\n}\n\n\/\/ we only need to implement Debug, since that is the default output level used\n\/\/ by go-plugin when encountering unstructured output on stderr.\nfunc (l *logPanicWrapper) Debug(msg string, args ...interface{}) {\n\t\/\/ We don't have access to the binary itself, so guess based on the stderr\n\t\/\/ output if this is the start of the traceback. An occasional false\n\t\/\/ positive shouldn't be a big deal, since this is only retrieved after an\n\t\/\/ error of some sort.\n\n\tpanicPrefix := strings.HasPrefix(msg, \"panic: \") || strings.HasPrefix(msg, \"fatal error: \")\n\n\tl.inPanic = l.inPanic || panicPrefix\n\n\tif l.inPanic && l.panicRecorder != nil {\n\t\tl.panicRecorder(msg)\n\t}\n\n\tl.Logger.Debug(msg, args...)\n}\n<|endoftext|>"} {"text":"package wallaby\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/eliquious\/xbinary\"\n)\n\n\/\/ IndexFactory creates an index. The reason for this is solely for future growth... perhaps a bit premature. The main reason is for future versions of log files or different backing stores.\ntype IndexFactory interface {\n\tGetOrCreateIndex(flags uint32) (*LogIndex, error)\n}\n\n\/\/ LogIndex maintains a list of all the records in the log file. IndexRecords\ntype LogIndex interface {\n\tSize() uint64\n\tHeader() FileHeader\n\tAppend(record IndexRecord) (n int, err error)\n\tSlice(offset int64, limit int64) (IndexSlice, error)\n\tFlush() error\n\tClose() error\n}\n\n\/\/ FileHeader describes which version the file was written with. Flags\n\/\/ represents boolean flags.\ntype FileHeader interface {\n\tVersion() uint8\n\tFlags() uint32\n}\n\n\/\/ IndexSlice contains several buffered index records for fast access.\ntype IndexSlice interface {\n\tGet(index int) (IndexRecord, error)\n\tSize() int\n}\n\n\/\/ IndexRecord describes each item in an index file.\ntype IndexRecord interface {\n\tTime() int64\n\tIndex() uint64\n\tOffset() int64\n\tTimeToLive() uint64\n\tIsExpired() bool\n}\n\n\/\/ BasicIndexRecord implements the bare IndexRecord interface.\ntype BasicIndexRecord struct {\n\tnanos int64\n\tindex uint64\n\toffset int64\n\tttl uint64\n}\n\n\/\/ Time returns when the record was written to the data file.\nfunc (i BasicIndexRecord) Time() int64 {\n\treturn i.nanos\n}\n\n\/\/ Index is a record's numerical id.\nfunc (i BasicIndexRecord) Index() uint64 {\n\treturn i.index\n}\n\n\/\/ Offset is the distance the data record is from the start of the data file.\nfunc (i BasicIndexRecord) Offset() int64 {\n\treturn i.offset\n}\n\n\/\/ TimeToLive allows for records to expire after a period of time. TTL is in\n\/\/ seconds.\nfunc (i BasicIndexRecord) TimeToLive() uint64 {\n\treturn i.ttl\n}\n\n\/\/ IsExpired is a helper function for the index record which returns `true` if\n\/\/ the current time is beyond the expiration time. The expiration time is\n\/\/ calculated as written time + TTL.\nfunc (i BasicIndexRecord) IsExpired() bool {\n\treturn time.Now().After(time.Unix(i.nanos, 0).Add(time.Duration(i.ttl)))\n}\n\n\/\/ BasicFileHeader is the simplest implementation of the FileHeader interface.\ntype BasicFileHeader struct {\n\tversion uint8\n\tflags uint32\n}\n\n\/\/ Version returns the file version.\nfunc (i BasicFileHeader) Version() uint8 {\n\treturn i.version\n}\n\n\/\/ Flags returns the boolean flags for the file.\nfunc (i BasicFileHeader) Flags() uint32 {\n\treturn i.flags\n}\n\n\/\/ VersionOneIndexRecord implements the bare IndexRecord interface.\ntype VersionOneIndexRecord struct {\n\tbuffer *[]byte\n\toffset int\n}\n\n\/\/ Time returns when the record was written to the data file.\nfunc (i VersionOneIndexRecord) Time() int64 {\n\tnanos, err := xbinary.LittleEndian.Int64(*i.buffer, 0+i.offset)\n\tif err != nil {\n\t\tnanos = 0\n\t}\n\n\treturn nanos\n}\n\n\/\/ Index is a record's numerical id.\nfunc (i VersionOneIndexRecord) Index() uint64 {\n\tindex, err := xbinary.LittleEndian.Uint64(*i.buffer, 8+i.offset)\n\tif err != nil {\n\t\tindex = 0\n\t}\n\n\treturn index\n}\n\n\/\/ Offset is the distance the data record is from the start of the data file.\nfunc (i VersionOneIndexRecord) Offset() int64 {\n\toffset, err := xbinary.LittleEndian.Int64(*i.buffer, 16+i.offset)\n\tif err != nil {\n\t\toffset = 0\n\t}\n\n\treturn offset\n}\n\n\/\/ TimeToLive allows for records to expire after a period of time. TTL is in\n\/\/ seconds.\nfunc (i VersionOneIndexRecord) TimeToLive() uint64 {\n\tttl, err := xbinary.LittleEndian.Uint64(*i.buffer, 24+i.offset)\n\tif err != nil {\n\t\tttl = 0\n\t}\n\n\treturn ttl\n}\n\n\/\/ IsExpired is a helper function for the index record which returns `true` if\n\/\/ the current time is beyond the expiration time. The expiration time is\n\/\/ calculated as written time + TTL.\nfunc (i VersionOneIndexRecord) IsExpired() bool {\n\treturn time.Now().After(time.Unix(i.Time(), 0).Add(time.Duration(i.TimeToLive())))\n}\n\n\/\/ VersionOneIndexFactory creates index files of v1.\ntype VersionOneIndexFactory struct {\n\tFilename string\n}\n\n\/\/ GetOrCreateIndex either creates a new file or reads from an existing index\n\/\/ file.\n\/\/\n\/\/ VersionOneLogHeader starts with a 3-byte string, \"IDX\", followed by an 8-bit\n\/\/ version. After the version, a uint32 represents the boolean flags.\n\/\/ The records start immediately following the bit flags.\nfunc (f VersionOneIndexFactory) GetOrCreateIndex(flags uint32) (LogIndex, error) {\n\n\t\/\/ try to open index file, return error on fail\n\tfile, err := os.OpenFile(f.Filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ get file stat, close file and return on error\n\tstat, err := file.Stat()\n\tif err != nil {\n\t\tfile.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ get header, close file and return on error\n\tbuf := make([]byte, VersionOneIndexHeaderSize)\n\tvar header BasicFileHeader\n\tvar size uint64\n\n\t\/\/ if file already has header\n\tif stat.Size() >= VersionOneIndexHeaderSize {\n\n\t\t\/\/ read file header, close and return upon error\n\t\tn, err := file.ReadAt(buf, 0)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\n\t\t\t\/\/ failed to read entire header\n\t\t} else if n != VersionOneIndexHeaderSize {\n\t\t\tfile.Close()\n\t\t\treturn nil, ErrReadIndexHeader\n\t\t}\n\n\t\t\/\/ read flags\n\t\tflags, err := xbinary.LittleEndian.Uint32(buf, 4)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ create header\n\t\theader = BasicFileHeader{flags: flags, version: buf[3]}\n\n\t\tsize = (uint64(stat.Size()) - uint64(VersionOneIndexHeaderSize)) \/ uint64(VersionOneIndexRecordSize)\n\t} else {\n\n\t\t\/\/ write magic string\n\t\txbinary.LittleEndian.PutString(buf, 0, \"IDX\")\n\n\t\t\/\/ write version\n\t\tbuf[3] = byte(VersionOne)\n\n\t\t\/\/ write boolean flags\n\t\txbinary.LittleEndian.PutUint32(buf, 4, flags)\n\n\t\t\/\/ write index header to file\n\t\t_, err := file.Write(buf)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ flush data to disk\n\t\terr = file.Sync()\n\t\tif err != nil {\n\t\t\treturn nil, ErrWriteIndexHeader\n\t\t}\n\n\t\t\/\/ create index header\n\t\theader = BasicFileHeader{VersionOne, flags}\n\n\t}\n\n\tvar lock sync.Mutex\n\twriter := bufio.NewWriterSize(file, 64*1024)\n\tidx := VersionOneIndexFile{\n\t\tfd: file,\n\t\twriter: writer,\n\t\theader: header,\n\t\tmutex: lock,\n\t\textbuf: xbinary.LittleEndian,\n\t\tsize: &size,\n\t\tbuffer: make([]byte, VersionOneIndexRecordSize)}\n\treturn idx, nil\n}\n\n\/\/ VersionOneIndexFile implements the IndexFile interface and is created by VersionOneIndexFactory.\ntype VersionOneIndexFile struct {\n\tfd *os.File\n\twriter *bufio.Writer\n\theader BasicFileHeader\n\tmutex sync.Mutex\n\textbuf xbinary.ExtendedBuffer\n\tsize *uint64\n\tbuffer []byte\n}\n\n\/\/ Flush writes any buffered data onto permanant storage.\nfunc (i VersionOneIndexFile) Flush() error {\n\ti.writer.Flush()\n\n\t\/\/ sync changes to disk\n\terr := i.fd.Sync()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Close flushed the index with permanant storage and closes the index.\nfunc (i VersionOneIndexFile) Close() error {\n\terr := i.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.fd.Close()\n}\n\n\/\/ Append adds an index record to the end of the index file. V1 index records have a time, an index and an offset in the data file.\nfunc (i VersionOneIndexFile) Append(record IndexRecord) (n int, err error) {\n\ti.mutex.Lock()\n\tdefer i.mutex.Unlock()\n\n\t\/\/ create buffer and byte count\n\tvar written int\n\n\t\/\/ write time\n\tn, _ = i.extbuf.PutInt64(i.buffer, 0, record.Time())\n\twritten += n\n\n\t\/\/ write index\n\tn, _ = i.extbuf.PutUint64(i.buffer, 8, record.Index())\n\twritten += n\n\n\t\/\/ write byte offset in record file\n\tn, _ = i.extbuf.PutInt64(i.buffer, 16, record.Offset())\n\twritten += n\n\n\t\/\/ check bytes written\n\tif written < VersionOneIndexRecordSize {\n\t\treturn written, ErrWriteIndexHeader\n\t}\n\n\t\/\/ write index buffer to file\n\tn, err = i.writer.Write(i.buffer)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\t\/\/ increment index size\n\ti.incrementSize()\n\n\t\/\/ return num bytes and nil error\n\treturn written, nil\n}\n\n\/\/ IncrementSize bumps the index size by one.\nfunc (i *VersionOneIndexFile) incrementSize() {\n\t\/\/ *i.size++\n\tatomic.AddUint64(i.size, 1)\n}\n\n\/\/ Size is the number of elements in the index. Which should coorespond with the number of records in the data file.\nfunc (i VersionOneIndexFile) Size() uint64 {\n\treturn atomic.LoadUint64(i.size)\n}\n\n\/\/ Header returns the file header which describes the index file.\nfunc (i VersionOneIndexFile) Header() FileHeader {\n\treturn i.header\n}\n\n\/\/ Slice returns multiple index records starting at the given offset.\nfunc (i VersionOneIndexFile) Slice(offset int64, limit int64) (IndexSlice, error) {\n\n\t\/\/ get size\n\tvar size = atomic.LoadUint64(i.size)\n\n\t\/\/ offset too or less than 0\n\tif offset > int64(size) || offset < 0 {\n\t\treturn nil, ErrSliceOutOfBounds\n\n\t\t\/\/ invalid limit\n\t} else if limit < 1 {\n\t\treturn nil, ErrSliceOutOfBounds\n\t}\n\n\tvar buf []byte\n\t\/\/ requested slice too large\n\tif limit > MaximumIndexSlice {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*MaximumIndexSlice)\n\n\t\t\/\/ request exceeds index size\n\t} else if uint64(offset+limit) > size {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*(uint64(offset+limit)-(size)))\n\n\t\t\/\/ full request can be satisfied\n\t} else {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*limit)\n\t}\n\n\t\/\/ read records into buffer\n\tread, err := i.fd.ReadAt(buf, int64(offset*VersionOneIndexRecordSize)+VersionOneIndexHeaderSize)\n\tif err != nil {\n\t\treturn nil, ErrReadIndex\n\t}\n\n\treturn VersionOneIndexSlice{buf, read \/ VersionOneIndexRecordSize}, nil\n}\n\n\/\/ VersionOneIndexSlice provides for retrieval of buffered index records\ntype VersionOneIndexSlice struct {\n\tbuffer []byte\n\tsize int\n}\n\n\/\/ Size returns the number of records in this slice.\nfunc (s VersionOneIndexSlice) Size() int {\n\treturn s.size\n}\n\n\/\/ Get returns a particular index record. ErrSliceOutOfBounds is returned is the record index given is < 0 or greater than the size of the slice.\nfunc (s VersionOneIndexSlice) Get(index int) (IndexRecord, error) {\n\tif index > s.size || index < 0 {\n\t\treturn nil, ErrSliceOutOfBounds\n\t}\n\n\treturn VersionOneIndexRecord{&s.buffer, index * VersionOneIndexRecordSize}, nil\n}\n\nfunc (s VersionOneIndexSlice) MarshalBinary() (data []byte, err error) {\n\treturn s.buffer, nil\n}\nMinor refactoring of Index related data structurespackage wallaby\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/eliquious\/xbinary\"\n)\n\n\/\/ IndexFactory creates an index. The reason for this is solely for future growth... perhaps a bit premature. The main reason is for future versions of log files or different backing stores.\n\/\/ type IndexFactory interface {\n\/\/ \tGetOrCreateIndex(flags uint32) (*LogIndex, error)\n\/\/ }\ntype IndexFactory func(filename string, version uint8, flags uint32) (LogIndex, error)\n\n\/\/ LogIndex maintains a list of all the records in the log file. IndexRecords\ntype LogIndex interface {\n\tSize() uint64\n\tHeader() FileHeader\n\tAppend(record IndexRecord) (n int, err error)\n\tSlice(offset int64, limit int64) (IndexSlice, error)\n\tFlush() error\n\tClose() error\n}\n\n\/\/ FileHeader describes which version the file was written with. Flags\n\/\/ represents boolean flags.\ntype FileHeader interface {\n\tVersion() uint8\n\tFlags() uint32\n}\n\n\/\/ IndexSlice contains several buffered index records for fast access.\ntype IndexSlice interface {\n\tGet(index int) (IndexRecord, error)\n\tSize() int\n}\n\n\/\/ IndexRecord describes each item in an index file.\ntype IndexRecord interface {\n\tTime() int64\n\tIndex() uint64\n\tOffset() int64\n\tTimeToLive() int64\n\tIsExpired() bool\n}\n\n\/\/ BasicIndexRecord implements the bare IndexRecord interface.\ntype BasicIndexRecord struct {\n\tnanos int64\n\tindex uint64\n\toffset int64\n\tttl int64\n}\n\n\/\/ Time returns when the record was written to the data file.\nfunc (i BasicIndexRecord) Time() int64 {\n\treturn i.nanos\n}\n\n\/\/ Index is a record's numerical id.\nfunc (i BasicIndexRecord) Index() uint64 {\n\treturn i.index\n}\n\n\/\/ Offset is the distance the data record is from the start of the data file.\nfunc (i BasicIndexRecord) Offset() int64 {\n\treturn i.offset\n}\n\n\/\/ TimeToLive allows for records to expire after a period of time. TTL is in\n\/\/ seconds.\nfunc (i BasicIndexRecord) TimeToLive() int64 {\n\treturn i.ttl\n}\n\n\/\/ IsExpired is a helper function for the index record which returns `true` if\n\/\/ the current time is beyond the expiration time. The expiration time is\n\/\/ calculated as written time + TTL.\nfunc (i BasicIndexRecord) IsExpired() bool {\n\treturn time.Now().After(time.Unix(i.nanos, 0).Add(time.Duration(i.ttl)))\n}\n\n\/\/ BasicFileHeader is the simplest implementation of the FileHeader interface.\ntype BasicFileHeader struct {\n\tversion uint8\n\tflags uint32\n}\n\n\/\/ Version returns the file version.\nfunc (i BasicFileHeader) Version() uint8 {\n\treturn i.version\n}\n\n\/\/ Flags returns the boolean flags for the file.\nfunc (i BasicFileHeader) Flags() uint32 {\n\treturn i.flags\n}\n\n\/\/ VersionOneIndexRecord implements the bare IndexRecord interface.\ntype VersionOneIndexRecord struct {\n\tbuffer *[]byte\n\toffset int\n}\n\n\/\/ Time returns when the record was written to the data file.\nfunc (i VersionOneIndexRecord) Time() int64 {\n\tnanos, err := xbinary.LittleEndian.Int64(*i.buffer, 0+i.offset)\n\tif err != nil {\n\t\tnanos = 0\n\t}\n\n\treturn nanos\n}\n\n\/\/ Index is a record's numerical id.\nfunc (i VersionOneIndexRecord) Index() uint64 {\n\tindex, err := xbinary.LittleEndian.Uint64(*i.buffer, 8+i.offset)\n\tif err != nil {\n\t\tindex = 0\n\t}\n\n\treturn index\n}\n\n\/\/ Offset is the distance the data record is from the start of the data file.\nfunc (i VersionOneIndexRecord) Offset() int64 {\n\toffset, err := xbinary.LittleEndian.Int64(*i.buffer, 16+i.offset)\n\tif err != nil {\n\t\toffset = 0\n\t}\n\n\treturn offset\n}\n\n\/\/ TimeToLive allows for records to expire after a period of time. TTL is in\n\/\/ seconds.\nfunc (i VersionOneIndexRecord) TimeToLive() int64 {\n\tttl, err := xbinary.LittleEndian.Int64(*i.buffer, 24+i.offset)\n\tif err != nil {\n\t\tttl = 0\n\t}\n\n\treturn ttl\n}\n\n\/\/ IsExpired is a helper function for the index record which returns `true` if\n\/\/ the current time is beyond the expiration time. The expiration time is\n\/\/ calculated as written time + TTL.\nfunc (i VersionOneIndexRecord) IsExpired() bool {\n\treturn time.Now().UnixNano() > i.Time()+i.TimeToLive()\n}\n\n\/\/ GetOrCreateIndex either creates a new file or reads from an existing index\n\/\/ file.\n\/\/\n\/\/ VersionOneLogHeader starts with a 3-byte string, \"IDX\", followed by an 8-bit\n\/\/ version. After the version, a uint32 represents the boolean flags.\n\/\/ The records start immediately following the bit flags.\nfunc VersionOneIndexFactory(filename string, version uint8, flags uint32) (LogIndex, error) {\n\n\t\/\/ try to open index file, return error on fail\n\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ get file stat, close file and return on error\n\tstat, err := file.Stat()\n\tif err != nil {\n\t\tfile.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ get header, close file and return on error\n\tbuf := make([]byte, VersionOneIndexHeaderSize)\n\tvar header BasicFileHeader\n\tvar size uint64\n\n\t\/\/ if file already has header\n\tif stat.Size() >= VersionOneIndexHeaderSize {\n\n\t\t\/\/ read file header, close and return upon error\n\t\tn, err := file.ReadAt(buf, 0)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\n\t\t\t\/\/ failed to read entire header\n\t\t} else if n != VersionOneIndexHeaderSize {\n\t\t\tfile.Close()\n\t\t\treturn nil, ErrReadIndexHeader\n\t\t}\n\n\t\t\/\/ read flags\n\t\tflags, err := xbinary.LittleEndian.Uint32(buf, 4)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ create header\n\t\theader = BasicFileHeader{flags: flags, version: buf[3]}\n\n\t\tsize = (uint64(stat.Size()) - uint64(VersionOneIndexHeaderSize)) \/ uint64(VersionOneIndexRecordSize)\n\t} else {\n\n\t\t\/\/ write magic string\n\t\txbinary.LittleEndian.PutString(buf, 0, string(IndexFileSignature))\n\n\t\t\/\/ write version\n\t\tbuf[3] = byte(VersionOne)\n\n\t\t\/\/ write boolean flags\n\t\txbinary.LittleEndian.PutUint32(buf, 4, flags)\n\n\t\t\/\/ write index header to file\n\t\t_, err := file.Write(buf)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ flush data to disk\n\t\terr = file.Sync()\n\t\tif err != nil {\n\t\t\treturn nil, ErrWriteIndexHeader\n\t\t}\n\n\t\t\/\/ create index header\n\t\theader = BasicFileHeader{VersionOne, flags}\n\n\t}\n\n\tvar lock sync.Mutex\n\twriter := bufio.NewWriterSize(file, 64*1024)\n\tidx := VersionOneIndexFile{\n\t\tfd: file,\n\t\twriter: writer,\n\t\theader: header,\n\t\tmutex: lock,\n\t\textbuf: xbinary.LittleEndian,\n\t\tsize: &size,\n\t\tbuffer: make([]byte, VersionOneIndexRecordSize)}\n\treturn idx, nil\n}\n\n\/\/ VersionOneIndexFile implements the IndexFile interface and is created by VersionOneIndexFactory.\ntype VersionOneIndexFile struct {\n\tfd *os.File\n\twriter *bufio.Writer\n\theader BasicFileHeader\n\tmutex sync.Mutex\n\textbuf xbinary.ExtendedBuffer\n\tsize *uint64\n\tbuffer []byte\n}\n\n\/\/ Flush writes any buffered data onto permanant storage.\nfunc (i VersionOneIndexFile) Flush() error {\n\ti.writer.Flush()\n\n\t\/\/ sync changes to disk\n\terr := i.fd.Sync()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Close flushed the index with permanant storage and closes the index.\nfunc (i VersionOneIndexFile) Close() error {\n\terr := i.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.fd.Close()\n}\n\n\/\/ Append adds an index record to the end of the index file. V1 index records have a time, an index and an offset in the data file.\nfunc (i VersionOneIndexFile) Append(record IndexRecord) (n int, err error) {\n\ti.mutex.Lock()\n\tdefer i.mutex.Unlock()\n\n\t\/\/ create buffer and byte count\n\tvar written int\n\n\t\/\/ write time\n\tn, _ = i.extbuf.PutInt64(i.buffer, 0, record.Time())\n\twritten += n\n\n\t\/\/ write index\n\tn, _ = i.extbuf.PutUint64(i.buffer, 8, record.Index())\n\twritten += n\n\n\t\/\/ write byte offset in record file\n\tn, _ = i.extbuf.PutInt64(i.buffer, 16, record.Offset())\n\twritten += n\n\n\t\/\/ write ttl\n\tn, _ = i.extbuf.PutInt64(i.buffer, 24, record.TimeToLive())\n\twritten += n\n\n\t\/\/ check bytes written\n\tif written < VersionOneIndexRecordSize {\n\t\treturn written, ErrWriteIndexHeader\n\t}\n\n\t\/\/ write index buffer to file\n\tn, err = i.writer.Write(i.buffer)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\t\/\/ increment index size\n\ti.incrementSize()\n\n\t\/\/ return num bytes and nil error\n\treturn written, nil\n}\n\n\/\/ IncrementSize bumps the index size by one.\nfunc (i *VersionOneIndexFile) incrementSize() {\n\t\/\/ *i.size++\n\tatomic.AddUint64(i.size, 1)\n}\n\n\/\/ Size is the number of elements in the index. Which should coorespond with the number of records in the data file.\nfunc (i VersionOneIndexFile) Size() uint64 {\n\treturn atomic.LoadUint64(i.size)\n}\n\n\/\/ Header returns the file header which describes the index file.\nfunc (i VersionOneIndexFile) Header() FileHeader {\n\treturn i.header\n}\n\n\/\/ Slice returns multiple index records starting at the given offset.\nfunc (i VersionOneIndexFile) Slice(offset int64, limit int64) (IndexSlice, error) {\n\n\t\/\/ get size\n\tvar size = atomic.LoadUint64(i.size)\n\n\t\/\/ offset too or less than 0\n\tif offset > int64(size) || offset < 0 {\n\t\treturn nil, ErrSliceOutOfBounds\n\n\t\t\/\/ invalid limit\n\t} else if limit < 1 {\n\t\treturn nil, ErrSliceOutOfBounds\n\t}\n\n\tvar buf []byte\n\t\/\/ requested slice too large\n\tif limit > MaximumIndexSlice {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*MaximumIndexSlice)\n\n\t\t\/\/ request exceeds index size\n\t} else if uint64(offset+limit) > size {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*(uint64(offset+limit)-(size)))\n\n\t\t\/\/ full request can be satisfied\n\t} else {\n\t\tbuf = make([]byte, VersionOneIndexRecordSize*limit)\n\t}\n\n\t\/\/ read records into buffer\n\tread, err := i.fd.ReadAt(buf, int64(offset*VersionOneIndexRecordSize)+VersionOneIndexHeaderSize)\n\tif err != nil {\n\t\treturn nil, ErrReadIndex\n\t}\n\n\treturn VersionOneIndexSlice{buf, read \/ VersionOneIndexRecordSize}, nil\n}\n\n\/\/ VersionOneIndexSlice provides for retrieval of buffered index records\ntype VersionOneIndexSlice struct {\n\tbuffer []byte\n\tsize int\n}\n\n\/\/ Size returns the number of records in this slice.\nfunc (s VersionOneIndexSlice) Size() int {\n\treturn s.size\n}\n\n\/\/ Get returns a particular index record. ErrSliceOutOfBounds is returned is the record index given is < 0 or greater than the size of the slice.\nfunc (s VersionOneIndexSlice) Get(index int) (IndexRecord, error) {\n\tif index > s.size || index < 0 {\n\t\treturn nil, ErrSliceOutOfBounds\n\t}\n\n\treturn VersionOneIndexRecord{&s.buffer, index * VersionOneIndexRecordSize}, nil\n}\n\nfunc (s VersionOneIndexSlice) MarshalBinary() (data []byte, err error) {\n\treturn s.buffer, nil\n}\n<|endoftext|>"} {"text":"package rest\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ Resource represents a domain model.\ntype Resource interface{}\n\n\/\/ ResourceHandler specifies the endpoint handlers for working with a resource. This\n\/\/ consists of the business logic for performing CRUD operations.\ntype ResourceHandler interface {\n\t\/\/ ResourceName is used to identify what resource a handler corresponds to and is\n\t\/\/ used in the endpoint URLs, i.e. \/api\/:version\/resourceName. This should be\n\t\/\/ unique across all ResourceHandlers.\n\tResourceName() string\n\n\t\/\/ CreateURI returns the URI for creating a resource.\n\tCreateURI() string\n\n\t\/\/ ReadURI returns the URI for reading a specific resource.\n\tReadURI() string\n\n\t\/\/ ReadListURI returns the URI for reading a list of resources.\n\tReadListURI() string\n\n\t\/\/ UpdateURI returns the URI for updating a specific resource.\n\tUpdateURI() string\n\n\t\/\/ UpdateListURI returns the URI for updating a list of resources.\n\tUpdateListURI() string\n\n\t\/\/ DeleteURI returns the URI for deleting a specific resource.\n\tDeleteURI() string\n\n\t\/\/ CreateResource is the logic that corresponds to creating a new resource at\n\t\/\/ POST \/api\/:version\/resourceName. Typically, this would insert a record into a\n\t\/\/ database. It returns the newly created resource or an error if the create failed.\n\tCreateResource(RequestContext, Payload, string) (Resource, error)\n\n\t\/\/ ReadResourceList is the logic that corresponds to reading multiple resources,\n\t\/\/ perhaps with specified query parameters accessed through the RequestContext. This\n\t\/\/ is mapped to GET \/api\/:version\/resourceName. Typically, this would make some sort\n\t\/\/ of database query to fetch the resources. It returns the slice of results, a\n\t\/\/ cursor (or empty) string, and error (or nil).\n\tReadResourceList(RequestContext, int, string, string) ([]Resource, string, error)\n\n\t\/\/ ReadResource is the logic that corresponds to reading a single resource by its ID\n\t\/\/ at GET \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database query to load the resource. If the resource doesn't exist, nil should be\n\t\/\/ returned along with an appropriate error.\n\tReadResource(RequestContext, string, string) (Resource, error)\n\n\t\/\/ UpdateResourceList is the logic that corresponds to updating a collection of\n\t\/\/ resources at PUT \/api\/:version\/resourceName. Typically, this would make some\n\t\/\/ sort of database update call. It returns the updated resources or an error if\n\t\/\/ the update failed.\n\tUpdateResourceList(RequestContext, []Payload, string) ([]Resource, error)\n\n\t\/\/ UpdateResource is the logic that corresponds to updating an existing resource at\n\t\/\/ PUT \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database update call. It returns the updated resource or an error if the update\n\t\/\/ failed.\n\tUpdateResource(RequestContext, string, Payload, string) (Resource, error)\n\n\t\/\/ DeleteResource is the logic that corresponds to deleting an existing resource at\n\t\/\/ DELETE \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database delete call. It returns the deleted resource or an error if the delete\n\t\/\/ failed.\n\tDeleteResource(RequestContext, string, string) (Resource, error)\n\n\t\/\/ Authenticate is logic that is used to authenticate requests. The default behavior\n\t\/\/ of Authenticate, seen in BaseResourceHandler, always returns nil, meaning all\n\t\/\/ requests are authenticated. Returning an error means that the request is\n\t\/\/ unauthorized and any error message will be sent back with the response.\n\tAuthenticate(*http.Request) error\n\n\t\/\/ Rules returns the resource rules to apply to incoming requests and outgoing\n\t\/\/ responses. The default behavior, seen in BaseResourceHandler, is to apply no\n\t\/\/ rules.\n\tRules() Rules\n}\n\n\/\/ requestHandler constructs http.HandlerFuncs responsible for handling HTTP requests.\ntype requestHandler struct {\n\tAPI\n}\n\n\/\/ handleCreate returns a HandlerFunc which will deserialize the request payload, pass\n\/\/ it to the provided create function, and then serialize and dispatch the response.\n\/\/ The serialization mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleCreate(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tdata, err := decodePayload(payloadString(r.Body))\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(err)\n\t\t\tctx = ctx.setStatus(http.StatusInternalServerError)\n\t\t} else {\n\t\t\tdata, err := applyInboundRules(data, rules)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresource, err := handler.CreateResource(ctx, data, ctx.Version())\n\t\t\t\tif err == nil {\n\t\t\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t\t\t}\n\t\t\t\tctx = ctx.setResult(resource)\n\t\t\t\tctx = ctx.setStatus(http.StatusCreated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx = ctx.setError(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleReadList returns a HandlerFunc which will pass the request context to the\n\/\/ provided read function and then serialize and dispatch the response. The\n\/\/ serialization mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleReadList(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresources, cursor, err := handler.ReadResourceList(\n\t\t\tctx, ctx.Limit(), ctx.Cursor(), version)\n\n\t\tif err == nil {\n\t\t\t\/\/ Apply rules to results.\n\t\t\tfor idx, resource := range resources {\n\t\t\t\tresources[idx] = applyOutboundRules(resource, rules)\n\t\t\t}\n\t\t}\n\n\t\tctx = ctx.setResult(resources)\n\t\tctx = ctx.setCursor(cursor)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleRead returns a HandlerFunc which will pass the resource id to the provided\n\/\/ read function and then serialize and dispatch the response. The serialization\n\/\/ mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleRead(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresource, err := handler.ReadResource(ctx, ctx.ResourceID(), version)\n\t\tif err == nil {\n\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t}\n\n\t\tctx = ctx.setResult(resource)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleUpdateList returns a HandlerFunc which will deserialize the request payload,\n\/\/ pass it to the provided update function, and then serialize and dispatch the\n\/\/ response. The serialization mechanism used is specified by the \"format\" query\n\/\/ parameter.\nfunc (h requestHandler) handleUpdateList(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tpayloadStr := payloadString(r.Body)\n\t\tvar data []Payload\n\t\tvar err error\n\t\tdata, err = decodePayloadSlice(payloadStr)\n\t\tif err != nil {\n\t\t\tvar p Payload\n\t\t\tp, err = decodePayload(payloadStr)\n\t\t\tdata = []Payload{p}\n\t\t\tfmt.Println(data)\n\t\t}\n\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(BadRequest(err.Error()))\n\t\t} else {\n\t\t\tfor i := range data {\n\t\t\t\tdata[i], err = applyInboundRules(data[i], rules)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresources, err := handler.UpdateResourceList(ctx, data, version)\n\t\t\t\tif err == nil {\n\t\t\t\t\t\/\/ Apply rules to results.\n\t\t\t\t\tfor idx, resource := range resources {\n\t\t\t\t\t\tresources[idx] = applyOutboundRules(resource, rules)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctx = ctx.setResult(resources)\n\t\t\t\tctx = ctx.setError(err)\n\t\t\t\tctx = ctx.setStatus(http.StatusOK)\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleUpdate returns a HandlerFunc which will deserialize the request payload,\n\/\/ pass it to the provided update function, and then serialize and dispatch the\n\/\/ response. The serialization mechanism used is specified by the \"format\" query\n\/\/ parameter.\nfunc (h requestHandler) handleUpdate(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tdata, err := decodePayload(payloadString(r.Body))\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(err)\n\t\t\tctx = ctx.setStatus(http.StatusInternalServerError)\n\t\t} else {\n\t\t\tdata, err := applyInboundRules(data, rules)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresource, err := handler.UpdateResource(\n\t\t\t\t\tctx, ctx.ResourceID(), data, version)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t\t\t}\n\n\t\t\t\tctx = ctx.setResult(resource)\n\t\t\t\tctx = ctx.setError(err)\n\t\t\t\tctx = ctx.setStatus(http.StatusOK)\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleDelete returns a HandlerFunc which will pass the resource id to the provided\n\/\/ delete function and then serialize and dispatch the response. The serialization\n\/\/ mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleDelete(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresource, err := handler.DeleteResource(ctx, ctx.ResourceID(), version)\n\t\tif err == nil {\n\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t}\n\n\t\tctx = ctx.setResult(resource)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ sendResponse writes a success or error response to the provided http.ResponseWriter\n\/\/ based on the contents of the RequestContext.\nfunc (h requestHandler) sendResponse(w http.ResponseWriter, ctx RequestContext) {\n\tstatus := ctx.Status()\n\trequestError := ctx.Error()\n\tresult := ctx.Result()\n\tformat := ctx.ResponseFormat()\n\n\tserializer, err := h.responseSerializer(format)\n\tif err != nil {\n\t\t\/\/ Fall back to json serialization.\n\t\tserializer = jsonSerializer{}\n\t\trequestError = NotImplemented(fmt.Sprintf(\"Format not implemented: %s\", format))\n\t}\n\n\tvar response response\n\tif requestError != nil {\n\t\tresponse = NewErrorResponse(requestError)\n\t} else {\n\t\tnextURL, _ := ctx.NextURL()\n\t\tresponse = NewSuccessResponse(result, status, nextURL)\n\t}\n\n\tsendResponse(w, response, serializer)\n}\n\n\/\/ sendResponse writes a response to the http.ResponseWriter.\nfunc sendResponse(w http.ResponseWriter, r response, serializer ResponseSerializer) {\n\tstatus := r.Status\n\tcontentType := serializer.ContentType()\n\tresponse, err := serializer.Serialize(r.Payload)\n\tif err != nil {\n\t\tlog.Printf(\"Response serialization failed: %s\", err)\n\t\tstatus = http.StatusInternalServerError\n\t\tcontentType = \"text\/plain\"\n\t\tresponse = []byte(err.Error())\n\t}\n\n\tw.Header().Set(\"Content-Type\", contentType)\n\tw.WriteHeader(status)\n\tw.Write(response)\n}\n\n\/\/ rulesForVersion returns a slice of Rules which apply to the given version.\nfunc rulesForVersion(r Rules, version string) Rules {\n\tif r == nil {\n\t\treturn &rules{}\n\t}\n\n\tfiltered := make([]*Rule, 0, r.Size())\n\tfor _, rule := range r.Contents() {\n\t\tif rule.Applies(version) {\n\t\t\tfiltered = append(filtered, rule)\n\t\t}\n\t}\n\n\treturn &rules{contents: filtered, resourceType: r.ResourceType()}\n}\n\n\/\/ decodePayload unmarshals the JSON payload and returns the resulting map. If the\n\/\/ content is empty, an empty map is returned. If decoding fails, nil is returned\n\/\/ with an error.\nfunc decodePayload(payload []byte) (Payload, error) {\n\tif len(payload) == 0 {\n\t\treturn map[string]interface{}{}, nil\n\t}\n\n\tvar data Payload\n\tif err := json.Unmarshal(payload, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\n\/\/ decodePayloadSlice unmarshals the JSON payload and returns the resulting slice.\n\/\/ If the content is empty, an empty list is returned. If decoding fails, nil is\n\/\/ returned with an error.\nfunc decodePayloadSlice(payload []byte) ([]Payload, error) {\n\tif len(payload) == 0 {\n\t\treturn []Payload{}, nil\n\t}\n\n\tvar data []Payload\n\tif err := json.Unmarshal(payload, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\n\/\/ payloadString returns the given io.Reader as a string. The reader must be rewound\n\/\/ after calling this in order to be read again.\nfunc payloadString(payload io.Reader) []byte {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(payload)\n\treturn buf.Bytes()\n}\nRemove debug print statementpackage rest\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ Resource represents a domain model.\ntype Resource interface{}\n\n\/\/ ResourceHandler specifies the endpoint handlers for working with a resource. This\n\/\/ consists of the business logic for performing CRUD operations.\ntype ResourceHandler interface {\n\t\/\/ ResourceName is used to identify what resource a handler corresponds to and is\n\t\/\/ used in the endpoint URLs, i.e. \/api\/:version\/resourceName. This should be\n\t\/\/ unique across all ResourceHandlers.\n\tResourceName() string\n\n\t\/\/ CreateURI returns the URI for creating a resource.\n\tCreateURI() string\n\n\t\/\/ ReadURI returns the URI for reading a specific resource.\n\tReadURI() string\n\n\t\/\/ ReadListURI returns the URI for reading a list of resources.\n\tReadListURI() string\n\n\t\/\/ UpdateURI returns the URI for updating a specific resource.\n\tUpdateURI() string\n\n\t\/\/ UpdateListURI returns the URI for updating a list of resources.\n\tUpdateListURI() string\n\n\t\/\/ DeleteURI returns the URI for deleting a specific resource.\n\tDeleteURI() string\n\n\t\/\/ CreateResource is the logic that corresponds to creating a new resource at\n\t\/\/ POST \/api\/:version\/resourceName. Typically, this would insert a record into a\n\t\/\/ database. It returns the newly created resource or an error if the create failed.\n\tCreateResource(RequestContext, Payload, string) (Resource, error)\n\n\t\/\/ ReadResourceList is the logic that corresponds to reading multiple resources,\n\t\/\/ perhaps with specified query parameters accessed through the RequestContext. This\n\t\/\/ is mapped to GET \/api\/:version\/resourceName. Typically, this would make some sort\n\t\/\/ of database query to fetch the resources. It returns the slice of results, a\n\t\/\/ cursor (or empty) string, and error (or nil).\n\tReadResourceList(RequestContext, int, string, string) ([]Resource, string, error)\n\n\t\/\/ ReadResource is the logic that corresponds to reading a single resource by its ID\n\t\/\/ at GET \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database query to load the resource. If the resource doesn't exist, nil should be\n\t\/\/ returned along with an appropriate error.\n\tReadResource(RequestContext, string, string) (Resource, error)\n\n\t\/\/ UpdateResourceList is the logic that corresponds to updating a collection of\n\t\/\/ resources at PUT \/api\/:version\/resourceName. Typically, this would make some\n\t\/\/ sort of database update call. It returns the updated resources or an error if\n\t\/\/ the update failed.\n\tUpdateResourceList(RequestContext, []Payload, string) ([]Resource, error)\n\n\t\/\/ UpdateResource is the logic that corresponds to updating an existing resource at\n\t\/\/ PUT \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database update call. It returns the updated resource or an error if the update\n\t\/\/ failed.\n\tUpdateResource(RequestContext, string, Payload, string) (Resource, error)\n\n\t\/\/ DeleteResource is the logic that corresponds to deleting an existing resource at\n\t\/\/ DELETE \/api\/:version\/resourceName\/{id}. Typically, this would make some sort of\n\t\/\/ database delete call. It returns the deleted resource or an error if the delete\n\t\/\/ failed.\n\tDeleteResource(RequestContext, string, string) (Resource, error)\n\n\t\/\/ Authenticate is logic that is used to authenticate requests. The default behavior\n\t\/\/ of Authenticate, seen in BaseResourceHandler, always returns nil, meaning all\n\t\/\/ requests are authenticated. Returning an error means that the request is\n\t\/\/ unauthorized and any error message will be sent back with the response.\n\tAuthenticate(*http.Request) error\n\n\t\/\/ Rules returns the resource rules to apply to incoming requests and outgoing\n\t\/\/ responses. The default behavior, seen in BaseResourceHandler, is to apply no\n\t\/\/ rules.\n\tRules() Rules\n}\n\n\/\/ requestHandler constructs http.HandlerFuncs responsible for handling HTTP requests.\ntype requestHandler struct {\n\tAPI\n}\n\n\/\/ handleCreate returns a HandlerFunc which will deserialize the request payload, pass\n\/\/ it to the provided create function, and then serialize and dispatch the response.\n\/\/ The serialization mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleCreate(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tdata, err := decodePayload(payloadString(r.Body))\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(err)\n\t\t\tctx = ctx.setStatus(http.StatusInternalServerError)\n\t\t} else {\n\t\t\tdata, err := applyInboundRules(data, rules)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresource, err := handler.CreateResource(ctx, data, ctx.Version())\n\t\t\t\tif err == nil {\n\t\t\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t\t\t}\n\t\t\t\tctx = ctx.setResult(resource)\n\t\t\t\tctx = ctx.setStatus(http.StatusCreated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx = ctx.setError(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleReadList returns a HandlerFunc which will pass the request context to the\n\/\/ provided read function and then serialize and dispatch the response. The\n\/\/ serialization mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleReadList(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresources, cursor, err := handler.ReadResourceList(\n\t\t\tctx, ctx.Limit(), ctx.Cursor(), version)\n\n\t\tif err == nil {\n\t\t\t\/\/ Apply rules to results.\n\t\t\tfor idx, resource := range resources {\n\t\t\t\tresources[idx] = applyOutboundRules(resource, rules)\n\t\t\t}\n\t\t}\n\n\t\tctx = ctx.setResult(resources)\n\t\tctx = ctx.setCursor(cursor)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleRead returns a HandlerFunc which will pass the resource id to the provided\n\/\/ read function and then serialize and dispatch the response. The serialization\n\/\/ mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleRead(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresource, err := handler.ReadResource(ctx, ctx.ResourceID(), version)\n\t\tif err == nil {\n\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t}\n\n\t\tctx = ctx.setResult(resource)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleUpdateList returns a HandlerFunc which will deserialize the request payload,\n\/\/ pass it to the provided update function, and then serialize and dispatch the\n\/\/ response. The serialization mechanism used is specified by the \"format\" query\n\/\/ parameter.\nfunc (h requestHandler) handleUpdateList(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tpayloadStr := payloadString(r.Body)\n\t\tvar data []Payload\n\t\tvar err error\n\t\tdata, err = decodePayloadSlice(payloadStr)\n\t\tif err != nil {\n\t\t\tvar p Payload\n\t\t\tp, err = decodePayload(payloadStr)\n\t\t\tdata = []Payload{p}\n\t\t}\n\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(BadRequest(err.Error()))\n\t\t} else {\n\t\t\tfor i := range data {\n\t\t\t\tdata[i], err = applyInboundRules(data[i], rules)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresources, err := handler.UpdateResourceList(ctx, data, version)\n\t\t\t\tif err == nil {\n\t\t\t\t\t\/\/ Apply rules to results.\n\t\t\t\t\tfor idx, resource := range resources {\n\t\t\t\t\t\tresources[idx] = applyOutboundRules(resource, rules)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tctx = ctx.setResult(resources)\n\t\t\t\tctx = ctx.setError(err)\n\t\t\t\tctx = ctx.setStatus(http.StatusOK)\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleUpdate returns a HandlerFunc which will deserialize the request payload,\n\/\/ pass it to the provided update function, and then serialize and dispatch the\n\/\/ response. The serialization mechanism used is specified by the \"format\" query\n\/\/ parameter.\nfunc (h requestHandler) handleUpdate(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tdata, err := decodePayload(payloadString(r.Body))\n\t\tif err != nil {\n\t\t\t\/\/ Payload decoding failed.\n\t\t\tctx = ctx.setError(err)\n\t\t\tctx = ctx.setStatus(http.StatusInternalServerError)\n\t\t} else {\n\t\t\tdata, err := applyInboundRules(data, rules)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Type coercion failed.\n\t\t\t\tctx = ctx.setError(UnprocessableRequest(err.Error()))\n\t\t\t} else {\n\t\t\t\tresource, err := handler.UpdateResource(\n\t\t\t\t\tctx, ctx.ResourceID(), data, version)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t\t\t}\n\n\t\t\t\tctx = ctx.setResult(resource)\n\t\t\t\tctx = ctx.setError(err)\n\t\t\t\tctx = ctx.setStatus(http.StatusOK)\n\t\t\t}\n\t\t}\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ handleDelete returns a HandlerFunc which will pass the resource id to the provided\n\/\/ delete function and then serialize and dispatch the response. The serialization\n\/\/ mechanism used is specified by the \"format\" query parameter.\nfunc (h requestHandler) handleDelete(handler ResourceHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := NewContext(nil, r)\n\t\tversion := ctx.Version()\n\t\trules := rulesForVersion(handler.Rules(), version)\n\n\t\tresource, err := handler.DeleteResource(ctx, ctx.ResourceID(), version)\n\t\tif err == nil {\n\t\t\tresource = applyOutboundRules(resource, rules)\n\t\t}\n\n\t\tctx = ctx.setResult(resource)\n\t\tctx = ctx.setError(err)\n\t\tctx = ctx.setStatus(http.StatusOK)\n\n\t\th.sendResponse(w, ctx)\n\t}\n}\n\n\/\/ sendResponse writes a success or error response to the provided http.ResponseWriter\n\/\/ based on the contents of the RequestContext.\nfunc (h requestHandler) sendResponse(w http.ResponseWriter, ctx RequestContext) {\n\tstatus := ctx.Status()\n\trequestError := ctx.Error()\n\tresult := ctx.Result()\n\tformat := ctx.ResponseFormat()\n\n\tserializer, err := h.responseSerializer(format)\n\tif err != nil {\n\t\t\/\/ Fall back to json serialization.\n\t\tserializer = jsonSerializer{}\n\t\trequestError = NotImplemented(fmt.Sprintf(\"Format not implemented: %s\", format))\n\t}\n\n\tvar response response\n\tif requestError != nil {\n\t\tresponse = NewErrorResponse(requestError)\n\t} else {\n\t\tnextURL, _ := ctx.NextURL()\n\t\tresponse = NewSuccessResponse(result, status, nextURL)\n\t}\n\n\tsendResponse(w, response, serializer)\n}\n\n\/\/ sendResponse writes a response to the http.ResponseWriter.\nfunc sendResponse(w http.ResponseWriter, r response, serializer ResponseSerializer) {\n\tstatus := r.Status\n\tcontentType := serializer.ContentType()\n\tresponse, err := serializer.Serialize(r.Payload)\n\tif err != nil {\n\t\tlog.Printf(\"Response serialization failed: %s\", err)\n\t\tstatus = http.StatusInternalServerError\n\t\tcontentType = \"text\/plain\"\n\t\tresponse = []byte(err.Error())\n\t}\n\n\tw.Header().Set(\"Content-Type\", contentType)\n\tw.WriteHeader(status)\n\tw.Write(response)\n}\n\n\/\/ rulesForVersion returns a slice of Rules which apply to the given version.\nfunc rulesForVersion(r Rules, version string) Rules {\n\tif r == nil {\n\t\treturn &rules{}\n\t}\n\n\tfiltered := make([]*Rule, 0, r.Size())\n\tfor _, rule := range r.Contents() {\n\t\tif rule.Applies(version) {\n\t\t\tfiltered = append(filtered, rule)\n\t\t}\n\t}\n\n\treturn &rules{contents: filtered, resourceType: r.ResourceType()}\n}\n\n\/\/ decodePayload unmarshals the JSON payload and returns the resulting map. If the\n\/\/ content is empty, an empty map is returned. If decoding fails, nil is returned\n\/\/ with an error.\nfunc decodePayload(payload []byte) (Payload, error) {\n\tif len(payload) == 0 {\n\t\treturn map[string]interface{}{}, nil\n\t}\n\n\tvar data Payload\n\tif err := json.Unmarshal(payload, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\n\/\/ decodePayloadSlice unmarshals the JSON payload and returns the resulting slice.\n\/\/ If the content is empty, an empty list is returned. If decoding fails, nil is\n\/\/ returned with an error.\nfunc decodePayloadSlice(payload []byte) ([]Payload, error) {\n\tif len(payload) == 0 {\n\t\treturn []Payload{}, nil\n\t}\n\n\tvar data []Payload\n\tif err := json.Unmarshal(payload, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\n\/\/ payloadString returns the given io.Reader as a string. The reader must be rewound\n\/\/ after calling this in order to be read again.\nfunc payloadString(payload io.Reader) []byte {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(payload)\n\treturn buf.Bytes()\n}\n<|endoftext|>"} {"text":"package gogame\n\n\/*\n#cgo pkg-config: sdl2\n#include \"SDL.h\"\n\nextern SDL_AudioDeviceID newAudioDevice(int frequency);\nextern void closeAudioDevice(SDL_AudioDeviceID id);\n\n*\/\nimport \"C\"\nimport \"errors\"\nimport \"unsafe\"\nimport \"math\"\n\nconst FREQUENCY = 44100\n\nvar toneCache = make(map[int]*ToneGenerator)\n\n\/\/export soundGoCallback\nfunc soundGoCallback(id int, ptr unsafe.Pointer, len int) {\n\tlen \/= 4\n\t\/\/ To create a Go slice backed by a C array\n\t\/\/ (without copying the original data), one needs to acquire this length\n\t\/\/ at runtime and use a type conversion to a pointer to a very big array and then\n\t\/\/ slice it to the length that you want (also remember to set\n\t\/\/ the cap if you're using Go 1.2 or later)\n\tslice := (*[1 << 30]float32)(ptr)[:len:len]\n\ttoneCache[id].feedSamples(slice)\n}\n\ntype ToneGenerator struct {\n\tdev C.SDL_AudioDeviceID\n\tamp float32\n\tfreq float32\n\tv float32\n\tperiod int\n\tj int\n}\n\nfunc NewToneGenerator() (*ToneGenerator, error) {\n\tdev := C.newAudioDevice(FREQUENCY)\n\tif dev == 0 {\n\t\treturn nil, errors.New(\"Can't open tone generator\")\n\t}\n\tsd := new(ToneGenerator)\n\tsd.dev = dev\n\ttoneCache[int(sd.dev)] = sd\n\treturn sd, nil\n}\n\nfunc (self *ToneGenerator) Start() {\n\tC.SDL_PauseAudioDevice(self.dev, 0)\n}\n\nfunc (self *ToneGenerator) Stop() {\n\tC.SDL_PauseAudioDevice(self.dev, 1)\n}\n\nfunc (self *ToneGenerator) SetFreq(freq int) {\n\tself.freq = float32(freq)\n\tself.period = int(2 * FREQUENCY \/ self.freq)\n}\n\nfunc (self *ToneGenerator) SetAmplitude(amp float32) {\n\tself.amp = amp\n}\n\nfunc (self *ToneGenerator) Close() {\n\tC.closeAudioDevice(self.dev)\n\tdelete(toneCache, int(self.dev))\n}\n\nfunc (self *ToneGenerator) feedSamples(data []float32) {\n\tfor i := 0; i < len(data); i++ {\n\t\tdata[i] = self.amp * float32(math.Sin(float64(self.v*2*math.Pi\/FREQUENCY)))\n\t\tif self.j > self.period {\n\t\t\tself.v -= float32(self.period) * self.freq\n\t\t\tself.j = 0\n\t\t} else {\n\t\t\tself.v += self.freq\n\t\t\tself.j++\n\t\t}\n\t}\n}\nWorking on sound...package gogame\n\n\/*\n#cgo pkg-config: sdl2\n#include \"SDL.h\"\n\nextern SDL_AudioDeviceID newAudioDevice(int frequency);\nextern void closeAudioDevice(SDL_AudioDeviceID id);\n\n*\/\nimport \"C\"\nimport \"errors\"\nimport \"unsafe\"\nimport \"math\"\nimport \"math\/rand\"\n\nconst FREQUENCY = 44100\n\nvar toneCache = make(map[int]*ToneGenerator)\n\nconst (\n\tGENERATOR_TYPE_TONE = iota\n\tGENERATOR_TYPE_NOISE\n)\n\n\/\/export soundGoCallback\nfunc soundGoCallback(id int, ptr unsafe.Pointer, len int) {\n\tlen \/= 4\n\t\/\/ To create a Go slice backed by a C array\n\t\/\/ (without copying the original data), one needs to acquire this length\n\t\/\/ at runtime and use a type conversion to a pointer to a very big array and then\n\t\/\/ slice it to the length that you want (also remember to set\n\t\/\/ the cap if you're using Go 1.2 or later)\n\tslice := (*[1 << 30]float32)(ptr)[:len:len]\n\ttoneCache[id].feedSamples(slice)\n}\n\ntype ToneGenerator struct {\n\tgenType int\n\tdev C.SDL_AudioDeviceID\n\tamp float32\n\tfreq float32\n\tv float32\n\tperiod int\n\tj int\n}\n\nfunc NewToneGenerator(genType int) (*ToneGenerator, error) {\n\tdev := C.newAudioDevice(FREQUENCY)\n\tif dev == 0 {\n\t\treturn nil, errors.New(\"Can't open tone generator\")\n\t}\n\tsd := new(ToneGenerator)\n\tsd.dev = dev\n\tsd.genType = genType\n\ttoneCache[int(sd.dev)] = sd\n\treturn sd, nil\n}\n\nfunc (self *ToneGenerator) Start() {\n\tC.SDL_PauseAudioDevice(self.dev, 0)\n}\n\nfunc (self *ToneGenerator) Stop() {\n\tC.SDL_PauseAudioDevice(self.dev, 1)\n}\n\nfunc (self *ToneGenerator) SetFreq(freq int) {\n\tself.freq = float32(freq)\n\tself.period = int(2 * FREQUENCY \/ self.freq)\n}\n\nfunc (self *ToneGenerator) SetAmplitude(amp float32) {\n\tself.amp = amp\n}\n\nfunc (self *ToneGenerator) Close() {\n\tC.closeAudioDevice(self.dev)\n\tdelete(toneCache, int(self.dev))\n}\n\nfunc (self *ToneGenerator) feedSamples(data []float32) {\n\tif self.genType == GENERATOR_TYPE_TONE {\n\t\tfor i := 0; i < len(data); i++ {\n\t\t\tdata[i] = self.amp * float32(math.Sin(float64(self.v*2*math.Pi\/FREQUENCY)))\n\t\t\tif self.j > self.period {\n\t\t\t\tself.v -= float32(self.period) * self.freq\n\t\t\t\tself.j = 0\n\t\t\t\t} else {\n\t\t\t\t\tself.v += self.freq\n\t\t\t\t\tself.j++\n\t\t\t\t}\n\t\t\t}\n\t} else if self.genType == GENERATOR_TYPE_NOISE {\n\t\tfor i := 0; i < len(data); i++ {\n\t\t\tdata[i] = self.amp * rand.Float32();\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package metainfo\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com\/cenkalti\/rain\/internal\/logger\"\n\t\"github.com\/zeebo\/bencode\"\n)\n\nvar (\n\terrInvalidPieceData = errors.New(\"invalid piece data\")\n\terrZeroPieceLength = errors.New(\"torrent has zero piece length\")\n\terrZeroPieces = errors.New(\"torrent has zero pieces\")\n\terrPieceLength = errors.New(\"piece length must be multiple of 16K\")\n)\n\n\/\/ Info contains information about torrent.\ntype Info struct {\n\tPieceLength uint32\n\tName string\n\tHash [20]byte\n\tLength int64\n\tNumPieces uint32\n\tBytes []byte\n\tPrivate bool\n\tFiles []File\n\tpieces []byte\n}\n\n\/\/ File represents a file inside a Torrent.\ntype File struct {\n\tLength int64\n\tPath string\n}\n\ntype file struct {\n\tLength int64 `bencode:\"length\"`\n\tPath []string `bencode:\"path\"`\n}\n\n\/\/ NewInfo returns info from bencoded bytes in b.\nfunc NewInfo(b []byte) (*Info, error) {\n\tvar ib struct {\n\t\tPieceLength uint32 `bencode:\"piece length\"`\n\t\tPieces []byte `bencode:\"pieces\"`\n\t\tName string `bencode:\"name\"`\n\t\tPrivate bencode.RawMessage `bencode:\"private\"`\n\t\tLength int64 `bencode:\"length\"` \/\/ Single File Mode\n\t\tFiles []file `bencode:\"files\"` \/\/ Multiple File mode\n\t}\n\tif err := bencode.DecodeBytes(b, &ib); err != nil {\n\t\treturn nil, err\n\t}\n\tif ib.PieceLength == 0 {\n\t\treturn nil, errZeroPieceLength\n\t}\n\tif len(ib.Pieces)%sha1.Size != 0 {\n\t\treturn nil, errInvalidPieceData\n\t}\n\tnumPieces := len(ib.Pieces) \/ sha1.Size\n\tif numPieces == 0 {\n\t\treturn nil, errZeroPieces\n\t}\n\t\/\/ \"..\" is not allowed in file names\n\tfor _, file := range ib.Files {\n\t\tfor _, path := range file.Path {\n\t\t\tif strings.TrimSpace(path) == \"..\" {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid file name: %q\", filepath.Join(file.Path...))\n\t\t\t}\n\t\t}\n\t}\n\ti := Info{\n\t\tPieceLength: ib.PieceLength,\n\t\tNumPieces: uint32(numPieces),\n\t\tpieces: ib.Pieces,\n\t\tName: ib.Name,\n\t\tPrivate: parsePrivateField(ib.Private),\n\t}\n\tmultiFile := len(ib.Files) > 0\n\tif multiFile {\n\t\tfor _, f := range ib.Files {\n\t\t\ti.Length += f.Length\n\t\t}\n\t} else {\n\t\ti.Length = ib.Length\n\t}\n\ttotalPieceDataLength := int64(i.PieceLength) * int64(i.NumPieces)\n\tdelta := totalPieceDataLength - i.Length\n\tif delta >= int64(i.PieceLength) || delta < 0 {\n\t\treturn nil, errInvalidPieceData\n\t}\n\ti.Bytes = b\n\n\t\/\/ calculate info hash\n\thash := sha1.New()\n\t_, _ = hash.Write(b)\n\tcopy(i.Hash[:], hash.Sum(nil))\n\n\t\/\/ name field is optional\n\tif ib.Name != \"\" {\n\t\ti.Name = ib.Name\n\t} else {\n\t\ti.Name = hex.EncodeToString(i.Hash[:])\n\t}\n\n\t\/\/ construct files\n\tif multiFile {\n\t\ti.Files = make([]File, len(ib.Files))\n\t\tfor j, f := range ib.Files {\n\t\t\tparts := make([]string, 0, len(f.Path)+1)\n\t\t\tparts = append(parts, cleanName(i.Name))\n\t\t\tfor _, p := range f.Path {\n\t\t\t\tparts = append(parts, cleanName(p))\n\t\t\t}\n\t\t\ti.Files[j] = File{\n\t\t\t\tPath: filepath.Join(parts...),\n\t\t\t\tLength: f.Length,\n\t\t\t}\n\t\t}\n\t} else {\n\t\ti.Files = []File{{Path: cleanName(i.Name), Length: i.Length}}\n\t}\n\treturn &i, nil\n}\n\nfunc cleanName(s string) string {\n\treturn cleanNameN(s, 255)\n}\n\nfunc cleanNameN(s string, max int) string {\n\ts = strings.ToValidUTF8(s, string(unicode.ReplacementChar))\n\ts = trimName(s, max)\n\ts = strings.ToValidUTF8(s, \"\")\n\treturn replaceSeparator(s)\n}\n\n\/\/ trimName trims the file name that it won't exceed 255 characters while keeping the extension.\nfunc trimName(s string, max int) string {\n\tif len(s) <= max {\n\t\treturn s\n\t}\n\text := path.Ext(s)\n\tif len(ext) > max {\n\t\treturn s[:max]\n\t}\n\treturn s[:max-len(ext)] + ext\n}\n\nfunc replaceSeparator(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r == '\/' {\n\t\t\treturn '_'\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parsePrivateField(s bencode.RawMessage) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tvar intVal int64\n\terr := bencode.DecodeBytes(s, &intVal)\n\tif err == nil {\n\t\treturn intVal != 0\n\t}\n\tvar stringVal string\n\terr = bencode.DecodeBytes(s, &stringVal)\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn !(stringVal == \"\" || stringVal == \"0\")\n}\n\n\/\/ NewInfoBytes creates a new Info dictionary by reading and hashing the files on the disk.\nfunc NewInfoBytes(root string, paths []string, private bool, pieceLength uint32, name string, log logger.Logger) ([]byte, error) {\n\tvar singleFileTorrent bool\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn nil, errors.New(\"no path specified\")\n\tcase 1:\n\t\tif name == \"\" {\n\t\t\tname = filepath.Base(paths[0])\n\t\t}\n\t\tfi, err := os.Stat(paths[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsingleFileTorrent = !fi.IsDir()\n\tdefault:\n\t\tif root == \"\" {\n\t\t\treturn nil, errors.New(\"no root specified\")\n\t\t}\n\t\tif name == \"\" {\n\t\t\treturn nil, errors.New(\"no name specified\")\n\t\t}\n\t}\n\ttotalLength, err := findTotalLength(paths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif totalLength == 0 {\n\t\treturn nil, errors.New(\"no files\")\n\t}\n\tif pieceLength == 0 {\n\t\tpieceLength = calculatePieceLength(totalLength)\n\t\tlog.Infof(\"Calculated piece length: %d K\", pieceLength>>10)\n\t} else if pieceLength%(16<<10) != 0 {\n\t\treturn nil, errPieceLength\n\t}\n\tbuf := make([]byte, pieceLength)\n\toffset := 0\n\tremaining := func() []byte { return buf[offset:] }\n\thash := sha1.New()\n\tvar files []file\n\tvar pieces []byte\n\tfor _, path := range paths {\n\t\trelroot := path\n\t\tif root != \"\" {\n\t\t\trelroot = root\n\t\t}\n\t\tvisit := func(vpath string, fi os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tf, err := os.Open(vpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\trelpath, err := filepath.Rel(relroot, vpath)\n\t\t\tlog.Infof(\"Adding %q\", relpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfiles = append(files, file{Path: filepath.SplitList(relpath), Length: fi.Size()})\n\t\t\tfor {\n\t\t\t\tn, err := io.ReadFull(f, remaining())\n\t\t\t\toffset += n\n\t\t\t\tif err == io.ErrUnexpectedEOF || err == io.EOF {\n\t\t\t\t\treturn nil \/\/ file finished, continue with next file\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t\/\/ buffer finished, calculate piece hash and append to pieces\n\t\t\t\t_, _ = hash.Write(buf)\n\t\t\t\tpieces = hash.Sum(pieces)\n\t\t\t\thash.Reset()\n\t\t\t\toffset = 0\n\t\t\t}\n\t\t}\n\t\terr = filepath.Walk(path, visit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t\/\/ hash remaining buffer\n\tif offset > 0 {\n\t\t_, _ = hash.Write(buf[:offset])\n\t\tpieces = hash.Sum(pieces)\n\t}\n\tb := struct {\n\t\tName string `bencode:\"name\"`\n\t\tPrivate bool `bencode:\"private\"`\n\t\tPieceLength uint32 `bencode:\"piece length\"`\n\t\tPieces []byte `bencode:\"pieces\"`\n\t\tLength int64 `bencode:\"length,omitempty\"` \/\/ Single File Mode\n\t\tFiles []file `bencode:\"files,omitempty\"` \/\/ Multiple File mode\n\t}{\n\t\tName: name,\n\t\tPrivate: private,\n\t\tPieceLength: pieceLength,\n\t\tPieces: pieces,\n\t}\n\tif singleFileTorrent {\n\t\tb.Length = totalLength\n\t} else {\n\t\tb.Files = files\n\t}\n\treturn bencode.EncodeBytes(b)\n}\n\n\/\/ PieceHash returns the hash of a piece at index.\nfunc (i *Info) PieceHash(index uint32) []byte {\n\tbegin := index * sha1.Size\n\tend := begin + sha1.Size\n\treturn i.pieces[begin:end]\n}\n\nfunc findTotalLength(paths []string) (n int64, err error) {\n\tfor _, path := range paths {\n\t\terr = filepath.Walk(path, func(path string, fi os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tn += fi.Size()\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc calculatePieceLength(totalLength int64) uint32 {\n\tconst maxPieces = 2000\n\tpieceLength := totalLength \/ maxPieces\n\tswitch {\n\tcase pieceLength < 32<<10:\n\t\treturn 32 << 10\n\tcase pieceLength > 16<<20:\n\t\treturn 16 << 20\n\tdefault:\n\t\t\/\/ round to next power of 2\n\t\tv := uint32(pieceLength)\n\t\tv--\n\t\tv |= v >> 1\n\t\tv |= v >> 2\n\t\tv |= v >> 4\n\t\tv |= v >> 8\n\t\tv |= v >> 16\n\t\tv++\n\t\treturn v\n\t}\n}\nfix path concatenation in torrent creationpackage metainfo\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com\/cenkalti\/rain\/internal\/logger\"\n\t\"github.com\/zeebo\/bencode\"\n)\n\nvar (\n\terrInvalidPieceData = errors.New(\"invalid piece data\")\n\terrZeroPieceLength = errors.New(\"torrent has zero piece length\")\n\terrZeroPieces = errors.New(\"torrent has zero pieces\")\n\terrPieceLength = errors.New(\"piece length must be multiple of 16K\")\n)\n\n\/\/ Info contains information about torrent.\ntype Info struct {\n\tPieceLength uint32\n\tName string\n\tHash [20]byte\n\tLength int64\n\tNumPieces uint32\n\tBytes []byte\n\tPrivate bool\n\tFiles []File\n\tpieces []byte\n}\n\n\/\/ File represents a file inside a Torrent.\ntype File struct {\n\tLength int64\n\tPath string\n}\n\ntype file struct {\n\tLength int64 `bencode:\"length\"`\n\tPath []string `bencode:\"path\"`\n}\n\n\/\/ NewInfo returns info from bencoded bytes in b.\nfunc NewInfo(b []byte) (*Info, error) {\n\tvar ib struct {\n\t\tPieceLength uint32 `bencode:\"piece length\"`\n\t\tPieces []byte `bencode:\"pieces\"`\n\t\tName string `bencode:\"name\"`\n\t\tPrivate bencode.RawMessage `bencode:\"private\"`\n\t\tLength int64 `bencode:\"length\"` \/\/ Single File Mode\n\t\tFiles []file `bencode:\"files\"` \/\/ Multiple File mode\n\t}\n\tif err := bencode.DecodeBytes(b, &ib); err != nil {\n\t\treturn nil, err\n\t}\n\tif ib.PieceLength == 0 {\n\t\treturn nil, errZeroPieceLength\n\t}\n\tif len(ib.Pieces)%sha1.Size != 0 {\n\t\treturn nil, errInvalidPieceData\n\t}\n\tnumPieces := len(ib.Pieces) \/ sha1.Size\n\tif numPieces == 0 {\n\t\treturn nil, errZeroPieces\n\t}\n\t\/\/ \"..\" is not allowed in file names\n\tfor _, file := range ib.Files {\n\t\tfor _, path := range file.Path {\n\t\t\tif strings.TrimSpace(path) == \"..\" {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid file name: %q\", filepath.Join(file.Path...))\n\t\t\t}\n\t\t}\n\t}\n\ti := Info{\n\t\tPieceLength: ib.PieceLength,\n\t\tNumPieces: uint32(numPieces),\n\t\tpieces: ib.Pieces,\n\t\tName: ib.Name,\n\t\tPrivate: parsePrivateField(ib.Private),\n\t}\n\tmultiFile := len(ib.Files) > 0\n\tif multiFile {\n\t\tfor _, f := range ib.Files {\n\t\t\ti.Length += f.Length\n\t\t}\n\t} else {\n\t\ti.Length = ib.Length\n\t}\n\ttotalPieceDataLength := int64(i.PieceLength) * int64(i.NumPieces)\n\tdelta := totalPieceDataLength - i.Length\n\tif delta >= int64(i.PieceLength) || delta < 0 {\n\t\treturn nil, errInvalidPieceData\n\t}\n\ti.Bytes = b\n\n\t\/\/ calculate info hash\n\thash := sha1.New()\n\t_, _ = hash.Write(b)\n\tcopy(i.Hash[:], hash.Sum(nil))\n\n\t\/\/ name field is optional\n\tif ib.Name != \"\" {\n\t\ti.Name = ib.Name\n\t} else {\n\t\ti.Name = hex.EncodeToString(i.Hash[:])\n\t}\n\n\t\/\/ construct files\n\tif multiFile {\n\t\ti.Files = make([]File, len(ib.Files))\n\t\tfor j, f := range ib.Files {\n\t\t\tparts := make([]string, 0, len(f.Path)+1)\n\t\t\tparts = append(parts, cleanName(i.Name))\n\t\t\tfor _, p := range f.Path {\n\t\t\t\tparts = append(parts, cleanName(p))\n\t\t\t}\n\t\t\ti.Files[j] = File{\n\t\t\t\tPath: filepath.Join(parts...),\n\t\t\t\tLength: f.Length,\n\t\t\t}\n\t\t}\n\t} else {\n\t\ti.Files = []File{{Path: cleanName(i.Name), Length: i.Length}}\n\t}\n\treturn &i, nil\n}\n\nfunc cleanName(s string) string {\n\treturn cleanNameN(s, 255)\n}\n\nfunc cleanNameN(s string, max int) string {\n\ts = strings.ToValidUTF8(s, string(unicode.ReplacementChar))\n\ts = trimName(s, max)\n\ts = strings.ToValidUTF8(s, \"\")\n\treturn replaceSeparator(s)\n}\n\n\/\/ trimName trims the file name that it won't exceed 255 characters while keeping the extension.\nfunc trimName(s string, max int) string {\n\tif len(s) <= max {\n\t\treturn s\n\t}\n\text := path.Ext(s)\n\tif len(ext) > max {\n\t\treturn s[:max]\n\t}\n\treturn s[:max-len(ext)] + ext\n}\n\nfunc replaceSeparator(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r == '\/' {\n\t\t\treturn '_'\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\nfunc parsePrivateField(s bencode.RawMessage) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tvar intVal int64\n\terr := bencode.DecodeBytes(s, &intVal)\n\tif err == nil {\n\t\treturn intVal != 0\n\t}\n\tvar stringVal string\n\terr = bencode.DecodeBytes(s, &stringVal)\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn !(stringVal == \"\" || stringVal == \"0\")\n}\n\n\/\/ NewInfoBytes creates a new Info dictionary by reading and hashing the files on the disk.\nfunc NewInfoBytes(root string, paths []string, private bool, pieceLength uint32, name string, log logger.Logger) ([]byte, error) {\n\tvar singleFileTorrent bool\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn nil, errors.New(\"no path specified\")\n\tcase 1:\n\t\tif name == \"\" {\n\t\t\tname = filepath.Base(paths[0])\n\t\t}\n\t\tfi, err := os.Stat(paths[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsingleFileTorrent = !fi.IsDir()\n\tdefault:\n\t\tif root == \"\" {\n\t\t\treturn nil, errors.New(\"no root specified\")\n\t\t}\n\t\tif name == \"\" {\n\t\t\treturn nil, errors.New(\"no name specified\")\n\t\t}\n\t}\n\ttotalLength, err := findTotalLength(paths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif totalLength == 0 {\n\t\treturn nil, errors.New(\"no files\")\n\t}\n\tif pieceLength == 0 {\n\t\tpieceLength = calculatePieceLength(totalLength)\n\t\tlog.Infof(\"Calculated piece length: %d K\", pieceLength>>10)\n\t} else if pieceLength%(16<<10) != 0 {\n\t\treturn nil, errPieceLength\n\t}\n\tbuf := make([]byte, pieceLength)\n\toffset := 0\n\tremaining := func() []byte { return buf[offset:] }\n\thash := sha1.New()\n\tvar files []file\n\tvar pieces []byte\n\tfor _, path := range paths {\n\t\trelroot := path\n\t\tif root != \"\" {\n\t\t\trelroot = root\n\t\t}\n\t\tvisit := func(vpath string, fi os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tf, err := os.Open(vpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\trelpath, err := filepath.Rel(relroot, vpath)\n\t\t\tlog.Infof(\"Adding %q\", relpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfiles = append(files, file{Path: strings.Split(relpath, string(os.PathSeparator)), Length: fi.Size()})\n\t\t\tfor {\n\t\t\t\tn, err := io.ReadFull(f, remaining())\n\t\t\t\toffset += n\n\t\t\t\tif err == io.ErrUnexpectedEOF || err == io.EOF {\n\t\t\t\t\treturn nil \/\/ file finished, continue with next file\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t\/\/ buffer finished, calculate piece hash and append to pieces\n\t\t\t\t_, _ = hash.Write(buf)\n\t\t\t\tpieces = hash.Sum(pieces)\n\t\t\t\thash.Reset()\n\t\t\t\toffset = 0\n\t\t\t}\n\t\t}\n\t\terr = filepath.Walk(path, visit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t\/\/ hash remaining buffer\n\tif offset > 0 {\n\t\t_, _ = hash.Write(buf[:offset])\n\t\tpieces = hash.Sum(pieces)\n\t}\n\tb := struct {\n\t\tName string `bencode:\"name\"`\n\t\tPrivate bool `bencode:\"private\"`\n\t\tPieceLength uint32 `bencode:\"piece length\"`\n\t\tPieces []byte `bencode:\"pieces\"`\n\t\tLength int64 `bencode:\"length,omitempty\"` \/\/ Single File Mode\n\t\tFiles []file `bencode:\"files,omitempty\"` \/\/ Multiple File mode\n\t}{\n\t\tName: name,\n\t\tPrivate: private,\n\t\tPieceLength: pieceLength,\n\t\tPieces: pieces,\n\t}\n\tif singleFileTorrent {\n\t\tb.Length = totalLength\n\t} else {\n\t\tb.Files = files\n\t}\n\treturn bencode.EncodeBytes(b)\n}\n\n\/\/ PieceHash returns the hash of a piece at index.\nfunc (i *Info) PieceHash(index uint32) []byte {\n\tbegin := index * sha1.Size\n\tend := begin + sha1.Size\n\treturn i.pieces[begin:end]\n}\n\nfunc findTotalLength(paths []string) (n int64, err error) {\n\tfor _, path := range paths {\n\t\terr = filepath.Walk(path, func(path string, fi os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tn += fi.Size()\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc calculatePieceLength(totalLength int64) uint32 {\n\tconst maxPieces = 2000\n\tpieceLength := totalLength \/ maxPieces\n\tswitch {\n\tcase pieceLength < 32<<10:\n\t\treturn 32 << 10\n\tcase pieceLength > 16<<20:\n\t\treturn 16 << 20\n\tdefault:\n\t\t\/\/ round to next power of 2\n\t\tv := uint32(pieceLength)\n\t\tv--\n\t\tv |= v >> 1\n\t\tv |= v >> 2\n\t\tv |= v >> 4\n\t\tv |= v >> 8\n\t\tv |= v >> 16\n\t\tv++\n\t\treturn v\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mipmap\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"math\"\n\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/affine\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/buffered\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\nvar graphicsDriver driver.Graphics\n\nfunc SetGraphicsDriver(graphics driver.Graphics) {\n\tgraphicsDriver = graphics\n}\n\nfunc BeginFrame() error {\n\treturn buffered.BeginFrame()\n}\n\nfunc EndFrame() error {\n\treturn buffered.EndFrame()\n}\n\n\/\/ Mipmap is a set of buffered.Image sorted by the order of mipmap level.\n\/\/ The level 0 image is a regular image and higher-level images are used for mipmap.\ntype Mipmap struct {\n\twidth int\n\theight int\n\tvolatile bool\n\torig *buffered.Image\n\timgs map[int]*buffered.Image\n}\n\nfunc New(width, height int, volatile bool) *Mipmap {\n\treturn &Mipmap{\n\t\twidth: width,\n\t\theight: height,\n\t\tvolatile: volatile,\n\t\torig: buffered.NewImage(width, height, volatile),\n\t\timgs: map[int]*buffered.Image{},\n\t}\n}\n\nfunc NewScreenFramebufferMipmap(width, height int) *Mipmap {\n\treturn &Mipmap{\n\t\twidth: width,\n\t\theight: height,\n\t\torig: buffered.NewScreenFramebufferImage(width, height),\n\t\timgs: map[int]*buffered.Image{},\n\t}\n}\n\nfunc (m *Mipmap) Dump(name string, blackbg bool) error {\n\treturn m.orig.Dump(name, blackbg)\n}\n\nfunc (m *Mipmap) Fill(clr color.RGBA) {\n\tm.orig.Fill(clr)\n\tm.disposeMipmaps()\n}\n\nfunc (m *Mipmap) ReplacePixels(pix []byte, x, y, width, height int) error {\n\tif err := m.orig.ReplacePixels(pix, x, y, width, height); err != nil {\n\t\treturn err\n\t}\n\tm.disposeMipmaps()\n\treturn nil\n}\n\nfunc (m *Mipmap) Pixels(x, y, width, height int) ([]byte, error) {\n\treturn m.orig.Pixels(x, y, width, height)\n}\n\nfunc (m *Mipmap) DrawTriangles(srcs [graphics.ShaderImageNum]*Mipmap, vertices []float32, indices []uint16, colorm *affine.ColorM, mode driver.CompositeMode, filter driver.Filter, address driver.Address, sourceRegion driver.Region, shader *Shader, uniforms []interface{}, canSkipMipmap bool) {\n\tif len(indices) == 0 {\n\t\treturn\n\t}\n\n\tlevel := 0\n\t\/\/ TODO: Do we need to check all the sources' states of being volatile?\n\tif !canSkipMipmap && srcs[0] != nil && !srcs[0].volatile && filter != driver.FilterScreen {\n\t\tlevel = math.MaxInt32\n\t\tfor i := 0; i < len(indices)\/3; i++ {\n\t\t\tconst n = graphics.VertexFloatNum\n\t\t\tdx0 := vertices[n*indices[3*i]+0]\n\t\t\tdy0 := vertices[n*indices[3*i]+1]\n\t\t\tsx0 := vertices[n*indices[3*i]+2]\n\t\t\tsy0 := vertices[n*indices[3*i]+3]\n\t\t\tdx1 := vertices[n*indices[3*i+1]+0]\n\t\t\tdy1 := vertices[n*indices[3*i+1]+1]\n\t\t\tsx1 := vertices[n*indices[3*i+1]+2]\n\t\t\tsy1 := vertices[n*indices[3*i+1]+3]\n\t\t\tdx2 := vertices[n*indices[3*i+2]+0]\n\t\t\tdy2 := vertices[n*indices[3*i+2]+1]\n\t\t\tsx2 := vertices[n*indices[3*i+2]+2]\n\t\t\tsy2 := vertices[n*indices[3*i+2]+3]\n\t\t\tif l := mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t\tif l := mipmapLevelFromDistance(dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t\tif l := mipmapLevelFromDistance(dx2, dy2, dx0, dy0, sx2, sy2, sx0, sy0, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t}\n\t\tif level == math.MaxInt32 {\n\t\t\tpanic(\"mipmap: level must be calculated at least once but not\")\n\t\t}\n\t}\n\n\tif colorm != nil && colorm.ScaleOnly() {\n\t\tbody, _ := colorm.UnsafeElements()\n\t\tcr := body[0]\n\t\tcg := body[5]\n\t\tcb := body[10]\n\t\tca := body[15]\n\t\tcolorm = nil\n\t\tconst n = graphics.VertexFloatNum\n\t\tfor i := 0; i < len(vertices)\/n; i++ {\n\t\t\tvertices[i*n+4] *= cr\n\t\t\tvertices[i*n+5] *= cg\n\t\t\tvertices[i*n+6] *= cb\n\t\t\tvertices[i*n+7] *= ca\n\t\t}\n\t}\n\n\tvar s *buffered.Shader\n\tif shader != nil {\n\t\ts = shader.shader\n\t}\n\n\tvar imgs [graphics.ShaderImageNum]*buffered.Image\n\tfor i, src := range srcs {\n\t\tif src == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif level != 0 {\n\t\t\tif img := src.level(level); img != nil {\n\t\t\t\tconst n = graphics.VertexFloatNum\n\t\t\t\ts := float32(pow2(level))\n\t\t\t\tfor i := 0; i < len(vertices)\/n; i++ {\n\t\t\t\t\tvertices[i*n+2] \/= s\n\t\t\t\t\tvertices[i*n+3] \/= s\n\t\t\t\t}\n\t\t\t\timgs[i] = img\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\timgs[i] = src.orig\n\t}\n\n\tm.orig.DrawTriangles(imgs, vertices, indices, colorm, mode, filter, address, sourceRegion, s, uniforms)\n\tm.disposeMipmaps()\n}\n\nfunc (m *Mipmap) level(level int) *buffered.Image {\n\tif level == 0 {\n\t\tpanic(\"ebiten: level must be non-zero at level\")\n\t}\n\n\tif m.volatile {\n\t\tpanic(\"ebiten: mipmap images for a volatile image is not implemented yet\")\n\t}\n\n\tif img, ok := m.imgs[level]; ok {\n\t\treturn img\n\t}\n\n\tvar src *buffered.Image\n\tvar vs []float32\n\tvar filter driver.Filter\n\tswitch {\n\tcase level == 1:\n\t\tsrc = m.orig\n\t\tvs = graphics.QuadVertices(0, 0, float32(m.width), float32(m.height), 0.5, 0, 0, 0.5, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterLinear\n\tcase level > 1:\n\t\tsrc = m.level(level - 1)\n\t\tif src == nil {\n\t\t\tm.imgs[level] = nil\n\t\t\treturn nil\n\t\t}\n\t\tw := sizeForLevel(m.width, level-1)\n\t\th := sizeForLevel(m.height, level-1)\n\t\tvs = graphics.QuadVertices(0, 0, float32(w), float32(h), 0.5, 0, 0, 0.5, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterLinear\n\tcase level == -1:\n\t\tsrc = m.orig\n\t\tvs = graphics.QuadVertices(0, 0, float32(m.width), float32(m.height), 2, 0, 0, 2, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterNearest\n\tcase level < -1:\n\t\tsrc = m.level(level + 1)\n\t\tif src == nil {\n\t\t\tm.imgs[level] = nil\n\t\t\treturn nil\n\t\t}\n\t\tw := sizeForLevel(m.width, level-1)\n\t\th := sizeForLevel(m.height, level-1)\n\t\tvs = graphics.QuadVertices(0, 0, float32(w), float32(h), 2, 0, 0, 2, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterNearest\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"ebiten: invalid level: %d\", level))\n\t}\n\tis := graphics.QuadIndices()\n\n\tw2 := sizeForLevel(m.width, level-1)\n\th2 := sizeForLevel(m.height, level-1)\n\tif w2 == 0 || h2 == 0 {\n\t\tm.imgs[level] = nil\n\t\treturn nil\n\t}\n\ts := buffered.NewImage(w2, h2, m.volatile)\n\ts.DrawTriangles([graphics.ShaderImageNum]*buffered.Image{src}, vs, is, nil, driver.CompositeModeCopy, filter, driver.AddressUnsafe, driver.Region{}, nil, nil)\n\tm.imgs[level] = s\n\n\treturn m.imgs[level]\n}\n\nfunc sizeForLevel(x int, level int) int {\n\tif level > 0 {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tx \/= 2\n\t\t\tif x == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < -level; i++ {\n\t\t\tx *= 2\n\t\t}\n\t}\n\treturn x\n}\n\nfunc (m *Mipmap) MarkDisposed() {\n\tm.disposeMipmaps()\n\tm.orig.MarkDisposed()\n\tm.orig = nil\n}\n\nfunc (m *Mipmap) disposeMipmaps() {\n\tfor _, img := range m.imgs {\n\t\timg.MarkDisposed()\n\t}\n\tfor k := range m.imgs {\n\t\tdelete(m.imgs, k)\n\t}\n}\n\n\/\/ mipmapLevel returns an appropriate mipmap level for the given distance.\nfunc mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, filter driver.Filter) int {\n\tif filter == driver.FilterScreen {\n\t\treturn 0\n\t}\n\n\td := (dx1-dx0)*(dx1-dx0) + (dy1-dy0)*(dy1-dy0)\n\ts := (sx1-sx0)*(sx1-sx0) + (sy1-sy0)*(sy1-sy0)\n\tif s == 0 {\n\t\treturn 0\n\t}\n\tscale := d \/ s\n\n\t\/\/ Use 'negative' mipmap to render edges correctly (#611, #907).\n\t\/\/ It looks like 128 is the enlargement factor that causes edge missings to pass the test TestImageStretch.\n\tvar tooBigScale float32 = 128\n\tif !graphicsDriver.HasHighPrecisionFloat() {\n\t\ttooBigScale = 4\n\t}\n\n\tif scale >= tooBigScale*tooBigScale {\n\t\t\/\/ If the filter is not nearest, the target needs to be rendered with graduation. Don't use mipmaps.\n\t\tif filter != driver.FilterNearest {\n\t\t\treturn 0\n\t\t}\n\n\t\tconst mipmapMaxSize = 1024\n\t\tw, h := sx1-sx0, sy1-sy0\n\t\tif w >= mipmapMaxSize || h >= mipmapMaxSize {\n\t\t\treturn 0\n\t\t}\n\n\t\tlevel := 0\n\t\tfor scale >= tooBigScale*tooBigScale {\n\t\t\tlevel--\n\t\t\tscale \/= 4\n\t\t\tw *= 2\n\t\t\th *= 2\n\t\t\tif w >= mipmapMaxSize || h >= mipmapMaxSize {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If tooBigScale is 4, level -10 means that the maximum scale is 4 * 2^10 = 4096. This should be\n\t\t\/\/ enough.\n\t\tif level < -10 {\n\t\t\tlevel = -10\n\t\t}\n\t\treturn level\n\t}\n\n\tif filter != driver.FilterLinear {\n\t\treturn 0\n\t}\n\n\tlevel := 0\n\tfor scale < 0.25 {\n\t\tlevel++\n\t\tscale *= 4\n\t}\n\n\tif level > 0 {\n\t\t\/\/ If the image can be scaled into 0 size, adjust the level. (#839)\n\t\tw, h := int(sx1-sx0), int(sy1-sy0)\n\t\tfor level >= 0 {\n\t\t\ts := 1 << uint(level)\n\t\t\tif (w > 0 && w\/s == 0) || (h > 0 && h\/s == 0) {\n\t\t\t\tlevel--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif level < 0 {\n\t\t\t\/\/ As the render source is too small, nothing is rendered.\n\t\t\treturn 0\n\t\t}\n\t}\n\n\tif level > 6 {\n\t\tlevel = 6\n\t}\n\n\treturn level\n}\n\nfunc pow2(power int) float32 {\n\tif power >= 0 {\n\t\tx := 1\n\t\treturn float32(x << uint(power))\n\t}\n\n\tx := float32(1)\n\tfor i := 0; i < -power; i++ {\n\t\tx \/= 2\n\t}\n\treturn x\n}\n\ntype Shader struct {\n\tshader *buffered.Shader\n}\n\nfunc NewShader(program *shaderir.Program) *Shader {\n\treturn &Shader{\n\t\tshader: buffered.NewShader(program),\n\t}\n}\n\nfunc (s *Shader) MarkDisposed() {\n\ts.shader.MarkDisposed()\n\ts.shader = nil\n}\nmipmap: Bug fix: HasHighPrecisionFloat cannot be called before the main loop\/\/ Copyright 2018 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mipmap\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"math\"\n\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/affine\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/buffered\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/graphics\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\nvar graphicsDriver driver.Graphics\n\nfunc SetGraphicsDriver(graphics driver.Graphics) {\n\tgraphicsDriver = graphics\n}\n\nfunc BeginFrame() error {\n\treturn buffered.BeginFrame()\n}\n\nfunc EndFrame() error {\n\treturn buffered.EndFrame()\n}\n\n\/\/ Mipmap is a set of buffered.Image sorted by the order of mipmap level.\n\/\/ The level 0 image is a regular image and higher-level images are used for mipmap.\ntype Mipmap struct {\n\twidth int\n\theight int\n\tvolatile bool\n\torig *buffered.Image\n\timgs map[int]*buffered.Image\n}\n\nfunc New(width, height int, volatile bool) *Mipmap {\n\treturn &Mipmap{\n\t\twidth: width,\n\t\theight: height,\n\t\tvolatile: volatile,\n\t\torig: buffered.NewImage(width, height, volatile),\n\t\timgs: map[int]*buffered.Image{},\n\t}\n}\n\nfunc NewScreenFramebufferMipmap(width, height int) *Mipmap {\n\treturn &Mipmap{\n\t\twidth: width,\n\t\theight: height,\n\t\torig: buffered.NewScreenFramebufferImage(width, height),\n\t\timgs: map[int]*buffered.Image{},\n\t}\n}\n\nfunc (m *Mipmap) Dump(name string, blackbg bool) error {\n\treturn m.orig.Dump(name, blackbg)\n}\n\nfunc (m *Mipmap) Fill(clr color.RGBA) {\n\tm.orig.Fill(clr)\n\tm.disposeMipmaps()\n}\n\nfunc (m *Mipmap) ReplacePixels(pix []byte, x, y, width, height int) error {\n\tif err := m.orig.ReplacePixels(pix, x, y, width, height); err != nil {\n\t\treturn err\n\t}\n\tm.disposeMipmaps()\n\treturn nil\n}\n\nfunc (m *Mipmap) Pixels(x, y, width, height int) ([]byte, error) {\n\treturn m.orig.Pixels(x, y, width, height)\n}\n\nfunc (m *Mipmap) DrawTriangles(srcs [graphics.ShaderImageNum]*Mipmap, vertices []float32, indices []uint16, colorm *affine.ColorM, mode driver.CompositeMode, filter driver.Filter, address driver.Address, sourceRegion driver.Region, shader *Shader, uniforms []interface{}, canSkipMipmap bool) {\n\tif len(indices) == 0 {\n\t\treturn\n\t}\n\n\tlevel := 0\n\t\/\/ TODO: Do we need to check all the sources' states of being volatile?\n\tif !canSkipMipmap && srcs[0] != nil && !srcs[0].volatile && filter != driver.FilterScreen {\n\t\tlevel = math.MaxInt32\n\t\tfor i := 0; i < len(indices)\/3; i++ {\n\t\t\tconst n = graphics.VertexFloatNum\n\t\t\tdx0 := vertices[n*indices[3*i]+0]\n\t\t\tdy0 := vertices[n*indices[3*i]+1]\n\t\t\tsx0 := vertices[n*indices[3*i]+2]\n\t\t\tsy0 := vertices[n*indices[3*i]+3]\n\t\t\tdx1 := vertices[n*indices[3*i+1]+0]\n\t\t\tdy1 := vertices[n*indices[3*i+1]+1]\n\t\t\tsx1 := vertices[n*indices[3*i+1]+2]\n\t\t\tsy1 := vertices[n*indices[3*i+1]+3]\n\t\t\tdx2 := vertices[n*indices[3*i+2]+0]\n\t\t\tdy2 := vertices[n*indices[3*i+2]+1]\n\t\t\tsx2 := vertices[n*indices[3*i+2]+2]\n\t\t\tsy2 := vertices[n*indices[3*i+2]+3]\n\t\t\tif l := mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t\tif l := mipmapLevelFromDistance(dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t\tif l := mipmapLevelFromDistance(dx2, dy2, dx0, dy0, sx2, sy2, sx0, sy0, filter); level > l {\n\t\t\t\tlevel = l\n\t\t\t}\n\t\t}\n\t\tif level == math.MaxInt32 {\n\t\t\tpanic(\"mipmap: level must be calculated at least once but not\")\n\t\t}\n\t}\n\n\tif colorm != nil && colorm.ScaleOnly() {\n\t\tbody, _ := colorm.UnsafeElements()\n\t\tcr := body[0]\n\t\tcg := body[5]\n\t\tcb := body[10]\n\t\tca := body[15]\n\t\tcolorm = nil\n\t\tconst n = graphics.VertexFloatNum\n\t\tfor i := 0; i < len(vertices)\/n; i++ {\n\t\t\tvertices[i*n+4] *= cr\n\t\t\tvertices[i*n+5] *= cg\n\t\t\tvertices[i*n+6] *= cb\n\t\t\tvertices[i*n+7] *= ca\n\t\t}\n\t}\n\n\tvar s *buffered.Shader\n\tif shader != nil {\n\t\ts = shader.shader\n\t}\n\n\tvar imgs [graphics.ShaderImageNum]*buffered.Image\n\tfor i, src := range srcs {\n\t\tif src == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif level != 0 {\n\t\t\tif img := src.level(level); img != nil {\n\t\t\t\tconst n = graphics.VertexFloatNum\n\t\t\t\ts := float32(pow2(level))\n\t\t\t\tfor i := 0; i < len(vertices)\/n; i++ {\n\t\t\t\t\tvertices[i*n+2] \/= s\n\t\t\t\t\tvertices[i*n+3] \/= s\n\t\t\t\t}\n\t\t\t\timgs[i] = img\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\timgs[i] = src.orig\n\t}\n\n\tm.orig.DrawTriangles(imgs, vertices, indices, colorm, mode, filter, address, sourceRegion, s, uniforms)\n\tm.disposeMipmaps()\n}\n\nfunc (m *Mipmap) level(level int) *buffered.Image {\n\tif level == 0 {\n\t\tpanic(\"ebiten: level must be non-zero at level\")\n\t}\n\n\tif m.volatile {\n\t\tpanic(\"ebiten: mipmap images for a volatile image is not implemented yet\")\n\t}\n\n\tif img, ok := m.imgs[level]; ok {\n\t\treturn img\n\t}\n\n\tvar src *buffered.Image\n\tvar vs []float32\n\tvar filter driver.Filter\n\tswitch {\n\tcase level == 1:\n\t\tsrc = m.orig\n\t\tvs = graphics.QuadVertices(0, 0, float32(m.width), float32(m.height), 0.5, 0, 0, 0.5, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterLinear\n\tcase level > 1:\n\t\tsrc = m.level(level - 1)\n\t\tif src == nil {\n\t\t\tm.imgs[level] = nil\n\t\t\treturn nil\n\t\t}\n\t\tw := sizeForLevel(m.width, level-1)\n\t\th := sizeForLevel(m.height, level-1)\n\t\tvs = graphics.QuadVertices(0, 0, float32(w), float32(h), 0.5, 0, 0, 0.5, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterLinear\n\tcase level == -1:\n\t\tsrc = m.orig\n\t\tvs = graphics.QuadVertices(0, 0, float32(m.width), float32(m.height), 2, 0, 0, 2, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterNearest\n\tcase level < -1:\n\t\tsrc = m.level(level + 1)\n\t\tif src == nil {\n\t\t\tm.imgs[level] = nil\n\t\t\treturn nil\n\t\t}\n\t\tw := sizeForLevel(m.width, level-1)\n\t\th := sizeForLevel(m.height, level-1)\n\t\tvs = graphics.QuadVertices(0, 0, float32(w), float32(h), 2, 0, 0, 2, 0, 0, 1, 1, 1, 1, false)\n\t\tfilter = driver.FilterNearest\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"ebiten: invalid level: %d\", level))\n\t}\n\tis := graphics.QuadIndices()\n\n\tw2 := sizeForLevel(m.width, level-1)\n\th2 := sizeForLevel(m.height, level-1)\n\tif w2 == 0 || h2 == 0 {\n\t\tm.imgs[level] = nil\n\t\treturn nil\n\t}\n\ts := buffered.NewImage(w2, h2, m.volatile)\n\ts.DrawTriangles([graphics.ShaderImageNum]*buffered.Image{src}, vs, is, nil, driver.CompositeModeCopy, filter, driver.AddressUnsafe, driver.Region{}, nil, nil)\n\tm.imgs[level] = s\n\n\treturn m.imgs[level]\n}\n\nfunc sizeForLevel(x int, level int) int {\n\tif level > 0 {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tx \/= 2\n\t\t\tif x == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < -level; i++ {\n\t\t\tx *= 2\n\t\t}\n\t}\n\treturn x\n}\n\nfunc (m *Mipmap) MarkDisposed() {\n\tm.disposeMipmaps()\n\tm.orig.MarkDisposed()\n\tm.orig = nil\n}\n\nfunc (m *Mipmap) disposeMipmaps() {\n\tfor _, img := range m.imgs {\n\t\timg.MarkDisposed()\n\t}\n\tfor k := range m.imgs {\n\t\tdelete(m.imgs, k)\n\t}\n}\n\n\/\/ mipmapLevel returns an appropriate mipmap level for the given distance.\nfunc mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, filter driver.Filter) int {\n\tif filter == driver.FilterScreen {\n\t\treturn 0\n\t}\n\n\td := (dx1-dx0)*(dx1-dx0) + (dy1-dy0)*(dy1-dy0)\n\ts := (sx1-sx0)*(sx1-sx0) + (sy1-sy0)*(sy1-sy0)\n\tif s == 0 {\n\t\treturn 0\n\t}\n\tscale := d \/ s\n\n\t\/\/ Use 'negative' mipmap to render edges correctly (#611, #907).\n\t\/\/ It looks like 128 is the enlargement factor that causes edge missings to pass the test TestImageStretch,\n\t\/\/ but we use 64 here for environments where the float precision is low (#1044, #1270).\n\tvar tooBigScale float32 = 64\n\n\tif scale >= tooBigScale*tooBigScale {\n\t\t\/\/ If the filter is not nearest, the target needs to be rendered with graduation. Don't use mipmaps.\n\t\tif filter != driver.FilterNearest {\n\t\t\treturn 0\n\t\t}\n\n\t\tconst mipmapMaxSize = 1024\n\t\tw, h := sx1-sx0, sy1-sy0\n\t\tif w >= mipmapMaxSize || h >= mipmapMaxSize {\n\t\t\treturn 0\n\t\t}\n\n\t\tlevel := 0\n\t\tfor scale >= tooBigScale*tooBigScale {\n\t\t\tlevel--\n\t\t\tscale \/= 4\n\t\t\tw *= 2\n\t\t\th *= 2\n\t\t\tif w >= mipmapMaxSize || h >= mipmapMaxSize {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If tooBigScale is 64, level -6 means that the maximum scale is 64 * 2^6 = 4096. This should be\n\t\t\/\/ enough.\n\t\tif level < -6 {\n\t\t\tlevel = -6\n\t\t}\n\t\treturn level\n\t}\n\n\tif filter != driver.FilterLinear {\n\t\treturn 0\n\t}\n\n\tlevel := 0\n\tfor scale < 0.25 {\n\t\tlevel++\n\t\tscale *= 4\n\t}\n\n\tif level > 0 {\n\t\t\/\/ If the image can be scaled into 0 size, adjust the level. (#839)\n\t\tw, h := int(sx1-sx0), int(sy1-sy0)\n\t\tfor level >= 0 {\n\t\t\ts := 1 << uint(level)\n\t\t\tif (w > 0 && w\/s == 0) || (h > 0 && h\/s == 0) {\n\t\t\t\tlevel--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif level < 0 {\n\t\t\t\/\/ As the render source is too small, nothing is rendered.\n\t\t\treturn 0\n\t\t}\n\t}\n\n\tif level > 6 {\n\t\tlevel = 6\n\t}\n\n\treturn level\n}\n\nfunc pow2(power int) float32 {\n\tif power >= 0 {\n\t\tx := 1\n\t\treturn float32(x << uint(power))\n\t}\n\n\tx := float32(1)\n\tfor i := 0; i < -power; i++ {\n\t\tx \/= 2\n\t}\n\treturn x\n}\n\ntype Shader struct {\n\tshader *buffered.Shader\n}\n\nfunc NewShader(program *shaderir.Program) *Shader {\n\treturn &Shader{\n\t\tshader: buffered.NewShader(program),\n\t}\n}\n\nfunc (s *Shader) MarkDisposed() {\n\ts.shader.MarkDisposed()\n\ts.shader = nil\n}\n<|endoftext|>"} {"text":"package kubelego\n\nimport (\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/jetstack\/kube-lego\/pkg\/ingress\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/extensions\"\n\t\"k8s.io\/kubernetes\/pkg\/client\/cache\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/controller\/framework\"\n\t\"k8s.io\/kubernetes\/pkg\/runtime\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/workqueue\"\n\t\"k8s.io\/kubernetes\/pkg\/watch\"\n)\n\nfunc ingressListFunc(c *client.Client, ns string) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\treturn c.Extensions().Ingress(ns).List(opts)\n\t}\n}\n\nfunc ingressWatchFunc(c *client.Client, ns string) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\treturn c.Extensions().Ingress(ns).Watch(options)\n\t}\n}\n\nfunc (kl *KubeLego) requestReconfigure() {\n\tkl.workQueue.Add(true)\n}\n\nfunc (kl *KubeLego) WatchReconfigure() {\n\n\tkl.workQueue = workqueue.New()\n\n\t\/\/ handle worker shutdown\n\tgo func() {\n\t\t<-kl.stopCh\n\t\tkl.workQueue.ShutDown()\n\t}()\n\n\tgo func() {\n\t\tkl.waitGroup.Add(1)\n\t\tdefer kl.waitGroup.Done()\n\t\tfor {\n\t\t\titem, quit := kl.workQueue.Get()\n\t\t\tif quit {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"worker: begin processing %v\", item)\n\t\t\tkl.Reconfigure()\n\t\t\tkl.Log().Debugf(\"worker: done processing %v\", item)\n\t\t\tkl.workQueue.Done(item)\n\t\t}\n\t}()\n}\n\nfunc (kl *KubeLego) WatchEvents() {\n\n\tkl.Log().Debugf(\"start watching ingress objects\")\n\n\tresyncPeriod := 10 * time.Second\n\n\tingEventHandler := framework.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\taddIng := obj.(*extensions.Ingress)\n\t\t\tif ingress.IgnoreIngress(addIng) != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"CREATE ingress\/%s\/%s\", addIng.Namespace, addIng.Name)\n\t\t\tkl.workQueue.Add(true)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdelIng := obj.(*extensions.Ingress)\n\t\t\tif ingress.IgnoreIngress(delIng) != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"DELETE ingress\/%s\/%s\", delIng.Namespace, delIng.Name)\n\t\t\tkl.workQueue.Add(true)\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tif !reflect.DeepEqual(old, cur) {\n\t\t\t\tupIng := cur.(*extensions.Ingress)\n\t\t\t\tif ingress.IgnoreIngress(upIng) != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tkl.Log().Debugf(\"UPDATE ingress\/%s\/%s\", upIng.Namespace, upIng.Name)\n\t\t\t\tkl.workQueue.Add(true)\n\t\t\t}\n\t\t},\n\t}\n\n\t_, controller := framework.NewInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc: ingressListFunc(kl.kubeClient, api.NamespaceAll),\n\t\t\tWatchFunc: ingressWatchFunc(kl.kubeClient, api.NamespaceAll),\n\t\t},\n\t\t&extensions.Ingress{},\n\t\tresyncPeriod,\n\t\tingEventHandler,\n\t)\n\n\tgo controller.Run(kl.stopCh)\n}\nRaise resync period to 60 seconds, should be more than enoughpackage kubelego\n\nimport (\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/jetstack\/kube-lego\/pkg\/ingress\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/extensions\"\n\t\"k8s.io\/kubernetes\/pkg\/client\/cache\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/controller\/framework\"\n\t\"k8s.io\/kubernetes\/pkg\/runtime\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/workqueue\"\n\t\"k8s.io\/kubernetes\/pkg\/watch\"\n)\n\nfunc ingressListFunc(c *client.Client, ns string) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\treturn c.Extensions().Ingress(ns).List(opts)\n\t}\n}\n\nfunc ingressWatchFunc(c *client.Client, ns string) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\treturn c.Extensions().Ingress(ns).Watch(options)\n\t}\n}\n\nfunc (kl *KubeLego) requestReconfigure() {\n\tkl.workQueue.Add(true)\n}\n\nfunc (kl *KubeLego) WatchReconfigure() {\n\n\tkl.workQueue = workqueue.New()\n\n\t\/\/ handle worker shutdown\n\tgo func() {\n\t\t<-kl.stopCh\n\t\tkl.workQueue.ShutDown()\n\t}()\n\n\tgo func() {\n\t\tkl.waitGroup.Add(1)\n\t\tdefer kl.waitGroup.Done()\n\t\tfor {\n\t\t\titem, quit := kl.workQueue.Get()\n\t\t\tif quit {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"worker: begin processing %v\", item)\n\t\t\tkl.Reconfigure()\n\t\t\tkl.Log().Debugf(\"worker: done processing %v\", item)\n\t\t\tkl.workQueue.Done(item)\n\t\t}\n\t}()\n}\n\nfunc (kl *KubeLego) WatchEvents() {\n\n\tkl.Log().Debugf(\"start watching ingress objects\")\n\n\tresyncPeriod := 60 * time.Second\n\n\tingEventHandler := framework.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\taddIng := obj.(*extensions.Ingress)\n\t\t\tif ingress.IgnoreIngress(addIng) != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"CREATE ingress\/%s\/%s\", addIng.Namespace, addIng.Name)\n\t\t\tkl.workQueue.Add(true)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdelIng := obj.(*extensions.Ingress)\n\t\t\tif ingress.IgnoreIngress(delIng) != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tkl.Log().Debugf(\"DELETE ingress\/%s\/%s\", delIng.Namespace, delIng.Name)\n\t\t\tkl.workQueue.Add(true)\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tif !reflect.DeepEqual(old, cur) {\n\t\t\t\tupIng := cur.(*extensions.Ingress)\n\t\t\t\tif ingress.IgnoreIngress(upIng) != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tkl.Log().Debugf(\"UPDATE ingress\/%s\/%s\", upIng.Namespace, upIng.Name)\n\t\t\t\tkl.workQueue.Add(true)\n\t\t\t}\n\t\t},\n\t}\n\n\t_, controller := framework.NewInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc: ingressListFunc(kl.kubeClient, api.NamespaceAll),\n\t\t\tWatchFunc: ingressWatchFunc(kl.kubeClient, api.NamespaceAll),\n\t\t},\n\t\t&extensions.Ingress{},\n\t\tresyncPeriod,\n\t\tingEventHandler,\n\t)\n\n\tgo controller.Run(kl.stopCh)\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/gorilla\/mux\"\n\tnlog \"github.com\/nuveo\/log\"\n\t\"github.com\/prest\/prest\/adapters\/postgres\"\n\t\"github.com\/prest\/prest\/config\"\n\t\"github.com\/prest\/prest\/config\/router\"\n\t\"github.com\/prest\/prest\/controllers\"\n\t\"github.com\/prest\/prest\/middlewares\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/urfave\/negroni\"\n)\n\n\/\/ RootCmd represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse: \"prest\",\n\tShort: \"Serve a RESTful API from any PostgreSQL database\",\n\tLong: `Serve a RESTful API from any PostgreSQL database, start HTTP server`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif config.PrestConf.Adapter == nil {\n\t\t\tnlog.Warningln(\"adapter is not set. Using the default (postgres)\")\n\t\t\tpostgres.Load()\n\t\t}\n\t\tstartServer()\n\t},\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tupCmd.AddCommand(authUpCmd)\n\tdownCmd.AddCommand(authDownCmd)\n\tmigrateCmd.AddCommand(downCmd)\n\tmigrateCmd.AddCommand(mversionCmd)\n\tmigrateCmd.AddCommand(nextCmd)\n\tmigrateCmd.AddCommand(redoCmd)\n\tmigrateCmd.AddCommand(upCmd)\n\tmigrateCmd.AddCommand(resetCmd)\n\tRootCmd.AddCommand(versionCmd)\n\tRootCmd.AddCommand(migrateCmd)\n\tmigrateCmd.PersistentFlags().StringVar(&urlConn, \"url\", driverURL(), \"Database driver url\")\n\tmigrateCmd.PersistentFlags().StringVar(&path, \"path\", config.PrestConf.MigrationsPath, \"Migrations directory\")\n\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n\/\/ MakeHandler reagister all routes\nfunc MakeHandler() http.Handler {\n\tn := middlewares.GetApp()\n\tr := router.Get()\n\tr.HandleFunc(\"\/databases\", controllers.GetDatabases).Methods(\"GET\")\n\tr.HandleFunc(\"\/schemas\", controllers.GetSchemas).Methods(\"GET\")\n\tr.HandleFunc(\"\/tables\", controllers.GetTables).Methods(\"GET\")\n\tr.HandleFunc(\"\/_QUERIES\/{queriesLocation}\/{script}\", controllers.ExecuteFromScripts)\n\tr.HandleFunc(\"\/{database}\/{schema}\", controllers.GetTablesByDatabaseAndSchema).Methods(\"GET\")\n\tr.HandleFunc(\"\/show\/{database}\/{schema}\/{table}\", controllers.ShowTable).Methods(\"GET\")\n\tcrudRoutes := mux.NewRouter().PathPrefix(\"\/\").Subrouter().StrictSlash(true)\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.SelectFromTables).Methods(\"GET\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.InsertInTables).Methods(\"POST\")\n\tcrudRoutes.HandleFunc(\"\/batch\/{database}\/{schema}\/{table}\", controllers.BatchInsertInTables).Methods(\"POST\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.DeleteFromTable).Methods(\"DELETE\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.UpdateTable).Methods(\"PUT\", \"PATCH\")\n\tr.PathPrefix(\"\/\").Handler(negroni.New(\n\t\tmiddlewares.AccessControl(),\n\t\tnegroni.Wrap(crudRoutes),\n\t))\n\tn.UseHandler(r)\n\treturn n\n}\n\nfunc startServer() {\n\thttp.Handle(config.PrestConf.ContextPath, MakeHandler())\n\tl := log.New(os.Stdout, \"[prest] \", 0)\n\n\tif !config.PrestConf.AccessConf.Restrict {\n\t\tnlog.Warningln(\"You are running pREST in public mode.\")\n\t}\n\n\tif config.PrestConf.Debug {\n\t\tnlog.DebugMode = config.PrestConf.Debug\n\t\tnlog.Warningln(\"You are running pREST in debug mode.\")\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", config.PrestConf.HTTPHost, config.PrestConf.HTTPPort)\n\tl.Printf(\"listening on %s and serving on %s\", addr, config.PrestConf.ContextPath)\n\tif config.PrestConf.HTTPSMode {\n\t\tl.Fatal(http.ListenAndServeTLS(addr, config.PrestConf.HTTPSCert, config.PrestConf.HTTPSKey, nil))\n\t}\n\tl.Fatal(http.ListenAndServe(addr, nil))\n}\nfeat(cmd): add \/auth route when auth is enabledpackage cmd\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/gorilla\/mux\"\n\tnlog \"github.com\/nuveo\/log\"\n\t\"github.com\/prest\/prest\/adapters\/postgres\"\n\t\"github.com\/prest\/prest\/config\"\n\t\"github.com\/prest\/prest\/config\/router\"\n\t\"github.com\/prest\/prest\/controllers\"\n\t\"github.com\/prest\/prest\/middlewares\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/urfave\/negroni\"\n)\n\n\/\/ RootCmd represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse: \"prest\",\n\tShort: \"Serve a RESTful API from any PostgreSQL database\",\n\tLong: `Serve a RESTful API from any PostgreSQL database, start HTTP server`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif config.PrestConf.Adapter == nil {\n\t\t\tnlog.Warningln(\"adapter is not set. Using the default (postgres)\")\n\t\t\tpostgres.Load()\n\t\t}\n\t\tstartServer()\n\t},\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tupCmd.AddCommand(authUpCmd)\n\tdownCmd.AddCommand(authDownCmd)\n\tmigrateCmd.AddCommand(downCmd)\n\tmigrateCmd.AddCommand(mversionCmd)\n\tmigrateCmd.AddCommand(nextCmd)\n\tmigrateCmd.AddCommand(redoCmd)\n\tmigrateCmd.AddCommand(upCmd)\n\tmigrateCmd.AddCommand(resetCmd)\n\tRootCmd.AddCommand(versionCmd)\n\tRootCmd.AddCommand(migrateCmd)\n\tmigrateCmd.PersistentFlags().StringVar(&urlConn, \"url\", driverURL(), \"Database driver url\")\n\tmigrateCmd.PersistentFlags().StringVar(&path, \"path\", config.PrestConf.MigrationsPath, \"Migrations directory\")\n\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\n\/\/ MakeHandler reagister all routes\nfunc MakeHandler() http.Handler {\n\tn := middlewares.GetApp()\n\tr := router.Get()\n\t\/\/ if auth is enabled\n\tif config.PrestConf.AuthEnabled {\n\t\tr.HandleFunc(\"\/auth\", controllers.Auth).Methods(\"POST\")\n\t}\n\tr.HandleFunc(\"\/databases\", controllers.GetDatabases).Methods(\"GET\")\n\tr.HandleFunc(\"\/schemas\", controllers.GetSchemas).Methods(\"GET\")\n\tr.HandleFunc(\"\/tables\", controllers.GetTables).Methods(\"GET\")\n\tr.HandleFunc(\"\/_QUERIES\/{queriesLocation}\/{script}\", controllers.ExecuteFromScripts)\n\tr.HandleFunc(\"\/{database}\/{schema}\", controllers.GetTablesByDatabaseAndSchema).Methods(\"GET\")\n\tr.HandleFunc(\"\/show\/{database}\/{schema}\/{table}\", controllers.ShowTable).Methods(\"GET\")\n\tcrudRoutes := mux.NewRouter().PathPrefix(\"\/\").Subrouter().StrictSlash(true)\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.SelectFromTables).Methods(\"GET\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.InsertInTables).Methods(\"POST\")\n\tcrudRoutes.HandleFunc(\"\/batch\/{database}\/{schema}\/{table}\", controllers.BatchInsertInTables).Methods(\"POST\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.DeleteFromTable).Methods(\"DELETE\")\n\tcrudRoutes.HandleFunc(\"\/{database}\/{schema}\/{table}\", controllers.UpdateTable).Methods(\"PUT\", \"PATCH\")\n\tr.PathPrefix(\"\/\").Handler(negroni.New(\n\t\tmiddlewares.AccessControl(),\n\t\tnegroni.Wrap(crudRoutes),\n\t))\n\tn.UseHandler(r)\n\treturn n\n}\n\nfunc startServer() {\n\thttp.Handle(config.PrestConf.ContextPath, MakeHandler())\n\tl := log.New(os.Stdout, \"[prest] \", 0)\n\n\tif !config.PrestConf.AccessConf.Restrict {\n\t\tnlog.Warningln(\"You are running pREST in public mode.\")\n\t}\n\n\tif config.PrestConf.Debug {\n\t\tnlog.DebugMode = config.PrestConf.Debug\n\t\tnlog.Warningln(\"You are running pREST in debug mode.\")\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", config.PrestConf.HTTPHost, config.PrestConf.HTTPPort)\n\tl.Printf(\"listening on %s and serving on %s\", addr, config.PrestConf.ContextPath)\n\tif config.PrestConf.HTTPSMode {\n\t\tl.Fatal(http.ListenAndServeTLS(addr, config.PrestConf.HTTPSCert, config.PrestConf.HTTPSKey, nil))\n\t}\n\tl.Fatal(http.ListenAndServe(addr, nil))\n}\n<|endoftext|>"} {"text":"\/\/ Package logentrus acts as a Logentries (https:\/\/logentries.com) hook\n\/\/ for Logrus (https:\/\/github.com\/Sirupsen\/logrus)\npackage logentrus\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\n\/\/ Hook used to send logs to logentries\ntype Hook struct {\n\tlevels []logrus.Level\n\ttoken string\n\tformatter *logrus.JSONFormatter\n\ttlsConfig *tls.Config\n\tconn net.Conn\n}\n\nconst (\n\thost = \"data.logentries.com\"\n\tport = 443\n\tretryCount = 3\n)\n\n\/\/ New creates and returns a new hook for use in Logrus\nfunc New(token, timestampFormat string, priority logrus.Level, config *tls.Config) (hook *Hook, err error) {\n\tif token == \"\" {\n\t\terr = fmt.Errorf(\"Unable to create new LogentriesHook since a Token is required\")\n\t} else {\n\t\thook = &Hook{\n\t\t\tlevels: logrus.AllLevels[:priority+1], \/\/ Include all levels at or within the provided priority\n\t\t\ttoken: token,\n\t\t\ttlsConfig: config,\n\t\t\tformatter: &logrus.JSONFormatter{\n\t\t\t\tTimestampFormat: timestampFormat,\n\t\t\t},\n\t\t}\n\n\t\terr = hook.dial()\n\t}\n\treturn\n}\n\n\/\/ Levels returns the log levels supported by this hook\nfunc (hook *Hook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\n\/\/ Fire formats and sends JSON entry to Logentries service\nfunc (hook *Hook) Fire(entry *logrus.Entry) (err error) {\n\tline, err := hook.format(entry)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to read entry | err: %v | entry: %+v\\n\", err, entry)\n\t\treturn err\n\t}\n\n\tif err = hook.write(line); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: Unable to write to conn | err: %v | line: %s\\n\", err, line)\n\t}\n\n\treturn\n}\n\nfunc (hook *Hook) dial() (err error) {\n\thook.conn, err = tls.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port), hook.tlsConfig)\n\treturn\n}\n\nfunc (hook *Hook) write(line string) (err error) {\n\tdata := []byte(hook.token + line)\n\n\t_, err = hook.conn.Write(data)\n\tfor i := 0; err != nil && i < retryCount; i++ {\n\t\tfmt.Fprintf(os.Stderr, \"WARNING: Trouble writing to conn; retrying %d of %d | err: %v\\n\", i, retryCount, err)\n\n\t\thook.conn.Close() \/\/ close connection and ignore error\n\t\tif dialErr := hook.dial(); dialErr != nil { \/\/ Problem with write, so dial new connection and retry if possible\n\t\t\tfmt.Fprintf(os.Stderr, \"ERROR: Unable to dial new connection | dialErr: %v\\n\", dialErr)\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = hook.conn.Write(data); err == nil {\n\t\t\tfmt.Fprint(os.Stderr, \"RECOVERED: Connection redialed and wrote successfully\")\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (hook Hook) format(entry *logrus.Entry) (string, error) {\n\tserialized, err := hook.formatter.Format(entry)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := string(serialized)\n\treturn str, nil\n}\nUpdate recovery message with newline suffix\/\/ Package logentrus acts as a Logentries (https:\/\/logentries.com) hook\n\/\/ for Logrus (https:\/\/github.com\/Sirupsen\/logrus)\npackage logentrus\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\n\/\/ Hook used to send logs to logentries\ntype Hook struct {\n\tlevels []logrus.Level\n\ttoken string\n\tformatter *logrus.JSONFormatter\n\ttlsConfig *tls.Config\n\tconn net.Conn\n}\n\nconst (\n\thost = \"data.logentries.com\"\n\tport = 443\n\tretryCount = 3\n)\n\n\/\/ New creates and returns a new hook for use in Logrus\nfunc New(token, timestampFormat string, priority logrus.Level, config *tls.Config) (hook *Hook, err error) {\n\tif token == \"\" {\n\t\terr = fmt.Errorf(\"Unable to create new LogentriesHook since a Token is required\")\n\t} else {\n\t\thook = &Hook{\n\t\t\tlevels: logrus.AllLevels[:priority+1], \/\/ Include all levels at or within the provided priority\n\t\t\ttoken: token,\n\t\t\ttlsConfig: config,\n\t\t\tformatter: &logrus.JSONFormatter{\n\t\t\t\tTimestampFormat: timestampFormat,\n\t\t\t},\n\t\t}\n\n\t\terr = hook.dial()\n\t}\n\treturn\n}\n\n\/\/ Levels returns the log levels supported by this hook\nfunc (hook *Hook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\n\/\/ Fire formats and sends JSON entry to Logentries service\nfunc (hook *Hook) Fire(entry *logrus.Entry) (err error) {\n\tline, err := hook.format(entry)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to read entry | err: %v | entry: %+v\\n\", err, entry)\n\t\treturn err\n\t}\n\n\tif err = hook.write(line); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: Unable to write to conn | err: %v | line: %s\\n\", err, line)\n\t}\n\n\treturn\n}\n\nfunc (hook *Hook) dial() (err error) {\n\thook.conn, err = tls.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port), hook.tlsConfig)\n\treturn\n}\n\nfunc (hook *Hook) write(line string) (err error) {\n\tdata := []byte(hook.token + line)\n\n\t_, err = hook.conn.Write(data) \/\/ initial write attempt\n\tfor i := 0; err != nil && i < retryCount; i++ {\n\t\tfmt.Fprintf(os.Stderr, \"WARNING: Trouble writing to conn; retrying %d of %d | err: %v\\n\", i, retryCount, err)\n\t\thook.conn.Close() \/\/ close connection and ignore error\n\t\tif dialErr := hook.dial(); dialErr != nil { \/\/ Problem with write, so dial new connection and retry if possible\n\t\t\tfmt.Fprintf(os.Stderr, \"ERROR: Unable to dial new connection | dialErr: %v\\n\", dialErr)\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = hook.conn.Write(data); err == nil { \/\/ retry write\n\t\t\tfmt.Fprintln(os.Stderr, \"RECOVERED: Connection redialed and wrote successfully\")\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (hook Hook) format(entry *logrus.Entry) (string, error) {\n\tserialized, err := hook.formatter.Format(entry)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := string(serialized)\n\treturn str, nil\n}\n<|endoftext|>"} {"text":"\/\/ Package logreplay provides a client that can replay HTTP requests based access logs.\n\/\/\n\/\/ The player can replay the requests once or infinitely in a loop. It can pause or\n\/\/ reset the scenario. It can replay the scenario with a concurrency level of choice.\n\/\/ The player accepts custom request definitions besides or instead of the access log\n\/\/ input.\n\/\/\n\/\/ The player is provided as an embeddable library, and a simple command is provided as\n\/\/ subpackage.\npackage logreplay\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\n\/\/ RedirectBehavior defines how to handle redirect responses.\ntype RedirectBehavior int\n\nconst (\n\n\t\/\/ NoFollow tells the player not to follow redirects.\n\tNoFollow RedirectBehavior = iota\n\n\t\/\/ SameHost tells the player to follow redirects only to the same host\n\t\/\/ as the request was made to.\n\tSameHost\n\n\t\/\/ Follow tells the player to follow all redirects. (Not recommended\n\t\/\/ during load tests.)\n\tFollow\n)\n\n\/\/ HaltPolicy defines whether to halt on failed requests. It is used in combination\n\/\/ with HaltThreshold.\ntype HaltPolicy int\n\nconst (\n\n\t\/\/ PauseOnError tells the player to pause requests when an error occurs.\n\tPauseOnError HaltPolicy = iota\n\n\t\/\/ StopOnError tells the player to stop requests when an error occurs.\n\tStopOnError\n\n\t\/\/ PauseOn500 tells the player to pause requests when an error or a 500 response occurs.\n\tPauseOn500\n\n\t\/\/ StopOn500 tells the player to stop requests when an error or a 500 response occurs.\n\tStopOn500\n\n\t\/\/ NoHalt tells the player to ignore all request errors and 500s.\n\tNoHalt\n)\n\nconst defaultHaltThreshold = 1 << 7\n\n\/\/ Request describes an individual request made by the player.\ntype Request struct {\n\n\t\/\/ Method is the HTTP method of the request. Defaults to GET.\n\tMethod string\n\n\t\/\/ Host is set as the Host header of the request. When no explicit server is\n\t\/\/ specified in the player options, the Host field will be used as the network\n\t\/\/ address of the request.\n\tHost string\n\n\t\/\/ Path is set as the HTTP path of the request.\n\tPath string\n\n\t\/\/ ContentLength defines the size of the randomly generated request payload.\n\t\/\/\n\t\/\/ When ContentLengthDeviation is defined, the actual size will be randomly\n\t\/\/ decided by ContentLength +\/- rand(ContentLengthDeviation).\n\t\/\/\n\t\/\/ The HTTP ContentLength header is set only when Chunked is false.\n\tContentLength int\n\n\t\/\/ ContentLengthDeviation defines how much the actual random content length of\n\t\/\/ a request can differ from ContentLength.\n\tContentLengthDeviation float64\n\n\t\/\/ Chunked defines if the request content should be sent with chunked transfer\n\t\/\/ encoding.\n\t\/\/\n\t\/\/ TODO: what to do with requests coming from the access logs\n\tChunked bool\n}\n\n\/\/ Parser can parse a log entry.\ntype Parser interface {\n\n\t\/\/ Parse parses a log entry. It accepts a log line as a string\n\t\/\/ and returns a Request definition.\n\tParse(string) Request\n}\n\n\/\/ Options is used to initialize a player.\ntype Options struct {\n\n\t\/\/ Requests to be executed by the player in the specified order.\n\t\/\/\n\t\/\/ When used together with AccessLog, requests defined in this field are\n\t\/\/ executed in the beginning of the scenario.\n\tRequests []Request\n\n\t\/\/ AccessLog is a source of scenario to be executed by the player. By default, it\n\t\/\/ expects a stream of Apache access log entries, and uses the %r field to forge\n\t\/\/ requests.\n\t\/\/\n\t\/\/ In addition to the Combined log format, the default parser accepts two additional\n\t\/\/ fields based on the Skipper (https:\/\/github.com\/zalando\/skipper) access logs,\n\t\/\/ where the request host is taken from the last field (following an integer for\n\t\/\/ duration.)\n\t\/\/\n\t\/\/ Known bugs in the default parser:\n\t\/\/\n\t\/\/ \t- escaped double quotes in the HTTP message not handled\n\t\/\/ \t- whitespace handling in the HTTP message: only whitespace\n\t\/\/\n\tAccessLog io.Reader\n\n\t\/\/ AccessLogFormat is a regular expression and can be used to override the default\n\t\/\/ parser expression. The expression can define the following named groups:\n\t\/\/ method, host, path. The captured submatches with these names will be used to\n\t\/\/ set the according field in the parsed request.\n\t\/\/\n\t\/\/ If Parser is set, this field is ignored.\n\tAccessLogFormat string\n\n\t\/\/ Parser is a custom parser for log entries (lines). It can be used e.g. to define\n\t\/\/ a JSON log parser.\n\tParser Parser\n\n\t\/\/ AccessLogHostField tells the access log parser to take the request from a\n\t\/\/ specific position in the Apache Combined Log Format. Defaults to 11. Value\n\t\/\/ -1 prevents to set the host from the access log. When the host field not\n\t\/\/ specified in the access log, or when taking it from there is disabled, the\n\t\/\/ value of the field Server is used as the host, or, if no server is specified,\n\t\/\/ localhost is used.\n\t\/\/\n\t\/\/ TODO: allow defining custom format\n\tAccessLogHostField int\n\n\t\/\/ Server is a network address to send the requests to.\n\tServer string\n\n\t\/\/ ConcurrentSessions tells the player how many concurrent clients should replay\n\t\/\/ the requests.\n\t\/\/\n\t\/\/ Defaults to 1.\n\tConcurrentSessions int\n\n\t\/\/ RedirectBehavior tells the player how to act on redirect responses.\n\tRedirectBehavior RedirectBehavior\n\n\t\/\/ PostContentLength tells the player the average request content size to send in\n\t\/\/ case of POST, PUT and PATCH requests read from the access log.\n\tPostContentLength int\n\n\t\/\/ PostContentLengthDeviation defines how much the actual random cotnent length of\n\t\/\/ a request read from the access log can differ from PostContentLength.\n\tPostContentLengthDeviation float64\n\n\t\/\/ Log defines a custom logger for the player.\n\tLog Logger\n\n\t\/\/ HaltPolicy tells the player what to do in case an error or a 500 response occurs.\n\t\/\/ The default is to pause on errors (500s ignored).\n\tHaltPolicy HaltPolicy\n\n\t\/\/ HaltThreshold tells the player after how many errors or 500s it should apply the\n\t\/\/ HaltPolicy. Default: 128.\n\tHaltThreshold int\n\n\t\/\/ Throttle maximizes the outgoing overall request per second rate.\n\tThrottle float64\n}\n\n\/\/ Player replays HTTP requests explicitly specified and\/or read from an Apache access log.\ntype Player struct {\n\toptions Options\n\taccessLog *reader\n\trequests []Request\n\tposition int\n\tclient *http.Client\n\terrors int\n\tserverErrors int\n}\n\n\/\/ New initialzies a player.\nfunc New(o Options) (*Player, error) {\n\tif o.Log == nil {\n\t\to.Log = newDefaultLog()\n\t}\n\n\tvar r *reader\n\tif o.AccessLog != nil {\n\t\tvar err error\n\t\tr, err = newReader(o.AccessLog, o.AccessLogFormat, o.Parser, o.Log)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &Player{\n\t\toptions: o,\n\t\taccessLog: r,\n\t\trequests: o.Requests,\n\t\tclient: &http.Client{Transport: &http.Transport{}},\n\t}, nil\n}\n\n\/\/ Play replays the requests infinitely with the specified concurrency. If an access log is\n\/\/ specified it reads it to the end only once, and it repeats the read requests from then on.\n\/\/\n\/\/ When the player is currently playing requests, it is a noop.\nfunc (p *Player) Play() {}\n\n\/\/ Once replays the requests once.\n\/\/\n\/\/ When the player is currently playing requests, it is a noop.\nfunc (p *Player) Once() {\n\tfor {\n\t\tif !func() bool {\n\t\t\tvar r Request\n\t\t\tif p.accessLog == nil {\n\t\t\t\tif p.position >= len(p.requests) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\tr = p.requests[p.position]\n\t\t\t\tp.position++\n\t\t\t} else {\n\t\t\t\tvar err error\n\t\t\t\tr, err = p.accessLog.ReadRequest()\n\t\t\t\tif err != nil && err != io.EOF {\n\t\t\t\t\tp.options.Log.Warnln(\"error while creating url:\", err)\n\n\t\t\t\t\tp.errors++\n\t\t\t\t\tif p.errors >= p.options.HaltThreshold {\n\t\t\t\t\t\tswitch p.options.HaltPolicy {\n\t\t\t\t\t\tcase StopOnError, StopOn500:\n\t\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\t\tp.Stop()\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\tcase PauseOnError, PauseOn500:\n\t\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\t\tp.Pause()\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn true\n\t\t\t\t} else if err == io.EOF {\n\t\t\t\t\tp.options.Log.Infoln(\"access log consumed\")\n\t\t\t\t\tp.accessLog = nil\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\tp.requests = append(\n\t\t\t\t\t\tp.requests[:p.position],\n\t\t\t\t\t\tappend(\n\t\t\t\t\t\t\t[]Request{r},\n\t\t\t\t\t\t\tp.requests[p.position:]...,\n\t\t\t\t\t\t)...,\n\t\t\t\t\t)\n\n\t\t\t\t\tp.position++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm := r.Method\n\t\t\tif m == \"\" {\n\t\t\t\tm = \"GET\"\n\t\t\t}\n\n\t\t\ta := p.options.Server\n\t\t\tif a == \"\" {\n\t\t\t\tif r.Host == \"\" {\n\t\t\t\t\ta = \"http:\/\/localhost\"\n\t\t\t\t} else {\n\t\t\t\t\ta = \"http:\/\/\" + r.Host\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tu, err := url.Parse(a)\n\t\t\tif err != nil {\n\t\t\t\tp.options.Log.Warnln(\"error while creating url:\", err)\n\n\t\t\t\tp.errors++\n\t\t\t\tif p.errors >= p.options.HaltThreshold {\n\t\t\t\t\tswitch p.options.HaltPolicy {\n\t\t\t\t\tcase StopOnError, StopOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Stop()\n\t\t\t\t\t\treturn false\n\t\t\t\t\tcase PauseOnError, PauseOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Pause()\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif u.Scheme == \"\" {\n\t\t\t\tu.Scheme = \"http\"\n\t\t\t}\n\n\t\t\tu.Path = r.Path\n\n\t\t\thr, err := http.NewRequest(m, u.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\tp.options.Log.Errorln(\"failed to create request\", err)\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\th := r.Host\n\t\t\tif h == \"\" {\n\t\t\t\th = p.options.Server\n\t\t\t}\n\n\t\t\tif h == \"\" {\n\t\t\t\th = \"localhost\"\n\t\t\t}\n\n\t\t\thr.Host = h\n\n\t\t\trsp, err := p.client.Do(hr)\n\t\t\tif err != nil {\n\t\t\t\tp.options.Log.Warnln(\"error while making request:\", err)\n\n\t\t\t\tp.errors++\n\t\t\t\tif p.errors >= p.options.HaltThreshold {\n\t\t\t\t\tswitch p.options.HaltPolicy {\n\t\t\t\t\tcase StopOnError, StopOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Stop()\n\t\t\t\t\t\treturn false\n\t\t\t\t\tcase PauseOnError, PauseOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Pause()\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tdefer rsp.Body.Close()\n\n\t\t\tif rsp.StatusCode >= http.StatusInternalServerError {\n\t\t\t\tp.serverErrors++\n\t\t\t\tif p.serverErrors > p.options.HaltThreshold {\n\t\t\t\t\tswitch p.options.HaltPolicy {\n\t\t\t\t\tcase StopOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"server errors exceeded threshold\")\n\t\t\t\t\t\tp.Stop()\n\t\t\t\t\t\treturn false\n\t\t\t\t\tcase PauseOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"server errors exceeded threshold\")\n\t\t\t\t\t\tp.Pause()\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t_, err = ioutil.ReadAll(rsp.Body)\n\t\t\tif err != nil {\n\t\t\t\tp.options.Log.Warnln(\"error while reading request:\", err)\n\n\t\t\t\tp.errors++\n\t\t\t\tif p.errors >= p.options.HaltThreshold {\n\t\t\t\t\tswitch p.options.HaltPolicy {\n\t\t\t\t\tcase StopOnError, StopOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Stop()\n\t\t\t\t\t\treturn false\n\t\t\t\t\tcase PauseOnError, PauseOn500:\n\t\t\t\t\t\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\t\t\t\t\t\tp.Pause()\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn true\n\t\t}() {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ Pause pauses the replay of the requests. When Play() or Once() are called after pause, the\n\/\/ replay is resumed at the next request in order.\nfunc (p *Player) Pause() {}\n\n\/\/ Stop stops the replay of the requests. When Play() or Once() are called after stop, the\n\/\/ replay is starts from the first request.\nfunc (p *Player) Stop() {}\nrefactor request loop\/\/ Package logreplay provides a client that can replay HTTP requests based access logs.\n\/\/\n\/\/ The player can replay the requests once or infinitely in a loop. It can pause or\n\/\/ reset the scenario. It can replay the scenario with a concurrency level of choice.\n\/\/ The player accepts custom request definitions besides or instead of the access log\n\/\/ input.\n\/\/\n\/\/ The player is provided as an embeddable library, and a simple command is provided as\n\/\/ subpackage.\npackage logreplay\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\n\/\/ RedirectBehavior defines how to handle redirect responses.\ntype RedirectBehavior int\n\nconst (\n\n\t\/\/ NoFollow tells the player not to follow redirects.\n\tNoFollow RedirectBehavior = iota\n\n\t\/\/ SameHost tells the player to follow redirects only to the same host\n\t\/\/ as the request was made to.\n\tSameHost\n\n\t\/\/ Follow tells the player to follow all redirects. (Not recommended\n\t\/\/ during load tests.)\n\tFollow\n)\n\n\/\/ HaltPolicy defines whether to halt on failed requests. It is used in combination\n\/\/ with HaltThreshold.\ntype HaltPolicy int\n\nconst (\n\n\t\/\/ PauseOnError tells the player to pause requests when an error occurs.\n\tPauseOnError HaltPolicy = iota\n\n\t\/\/ StopOnError tells the player to stop requests when an error occurs.\n\tStopOnError\n\n\t\/\/ PauseOn500 tells the player to pause requests when an error or a 500 response occurs.\n\tPauseOn500\n\n\t\/\/ StopOn500 tells the player to stop requests when an error or a 500 response occurs.\n\tStopOn500\n\n\t\/\/ NoHalt tells the player to ignore all request errors and 500s.\n\tNoHalt\n)\n\nconst defaultHaltThreshold = 1 << 7\n\n\/\/ Request describes an individual request made by the player.\ntype Request struct {\n\n\t\/\/ Method is the HTTP method of the request. Defaults to GET.\n\tMethod string\n\n\t\/\/ Host is set as the Host header of the request. When no explicit server is\n\t\/\/ specified in the player options, the Host field will be used as the network\n\t\/\/ address of the request.\n\tHost string\n\n\t\/\/ Path is set as the HTTP path of the request.\n\tPath string\n\n\t\/\/ ContentLength defines the size of the randomly generated request payload.\n\t\/\/\n\t\/\/ When ContentLengthDeviation is defined, the actual size will be randomly\n\t\/\/ decided by ContentLength +\/- rand(ContentLengthDeviation).\n\t\/\/\n\t\/\/ The HTTP ContentLength header is set only when Chunked is false.\n\tContentLength int\n\n\t\/\/ ContentLengthDeviation defines how much the actual random content length of\n\t\/\/ a request can differ from ContentLength.\n\tContentLengthDeviation float64\n\n\t\/\/ Chunked defines if the request content should be sent with chunked transfer\n\t\/\/ encoding.\n\t\/\/\n\t\/\/ TODO: what to do with requests coming from the access logs\n\tChunked bool\n}\n\n\/\/ Parser can parse a log entry.\ntype Parser interface {\n\n\t\/\/ Parse parses a log entry. It accepts a log line as a string\n\t\/\/ and returns a Request definition.\n\tParse(string) Request\n}\n\n\/\/ Options is used to initialize a player.\ntype Options struct {\n\n\t\/\/ Requests to be executed by the player in the specified order.\n\t\/\/\n\t\/\/ When used together with AccessLog, requests defined in this field are\n\t\/\/ executed in the beginning of the scenario.\n\tRequests []Request\n\n\t\/\/ AccessLog is a source of scenario to be executed by the player. By default, it\n\t\/\/ expects a stream of Apache access log entries, and uses the %r field to forge\n\t\/\/ requests.\n\t\/\/\n\t\/\/ In addition to the Combined log format, the default parser accepts two additional\n\t\/\/ fields based on the Skipper (https:\/\/github.com\/zalando\/skipper) access logs,\n\t\/\/ where the request host is taken from the last field (following an integer for\n\t\/\/ duration.)\n\t\/\/\n\t\/\/ Known bugs in the default parser:\n\t\/\/\n\t\/\/ \t- escaped double quotes in the HTTP message not handled\n\t\/\/ \t- whitespace handling in the HTTP message: only whitespace\n\t\/\/\n\tAccessLog io.Reader\n\n\t\/\/ AccessLogFormat is a regular expression and can be used to override the default\n\t\/\/ parser expression. The expression can define the following named groups:\n\t\/\/ method, host, path. The captured submatches with these names will be used to\n\t\/\/ set the according field in the parsed request.\n\t\/\/\n\t\/\/ If Parser is set, this field is ignored.\n\tAccessLogFormat string\n\n\t\/\/ Parser is a custom parser for log entries (lines). It can be used e.g. to define\n\t\/\/ a JSON log parser.\n\tParser Parser\n\n\t\/\/ AccessLogHostField tells the access log parser to take the request from a\n\t\/\/ specific position in the Apache Combined Log Format. Defaults to 11. Value\n\t\/\/ -1 prevents to set the host from the access log. When the host field not\n\t\/\/ specified in the access log, or when taking it from there is disabled, the\n\t\/\/ value of the field Server is used as the host, or, if no server is specified,\n\t\/\/ localhost is used.\n\t\/\/\n\t\/\/ TODO: allow defining custom format\n\tAccessLogHostField int\n\n\t\/\/ Server is a network address to send the requests to.\n\tServer string\n\n\t\/\/ ConcurrentSessions tells the player how many concurrent clients should replay\n\t\/\/ the requests.\n\t\/\/\n\t\/\/ Defaults to 1.\n\tConcurrentSessions int\n\n\t\/\/ RedirectBehavior tells the player how to act on redirect responses.\n\tRedirectBehavior RedirectBehavior\n\n\t\/\/ PostContentLength tells the player the average request content size to send in\n\t\/\/ case of POST, PUT and PATCH requests read from the access log.\n\tPostContentLength int\n\n\t\/\/ PostContentLengthDeviation defines how much the actual random cotnent length of\n\t\/\/ a request read from the access log can differ from PostContentLength.\n\tPostContentLengthDeviation float64\n\n\t\/\/ Log defines a custom logger for the player.\n\tLog Logger\n\n\t\/\/ HaltPolicy tells the player what to do in case an error or a 500 response occurs.\n\t\/\/ The default is to pause on errors (500s ignored).\n\tHaltPolicy HaltPolicy\n\n\t\/\/ HaltThreshold tells the player after how many errors or 500s it should apply the\n\t\/\/ HaltPolicy. Default: 128.\n\tHaltThreshold int\n\n\t\/\/ Throttle maximizes the outgoing overall request per second rate.\n\tThrottle float64\n}\n\n\/\/ Player replays HTTP requests explicitly specified and\/or read from an Apache access log.\ntype Player struct {\n\toptions Options\n\taccessLog *reader\n\trequests []Request\n\tposition int\n\tclient *http.Client\n\terrors int\n\tserverErrors int\n}\n\nvar errServerStatus = errors.New(\"unexpected server status\")\n\n\/\/ New initialzies a player.\nfunc New(o Options) (*Player, error) {\n\tif o.Log == nil {\n\t\to.Log = newDefaultLog()\n\t}\n\n\tvar r *reader\n\tif o.AccessLog != nil {\n\t\tvar err error\n\t\tr, err = newReader(o.AccessLog, o.AccessLogFormat, o.Parser, o.Log)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &Player{\n\t\toptions: o,\n\t\taccessLog: r,\n\t\trequests: o.Requests,\n\t\tclient: &http.Client{Transport: &http.Transport{}},\n\t}, nil\n}\n\nfunc (p *Player) nextRequest() (Request, bool) {\n\tvar r Request\n\tif p.accessLog == nil {\n\t\tif p.position >= len(p.requests) {\n\t\t\treturn r, false\n\t\t}\n\n\t\tr = p.requests[p.position]\n\t\tp.position++\n\t\treturn r, true\n\t}\n\n\tvar err error\n\tr, err = p.accessLog.ReadRequest()\n\tif err != nil && err != io.EOF {\n\t\tp.options.Log.Warnln(\"error while reading access log:\", err)\n\n\t\tp.errors++\n\t\tif p.checkHaltError() {\n\t\t\treturn r, false\n\t\t}\n\n\t\treturn p.nextRequest()\n\t}\n\n\tif err == io.EOF {\n\t\tp.accessLog = nil\n\t\treturn p.nextRequest()\n\t}\n\n\tp.requests = append(\n\t\tp.requests[:p.position],\n\t\tappend(\n\t\t\t[]Request{r},\n\t\t\tp.requests[p.position:]...,\n\t\t)...,\n\t)\n\n\tp.position++\n\treturn r, true\n}\n\nfunc (p *Player) createHTTPRequest(r Request) (*http.Request, error) {\n\tm := r.Method\n\tif m == \"\" {\n\t\tm = \"GET\"\n\t}\n\n\ta := p.options.Server\n\tif a == \"\" {\n\t\tif r.Host == \"\" {\n\t\t\ta = \"http:\/\/localhost\"\n\t\t} else {\n\t\t\ta = \"http:\/\/\" + r.Host\n\t\t}\n\t}\n\n\tu, err := url.Parse(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif u.Scheme == \"\" {\n\t\tu.Scheme = \"http\"\n\t}\n\n\tu.Path = r.Path\n\n\thr, err := http.NewRequest(m, u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := r.Host\n\tif h == \"\" {\n\t\th = p.options.Server\n\t}\n\n\tif h == \"\" {\n\t\th = \"localhost\"\n\t}\n\n\thr.Host = h\n\n\treturn hr, nil\n}\n\nfunc (p *Player) sendRequest(r Request) error {\n\thr, err := p.createHTTPRequest(r)\n\tif err != nil {\n\t\tp.options.Log.Errorln(\"failed to create request\", err)\n\t\treturn err\n\t}\n\n\trsp, err := p.client.Do(hr)\n\tif err != nil {\n\t\tp.options.Log.Warnln(\"error while making request:\", err)\n\t\treturn err\n\t}\n\n\tdefer rsp.Body.Close()\n\n\tif rsp.StatusCode >= http.StatusInternalServerError {\n\t\treturn errServerStatus\n\t}\n\n\t_, err = ioutil.ReadAll(rsp.Body)\n\tif err != nil {\n\t\tp.options.Log.Warnln(\"error while reading request body:\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (p *Player) checkHaltError() bool {\n\tif p.errors < p.options.HaltThreshold {\n\t\treturn false\n\t}\n\n\tp.options.Log.Errorln(\"request errors exceeded threshold\")\n\n\tswitch p.options.HaltPolicy {\n\tcase StopOnError, StopOn500:\n\t\tp.Stop()\n\t\treturn true\n\tcase PauseOnError, PauseOn500:\n\t\tp.Pause()\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (p *Player) checkHaltStatus() bool {\n\tif p.serverErrors < p.options.HaltThreshold {\n\t\treturn false\n\t}\n\n\tp.options.Log.Errorln(\"server errors exceeded threshold\")\n\n\tswitch p.options.HaltPolicy {\n\tcase StopOn500:\n\t\tp.Stop()\n\t\treturn true\n\tcase PauseOn500:\n\t\tp.Pause()\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ Play replays the requests infinitely with the specified concurrency. If an access log is\n\/\/ specified it reads it to the end only once, and it repeats the read requests from then on.\n\/\/\n\/\/ When the player is currently playing requests, it is a noop.\nfunc (p *Player) Play() {}\n\n\/\/ Once replays the requests once.\n\/\/\n\/\/ When the player is currently playing requests, it is a noop.\nfunc (p *Player) Once() {\n\tfor {\n\t\tr, ok := p.nextRequest()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\terr := p.sendRequest(r)\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch err {\n\t\tcase errServerStatus:\n\t\t\tp.serverErrors++\n\t\t\tif p.checkHaltStatus() {\n\t\t\t\tbreak\n\t\t\t}\n\t\tdefault:\n\t\t\tp.errors++\n\t\t\tif p.checkHaltError() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Pause pauses the replay of the requests. When Play() or Once() are called after pause, the\n\/\/ replay is resumed at the next request in order.\nfunc (p *Player) Pause() {}\n\n\/\/ Stop stops the replay of the requests. When Play() or Once() are called after stop, the\n\/\/ replay is starts from the first request.\nfunc (p *Player) Stop() {}\n<|endoftext|>"} {"text":"package pinbook\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"github.com\/justinas\/nosurf\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"html\/template\"\n\t\"image\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst PageSize = 6\n\ntype Pagination struct {\n\tPosts []Post `json:\"posts\"`\n\tTotal int `json:\"total\"`\n\tIsFirst bool `json:\"isFirst\"`\n\tIsLast bool `json:\"isLast\"`\n\tPage int `json:\"page\"`\n\tSkip int `json:\"-\"`\n}\n\nfunc NewPagination(page int, total int) *Pagination {\n\n\tnumPages := (total \/ PageSize)\n\tskip := (page - 1) * PageSize\n\n\treturn &Pagination{\n\t\tTotal: total,\n\t\tIsFirst: page == 1,\n\t\tIsLast: page == numPages,\n\t\tPage: page,\n\t\tSkip: skip,\n\t}\n\n}\n\ntype handlerFunc func(*Context) error\n\nfunc makeHandler(app *App, h handlerFunc, authRequired bool) httprouter.Handle {\n\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tc := NewContext(app, w, r, ps)\n\n\t\tif authRequired {\n\t\t\tif err := c.GetUser(); err != nil {\n\t\t\t\tc.HandleError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif c.User == nil {\n\t\t\t\tc.Status(http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\terr := h(c)\n\t\tif err != nil {\n\t\t\t\/\/ http error handling here...\n\t\t\tswitch e := err.(type) {\n\t\t\t\/*\n\t\t\t\tcase mgo.ErrNotFound:\n\t\t\t\t\thttp.NotFound(c.Response, c.Request)\n\t\t\t\t\treturn\n\t\t\t*\/\n\t\t\tcase *ErrorMap:\n\t\t\t\tc.JSON(e.Errors, http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tc.HandleError(e)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc logoutHandler(c *Context) error {\n\tc.Logout()\n\tc.Redirect(\"\/\")\n\treturn nil\n}\n\nfunc indexPageHandler(c *Context) error {\n\tif err := c.GetUser(); err != nil {\n\t\treturn err\n\t}\n\tuserJson, err := json.Marshal(c.User)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ get csrf token, user\n\tctx := make(TemplateContext)\n\tctx[\"csrfToken\"] = nosurf.Token(c.Request)\n\tctx[\"user\"] = template.JS(userJson)\n\treturn c.Render(\"templates\/index.html\", ctx, http.StatusOK)\n}\n\nfunc loginHandler(c *Context) error {\n\n\ts := &struct {\n\t\tIdentity string `json:\"identity\"`\n\t\tPassword string `json:\"password\"`\n\t}{}\n\n\tif err := c.DecodeJSON(s); err != nil {\n\t\treturn err\n\t}\n\n\tuser := &User{}\n\n\tif err := c.DB.Users.Find(bson.M{\"name\": s.Identity}).One(&user); err != nil {\n\t\treturn err\n\t}\n\tc.Login(user)\n\treturn c.JSON(user, http.StatusOK)\n\n}\n\nfunc voteHandler(score int, c *Context) error {\n\n\tquery := bson.M{\"$and\": []bson.M{\n\t\tbson.M{\"_id\": c.GetObjectId(\"id\")},\n\t\tbson.M{\"author\": bson.M{\"$ne\": c.User.Id}},\n\t\tbson.M{\"_id\": bson.M{\"$nin\": c.User.Votes}}}}\n\n\tpost := &Post{}\n\n\tif err := c.DB.Posts.Find(query).One(&post); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Posts.UpdateId(post.Id, bson.M{\"$inc\": bson.M{\"score\": score}}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(post.AuthorId, bson.M{\"$inc\": bson.M{\"totalScore\": score}}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(c.User.Id, bson.M{\"$set\": bson.M{\"votes\": append(c.User.Votes, post.Id)}}); err != nil {\n\t\treturn err\n\t}\n\n\tc.Status(http.StatusNoContent)\n\treturn nil\n}\n\nfunc downvoteHandler(c *Context) error {\n\treturn voteHandler(-1, c)\n}\n\nfunc upvoteHandler(c *Context) error {\n\treturn voteHandler(1, c)\n}\n\nfunc deletePostHandler(c *Context) error {\n\n\tpost := &Post{}\n\tquery := bson.M{\"_id\": c.GetObjectId(\"id\"), \"author\": c.User.Id}\n\n\tif err := c.DB.Posts.Find(query).One(&post); err != nil {\n\t\tc.NotFound()\n\t\treturn nil\n\t}\n\n\tif err := os.Remove(path.Join(c.Cfg.UploadsDir, post.Image)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Posts.Remove(query); err != nil {\n\t\treturn err\n\t}\n\n\tc.Status(http.StatusNoContent)\n\treturn nil\n}\n\nfunc submitPostHandler(c *Context) error {\n\n\tform := &PostForm{}\n\n\tif err := c.Validate(form); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ fetch image\n\n\tresp, err := http.Get(form.Image)\n\tif err != nil {\n\t\tc.String(\"Unable to find image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\tdefer resp.Body.Close()\n\n\tvar img image.Image\n\n\text := path.Ext(form.Image)\n\n\tswitch ext {\n\tcase \".jpg\":\n\t\timg, err = jpeg.Decode(resp.Body)\n\tcase \".png\":\n\t\timg, err = png.Decode(resp.Body)\n\tdefault:\n\t\tc.String(\"Not a valid image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\tc.String(\"Unable to process image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\tt := resize.Thumbnail(300, 500, img, resize.NearestNeighbor)\n\n\tpostId := bson.NewObjectId()\n\n\tfilename := fmt.Sprintf(\"%s%s\", postId.Hex(), ext)\n\tfullPath := path.Join(c.Cfg.UploadsDir, filename)\n\n\tout, err := os.Create(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tswitch ext {\n\tcase \".jpg\":\n\t\tjpeg.Encode(out, t, nil)\n\tcase \".png\":\n\t\tpng.Encode(out, t)\n\tdefault:\n\t\tc.String(\"Not a valid image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\t\/\/ save image\n\tpost := &Post{\n\t\tId: postId,\n\t\tTitle: form.Title,\n\t\tImage: filename,\n\t\tURL: form.URL,\n\t\tComment: form.Comment,\n\t\tAuthorId: c.User.Id,\n\t\tCreated: time.Now(),\n\t\tScore: 1,\n\t}\n\tif err := c.DB.Posts.Insert(post); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(c.User.Id, bson.M{\"$inc\": bson.M{\"totalScore\": 1}}); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.JSON(post, http.StatusOK)\n}\n\nfunc userHandler(c *Context) error {\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\tuser := &Author{}\n\n\terr := c.DB.Users.Find(bson.M{\"name\": c.Params.ByName(\"name\")}).One(&user)\n\n\tq := c.DB.Posts.Find(bson.M{\"author\": user.Id})\n\n\ttotal, err := q.Count()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpage, err := strconv.Atoi(c.Query(\"orderBy\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\terr = q.Sort(\"-\" + orderBy).Skip(result.Skip).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, post := range posts {\n\t\tpost.Author = user\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n\n}\n\nfunc userExists(field string, c *Context) error {\n\tvalue := c.Query(field)\n\tif value == \"\" {\n\t\tc.String(\"No value\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\tcount, err := c.DB.Users.Find(bson.M{field: value}).Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpayload := make(map[string]bool)\n\tpayload[\"exists\"] = count > 0\n\treturn c.JSON(payload, http.StatusOK)\n}\n\nfunc emailExists(c *Context) error {\n\treturn userExists(\"email\", c)\n}\n\nfunc nameExists(c *Context) error {\n\treturn userExists(\"name\", c)\n}\n\nfunc signupHandler(c *Context) error {\n\n\tform := &SignupForm{}\n\tif err := c.Validate(form); err != nil {\n\t\treturn err\n\t}\n\n\tpassword, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser := &User{\n\t\tId: bson.NewObjectId(),\n\t\tCreated: time.Now(),\n\t\tName: form.Name,\n\t\tEmail: form.Email,\n\t\tPassword: string(password),\n\t}\n\n\tif err := c.DB.Users.Insert(user); err != nil {\n\t\treturn err\n\t}\n\n\tsession := c.GetSession()\n\tsession.Set(\"userid\", user.Id.Hex())\n\n\treturn c.JSON(user, http.StatusOK)\n\n}\n\nfunc searchHandler(c *Context) error {\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\t\/\/page := r.URL.Query[\"page\"]\n\tsearch := bson.M{\"$regex\": bson.RegEx{c.Query(\"q\"), \"i\"}}\n\n\tq := c.DB.Posts.Find(bson.M{\"$or\": []bson.M{bson.M{\"title\": search}, bson.M{\"url\": search}}})\n\n\ttotal, err := q.Count()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = q.Sort(\"-\" + orderBy).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage, err := strconv.Atoi(c.Query(\"page\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\tfor _, post := range posts {\n\t\terr = c.DB.Users.Find(\n\t\t\tbson.M{\"_id\": post.AuthorId}).Select(\n\t\t\tbson.M{\"_id\": 1, \"name\": 1}).One(\n\t\t\t&post.Author)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n\n}\n\nfunc postsHandler(c *Context) error {\n\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\ttotal, err := c.DB.Posts.Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage, err := strconv.Atoi(c.Query(\"page\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\terr = c.DB.Posts.Find(nil).Sort(\"-\" + orderBy).Skip(result.Skip).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, post := range posts {\n\t\terr = c.DB.Users.Find(\n\t\t\tbson.M{\"_id\": post.AuthorId}).Select(\n\t\t\tbson.M{\"_id\": 1, \"name\": 1}).One(\n\t\t\t&post.Author)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n}\n\nfunc getRouter(app *App) http.Handler {\n\n\trouter := httprouter.New()\n\n\t\/\/ public api\n\n\trouter.GET(\"\/api\/posts\/\", makeHandler(app, postsHandler, false))\n\trouter.GET(\"\/api\/search\/\", makeHandler(app, searchHandler, false))\n\trouter.GET(\"\/api\/user\/:name\", makeHandler(app, userHandler, false))\n\trouter.POST(\"\/api\/login\/\", makeHandler(app, loginHandler, false))\n\n\t\/\/ private api\n\n\trouter.POST(\"\/api\/auth\/submit\/\", makeHandler(app, submitPostHandler, true))\n\trouter.PUT(\"\/api\/auth\/downvote\/:id\", makeHandler(app, downvoteHandler, true))\n\trouter.PUT(\"\/api\/auth\/\/upvote\/:id\", makeHandler(app, upvoteHandler, true))\n\trouter.DELETE(\"\/api\/auth\/:id\", makeHandler(app, deletePostHandler, true))\n\n\t\/\/ static files\n\n\trouter.ServeFiles(\"\/static\/*filepath\", http.Dir(app.Cfg.StaticDir))\n\trouter.ServeFiles(\"\/uploads\/*filepath\", http.Dir(app.Cfg.UploadsDir))\n\n\t\/\/ main pages\n\n\trouter.GET(\"\/logout\/\", makeHandler(app, logoutHandler, false))\n\n\tindexPage := makeHandler(app, indexPageHandler, false)\n\n\tmainRoutes := []string{\n\t\t\"\/\",\n\t\t\"\/login\",\n\t\t\"\/search\",\n\t\t\"\/latest\",\n\t\t\"\/user\/:name\",\n\t\t\"\/submit\",\n\t}\n\n\tfor _, route := range mainRoutes {\n\t\trouter.GET(route, indexPage)\n\t}\n\n\treturn router\n\n}\nGo routine for deletepackage pinbook\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"github.com\/justinas\/nosurf\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"html\/template\"\n\t\"image\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst PageSize = 6\n\ntype Pagination struct {\n\tPosts []Post `json:\"posts\"`\n\tTotal int `json:\"total\"`\n\tIsFirst bool `json:\"isFirst\"`\n\tIsLast bool `json:\"isLast\"`\n\tPage int `json:\"page\"`\n\tSkip int `json:\"-\"`\n}\n\nfunc NewPagination(page int, total int) *Pagination {\n\n\tnumPages := (total \/ PageSize)\n\tskip := (page - 1) * PageSize\n\n\treturn &Pagination{\n\t\tTotal: total,\n\t\tIsFirst: page == 1,\n\t\tIsLast: page == numPages,\n\t\tPage: page,\n\t\tSkip: skip,\n\t}\n\n}\n\ntype handlerFunc func(*Context) error\n\nfunc makeHandler(app *App, h handlerFunc, authRequired bool) httprouter.Handle {\n\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tc := NewContext(app, w, r, ps)\n\n\t\tif authRequired {\n\t\t\tif err := c.GetUser(); err != nil {\n\t\t\t\tc.HandleError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif c.User == nil {\n\t\t\t\tc.Status(http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\terr := h(c)\n\t\tif err != nil {\n\t\t\t\/\/ http error handling here...\n\t\t\tswitch e := err.(type) {\n\t\t\t\/*\n\t\t\t\tcase mgo.ErrNotFound:\n\t\t\t\t\thttp.NotFound(c.Response, c.Request)\n\t\t\t\t\treturn\n\t\t\t*\/\n\t\t\tcase *ErrorMap:\n\t\t\t\tc.JSON(e.Errors, http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tc.HandleError(e)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc logoutHandler(c *Context) error {\n\tc.Logout()\n\tc.Redirect(\"\/\")\n\treturn nil\n}\n\nfunc indexPageHandler(c *Context) error {\n\tif err := c.GetUser(); err != nil {\n\t\treturn err\n\t}\n\tuserJson, err := json.Marshal(c.User)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ get csrf token, user\n\tctx := make(TemplateContext)\n\tctx[\"csrfToken\"] = nosurf.Token(c.Request)\n\tctx[\"user\"] = template.JS(userJson)\n\treturn c.Render(\"templates\/index.html\", ctx, http.StatusOK)\n}\n\nfunc loginHandler(c *Context) error {\n\n\ts := &struct {\n\t\tIdentity string `json:\"identity\"`\n\t\tPassword string `json:\"password\"`\n\t}{}\n\n\tif err := c.DecodeJSON(s); err != nil {\n\t\treturn err\n\t}\n\n\tuser := &User{}\n\n\tif err := c.DB.Users.Find(bson.M{\"name\": s.Identity}).One(&user); err != nil {\n\t\treturn err\n\t}\n\tc.Login(user)\n\treturn c.JSON(user, http.StatusOK)\n\n}\n\nfunc voteHandler(score int, c *Context) error {\n\n\tquery := bson.M{\"$and\": []bson.M{\n\t\tbson.M{\"_id\": c.GetObjectId(\"id\")},\n\t\tbson.M{\"author\": bson.M{\"$ne\": c.User.Id}},\n\t\tbson.M{\"_id\": bson.M{\"$nin\": c.User.Votes}}}}\n\n\tpost := &Post{}\n\n\tif err := c.DB.Posts.Find(query).One(&post); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Posts.UpdateId(post.Id, bson.M{\"$inc\": bson.M{\"score\": score}}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(post.AuthorId, bson.M{\"$inc\": bson.M{\"totalScore\": score}}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(c.User.Id, bson.M{\"$set\": bson.M{\"votes\": append(c.User.Votes, post.Id)}}); err != nil {\n\t\treturn err\n\t}\n\n\tc.Status(http.StatusNoContent)\n\treturn nil\n}\n\nfunc downvoteHandler(c *Context) error {\n\treturn voteHandler(-1, c)\n}\n\nfunc upvoteHandler(c *Context) error {\n\treturn voteHandler(1, c)\n}\n\nfunc deletePostHandler(c *Context) error {\n\n\tpost := &Post{}\n\tquery := bson.M{\"_id\": c.GetObjectId(\"id\"), \"author\": c.User.Id}\n\n\tif err := c.DB.Posts.Find(query).One(&post); err != nil {\n\t\tc.NotFound()\n\t\treturn nil\n\t}\n\n\tgo func() {\n\t\tif err := os.Remove(path.Join(c.Cfg.UploadsDir, post.Image)); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}()\n\n\tif err := c.DB.Posts.Remove(query); err != nil {\n\t\treturn err\n\t}\n\n\tc.Status(http.StatusNoContent)\n\treturn nil\n}\n\nfunc submitPostHandler(c *Context) error {\n\n\tform := &PostForm{}\n\n\tif err := c.Validate(form); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ fetch image\n\n\tresp, err := http.Get(form.Image)\n\tif err != nil {\n\t\tc.String(\"Unable to find image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\tdefer resp.Body.Close()\n\n\tvar img image.Image\n\n\text := path.Ext(form.Image)\n\n\tswitch ext {\n\tcase \".jpg\":\n\t\timg, err = jpeg.Decode(resp.Body)\n\tcase \".png\":\n\t\timg, err = png.Decode(resp.Body)\n\tdefault:\n\t\tc.String(\"Not a valid image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\tc.String(\"Unable to process image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\tt := resize.Thumbnail(300, 500, img, resize.NearestNeighbor)\n\n\tpostId := bson.NewObjectId()\n\n\tfilename := fmt.Sprintf(\"%s%s\", postId.Hex(), ext)\n\tfullPath := path.Join(c.Cfg.UploadsDir, filename)\n\n\tout, err := os.Create(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tswitch ext {\n\tcase \".jpg\":\n\t\tjpeg.Encode(out, t, nil)\n\tcase \".png\":\n\t\tpng.Encode(out, t)\n\tdefault:\n\t\tc.String(\"Not a valid image\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\t\/\/ save image\n\tpost := &Post{\n\t\tId: postId,\n\t\tTitle: form.Title,\n\t\tImage: filename,\n\t\tURL: form.URL,\n\t\tComment: form.Comment,\n\t\tAuthorId: c.User.Id,\n\t\tCreated: time.Now(),\n\t\tScore: 1,\n\t}\n\tif err := c.DB.Posts.Insert(post); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.DB.Users.UpdateId(c.User.Id, bson.M{\"$inc\": bson.M{\"totalScore\": 1}}); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.JSON(post, http.StatusOK)\n}\n\nfunc userHandler(c *Context) error {\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\tuser := &Author{}\n\n\terr := c.DB.Users.Find(bson.M{\"name\": c.Params.ByName(\"name\")}).One(&user)\n\n\tq := c.DB.Posts.Find(bson.M{\"author\": user.Id})\n\n\ttotal, err := q.Count()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpage, err := strconv.Atoi(c.Query(\"orderBy\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\terr = q.Sort(\"-\" + orderBy).Skip(result.Skip).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, post := range posts {\n\t\tpost.Author = user\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n\n}\n\nfunc userExists(field string, c *Context) error {\n\tvalue := c.Query(field)\n\tif value == \"\" {\n\t\tc.String(\"No value\", http.StatusBadRequest)\n\t\treturn nil\n\t}\n\tcount, err := c.DB.Users.Find(bson.M{field: value}).Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpayload := make(map[string]bool)\n\tpayload[\"exists\"] = count > 0\n\treturn c.JSON(payload, http.StatusOK)\n}\n\nfunc emailExists(c *Context) error {\n\treturn userExists(\"email\", c)\n}\n\nfunc nameExists(c *Context) error {\n\treturn userExists(\"name\", c)\n}\n\nfunc signupHandler(c *Context) error {\n\n\tform := &SignupForm{}\n\tif err := c.Validate(form); err != nil {\n\t\treturn err\n\t}\n\n\tpassword, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser := &User{\n\t\tId: bson.NewObjectId(),\n\t\tCreated: time.Now(),\n\t\tName: form.Name,\n\t\tEmail: form.Email,\n\t\tPassword: string(password),\n\t}\n\n\tif err := c.DB.Users.Insert(user); err != nil {\n\t\treturn err\n\t}\n\n\tsession := c.GetSession()\n\tsession.Set(\"userid\", user.Id.Hex())\n\n\treturn c.JSON(user, http.StatusOK)\n\n}\n\nfunc searchHandler(c *Context) error {\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\t\/\/page := r.URL.Query[\"page\"]\n\tsearch := bson.M{\"$regex\": bson.RegEx{c.Query(\"q\"), \"i\"}}\n\n\tq := c.DB.Posts.Find(bson.M{\"$or\": []bson.M{bson.M{\"title\": search}, bson.M{\"url\": search}}})\n\n\ttotal, err := q.Count()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = q.Sort(\"-\" + orderBy).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage, err := strconv.Atoi(c.Query(\"page\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\tfor _, post := range posts {\n\t\terr = c.DB.Users.Find(\n\t\t\tbson.M{\"_id\": post.AuthorId}).Select(\n\t\t\tbson.M{\"_id\": 1, \"name\": 1}).One(\n\t\t\t&post.Author)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n\n}\n\nfunc postsHandler(c *Context) error {\n\n\tvar posts []Post\n\n\torderBy := c.Query(\"orderBy\")\n\tif orderBy != \"created\" && orderBy != \"score\" {\n\t\torderBy = \"created\"\n\t}\n\n\ttotal, err := c.DB.Posts.Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage, err := strconv.Atoi(c.Query(\"page\"))\n\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tresult := NewPagination(page, total)\n\n\terr = c.DB.Posts.Find(nil).Sort(\"-\" + orderBy).Skip(result.Skip).Limit(12).All(&posts)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, post := range posts {\n\t\terr = c.DB.Users.Find(\n\t\t\tbson.M{\"_id\": post.AuthorId}).Select(\n\t\t\tbson.M{\"_id\": 1, \"name\": 1}).One(\n\t\t\t&post.Author)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.Posts = append(result.Posts, post)\n\t}\n\n\treturn c.JSON(result, http.StatusOK)\n}\n\nfunc getRouter(app *App) http.Handler {\n\n\trouter := httprouter.New()\n\n\t\/\/ public api\n\n\trouter.GET(\"\/api\/posts\/\", makeHandler(app, postsHandler, false))\n\trouter.GET(\"\/api\/search\/\", makeHandler(app, searchHandler, false))\n\trouter.GET(\"\/api\/user\/:name\", makeHandler(app, userHandler, false))\n\trouter.POST(\"\/api\/login\/\", makeHandler(app, loginHandler, false))\n\n\t\/\/ private api\n\n\trouter.POST(\"\/api\/auth\/submit\/\", makeHandler(app, submitPostHandler, true))\n\trouter.PUT(\"\/api\/auth\/downvote\/:id\", makeHandler(app, downvoteHandler, true))\n\trouter.PUT(\"\/api\/auth\/\/upvote\/:id\", makeHandler(app, upvoteHandler, true))\n\trouter.DELETE(\"\/api\/auth\/:id\", makeHandler(app, deletePostHandler, true))\n\n\t\/\/ static files\n\n\trouter.ServeFiles(\"\/static\/*filepath\", http.Dir(app.Cfg.StaticDir))\n\trouter.ServeFiles(\"\/uploads\/*filepath\", http.Dir(app.Cfg.UploadsDir))\n\n\t\/\/ main pages\n\n\trouter.GET(\"\/logout\/\", makeHandler(app, logoutHandler, false))\n\n\tindexPage := makeHandler(app, indexPageHandler, false)\n\n\tmainRoutes := []string{\n\t\t\"\/\",\n\t\t\"\/login\",\n\t\t\"\/search\",\n\t\t\"\/latest\",\n\t\t\"\/user\/:name\",\n\t\t\"\/submit\",\n\t}\n\n\tfor _, route := range mainRoutes {\n\t\trouter.GET(route, indexPage)\n\t}\n\n\treturn router\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport \"fmt\"\n\nfunc Generate(ch chan<- int) {\n\tfor i := 2; ; i++ {\n\t\tch <- i\n\t}\n}\n\nfunc Filter(ch <-chan int, out chan<- int, prime int) {\n\tfor {\n\t\ti := <-ch\n\t\tif i%prime != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n}\n\nfunc main() {\n\tch := make(chan int)\n\tgo Generate(ch)\n\tfor i := 0; i < 10; i++ {\n\t\tprime := <-ch\n\t\tfmt.Println(prime)\n\t\tout := make(chan int)\n\t\tgo Filter(ch, out, prime)\n\t\tch = out\n\t}\n}Add timeouts to primesieve examplepackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc Generate(ch chan<- int) {\n\tfor i := 2; ; i++ {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t\tch <- i\n\t}\n}\n\nfunc Filter(ch <-chan int, out chan<- int, prime int) {\n\tfor {\n\t\ti := <-ch\n\t\tif i%prime != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n}\n\nfunc main() {\n\tch := make(chan int)\n\tgo Generate(ch)\n\tfor i := 0; i < 10; i++ {\n\t\tprime := <-ch\n\t\tfmt.Println(prime)\n\t\tout := make(chan int)\n\t\tgo Filter(ch, out, prime)\n\t\tch = out\n\t}\n}\n<|endoftext|>"} {"text":"package eventer\n\n\/\/ Basic receiver interface.\ntype Receiver interface {\n\tSend(Event)\n}\n\n\/\/ Receiver as channel\ntype Channel chan Event\n\nfunc (self Channel) Send(ev Event) {\n\tself <- ev\n}\n\n\/\/ Receiver as function\ntype Function func(ev Event)\n\nfunc (self Function) Send(ev Event) {\n\tself(ev)\n}\n\ntype Event struct {\n\tType string\n\tData interface{}\n}\n\ntype Channels map[string][]Receiver\n\ntype EventMachine struct {\n\tchannels Channels\n}\n\nfunc New() *EventMachine {\n\treturn &EventMachine{\n\t\tchannels: make(Channels),\n\t}\n}\n\nfunc (self *EventMachine) add(typ string, r Receiver) {\n\tself.channels[typ] = append(self.channels[typ], r)\n}\n\n\/\/ Generalised methods for the known receiver types\n\/\/ * Channel\n\/\/ * Function\nfunc (self *EventMachine) On(typ string, r interface{}) {\n\tif eventFunc, ok := r.(func(Event)); ok {\n\t\tself.RegisterFunc(typ, eventFunc)\n\t} else if eventChan, ok := r.(Channel); ok {\n\t\tself.RegisterChannel(typ, eventChan)\n\t} else {\n\t\tpanic(\"Invalid type for EventMachine::On\")\n\t}\n}\n\nfunc (self *EventMachine) RegisterChannel(typ string, c Channel) {\n\tself.add(typ, c)\n}\n\nfunc (self *EventMachine) RegisterFunc(typ string, f Function) {\n\tself.add(typ, f)\n}\n\nfunc (self *EventMachine) Register(typ string) Channel {\n\tc := make(Channel, 1)\n\tself.add(typ, c)\n\n\treturn c\n}\n\nfunc (self *EventMachine) Post(typ string, data interface{}) {\n\tif self.channels[typ] != nil {\n\t\tev := Event{typ, data}\n\t\tfor _, receiver := range self.channels[typ] {\n\t\t\t\/\/ Blocking is OK. These are internals and need to be handled\n\t\t\treceiver.Send(ev)\n\t\t}\n\t}\n}\neventer: fix data racepackage eventer\n\nimport \"sync\"\n\n\/\/ Basic receiver interface.\ntype Receiver interface {\n\tSend(Event)\n}\n\n\/\/ Receiver as channel\ntype Channel chan Event\n\nfunc (self Channel) Send(ev Event) {\n\tself <- ev\n}\n\n\/\/ Receiver as function\ntype Function func(ev Event)\n\nfunc (self Function) Send(ev Event) {\n\tself(ev)\n}\n\ntype Event struct {\n\tType string\n\tData interface{}\n}\n\ntype Channels map[string][]Receiver\n\ntype EventMachine struct {\n\tmu sync.RWMutex\n\tchannels Channels\n}\n\nfunc New() *EventMachine {\n\treturn &EventMachine{channels: make(Channels)}\n}\n\nfunc (self *EventMachine) add(typ string, r Receiver) {\n\tself.mu.Lock()\n\tself.channels[typ] = append(self.channels[typ], r)\n\tself.mu.Unlock()\n}\n\n\/\/ Generalised methods for the known receiver types\n\/\/ * Channel\n\/\/ * Function\nfunc (self *EventMachine) On(typ string, r interface{}) {\n\tif eventFunc, ok := r.(func(Event)); ok {\n\t\tself.RegisterFunc(typ, eventFunc)\n\t} else if eventChan, ok := r.(Channel); ok {\n\t\tself.RegisterChannel(typ, eventChan)\n\t} else {\n\t\tpanic(\"Invalid type for EventMachine::On\")\n\t}\n}\n\nfunc (self *EventMachine) RegisterChannel(typ string, c Channel) {\n\tself.add(typ, c)\n}\n\nfunc (self *EventMachine) RegisterFunc(typ string, f Function) {\n\tself.add(typ, f)\n}\n\nfunc (self *EventMachine) Register(typ string) Channel {\n\tc := make(Channel, 1)\n\tself.add(typ, c)\n\treturn c\n}\n\nfunc (self *EventMachine) Post(typ string, data interface{}) {\n\tself.mu.RLock()\n\tif self.channels[typ] != nil {\n\t\tev := Event{typ, data}\n\t\tfor _, receiver := range self.channels[typ] {\n\t\t\t\/\/ Blocking is OK. These are internals and need to be handled\n\t\t\treceiver.Send(ev)\n\t\t}\n\t}\n\tself.mu.RUnlock()\n}\n<|endoftext|>"} {"text":"package events\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nvar (\n\tTutumEndpoint string\n\tTutumAuth string\n\tUserAgent string\n)\n\nfunc SendContainerEvent(event Event) {\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot marshal the posting data: %s\\n\", event)\n\t}\n\n\tcounter := 0\n\tfor {\n\t\terr := sendData(TutumEndpoint, data)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tif counter > 720 {\n\t\t\t\tlog.Println(\"Too many reties, give up\")\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcounter += 1\n\t\t\t\tlog.Println(\"Retry in 5 seconds\")\n\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc sendData(url string, data []byte) error {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(data))\n\tif err != nil {\n\t\tSendError(err, \"Failed to create http.NewRequest\", nil)\n\t\treturn err\n\t}\n\treq.Header.Add(\"Authorization\", TutumAuth)\n\treq.Header.Add(\"User-Agent\", UserAgent)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\textra := map[string]interface{}{\"data\": string(data)}\n\t\tSendError(err, \"Failed to POST the http request\", extra)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode >= 400 {\n\t\tlog.Printf(\"Send event failed: %s - %s\", resp.Status, string(data))\n\t\textra := map[string]interface{}{\"data\": string(data)}\n\t\tSendError(errors.New(resp.Status), \"http error\", extra)\n\t\tif resp.StatusCode >= 500 {\n\t\t\treturn errors.New(resp.Status)\n\t\t}\n\t}\n\treturn nil\n}\nfactorial retry on 500 errorpackage events\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nvar (\n\tTutumEndpoint string\n\tTutumAuth string\n\tUserAgent string\n)\n\nfunc SendContainerEvent(event Event) {\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot marshal the posting data: %s\\n\", event)\n\t}\n\n\tcounter := 1\n\tfor {\n\t\terr := sendData(TutumEndpoint, data)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tif counter > 100 {\n\t\t\t\tlog.Println(\"Too many reties, give up\")\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcounter *= 2\n\t\t\t\tlog.Printf(\"%s: Retry in %d seconds\", err, counter)\n\t\t\t\ttime.Sleep(time.Duration(counter) * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc sendData(url string, data []byte) error {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(data))\n\tif err != nil {\n\t\tSendError(err, \"Failed to create http.NewRequest\", nil)\n\t\treturn err\n\t}\n\treq.Header.Add(\"Authorization\", TutumAuth)\n\treq.Header.Add(\"User-Agent\", UserAgent)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\textra := map[string]interface{}{\"data\": string(data)}\n\t\tSendError(err, \"Failed to POST the http request\", extra)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode >= 400 {\n\t\tlog.Printf(\"Send event failed: %s - %s\", resp.Status, string(data))\n\t\textra := map[string]interface{}{\"data\": string(data)}\n\t\tSendError(errors.New(resp.Status), \"http error\", extra)\n\t\tif resp.StatusCode >= 500 {\n\t\t\treturn errors.New(resp.Status)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/joshsoftware\/curem\/config\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\ntype lead struct {\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tContactId bson.ObjectId `bson:\"contactId,omitempty\" json:\"contactId,omitempty\"`\n\tSource string `bson:\"source,omitempty\" json:\"source,omitempty\"`\n\tOwner string `bson:\"owner,omitempty\" json:\"owner,omitempty\"`\n\tStatus string `bson:\"status,omitempty\" json:\"status,omitempty\"`\n\tTeamSize float64 `bson:\"teamSize,omitempty\" json:\"teamSize,omitempty\"`\n\tRatePerHour float64 `bson:\"ratePerHour,omitempty\" json:\"ratePerHour,omitempty\"`\n\tDurationInMonths float64 `bson:\"durationInMonths,omitempty\" json:\"durationInMonths,omitempty\"`\n\tEstimatedStartDate string `bson:\"estimatedStartDate,omitempty\" json:\"estimatedStartDate,omitempty\"`\n\tComments []string `bson:\"comments,omitempty\" json:\"comments,omitempty\"`\n\tCreatedAt time.Time `bson:\"createdAt,omitempty\" json:\"createdAt,omitempty\"`\n\tUpdatedAt time.Time `bson:\"updatedAt,omitempty\" json:\"updatedAt,omitempty\"`\n}\n\ntype incomingLead struct {\n\tId *bson.ObjectId `json:\"id\"`\n\tContactId *bson.ObjectId `json:\"contactId,omitempty\"`\n\tSource *string `json:\"source,omitempty\"`\n\tOwner *string `json:\"owner,omitempty\"`\n\tStatus *string `json:\"status,omitempty\"`\n\tTeamSize *float64 `json:\"teamSize,omitempty\"`\n\tRatePerHour *float64 `json:\"ratePerHour,omitempty\"`\n\tDurationInMonths *float64 `json:\"durationInMonths,omitempty\"`\n\tEstimatedStartDate *string `json:\"estimatedStartDate,omitempty\"`\n\tComments *[]string `json:\"comments,omitempty\"`\n}\n\nfunc (l *lead) copyIncomingFields(i *incomingLead) error {\n\tif i.Id != nil {\n\t\tif *i.Id != l.Id {\n\t\t\treturn errors.New(\"Id doesn't match\")\n\t\t}\n\t}\n\tif i.ContactId != nil {\n\t\tl.Id = *i.Id\n\t}\n\tif i.Source != nil {\n\t\tl.Source = *i.Source\n\t}\n\tif i.Owner != nil {\n\t\tl.Owner = *i.Owner\n\t}\n\tif i.Status != nil {\n\t\tl.Status = *i.Status\n\t}\n\tif i.TeamSize != nil {\n\t\tl.TeamSize = *i.TeamSize\n\t}\n\tif i.RatePerHour != nil {\n\t\tl.RatePerHour = *i.RatePerHour\n\t}\n\tif i.DurationInMonths != nil {\n\t\tl.DurationInMonths = *i.DurationInMonths\n\t}\n\tif i.EstimatedStartDate != nil {\n\t\tl.EstimatedStartDate = *i.EstimatedStartDate\n\t}\n\tif i.Comments != nil {\n\t\tl.Comments = *i.Comments\n\t}\n\treturn nil\n}\n\n\/\/ NewLead takes the fields of a lead, initializes a struct of lead type and returns\n\/\/ the pointer to that struct.\n\/\/ Also, It inserts the lead object into the database.\nfunc NewLead(cid bson.ObjectId, source, owner, status string, teamsize, rate, duration float64,\n\tstart string, comments []string) (*lead, error) {\n\tdoc := lead{\n\t\tId: bson.NewObjectId(),\n\t\tContactId: cid,\n\t\tSource: source,\n\t\tOwner: owner,\n\t\tStatus: status,\n\t\tTeamSize: teamsize,\n\t\tRatePerHour: rate,\n\t\tDurationInMonths: duration,\n\t\tEstimatedStartDate: start,\n\t\tComments: comments,\n\t}\n\n\tdoc.CreatedAt = doc.Id.Time()\n\tdoc.UpdatedAt = doc.CreatedAt\n\n\terr := config.LeadsCollection.Insert(doc)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &doc, nil\n}\n\n\/\/ GetLead takes the lead Id as an argument and returns a pointer to a lead object.\nfunc GetLead(i bson.ObjectId) (*lead, error) {\n\tvar l lead\n\terr := config.LeadsCollection.FindId(i).One(&l)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &l, nil\n}\n\n\/\/ GetAllLeads fetches all the leads from the database.\nfunc GetAllLeads() ([]lead, error) {\n\tvar l []lead\n\terr := config.LeadsCollection.Find(nil).All(&l)\n\tif err != nil {\n\t\treturn []lead{}, err\n\t}\n\treturn l, nil\n}\n\n\/\/ Update updates the lead in the database.\n\/\/ First, fetch a lead from the database and change the necessary fields.\n\/\/ Then call the Update method on that lead object.\nfunc (l *lead) Update() error {\n\tl.UpdatedAt = bson.Now()\n\terr := config.LeadsCollection.UpdateId(l.Id, l)\n\treturn err\n}\n\n\/\/ Delete deletes the lead from the database.\nfunc (l *lead) Delete() error {\n\treturn config.LeadsCollection.RemoveId(l.Id)\n}\nAdd Validate method for *lead typepackage main\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/joshsoftware\/curem\/config\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\ntype lead struct {\n\tId bson.ObjectId `bson:\"_id\" json:\"id\"`\n\tContactId bson.ObjectId `bson:\"contactId,omitempty\" json:\"contactId,omitempty\"`\n\tSource string `bson:\"source,omitempty\" json:\"source,omitempty\"`\n\tOwner string `bson:\"owner,omitempty\" json:\"owner,omitempty\"`\n\tStatus string `bson:\"status,omitempty\" json:\"status,omitempty\"`\n\tTeamSize float64 `bson:\"teamSize,omitempty\" json:\"teamSize,omitempty\"`\n\tRatePerHour float64 `bson:\"ratePerHour,omitempty\" json:\"ratePerHour,omitempty\"`\n\tDurationInMonths float64 `bson:\"durationInMonths,omitempty\" json:\"durationInMonths,omitempty\"`\n\tEstimatedStartDate string `bson:\"estimatedStartDate,omitempty\" json:\"estimatedStartDate,omitempty\"`\n\tComments []string `bson:\"comments,omitempty\" json:\"comments,omitempty\"`\n\tCreatedAt time.Time `bson:\"createdAt,omitempty\" json:\"createdAt,omitempty\"`\n\tUpdatedAt time.Time `bson:\"updatedAt,omitempty\" json:\"updatedAt,omitempty\"`\n}\n\ntype incomingLead struct {\n\tId *bson.ObjectId `json:\"id\"`\n\tContactId *bson.ObjectId `json:\"contactId,omitempty\"`\n\tSource *string `json:\"source,omitempty\"`\n\tOwner *string `json:\"owner,omitempty\"`\n\tStatus *string `json:\"status,omitempty\"`\n\tTeamSize *float64 `json:\"teamSize,omitempty\"`\n\tRatePerHour *float64 `json:\"ratePerHour,omitempty\"`\n\tDurationInMonths *float64 `json:\"durationInMonths,omitempty\"`\n\tEstimatedStartDate *string `json:\"estimatedStartDate,omitempty\"`\n\tComments *[]string `json:\"comments,omitempty\"`\n}\n\nfunc (l *lead) copyIncomingFields(i *incomingLead) error {\n\tif i.Id != nil {\n\t\tif *i.Id != l.Id {\n\t\t\treturn errors.New(\"Id doesn't match\")\n\t\t}\n\t}\n\tif i.ContactId != nil {\n\t\tl.Id = *i.Id\n\t}\n\tif i.Source != nil {\n\t\tl.Source = *i.Source\n\t}\n\tif i.Owner != nil {\n\t\tl.Owner = *i.Owner\n\t}\n\tif i.Status != nil {\n\t\tl.Status = *i.Status\n\t}\n\tif i.TeamSize != nil {\n\t\tl.TeamSize = *i.TeamSize\n\t}\n\tif i.RatePerHour != nil {\n\t\tl.RatePerHour = *i.RatePerHour\n\t}\n\tif i.DurationInMonths != nil {\n\t\tl.DurationInMonths = *i.DurationInMonths\n\t}\n\tif i.EstimatedStartDate != nil {\n\t\tl.EstimatedStartDate = *i.EstimatedStartDate\n\t}\n\tif i.Comments != nil {\n\t\tl.Comments = *i.Comments\n\t}\n\treturn nil\n}\n\n\/\/ NewLead takes the fields of a lead, initializes a struct of lead type and returns\n\/\/ the pointer to that struct.\n\/\/ Also, It inserts the lead object into the database.\nfunc NewLead(cid bson.ObjectId, source, owner, status string, teamsize, rate, duration float64,\n\tstart string, comments []string) (*lead, error) {\n\tdoc := lead{\n\t\tId: bson.NewObjectId(),\n\t\tContactId: cid,\n\t\tSource: source,\n\t\tOwner: owner,\n\t\tStatus: status,\n\t\tTeamSize: teamsize,\n\t\tRatePerHour: rate,\n\t\tDurationInMonths: duration,\n\t\tEstimatedStartDate: start,\n\t\tComments: comments,\n\t}\n\n\tdoc.CreatedAt = doc.Id.Time()\n\tdoc.UpdatedAt = doc.CreatedAt\n\n\terr := config.LeadsCollection.Insert(doc)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &doc, nil\n}\n\nfunc (l *lead) Validate() error {\n\tif l.Source == \"\" {\n\t\treturn errors.New(\"Source can't be empty\")\n\t}\n\tif l.Owner == \"\" {\n\t\treturn errors.New(\"Owner can't be empty\")\n\t}\n\tif l.Status == \"\" {\n\t\treturn errors.New(\"Status can't be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ GetLead takes the lead Id as an argument and returns a pointer to a lead object.\nfunc GetLead(i bson.ObjectId) (*lead, error) {\n\tvar l lead\n\terr := config.LeadsCollection.FindId(i).One(&l)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &l, nil\n}\n\n\/\/ GetAllLeads fetches all the leads from the database.\nfunc GetAllLeads() ([]lead, error) {\n\tvar l []lead\n\terr := config.LeadsCollection.Find(nil).All(&l)\n\tif err != nil {\n\t\treturn []lead{}, err\n\t}\n\treturn l, nil\n}\n\n\/\/ Update updates the lead in the database.\n\/\/ First, fetch a lead from the database and change the necessary fields.\n\/\/ Then call the Update method on that lead object.\nfunc (l *lead) Update() error {\n\tl.UpdatedAt = bson.Now()\n\terr := config.LeadsCollection.UpdateId(l.Id, l)\n\treturn err\n}\n\n\/\/ Delete deletes the lead from the database.\nfunc (l *lead) Delete() error {\n\treturn config.LeadsCollection.RemoveId(l.Id)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\n\t\"github.com\/Hellspam\/goharproxy\"\n)\nimport (\n\t_ \"net\/http\/pprof\"\n\t\"flag\"\n)\n\n\nfunc main() {\n\tport := flag.Int(\"p\", 8080, \"Port to listen on\")\n\tflag.Parse()\n\tgo func() {\n\t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\t}()\n\tharproxy.NewProxyServer(*port)\n}\n\n\nUpdate main.gopackage main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\n\t\"github.com\/Hellspam\/goharproxy\"\n)\nimport (\n\t_ \"net\/http\/pprof\"\n\t\"flag\"\n)\n\n\nfunc main() {\n\tport := flag.Int(\"p\", 8080, \"Port to listen on\")\n\tflag.Parse()\n\tgo func() {\n\t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\t}()\n\tgoharproxy.NewProxyServer(*port)\n}\n\n\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tgh \"github.com\/barakb\/create-branch\/github\"\n\t\"github.com\/barakb\/create-branch\/handlers\"\n\t\"github.com\/barakb\/create-branch\/session\"\n\t\"github.com\/vharitonsky\/iniflags\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n)\n\nfunc init() {\n\tgs, err := session.NewManager(\"memory\", \"gosessionid\", 10*1000*1000*1000)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to create session manager error is: %#v\\n\", err)\n\t\treturn\n\t}\n\tsession.GlobalSessions = gs\n}\n\nvar port = flag.Int(\"port\", 4430, \"Configure the server port\")\n\nvar repos = flag.String(\"repos\", defaultRepoFile(), \"Configure the where the repositories file\")\n\nfunc main() {\n\tiniflags.Parse()\n\trepos, err := readRepos(*repos)\n\tif err != nil {\n\t\tfmt.Printf(\"Error:%s\\n\", err.Error())\n\t\treturn\n\t}\n\tgh.ReposNames = repos\n\tgo session.GlobalSessions.GC()\n\twebsocketHandler := &handlers.WebSocketHandler{}\n\thttp.Handle(\"\/\", handlers.MustAuth(handlers.MainHandler{File: \"index.html\"}))\n\thttp.Handle(\"\/events\", handlers.MustAuth(websocket.Handler(websocketHandler.Handler)))\n\thttp.Handle(\"\/logout\", handlers.MustAuth(handlers.LogoutHandler{}))\n\thttp.Handle(\"\/githuboa_cb\", handlers.GithubLoginHandler{})\n\thttp.Handle(\"\/api\/create_branch\/\", handlers.MustAuth(handlers.CreateBranchHandler{websocketHandler}))\n\thttp.Handle(\"\/api\/delete_branch\/\", handlers.MustAuth(handlers.DeleteBranchHandler{websocketHandler}))\n\thttp.Handle(\"\/api\/get_branches\/\", handlers.MustAuth(handlers.GetBranchsHandler{websocketHandler}))\n\thttp.Handle(\"\/web\/\", handlers.MustAuth(http.StripPrefix(\"\/web\/\", http.FileServer(http.Dir(\"web\")))))\n\tfmt.Printf(\"Server started on https:\/\/localhost:%d\\n\", *port)\n\tfmt.Println(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", *port), \"keys\/server.pem\", \"keys\/server.key\", nil))\n}\n\nfunc defaultRepoFile() string {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"repos.txt\"\n\t}\n\treturn fmt.Sprintf(\"%s\/repos.txt\", dir)\n}\n\nfunc readRepos(repos string) ([]string, error) {\n\tbytes, err := ioutil.ReadFile(repos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstr := string(bytes)\n\treturn regexp.MustCompile(\"\\\\s+\").Split(str, -1), nil\n}\nFix errors.package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tgh \"github.com\/barakb\/create-branch\/github\"\n\t\"github.com\/barakb\/create-branch\/handlers\"\n\t\"github.com\/barakb\/create-branch\/session\"\n\t\"github.com\/vharitonsky\/iniflags\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n)\n\nfunc init() {\n\tgs, err := session.NewManager(\"memory\", \"gosessionid\", 10*1000*1000*1000)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to create session manager error is: %#v\\n\", err)\n\t\treturn\n\t}\n\tsession.GlobalSessions = gs\n}\n\nvar port = flag.Int(\"port\", 4430, \"Configure the server port\")\n\nvar repos = flag.String(\"repos\", defaultRepoFile(), \"Configure the where the repositories file\")\n\nfunc main() {\n\tiniflags.Parse()\n\trepos, err := readRepos(*repos)\n\tif err != nil {\n\t\tfmt.Printf(\"Error:%s\\n\", err.Error())\n\t\treturn\n\t}\n\tgh.ReposNames = repos\n\tgo session.GlobalSessions.GC()\n\twebsocketHandler := &handlers.WebSocketHandler{}\n\thttp.Handle(\"\/\", handlers.MustAuth(handlers.MainHandler{File: \"index.html\"}))\n\thttp.Handle(\"\/events\", handlers.MustAuth(websocket.Handler(websocketHandler.Handler)))\n\thttp.Handle(\"\/logout\", handlers.MustAuth(handlers.LogoutHandler{}))\n\thttp.Handle(\"\/githuboa_cb\", handlers.GithubLoginHandler{})\n\thttp.Handle(\"\/api\/create_branch\/\", handlers.MustAuth(handlers.CreateBranchHandler{WS:websocketHandler}))\n\thttp.Handle(\"\/api\/delete_branch\/\", handlers.MustAuth(handlers.DeleteBranchHandler{WS:websocketHandler}))\n\thttp.Handle(\"\/api\/get_branches\/\", handlers.MustAuth(handlers.GetBranchsHandler{WS:websocketHandler}))\n\thttp.Handle(\"\/web\/\", handlers.MustAuth(http.StripPrefix(\"\/web\/\", http.FileServer(http.Dir(\"web\")))))\n\tfmt.Printf(\"Server started on https:\/\/localhost:%d\\n\", *port)\n\tfmt.Println(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", *port), \"keys\/server.pem\", \"keys\/server.key\", nil))\n}\n\nfunc defaultRepoFile() string {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"repos.txt\"\n\t}\n\treturn fmt.Sprintf(\"%s\/repos.txt\", dir)\n}\n\nfunc readRepos(repos string) ([]string, error) {\n\tbytes, err := ioutil.ReadFile(repos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstr := string(bytes)\n\treturn regexp.MustCompile(\"\\\\s+\").Split(str, -1), nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/ryscheng\/pdb\/common\"\n\t\"github.com\/ryscheng\/pdb\/server\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.Println(\"------------------\")\n\tlog.Println(\"--- PDB Server ---\")\n\tlog.Println(\"------------------\")\n\n\t\/\/ For trace debug status\n\tgo http.ListenAndServe(\"localhost:8080\", nil)\n\n\t\/\/ Config\n\t\/\/trustDomainConfig0 := common.NewTrustDomainConfig(\"t0\", \"localhost:9000\", true, false)\n\t\/\/trustDomainConfig1 := common.NewTrustDomainConfig(\"t1\", \"localhost:9001\", true, false)\n\ttrustDomainConfig0 := common.NewTrustDomainConfig(\"t0\", \"172.30.2.10:9000\", true, false)\n\ttrustDomainConfig1 := common.NewTrustDomainConfig(\"t1\", \"172.30.2.221:9000\", true, false)\n\tglobalConfig := common.GlobalConfigFromFile(\"globalconfig.json\")\n\tglobalConfig.TrustDomains = []*common.TrustDomainConfig{trustDomainConfig0, trustDomainConfig1}\n\n\ts := server.NewCentralized(\"s\", *globalConfig, nil, false)\n\t\/\/s := server.NewCentralized(\"s\", globalConfig, common.NewFollowerRpc(\"t0->t1\", trustDomainConfig1), true)\n\t_ = server.NewNetworkRpc(s, 9000)\n\n\tlog.Println(s)\n\n\tfor {\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n}\ncentralized needs socketpackage main\n\nimport (\n\t\"github.com\/ryscheng\/pdb\/common\"\n\t\"github.com\/ryscheng\/pdb\/server\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nfunc main() {\n\tlog.Println(\"------------------\")\n\tlog.Println(\"--- PDB Server ---\")\n\tlog.Println(\"------------------\")\n\n\t\/\/ For trace debug status\n\tgo http.ListenAndServe(\"localhost:8080\", nil)\n\n\t\/\/ Config\n\t\/\/trustDomainConfig0 := common.NewTrustDomainConfig(\"t0\", \"localhost:9000\", true, false)\n\t\/\/trustDomainConfig1 := common.NewTrustDomainConfig(\"t1\", \"localhost:9001\", true, false)\n\ttrustDomainConfig0 := common.NewTrustDomainConfig(\"t0\", \"172.30.2.10:9000\", true, false)\n\ttrustDomainConfig1 := common.NewTrustDomainConfig(\"t1\", \"172.30.2.221:9000\", true, false)\n\tglobalConfig := common.GlobalConfigFromFile(\"globalconfig.json\")\n\tglobalConfig.TrustDomains = []*common.TrustDomainConfig{trustDomainConfig0, trustDomainConfig1}\n\n\ts := server.NewCentralized(\"s\", \"..\/pird\/pir.socket\", *globalConfig, nil, false)\n\t\/\/s := server.NewCentralized(\"s\", \"..\/pird\/pir.socket\", *globalConfig, common.NewFollowerRpc(\"t0->t1\", trustDomainConfig1), true)\n\t_ = server.NewNetworkRpc(s, 9000)\n\n\tlog.Println(s)\n\n\tfor {\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n}\n<|endoftext|>"} {"text":"package executor\n\nimport (\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/intelsdi-x\/swan\/pkg\/executor\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestParallel(t *testing.T) {\n\tSkipConvey(\"When using Parallel to decorate local executor\", t, func() {\n\t\tparallel := executor.NewLocalIsolated(executor.NewParallel(5))\n\t\tConvey(\"Process should be executed 5 times\", func() {\n\t\t\ttask, err := parallel.Execute(\"sleep inf\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(task, ShouldNotBeNil)\n\t\t\t\/\/ NOTE: We have to wait a bit for parallel to launch commands, though.\n\t\t\tisStopped := task.Wait(1000 * time.Millisecond)\n\t\t\tSo(isStopped, ShouldBeFalse)\n\n\t\t\tdefer task.Stop()\n\t\t\tdefer task.Clean()\n\t\t\tdefer task.EraseOutput()\n\n\t\t\tcmd := exec.Command(\"pgrep\", \"sleep\")\n\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tpids := strings.Split(strings.TrimSpace(string(output)), \"\\n\")\n\t\t\tSo(len(pids), ShouldBeGreaterThan, 0)\n\t\t\tConvey(\"When I stop parallel process\", func() {\n\t\t\t\terr = task.Stop()\n\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\tConvey(\"All the child processes should be stopped\", func() {\n\t\t\t\t\tisStopped := task.Wait(0)\n\t\t\t\t\tSo(isStopped, ShouldBeTrue)\n\t\t\t\t\tcmd = exec.Command(\"pgrep\", \"sleep\")\n\t\t\t\t\terr = cmd.Run()\n\n\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\tSo(cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus(), ShouldEqual, 1)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\nSCE-592: Integration test fails in TestParallel (#306)package executor\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/intelsdi-x\/swan\/pkg\/executor\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestParallel(t *testing.T) {\n\tfile, err := ioutil.TempFile(\".\", \"parallel\")\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\tdefer os.Remove(file.Name())\n\n\tConvey(\"When using Parallel to decorate local executor\", t, func() {\n\t\tparallel := executor.NewLocalIsolated(executor.NewParallel(5))\n\t\tConvey(\"Process should be executed 5 times\", func() {\n\t\t\tcmdStr := fmt.Sprintf(\"tailf %s\", file.Name())\n\t\t\ttask, err := parallel.Execute(cmdStr)\n\t\t\tdefer task.EraseOutput()\n\t\t\tdefer task.Clean()\n\t\t\tdefer task.Stop()\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(task, ShouldNotBeNil)\n\t\t\t\/\/ NOTE: We have to wait a bit for parallel to launch commands, though.\n\t\t\tisStopped := task.Wait(1000 * time.Millisecond)\n\t\t\tSo(isStopped, ShouldBeFalse)\n\n\t\t\tcmd := exec.Command(\"pgrep\", \"-f\", cmdStr)\n\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tpids := strings.Split(strings.TrimSpace(string(output)), \"\\n\")\n\t\t\tSo(len(pids), ShouldBeGreaterThan, 0)\n\t\t\tConvey(\"When I stop parallel process\", func() {\n\t\t\t\terr = task.Stop()\n\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\tConvey(\"All the child processes should be stopped\", func() {\n\t\t\t\t\tisStopped := task.Wait(0)\n\t\t\t\t\tSo(isStopped, ShouldBeTrue)\n\t\t\t\t\tcmd = exec.Command(\"pgrep\", \"-f\", cmdStr)\n\t\t\t\t\terr = cmd.Run()\n\n\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\tSo(cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus(), ShouldEqual, 1)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"simonwaldherr.de\/go\/golibs\/as\"\n\t\"simonwaldherr.de\/go\/golibs\/cachedfile\"\n\t\"simonwaldherr.de\/go\/golibs\/gopath\"\n\t\"simonwaldherr.de\/go\/gwv\"\n\t\"strings\"\n)\n\nfunc absExePath() (name string, err error) {\n\tname = os.Args[0]\n\n\tif name[0] == '.' {\n\t\tname, err = filepath.Abs(name)\n\t\tif err == nil {\n\t\t\tname = filepath.Clean(name)\n\t\t}\n\t} else {\n\t\tname, err = exec.LookPath(filepath.Clean(name))\n\t}\n\treturn\n}\n\nconst (\n\tPathVar = \"PATH\"\n)\n\nfunc CommandPath(cmdName string) (string, error) {\n\tswitch cmdName[0] {\n\tcase '.', os.PathSeparator:\n\t\twd, err := os.Getwd()\n\t\treturn path.Join(wd, cmdName), err\n\t}\n\tdirectories := strings.Split(os.Getenv(PathVar), string(os.PathListSeparator))\n\tfor _, directory := range directories {\n\t\tfi, err := os.Stat(path.Join(directory, cmdName))\n\t\tif err == nil && fi.Mode().IsRegular() {\n\t\t\treturn path.Join(directory, cmdName), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Can't find the right path for %s\", cmdName)\n}\n\nfunc main() {\n\tdir := gopath.Dir()\n\tfmt.Println(\"DIR 1:\", gopath.WD())\n\tfmt.Println(\"DIR 2:\", dir)\n\tHTTPD := gwv.NewWebServer(8080, 60)\n\tHTTPD.ConfigSSL(4443, \"ssl.key\", \"ssl.cert\", true)\n\n\tHTTPD.URLhandler(\n\t\tgwv.Robots(as.String(cachedfile.Read(filepath.Join(dir, \"..\", \"static\", \"robots.txt\")))),\n\t\tgwv.Favicon(filepath.Join(dir, \"..\", \"static\", \"favicon.ico\")),\n\t\tgwv.StaticFiles(\"\/\", dir),\n\t)\n\n\tlog.Print(\"starting\")\n\tHTTPD.Start()\n\tHTTPD.WG.Add(1)\n\tlog.Print(\"started\")\n\tHTTPD.WG.Wait()\n\tlog.Print(\"stopped\")\n}\nfix ssl path in demo_01\/\/ +build local\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"simonwaldherr.de\/go\/golibs\/as\"\n\t\"simonwaldherr.de\/go\/golibs\/cachedfile\"\n\t\"simonwaldherr.de\/go\/golibs\/gopath\"\n\t\"simonwaldherr.de\/go\/gwv\"\n\t\"strings\"\n)\n\nfunc absExePath() (name string, err error) {\n\tname = os.Args[0]\n\n\tif name[0] == '.' {\n\t\tname, err = filepath.Abs(name)\n\t\tif err == nil {\n\t\t\tname = filepath.Clean(name)\n\t\t}\n\t} else {\n\t\tname, err = exec.LookPath(filepath.Clean(name))\n\t}\n\treturn\n}\n\nconst (\n\tPathVar = \"PATH\"\n)\n\nfunc CommandPath(cmdName string) (string, error) {\n\tswitch cmdName[0] {\n\tcase '.', os.PathSeparator:\n\t\twd, err := os.Getwd()\n\t\treturn path.Join(wd, cmdName), err\n\t}\n\tdirectories := strings.Split(os.Getenv(PathVar), string(os.PathListSeparator))\n\tfor _, directory := range directories {\n\t\tfi, err := os.Stat(path.Join(directory, cmdName))\n\t\tif err == nil && fi.Mode().IsRegular() {\n\t\t\treturn path.Join(directory, cmdName), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Can't find the right path for %s\", cmdName)\n}\n\nfunc main() {\n\tdir := gopath.Dir()\n\tfmt.Println(\"DIR 1:\", gopath.WD())\n\tfmt.Println(\"DIR 2:\", dir)\n\tHTTPD := gwv.NewWebServer(8080, 60)\n\tHTTPD.ConfigSSL(4443, filepath.Join(dir, \"..\", \"ssl.key\"), filepath.Join(dir, \"..\", \"ssl.cert\"), true)\n\n\tHTTPD.URLhandler(\n\t\tgwv.Robots(as.String(cachedfile.Read(filepath.Join(dir, \"..\", \"static\", \"robots.txt\")))),\n\t\tgwv.Favicon(filepath.Join(dir, \"..\", \"static\", \"favicon.ico\")),\n\t\tgwv.StaticFiles(\"\/\", dir),\n\t)\n\n\tlog.Print(\"starting\")\n\tHTTPD.Start()\n\tHTTPD.WG.Add(1)\n\tlog.Print(\"started\")\n\tHTTPD.WG.Wait()\n\tlog.Print(\"stopped\")\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"go.sgr\"\n)\n\nfunc main() {\n\tfmt.Println(\"normal text\")\n\n\tfmt.Printf(sgr.MustFormat(sgr.FgBlack, \"%s\\n\"), \"FgBlack\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgRed, \"%s\\n\"), \"FgRed\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgGreen, \"%s\\n\"), \"FgGreen\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgYellow, \"%s\\n\"), \"FgYellow\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgBlue, \"%s\\n\"), \"FgBlue\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgMagenta, \"%s\\n\"), \"FgMagenta\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgCyan, \"%s\\n\"), \"FgCyan\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgGrey, \"%s\\n\"), \"FgGrey\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgWhite, \"%s\\n\"), \"FgWhite\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgBlack, \"%s\\n\"), \"BgBlack\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgRed, \"%s\\n\"), \"BgRed\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgGreen, \"%s\\n\"), \"BgGreen\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgYellow, \"%s\\n\"), \"BgYellow\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgBlue, \"%s\\n\"), \"BgBlue\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgMagenta, \"%s\\n\"), \"BgMagenta\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgCyan, \"%s\\n\"), \"BgCyan\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgGrey, \"%s\\n\"), \"BgGrey\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgWhite, \"%s\\n\"), \"BgWhite\")\n\n\tfmt.Printf(sgr.MustFormat(sgr.Reset, \"%s \"), \"Reset\")\n\tfmt.Printf(sgr.MustFormat(sgr.ResetForegroundColor, \"%s \"), \"ResetForegroundColor\")\n\tfmt.Printf(sgr.MustFormat(sgr.ResetBackgroundColor, \"%s \"), \"ResetBackgroundColor\")\n\tfmt.Printf(sgr.MustFormat(sgr.Bold, \"%s \"), \"Bold\")\n\tfmt.Printf(sgr.MustFormat(sgr.BoldOff, \"%s \"), \"BoldOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Underline, \"%s \"), \"Underline\")\n\tfmt.Printf(sgr.MustFormat(sgr.UnderlineOff, \"%s \"), \"UnderlineOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Blink, \"%s \"), \"Blink\")\n\tfmt.Printf(sgr.MustFormat(sgr.BlinkOff, \"%s \"), \"BlinkOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.ImageNegative, \"%s \"), \"ImageNegative\")\n\tfmt.Printf(sgr.MustFormat(sgr.ImagePositive, \"%s \"), \"ImagePositive\")\n\tfmt.Printf(sgr.MustFormat(sgr.Framed, \"%s \"), \"Framed\")\n\tfmt.Printf(sgr.MustFormat(sgr.Encircled, \"%s \"), \"Encircled\")\n\tfmt.Printf(sgr.MustFormat(sgr.FramedEncircledOff, \"%s \"), \"FramedEncircledOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Overlined, \"%s \"), \"Overlined\")\n\tfmt.Printf(sgr.MustFormat(sgr.OverlinedOff, \"%s \"), \"OverlinedOff\")\n}\nCustom colors. Comments.package main\n\nimport (\n\t\"fmt\"\n\t\"go.sgr\"\n)\n\nfunc main() {\n\tfmt.Println(\"normal text\")\n\n\t\/\/ Defined colors\n\tfmt.Printf(sgr.MustFormat(sgr.FgBlack, \"%s\\n\"), \"FgBlack\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgRed, \"%s\\n\"), \"FgRed\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgGreen, \"%s\\n\"), \"FgGreen\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgYellow, \"%s\\n\"), \"FgYellow\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgBlue, \"%s\\n\"), \"FgBlue\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgMagenta, \"%s\\n\"), \"FgMagenta\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgCyan, \"%s\\n\"), \"FgCyan\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgGrey, \"%s\\n\"), \"FgGrey\")\n\tfmt.Printf(sgr.MustFormat(sgr.FgWhite, \"%s\\n\"), \"FgWhite\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgBlack, \"%s\\n\"), \"BgBlack\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgRed, \"%s\\n\"), \"BgRed\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgGreen, \"%s\\n\"), \"BgGreen\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgYellow, \"%s\\n\"), \"BgYellow\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgBlue, \"%s\\n\"), \"BgBlue\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgMagenta, \"%s\\n\"), \"BgMagenta\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgCyan, \"%s\\n\"), \"BgCyan\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgGrey, \"%s\\n\"), \"BgGrey\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgWhite, \"%s\\n\"), \"BgWhite\")\n\n\t\/\/ Custom colors\n\tfmt.Printf(sgr.MustFormat(sgr.FgColor(69), \"%s\\n\"), \"FgColor(69)\")\n\tfmt.Printf(sgr.MustFormat(sgr.BgColor(90), \"%s\\n\"), \"BgColor(90)\")\n\n\t\/\/ Options\n\tfmt.Printf(sgr.MustFormat(sgr.Reset, \"%s \"), \"Reset\")\n\tfmt.Printf(sgr.MustFormat(sgr.ResetForegroundColor, \"%s \"), \"ResetForegroundColor\")\n\tfmt.Printf(sgr.MustFormat(sgr.ResetBackgroundColor, \"%s \"), \"ResetBackgroundColor\")\n\tfmt.Printf(sgr.MustFormat(sgr.Bold, \"%s \"), \"Bold\")\n\tfmt.Printf(sgr.MustFormat(sgr.BoldOff, \"%s \"), \"BoldOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Underline, \"%s \"), \"Underline\")\n\tfmt.Printf(sgr.MustFormat(sgr.UnderlineOff, \"%s \"), \"UnderlineOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Blink, \"%s \"), \"Blink\")\n\tfmt.Printf(sgr.MustFormat(sgr.BlinkOff, \"%s \"), \"BlinkOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.ImageNegative, \"%s \"), \"ImageNegative\")\n\tfmt.Printf(sgr.MustFormat(sgr.ImagePositive, \"%s \"), \"ImagePositive\")\n\tfmt.Printf(sgr.MustFormat(sgr.Framed, \"%s \"), \"Framed\")\n\tfmt.Printf(sgr.MustFormat(sgr.Encircled, \"%s \"), \"Encircled\")\n\tfmt.Printf(sgr.MustFormat(sgr.FramedEncircledOff, \"%s \"), \"FramedEncircledOff\")\n\tfmt.Printf(sgr.MustFormat(sgr.Overlined, \"%s \"), \"Overlined\")\n\tfmt.Printf(sgr.MustFormat(sgr.OverlinedOff, \"%s \"), \"OverlinedOff\")\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/mattn\/go-uwsgi\"\n\t\"path\/filepath\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\n)\n\nfunc main() {\n\ts := \"\/tmp\/uwsgi.sock\"\n\tos.Remove(s)\n\tl, e := net.Listen(\"unix\", s)\n\tos.Chmod(s, 0666)\n\tif e != nil {\n\t\tprintln(e.Error())\n\t\tos.Exit(1)\n\t}\n http.Serve(&uwsgi.Listener{l}, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\tpath := req.URL.Path\n\t\tfile := filepath.Join(\".\", filepath.FromSlash(path))\n\t\tf, e := os.Stat(file)\n\t\tif e == nil && f.IsDir() && path[len(path)-1] != '\/' {\n\t\t\trw.Header().Set(\"Location\", req.URL.Path + \"\/\")\n\t\t\trw.WriteHeader(http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.ServeFile(rw, req, filepath.Join(\".\", filepath.FromSlash(req.URL.Path)))\n\t}))\n}\nget root.package main\n\nimport (\n\t\"github.com\/mattn\/go-uwsgi\"\n\t\"path\/filepath\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\n)\n\nfunc main() {\n\ts := \"\/tmp\/uwsgi.sock\"\n\tos.Remove(s)\n\tl, e := net.Listen(\"unix\", s)\n\tos.Chmod(s, 0666)\n\tif e != nil {\n\t\tprintln(e.Error())\n\t\tos.Exit(1)\n\t}\n\troot, _ := filepath.Split(os.Args[0])\n\troot, _ = filepath.Abs(root)\n http.Serve(&uwsgi.Listener{l}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tpath := r.URL.Path\n\t\tfile := filepath.Join(root, filepath.FromSlash(path))\n\t\tf, e := os.Stat(file)\n\t\tif e == nil && f.IsDir() && path[len(path)-1] != '\/' {\n\t\t\tw.Header().Set(\"Location\", r.URL.Path + \"\/\")\n\t\t\tw.WriteHeader(http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.ServeFile(w, r, file)\n\t}))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/getsentry\/raven-go\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nfunc trace() *raven.Stacktrace {\n\treturn raven.NewStacktrace(0, 2, nil)\n}\n\nfunc main() {\n\tclient, err := raven.NewClient(os.Args[1], map[string]string{\"foo\": \"bar\"})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thttpReq, _ := http.NewRequest(\"GET\", \"http:\/\/example.com\/foo?bar=true\", nil)\n\thttpReq.RemoteAddr = \"127.0.0.1:80\"\n\thttpReq.Header = http.Header{\"Content-Type\": {\"text\/html\"}, \"Content-Length\": {\"42\"}}\n\tpacket := &raven.Packet{Message: \"Test report\", Interfaces: []raven.Interface{raven.NewException(errors.New(\"example\"), trace()), raven.NewHttp(httpReq)}}\n\t_, ch := client.Capture(packet, nil)\n\tif err = <-ch; err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"sent packet successfully\")\n}\n\n\/\/ CheckError sends error report to sentry and records event id and error name to the logs\nfunc CheckError(err error, r *http.Request) {\n\tpacket = raven.NewPacket(err.Error(), raven.NewException(err, trace()), raven.NewHttp(r))\n\teventID, _ := client.Capture(packet, nil)\n\tmessage := fmt.Sprintf(\"Error event with id \\\"%s\\\" - %s\", eventID, err.Error())\n\tlog.Println(message)\n}\nfix travis buildpackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/getsentry\/raven-go\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nfunc trace() *raven.Stacktrace {\n\treturn raven.NewStacktrace(0, 2, nil)\n}\n\nfunc main() {\n\tclient, err := raven.NewClient(os.Args[1], map[string]string{\"foo\": \"bar\"})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thttpReq, _ := http.NewRequest(\"GET\", \"http:\/\/example.com\/foo?bar=true\", nil)\n\thttpReq.RemoteAddr = \"127.0.0.1:80\"\n\thttpReq.Header = http.Header{\"Content-Type\": {\"text\/html\"}, \"Content-Length\": {\"42\"}}\n\tpacket := &raven.Packet{Message: \"Test report\", Interfaces: []raven.Interface{raven.NewException(errors.New(\"example\"), trace()), raven.NewHttp(httpReq)}}\n\t_, ch := client.Capture(packet, nil)\n\tif err = <-ch; err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"sent packet successfully\")\n}\n\n\/\/ CheckError sends error report to sentry and records event id and error name to the logs\nfunc CheckError(err error, r *http.Request) {\n\tclient, err := raven.NewClient(os.Args[1], map[string]string{\"foo\": \"bar\"})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tpacket := raven.NewPacket(err.Error(), raven.NewException(err, trace()), raven.NewHttp(r))\n\teventID, _ := client.Capture(packet, nil)\n\tmessage := fmt.Sprintf(\"Error event with id \\\"%s\\\" - %s\", eventID, err.Error())\n\tlog.Println(message)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage syslog\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"bytes\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/---------------------------------------------------------------------\n\nfunc fileEquals(t *testing.T, expected string, fileName string) {\n\tassert := assert.New(t)\n\n\tbuf, err := ioutil.ReadFile(fileName)\n\tassert.NoError(err)\n\n\tassert.EqualValues(expected, string(buf))\n}\n\nfunc fileExist(s string) bool {\n\tif _, err := os.Stat(s); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc safeRemove(s string) error {\n\tif fileExist(s) {\n\t\terr := os.Remove(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc makeMessage(sde bool) (*Message, string) {\n\tm := NewMessage()\n\n\t\/\/ because ParseMessageString isn't as accurate as we could be\n\tnow := time.Now().Round(time.Second)\n\n\tm.Facility = DefaultFacility\n\tm.Severity = Fatal \/\/ pri = 1*8 + 2 = 10\n\tm.Version = DefaultVersion\n\tm.TimeStamp = now\n\tm.HostName = \"HOST\"\n\tm.Application = \"APPLICATION\"\n\tm.Process = \"1234\"\n\tm.MessageID = \"msg1of2\"\n\tm.AuditData = nil\n\tm.MetricData = nil\n\tm.Message = \"Yow\"\n\n\texpected := \"<10>1 \" + m.TimeStamp.Format(time.RFC3339) + \" HOST APPLICATION 1234 msg1of2 - Yow\"\n\n\tif sde {\n\t\tm.AuditData = &AuditElement{\n\t\t\tActor: \"=actor=\",\n\t\t\tAction: \"-action-\",\n\t\t\tActee: \"_actee_\",\n\t\t}\n\t\tm.MetricData = &MetricElement{\n\t\t\tName: \"=name=\",\n\t\t\tValue: -3.14,\n\t\t\tObject: \"_object_\",\n\t\t}\n\n\t\texpected = \"<10>1 \" + m.TimeStamp.Format(time.RFC3339) + \" HOST APPLICATION 1234 msg1of2 \" +\n\t\t\t\"[pzaudit@48851 actor=\\\"=actor=\\\" action=\\\"-action-\\\" actee=\\\"_actee_\\\"] \" +\n\t\t\t\"[pzmetric@48851 name=\\\"=name=\\\" value=\\\"-3.140000\\\" object=\\\"_object_\\\"] \" +\n\t\t\t\"Yow\"\n\t}\n\n\treturn m, expected\n}\n\n\/\/---------------------------------------------------------------------\n\nfunc Test01Message(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(false)\n\n\ts := m.String()\n\tassert.EqualValues(expected, s)\n\n\t\/\/\tmm, err := ParseMessageString(expected)\n\t\/\/\tassert.NoError(err)\n\n\t\/\/\tassert.EqualValues(m, mm)\n}\n\nfunc Test02MessageSDE(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(true)\n\n\ts := m.String()\n\tassert.EqualValues(expected, s)\n\n\t\/\/ TODO: this won't work until we make the parser understand SDEs\n\t\/\/mm, err := ParseMessageString(expected)\n\t\/\/assert.NoError(err)\n\t\/\/assert.EqualValues(m, mm)\n}\n\nfunc Test03Writer(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(false)\n\n\t{\n\t\t\/\/ verify error if no io.Writer given\n\t\tw := &Writer{Writer: nil}\n\t\terr := w.Write(m)\n\t\tassert.Error(err)\n\t}\n\n\t{\n\t\t\/\/ a simple kind of writer\n\t\tvar buf bytes.Buffer\n\t\tw := &Writer{Writer: &buf}\n\t\terr := w.Write(m)\n\t\tassert.NoError(err)\n\n\t\tactual := buf.String()\n\t\tassert.EqualValues(expected, actual)\n\t}\n}\n\nfunc Test04FileWriter(t *testing.T) {\n\tvar err error\n\n\tassert := assert.New(t)\n\n\tfname := \".\/testsyslog.txt\"\n\n\terr = safeRemove(fname)\n\tassert.NoError(err)\n\n\tm1, expected1 := makeMessage(false)\n\tm2, expected2 := makeMessage(true)\n\t{\n\t\tw := &FileWriter{FileName: fname}\n\t\terr = w.Write(m1)\n\t\tassert.NoError(err)\n\t\terr = w.Close()\n\t\tassert.NoError(err)\n\n\t\tfileEquals(t, expected1+\"\\n\", fname)\n\t}\n\n\t{\n\t\tw := &FileWriter{FileName: fname}\n\t\terr = w.Write(m2)\n\t\tassert.NoError(err)\n\t\terr = w.Close()\n\t\tassert.NoError(err)\n\t\tfileEquals(t, expected1+\"\\n\"+expected2+\"\\n\", fname)\n\t}\n\n\terr = safeRemove(fname)\n\tassert.NoError(err)\n}\n\nfunc Test05Logger(t *testing.T) {\n\tassert := assert.New(t)\n\n\t\/\/ the following clause is what a developer would do\n\tvar buf bytes.Buffer\n\t{\n\t\twriter := &Writer{\n\t\t\tWriter: &buf,\n\t\t}\n\t\tlogger := NewLogger(writer, \"testapp\")\n\t\tlogger.UseSourceElement = false\n\t\tlogger.Debug(\"debug %d\", 999)\n\t\tlogger.Info(\"info %d\", 123)\n\t\tlogger.Notice(\"notice %d\", 321)\n\t\tlogger.Warning(\"bonk %d\", 3)\n\t\tlogger.Error(\"Bonk %s\", \".1\")\n\t\tlogger.Fatal(\"BONK %f\", 4.0)\n\t\tlogger.Audit(\"1\", \"2\", \"3\", \"brown%s\", \"fox\")\n\t\tlogger.Metric(\"i\", 5952567, \"k\", \"lazy%s\", \"dog\")\n\t}\n\n\tmssg := buf.String()\n\n\tcheck := func(severity Severity, str string) {\n\t\tfacility := DefaultFacility\n\t\thost, err := os.Hostname()\n\t\tassert.NoError(err)\n\t\tassert.Contains(mssg, fmt.Sprintf(\"<%d>\", facility*8+severity.Value()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %d \", os.Getpid()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %s \", host))\n\t\tassert.Contains(mssg, str)\n\t}\n\n\tcheck(Debug, \"debug 999\")\n\tcheck(Informational, \"info 123\")\n\tcheck(Notice, \"notice 321\")\n\tcheck(Warning, \"bonk 3\")\n\tcheck(Error, \"Bonk .1\")\n\tcheck(Fatal, \"BONK 4.0\")\n\tcheck(Notice, \"Actor=\\\"1\\\"\")\n\tcheck(Notice, \"brownfox\")\n\tcheck(Notice, \"Value=\\\"5952567.0\")\n\tcheck(Notice, \"lazydog\")\n}\n\nfunc Test06LogLevel(t *testing.T) {\n\tassert := assert.New(t)\n\n\tvar buf bytes.Buffer\n\t{\n\t\twriter := &Writer{\n\t\t\tWriter: &buf,\n\t\t}\n\t\tlogger := NewLogger(writer, \"testapp\")\n\t\tlogger.UseSourceElement = false\n\t\tlogger.MinimumSeverity = Error\n\t\tlogger.Warning(\"bonk\")\n\t\tlogger.Error(\"Bonk\")\n\t\tlogger.Fatal(\"BONK\")\n\t}\n\n\tmssg := buf.String()\n\n\tcheck := func(severity Severity, str string) {\n\t\tfacility := DefaultFacility\n\t\thost, err := os.Hostname()\n\t\tassert.NoError(err)\n\t\tassert.Contains(mssg, fmt.Sprintf(\"<%d>\", facility*8+severity.Value()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %d \", os.Getpid()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %s \", host))\n\t\tassert.Contains(mssg, str)\n\t}\n\n\t\/\/pri(Warning, \"bonk\")\n\tassert.NotContains(mssg, \"bonk\")\n\n\tcheck(Error, \"Bonk\")\n\tcheck(Fatal, \"BONK\")\n}\n\nfunc Test07StackFrame(t *testing.T) {\n\tassert := assert.New(t)\n\n\tfunction, file, line := stackFrame(-1)\n\t\/\/log.Printf(\"%s\\t%s\\t%d\", function, file, line)\n\tassert.EqualValues(file, \"SyslogMessage.go\")\n\tassert.True(line > 1 && line < 1000)\n\tassert.EqualValues(\"syslog.stackFrame\", function)\n\n\tfunction, file, line = stackFrame(0)\n\t\/\/log.Printf(\"%s\\t%s\\t%d\", function, file, line)\n\tassert.EqualValues(file, \"Syslog_test.go\")\n\tassert.True(line > 1 && line < 1000)\n\tassert.EqualValues(\"syslog.Test07StackFrame\", function)\n}\ntypos\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage syslog\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"bytes\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/---------------------------------------------------------------------\n\nfunc fileEquals(t *testing.T, expected string, fileName string) {\n\tassert := assert.New(t)\n\n\tbuf, err := ioutil.ReadFile(fileName)\n\tassert.NoError(err)\n\n\tassert.EqualValues(expected, string(buf))\n}\n\nfunc fileExist(s string) bool {\n\tif _, err := os.Stat(s); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc safeRemove(s string) error {\n\tif fileExist(s) {\n\t\terr := os.Remove(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc makeMessage(sde bool) (*Message, string) {\n\tm := NewMessage()\n\n\t\/\/ because ParseMessageString isn't as accurate as we could be\n\tnow := time.Now().Round(time.Second)\n\n\tm.Facility = DefaultFacility\n\tm.Severity = Fatal \/\/ pri = 1*8 + 2 = 10\n\tm.Version = DefaultVersion\n\tm.TimeStamp = now\n\tm.HostName = \"HOST\"\n\tm.Application = \"APPLICATION\"\n\tm.Process = \"1234\"\n\tm.MessageID = \"msg1of2\"\n\tm.AuditData = nil\n\tm.MetricData = nil\n\tm.Message = \"Yow\"\n\n\texpected := \"<10>1 \" + m.TimeStamp.Format(time.RFC3339) + \" HOST APPLICATION 1234 msg1of2 - Yow\"\n\n\tif sde {\n\t\tm.AuditData = &AuditElement{\n\t\t\tActor: \"=actor=\",\n\t\t\tAction: \"-action-\",\n\t\t\tActee: \"_actee_\",\n\t\t}\n\t\tm.MetricData = &MetricElement{\n\t\t\tName: \"=name=\",\n\t\t\tValue: -3.14,\n\t\t\tObject: \"_object_\",\n\t\t}\n\n\t\texpected = \"<10>1 \" + m.TimeStamp.Format(time.RFC3339) + \" HOST APPLICATION 1234 msg1of2 \" +\n\t\t\t\"[pzaudit@48851 actor=\\\"=actor=\\\" action=\\\"-action-\\\" actee=\\\"_actee_\\\"] \" +\n\t\t\t\"[pzmetric@48851 name=\\\"=name=\\\" value=\\\"-3.140000\\\" object=\\\"_object_\\\"] \" +\n\t\t\t\"Yow\"\n\t}\n\n\treturn m, expected\n}\n\n\/\/---------------------------------------------------------------------\n\nfunc Test01Message(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(false)\n\n\ts := m.String()\n\tassert.EqualValues(expected, s)\n\n\t\/\/\tmm, err := ParseMessageString(expected)\n\t\/\/\tassert.NoError(err)\n\n\t\/\/\tassert.EqualValues(m, mm)\n}\n\nfunc Test02MessageSDE(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(true)\n\n\ts := m.String()\n\tassert.EqualValues(expected, s)\n\n\t\/\/ TODO: this won't work until we make the parser understand SDEs\n\t\/\/mm, err := ParseMessageString(expected)\n\t\/\/assert.NoError(err)\n\t\/\/assert.EqualValues(m, mm)\n}\n\nfunc Test03Writer(t *testing.T) {\n\tassert := assert.New(t)\n\n\tm, expected := makeMessage(false)\n\n\t{\n\t\t\/\/ verify error if no io.Writer given\n\t\tw := &Writer{Writer: nil}\n\t\terr := w.Write(m)\n\t\tassert.Error(err)\n\t}\n\n\t{\n\t\t\/\/ a simple kind of writer\n\t\tvar buf bytes.Buffer\n\t\tw := &Writer{Writer: &buf}\n\t\terr := w.Write(m)\n\t\tassert.NoError(err)\n\n\t\tactual := buf.String()\n\t\tassert.EqualValues(expected, actual)\n\t}\n}\n\nfunc Test04FileWriter(t *testing.T) {\n\tvar err error\n\n\tassert := assert.New(t)\n\n\tfname := \".\/testsyslog.txt\"\n\n\terr = safeRemove(fname)\n\tassert.NoError(err)\n\n\tm1, expected1 := makeMessage(false)\n\tm2, expected2 := makeMessage(true)\n\t{\n\t\tw := &FileWriter{FileName: fname}\n\t\terr = w.Write(m1)\n\t\tassert.NoError(err)\n\t\terr = w.Close()\n\t\tassert.NoError(err)\n\n\t\tfileEquals(t, expected1+\"\\n\", fname)\n\t}\n\n\t{\n\t\tw := &FileWriter{FileName: fname}\n\t\terr = w.Write(m2)\n\t\tassert.NoError(err)\n\t\terr = w.Close()\n\t\tassert.NoError(err)\n\t\tfileEquals(t, expected1+\"\\n\"+expected2+\"\\n\", fname)\n\t}\n\n\terr = safeRemove(fname)\n\tassert.NoError(err)\n}\n\nfunc Test05Logger(t *testing.T) {\n\tassert := assert.New(t)\n\n\t\/\/ the following clause is what a developer would do\n\tvar buf bytes.Buffer\n\t{\n\t\twriter := &Writer{\n\t\t\tWriter: &buf,\n\t\t}\n\t\tlogger := NewLogger(writer, \"testapp\")\n\t\tlogger.UseSourceElement = false\n\t\tlogger.Debug(\"debug %d\", 999)\n\t\tlogger.Info(\"info %d\", 123)\n\t\tlogger.Notice(\"notice %d\", 321)\n\t\tlogger.Warning(\"bonk %d\", 3)\n\t\tlogger.Error(\"Bonk %s\", \".1\")\n\t\tlogger.Fatal(\"BONK %f\", 4.0)\n\t\tlogger.Audit(\"1\", \"2\", \"3\", \"brown%s\", \"fox\")\n\t\tlogger.Metric(\"i\", 5952567, \"k\", \"lazy%s\", \"dog\")\n\t}\n\n\tmssg := buf.String()\n\n\tcheck := func(severity Severity, str string) {\n\t\tfacility := DefaultFacility\n\t\thost, err := os.Hostname()\n\t\tassert.NoError(err)\n\t\tassert.Contains(mssg, fmt.Sprintf(\"<%d>\", facility*8+severity.Value()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %d \", os.Getpid()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %s \", host))\n\t\tassert.Contains(mssg, str)\n\t}\n\n\tcheck(Debug, \"debug 999\")\n\tcheck(Informational, \"info 123\")\n\tcheck(Notice, \"notice 321\")\n\tcheck(Warning, \"bonk 3\")\n\tcheck(Error, \"Bonk .1\")\n\tcheck(Fatal, \"BONK 4.0\")\n\tcheck(Notice, \"actor=\\\"1\\\"\")\n\tcheck(Notice, \"brownfox\")\n\tcheck(Notice, \"value=\\\"5952567.0\")\n\tcheck(Notice, \"lazydog\")\n}\n\nfunc Test06LogLevel(t *testing.T) {\n\tassert := assert.New(t)\n\n\tvar buf bytes.Buffer\n\t{\n\t\twriter := &Writer{\n\t\t\tWriter: &buf,\n\t\t}\n\t\tlogger := NewLogger(writer, \"testapp\")\n\t\tlogger.UseSourceElement = false\n\t\tlogger.MinimumSeverity = Error\n\t\tlogger.Warning(\"bonk\")\n\t\tlogger.Error(\"Bonk\")\n\t\tlogger.Fatal(\"BONK\")\n\t}\n\n\tmssg := buf.String()\n\n\tcheck := func(severity Severity, str string) {\n\t\tfacility := DefaultFacility\n\t\thost, err := os.Hostname()\n\t\tassert.NoError(err)\n\t\tassert.Contains(mssg, fmt.Sprintf(\"<%d>\", facility*8+severity.Value()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %d \", os.Getpid()))\n\t\tassert.Contains(mssg, fmt.Sprintf(\" %s \", host))\n\t\tassert.Contains(mssg, str)\n\t}\n\n\t\/\/pri(Warning, \"bonk\")\n\tassert.NotContains(mssg, \"bonk\")\n\n\tcheck(Error, \"Bonk\")\n\tcheck(Fatal, \"BONK\")\n}\n\nfunc Test07StackFrame(t *testing.T) {\n\tassert := assert.New(t)\n\n\tfunction, file, line := stackFrame(-1)\n\t\/\/log.Printf(\"%s\\t%s\\t%d\", function, file, line)\n\tassert.EqualValues(file, \"SyslogMessage.go\")\n\tassert.True(line > 1 && line < 1000)\n\tassert.EqualValues(\"syslog.stackFrame\", function)\n\n\tfunction, file, line = stackFrame(0)\n\t\/\/log.Printf(\"%s\\t%s\\t%d\", function, file, line)\n\tassert.EqualValues(file, \"Syslog_test.go\")\n\tassert.True(line > 1 && line < 1000)\n\tassert.EqualValues(\"syslog.Test07StackFrame\", function)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ +build go1.3\n\npackage lxdclient\n\nimport (\n\t\"bytes\"\n)\n\ntype closingBuffer struct {\n\tbytes.Buffer\n}\n\n\/\/ Close implements io.Closer.\nfunc (closingBuffer) Close() error {\n\treturn nil\n}\nAdd IsInstalledLocally and IsRunningLocally lxdclient helpers.\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ +build go1.3\n\npackage lxdclient\n\nimport (\n\t\"bytes\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/utils\/series\"\n\n\t\"github.com\/juju\/juju\/service\"\n\t\"github.com\/juju\/juju\/service\/common\"\n)\n\ntype closingBuffer struct {\n\tbytes.Buffer\n}\n\n\/\/ Close implements io.Closer.\nfunc (closingBuffer) Close() error {\n\treturn nil\n}\n\n\/\/ IsInstalledLocally returns true if LXD is installed locally.\nfunc IsInstalledLocally() (bool, error) {\n\tnames, err := service.ListServices()\n\tif err != nil {\n\t\treturn false, errors.Trace(err)\n\t}\n\tfor _, name := range names {\n\t\tif name == \"lxd\" {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n\/\/ IsRunningLocally returns true if LXD is running locally.\nfunc IsRunningLocally() (bool, error) {\n\tinstalled, err := IsInstalledLocally()\n\tif err != nil {\n\t\treturn installed, errors.Trace(err)\n\t}\n\tif !installed {\n\t\treturn false, nil\n\t}\n\n\tsvc, err := service.NewService(\"lxd\", common.Conf{}, series.HostSeries())\n\tif err != nil {\n\t\treturn false, errors.Trace(err)\n\t}\n\n\trunning, err := svc.Running()\n\tif err != nil {\n\t\treturn running, errors.Trace(err)\n\t}\n\n\treturn running, nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/mackerelio\/mackerel-agent\/command\"\n)\n\nfunc TestParseFlags(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`verbose=false\nroot=\"\/hoge\/fuga\"\napikey=\"DUMMYAPIKEY\"\ndiagnostic=false\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\tmergedConfig, _ := resolveConfig([]string{\"-conf=\" + confFile.Name(), \"-role=My-Service:default,INVALID#SERVICE\", \"-verbose\", \"-diagnostic\"})\n\n\tt.Logf(\" apibase: %v\", mergedConfig.Apibase)\n\tt.Logf(\" apikey: %v\", mergedConfig.Apikey)\n\tt.Logf(\" root: %v\", mergedConfig.Root)\n\tt.Logf(\" pidfile: %v\", mergedConfig.Pidfile)\n\tt.Logf(\" diagnostic: %v\", mergedConfig.Diagnostic)\n\tt.Logf(\"roleFullnames: %v\", mergedConfig.Roles)\n\tt.Logf(\" verbose: %v\", mergedConfig.Verbose)\n\n\tif mergedConfig.Root != \"\/hoge\/fuga\" {\n\t\tt.Errorf(\"Root(confing from file) should be \/hoge\/fuga but: %v\", mergedConfig.Root)\n\t}\n\n\tif len(mergedConfig.Roles) != 1 || mergedConfig.Roles[0] != \"My-Service:default\" {\n\t\tt.Error(\"Roles(config from command line option) should be parsed\")\n\t}\n\n\tif mergedConfig.Verbose != true {\n\t\tt.Error(\"Verbose(overwritten by command line option) shoud be true\")\n\t}\n\n\tif mergedConfig.Diagnostic != true {\n\t\tt.Error(\"Diagnostic(overwritten by command line option) shoud be true\")\n\t}\n}\n\nfunc TestParseFlagsPrintVersion(t *testing.T) {\n\tconfig, otherOptions := resolveConfig([]string{\"-version\"})\n\n\tif config.Verbose != false {\n\t\tt.Error(\"with -version args, variables of config should have default values\")\n\t}\n\n\tif otherOptions.printVersion == false {\n\t\tt.Error(\"with -version args, printVersion should be true\")\n\t}\n}\n\nfunc TestParseFlagsRunOnce(t *testing.T) {\n\tconfig, otherOptions := resolveConfig([]string{\"-once\"})\n\n\tif config.Verbose != false {\n\t\tt.Error(\"with -version args, variables of config should have default values\")\n\t}\n\n\tif otherOptions.runOnce == false {\n\t\tt.Error(\"with -once args, RunOnce should be true\")\n\t}\n}\n\nfunc TestDetectForce(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tconf, force, err := resolveConfigForRetire(argv)\n\tif force {\n\t\tt.Errorf(\"force should be false\")\n\t}\n\tif conf.Apikey != \"DUMMYAPIKEY\" {\n\t\tt.Errorf(\"Apikey should be 'DUMMYAPIKEY'\")\n\t}\n\n\targv = append(argv, \"-force\")\n\tconf, force, err = resolveConfigForRetire(argv)\n\tif !force {\n\t\tt.Errorf(\"force should be true\")\n\t}\n\tif conf.Apikey != \"DUMMYAPIKEY\" {\n\t\tt.Errorf(\"Apikey should be 'DUMMYAPIKEY'\")\n\t}\n}\n\nfunc TestCreateAndRemovePidFile(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"failed to create tmpfile, %s\", err)\n\t}\n\tfpath := file.Name()\n\tdefer os.Remove(fpath)\n\n\terr = createPidFile(fpath)\n\tif err != nil {\n\t\tt.Errorf(\"pid file should be created but, %s\", err)\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\tif err := createPidFile(fpath); err == nil || !strings.HasPrefix(err.Error(), \"Pidfile found, try stopping another running mackerel-agent or delete\") {\n\t\t\tt.Errorf(\"creating pid file should be failed when the running process exists, %s\", err)\n\t\t}\n\t}\n\n\tremovePidFile(fpath)\n\tif err := createPidFile(fpath); err != nil {\n\t\tt.Errorf(\"pid file should be created but, %s\", err)\n\t}\n\n\tremovePidFile(fpath)\n\tioutil.WriteFile(fpath, []byte(fmt.Sprint(math.MaxInt32)), 0644)\n\tif err := createPidFile(fpath); err != nil {\n\t\tt.Errorf(\"old pid file should be ignored and new pid file should be created but, %s\", err)\n\t}\n}\n\nfunc TestSignalHandler(t *testing.T) {\n\tctx := &command.Context{}\n\ttermCh := make(chan struct{})\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)\n\tgo signalHandler(c, ctx, termCh)\n\n\tresultCh := make(chan int)\n\n\tmaxTerminatingInterval = 100 * time.Millisecond\n\tc <- os.Interrupt\n\tc <- os.Interrupt\n\n\tgo func() {\n\t\t<-termCh\n\t\t<-termCh\n\t\t<-termCh\n\t\t<-termCh\n\t\tresultCh <- 0\n\t}()\n\n\tgo func() {\n\t\ttime.Sleep(time.Second)\n\t\tresultCh <- 1\n\t}()\n\n\tif r := <-resultCh; r != 0 {\n\t\tt.Errorf(\"Something went wrong\")\n\t}\n}\n\nfunc TestConfigTestOK(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusOK {\n\t\tt.Errorf(\"configtest(ok) must be return exitStatusOK\")\n\t}\n}\n\nfunc TestConfigTestNotFound(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name() + \"xxx\"}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusError {\n\t\tt.Errorf(\"configtest(failed) must be return existStatusError\")\n\t}\n}\n\nfunc TestConfigTestInvalidFormat(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n[plugin.checks.foo ]\ncommand = \"bar\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusError {\n\t\tt.Errorf(\"configtest(failed) must be return exitStatusError\")\n\t}\n}\nadd test for doRetirepackage main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/mackerelio\/mackerel-agent\/command\"\n)\n\nfunc TestParseFlags(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`verbose=false\nroot=\"\/hoge\/fuga\"\napikey=\"DUMMYAPIKEY\"\ndiagnostic=false\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\tmergedConfig, _ := resolveConfig([]string{\"-conf=\" + confFile.Name(), \"-role=My-Service:default,INVALID#SERVICE\", \"-verbose\", \"-diagnostic\"})\n\n\tt.Logf(\" apibase: %v\", mergedConfig.Apibase)\n\tt.Logf(\" apikey: %v\", mergedConfig.Apikey)\n\tt.Logf(\" root: %v\", mergedConfig.Root)\n\tt.Logf(\" pidfile: %v\", mergedConfig.Pidfile)\n\tt.Logf(\" diagnostic: %v\", mergedConfig.Diagnostic)\n\tt.Logf(\"roleFullnames: %v\", mergedConfig.Roles)\n\tt.Logf(\" verbose: %v\", mergedConfig.Verbose)\n\n\tif mergedConfig.Root != \"\/hoge\/fuga\" {\n\t\tt.Errorf(\"Root(confing from file) should be \/hoge\/fuga but: %v\", mergedConfig.Root)\n\t}\n\n\tif len(mergedConfig.Roles) != 1 || mergedConfig.Roles[0] != \"My-Service:default\" {\n\t\tt.Error(\"Roles(config from command line option) should be parsed\")\n\t}\n\n\tif mergedConfig.Verbose != true {\n\t\tt.Error(\"Verbose(overwritten by command line option) shoud be true\")\n\t}\n\n\tif mergedConfig.Diagnostic != true {\n\t\tt.Error(\"Diagnostic(overwritten by command line option) shoud be true\")\n\t}\n}\n\nfunc TestParseFlagsPrintVersion(t *testing.T) {\n\tconfig, otherOptions := resolveConfig([]string{\"-version\"})\n\n\tif config.Verbose != false {\n\t\tt.Error(\"with -version args, variables of config should have default values\")\n\t}\n\n\tif otherOptions.printVersion == false {\n\t\tt.Error(\"with -version args, printVersion should be true\")\n\t}\n}\n\nfunc TestParseFlagsRunOnce(t *testing.T) {\n\tconfig, otherOptions := resolveConfig([]string{\"-once\"})\n\n\tif config.Verbose != false {\n\t\tt.Error(\"with -version args, variables of config should have default values\")\n\t}\n\n\tif otherOptions.runOnce == false {\n\t\tt.Error(\"with -once args, RunOnce should be true\")\n\t}\n}\n\nfunc TestDetectForce(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tconf, force, err := resolveConfigForRetire(argv)\n\tif force {\n\t\tt.Errorf(\"force should be false\")\n\t}\n\tif conf.Apikey != \"DUMMYAPIKEY\" {\n\t\tt.Errorf(\"Apikey should be 'DUMMYAPIKEY'\")\n\t}\n\n\targv = append(argv, \"-force\")\n\tconf, force, err = resolveConfigForRetire(argv)\n\tif !force {\n\t\tt.Errorf(\"force should be true\")\n\t}\n\tif conf.Apikey != \"DUMMYAPIKEY\" {\n\t\tt.Errorf(\"Apikey should be 'DUMMYAPIKEY'\")\n\t}\n}\n\nfunc TestResolveConfigForRetire(t *testing.T) {\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\t\/\/ Allow accepting unnecessary options, pidfile, diagnostic and role.\n\t\/\/ Because, these options are potentially passed in initd script by using $OTHER_OPTS.\n\targv := []string{\n\t\t\"-conf=\" + confFile.Name(),\n\t\t\"-apibase=https:\/\/mackerel.io\",\n\t\t\"-pidfile=hoge\",\n\t\t\"-root=hoge\",\n\t\t\"-verbose\",\n\t\t\"-diagnostic\",\n\t\t\"-apikey=hogege\",\n\t\t\"-role=hoge:fuga\",\n\t}\n\n\tconf, force, err := resolveConfigForRetire(argv)\n\tif force {\n\t\tt.Errorf(\"force should be false\")\n\t}\n\tif conf.Apikey != \"hogege\" {\n\t\tt.Errorf(\"Apikey should be 'hogege'\")\n\t}\n}\n\nfunc TestCreateAndRemovePidFile(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"failed to create tmpfile, %s\", err)\n\t}\n\tfpath := file.Name()\n\tdefer os.Remove(fpath)\n\n\terr = createPidFile(fpath)\n\tif err != nil {\n\t\tt.Errorf(\"pid file should be created but, %s\", err)\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\tif err := createPidFile(fpath); err == nil || !strings.HasPrefix(err.Error(), \"Pidfile found, try stopping another running mackerel-agent or delete\") {\n\t\t\tt.Errorf(\"creating pid file should be failed when the running process exists, %s\", err)\n\t\t}\n\t}\n\n\tremovePidFile(fpath)\n\tif err := createPidFile(fpath); err != nil {\n\t\tt.Errorf(\"pid file should be created but, %s\", err)\n\t}\n\n\tremovePidFile(fpath)\n\tioutil.WriteFile(fpath, []byte(fmt.Sprint(math.MaxInt32)), 0644)\n\tif err := createPidFile(fpath); err != nil {\n\t\tt.Errorf(\"old pid file should be ignored and new pid file should be created but, %s\", err)\n\t}\n}\n\nfunc TestSignalHandler(t *testing.T) {\n\tctx := &command.Context{}\n\ttermCh := make(chan struct{})\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)\n\tgo signalHandler(c, ctx, termCh)\n\n\tresultCh := make(chan int)\n\n\tmaxTerminatingInterval = 100 * time.Millisecond\n\tc <- os.Interrupt\n\tc <- os.Interrupt\n\n\tgo func() {\n\t\t<-termCh\n\t\t<-termCh\n\t\t<-termCh\n\t\t<-termCh\n\t\tresultCh <- 0\n\t}()\n\n\tgo func() {\n\t\ttime.Sleep(time.Second)\n\t\tresultCh <- 1\n\t}()\n\n\tif r := <-resultCh; r != 0 {\n\t\tt.Errorf(\"Something went wrong\")\n\t}\n}\n\nfunc TestConfigTestOK(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusOK {\n\t\tt.Errorf(\"configtest(ok) must be return exitStatusOK\")\n\t}\n}\n\nfunc TestConfigTestNotFound(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name() + \"xxx\"}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusError {\n\t\tt.Errorf(\"configtest(failed) must be return existStatusError\")\n\t}\n}\n\nfunc TestConfigTestInvalidFormat(t *testing.T) {\n\t\/\/ prepare dummy config\n\tconfFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Fatalf(\"Could not create temprary config file for test\")\n\t}\n\tconfFile.WriteString(`apikey=\"DUMMYAPIKEY\"\n[plugin.checks.foo ]\ncommand = \"bar\"\n`)\n\tconfFile.Sync()\n\tconfFile.Close()\n\tdefer os.Remove(confFile.Name())\n\n\targv := []string{\"-conf=\" + confFile.Name()}\n\tstatus := doConfigtest(argv)\n\n\tif status != exitStatusError {\n\t\tt.Errorf(\"configtest(failed) must be return exitStatusError\")\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport(\n\t\"regexp\"\n)\n\nconst(\n\tregex_date = `\\d{4}[-\/\\.]\\d{2}[-\/\\.]\\d{2}`\n\tregex_xp = `\\(?\\d*xp\\)?`\n\tregex_mark = `[\\*\\+\\-]`\n\tregex_value = `([\\+\\-])?\\d{1,2}`\n\tregex_blank = `[\\t ]*`\n\tregex_date_separator = `[\/-\\.]`\n\tdate_format = `2006\/02\/03`\n)\n\ntype Line struct {\n\traw\tstring\n}\n\n\/\/ creates a new line given a raw value\nfunc NewLine(raw string) *Line {\n\treturn &Line{\n\t\traw: raw,\n\t}\n}\n\n\/\/ returns true if the line contains a date\nfunc (l *line) HasDate() (m bool) {\n\tm, _ regexp.MatchString(`^` + regex_blank + regex_date, l.raw)\n\treturn\n}\n\n\/\/ returns the date within the line and removes it\nfunc (l *line) GetDate() (s string) {\n\tif !l.HasDate() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(`^` + regex_blank + regex_date)\n\ts = r.FindString(l.raw)\n\tr := regexp.MustCompile(regex_date_separator)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = r.ReplaceAllString(s, \"\/\")\n\ts = strings.TrimSpace(s)\n}\n\n\/\/ returns true if the line contains xp\nfunc (l *line) HasXp() (m bool) {\n\tm, _ regexp.MatchString(regex_xp, l.raw)\n\treturn\n}\n\n\/\/ returns the xp within the line and removes it\nfunc (l *line) GetXp() (s string) {\n\tif !l.HasXp() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(regex_xp)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = regexp.MustCompile(`\\d*`).FindString(s)\n}\n\n\/\/ returns true if the line contains mark\nfunc (l *line) HasMark() (m bool) {\n\tm, _ regexp.MatchString(regex_mark, l.raw)\n\treturn\n}\n\n\/\/ returns the mark within the line and removes it\nfunc (l *line) GetMark() (s string) {\n\tif !l.HasMark() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(regex_mark)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = strings.TrimSpace(s)\n}\n\n\/\/ returns true if the line contains value\nfunc (l *line) HasValue() (m bool) {\n\tm, _ regexp.MatchString(regex_value, l.raw)\n\treturn\n}\n\n\/\/ returns the value within the line and removes it\nfunc (l *line) GetValue() (s string) {\n\tif !l.HasValue() {\n\t\treturn\n\t}\n\tr = regexp.MustCompile(regex_value)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n}\n\n\/\/ returns true if the line contains an label\nfunc (l *line) HasKey() bool {\n\treturn strings.Contains(l.raw, \":\")\n}\n\n\/\/ returns the key within the line and removes it\nfunc (l *line) GetKey() (s string) {\n\tif !l.HasKey() {\n\t\treturn\n\t}\n\tsplit := strings.SplitN(l.raw, \":\", 2)\n\ts = split[0]\n\tl.raw = split[1]\n\ts = strings.TrimSpace(s)\n\treturn\n}\n\n\/\/ returns the label within the line and removes it\nfunc (l *line) GetLabel() (s string) {\n\treturn strings.TrimSpace(l.raw)\n}Removes useless constant.package main\n\nimport(\n\t\"regexp\"\n)\n\nconst(\n\tregex_date = `^[\\t ]*\\d{4}[-\/\\.]\\d{2}[-\/\\.]\\d{2}`\n\tregex_xp = `\\(?\\d*xp\\)?`\n\tregex_mark = `[\\*\\+\\-]`\n\tregex_value = `([\\+\\-])?\\d{1,2}`\n\tregex_date_separator = `[\/-\\.]`\n\tdate_format = `2006\/02\/03`\n)\n\ntype Line struct {\n\traw\tstring\n}\n\n\/\/ creates a new line given a raw value\nfunc NewLine(raw string) *Line {\n\treturn &Line{\n\t\traw: raw,\n\t}\n}\n\n\/\/ returns true if the line contains a date\nfunc (l *line) HasDate() (m bool) {\n\tm, _ regexp.MatchString(regex_date, l.raw)\n\treturn\n}\n\n\/\/ returns the date within the line and removes it\nfunc (l *line) GetDate() (s string) {\n\tif !l.HasDate() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(regex_date)\n\ts = r.FindString(l.raw)\n\tr := regexp.MustCompile(regex_date_separator)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = r.ReplaceAllString(s, \"\/\")\n\ts = strings.TrimSpace(s)\n}\n\n\/\/ returns true if the line contains xp\nfunc (l *line) HasXp() (m bool) {\n\tm, _ regexp.MatchString(regex_xp, l.raw)\n\treturn\n}\n\n\/\/ returns the xp within the line and removes it\nfunc (l *line) GetXp() (s string) {\n\tif !l.HasXp() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(regex_xp)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = regexp.MustCompile(`\\d*`).FindString(s)\n}\n\n\/\/ returns true if the line contains mark\nfunc (l *line) HasMark() (m bool) {\n\tm, _ regexp.MatchString(regex_mark, l.raw)\n\treturn\n}\n\n\/\/ returns the mark within the line and removes it\nfunc (l *line) GetMark() (s string) {\n\tif !l.HasMark() {\n\t\treturn\n\t}\n\tr := regexp.MustCompile(regex_mark)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n\ts = strings.TrimSpace(s)\n}\n\n\/\/ returns true if the line contains value\nfunc (l *line) HasValue() (m bool) {\n\tm, _ regexp.MatchString(regex_value, l.raw)\n\treturn\n}\n\n\/\/ returns the value within the line and removes it\nfunc (l *line) GetValue() (s string) {\n\tif !l.HasValue() {\n\t\treturn\n\t}\n\tr = regexp.MustCompile(regex_value)\n\ts = r.FindString(l.raw)\n\tl.raw = strings.Replace(l.raw, s, \"\", 1)\n}\n\n\/\/ returns true if the line contains an label\nfunc (l *line) HasKey() bool {\n\treturn strings.Contains(l.raw, \":\")\n}\n\n\/\/ returns the key within the line and removes it\nfunc (l *line) GetKey() (s string) {\n\tif !l.HasKey() {\n\t\treturn\n\t}\n\tsplit := strings.SplitN(l.raw, \":\", 2)\n\ts = split[0]\n\tl.raw = split[1]\n\ts = strings.TrimSpace(s)\n\treturn\n}\n\n\/\/ returns the label within the line and removes it\nfunc (l *line) GetLabel() (s string) {\n\treturn strings.TrimSpace(l.raw)\n}<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestReadLines(t *testing.T) {\n\n\tassert := assert.New(t)\n\tlines, err := readLines(\".\/test.chordpro\")\n\n\tassert.Nil(err)\n\tassert.Equal(\"{t: Hello world}\", lines[0], \"they should be equal\")\n\tassert.Equal(\"\", lines[4], \"they should be equal\")\n\tassert.Equal(\"[G]Lorem ipsum dolor sit amet, [D\/F#]consectetur adipiscing elit. Don[Em]ec a diam lectus.\", lines[5], \"they should be equal\")\n}\n:white_check_mark: Add test for getLineTypepackage main\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestReadLines(t *testing.T) {\n\n\tassert := assert.New(t)\n\tlines, err := readLines(\".\/test.chordpro\")\n\n\tassert.Nil(err)\n\tassert.Equal(\"{t: Hello world}\", lines[0], \"they should be equal\")\n\tassert.Equal(\"\", lines[4], \"they should be equal\")\n\tassert.Equal(\"[G]Lorem ipsum dolor sit amet, [D\/F#]consectetur adipiscing elit. Don[Em]ec a diam lectus.\", lines[5], \"they should be equal\")\n\n}\n\nfunc TestGetLineType(t *testing.T) {\n\n\tassert := assert.New(t)\n\tlines, err := readLines(\".\/test.chordpro\")\n\n\tassert.Nil(err)\n\n\t\/\/ Testing title type\n\ttitleType, _, _ := getLineType(lines[0])\n\tassert.Equal(\"title\", titleType, \"they should have the same type\")\n\n\t\/\/ Testing subtitle type\n\tstType, _, _ := getLineType(lines[1])\n\tassert.Equal(\"subtitle\", stType, \"they should have the same type\")\n\n\t\/\/ Testing comment type\n\tcommentType, _, _ := getLineType(lines[3])\n\tassert.Equal(\"comment\", commentType, \"they should have the same type\")\n\n\t\/\/ Testing verse type\n\tverseType, _, _ := getLineType(lines[5])\n\tassert.Equal(\"verse\", verseType, \"they should have the same type\")\n}\n<|endoftext|>"} {"text":"package thermal\n\ntype line struct {\n\tid [16]byte\n\tat int\n\tsharedSecret [32]byte\n}\n\ntype lineSession struct {\n\tlocalLine line\n\tremoteLine line\n\tencryptionKey [32]byte\n\tdecryptionKey [32]byte\n}\n\ntype lineMap map[string]lineSession\nadjust namespackage thermal\n\ntype lineHalf struct {\n\tid [16]byte\n\tat int\n\tsharedSecret [32]byte\n}\n\ntype lineSession struct {\n\tlocal lineHalf\n\tremote lineHalf\n\tencryptionKey [32]byte\n\tdecryptionKey [32]byte\n}\n\ntype lineMap map[string]lineSession\n<|endoftext|>"} {"text":"package tachymeter_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/jamiealquiza\/tachymeter\"\n)\n\nfunc TestReset(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.AddTime(time.Second)\n\tta.AddTime(time.Second)\n\tta.AddTime(time.Second)\n\tta.Reset()\n\n\tif ta.Count != 0 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestAddTime(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.AddTime(time.Millisecond)\n\n\tif ta.Times[0] != time.Millisecond {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestSetWallTime(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.SetWallTime(time.Millisecond)\n\n\tif ta.WallTime != time.Millisecond {\n\t\tt.Fail()\n\t}\n}\nadded AddTime benches to testpackage tachymeter_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/jamiealquiza\/tachymeter\"\n)\n\nfunc BenchmarkAddTime(b *testing.B) {\n\tb.StopTimer()\n\n\tta := tachymeter.New(&tachymeter.Config{Size: b.N})\n\td := time.Millisecond\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tta.AddTime(d)\n\t}\n}\n\nfunc BenchmarkAddTimeSampling(b *testing.B) {\n\tb.StopTimer()\n\n\tta := tachymeter.New(&tachymeter.Config{Size: 100})\n\td := time.Millisecond\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tta.AddTime(d)\n\t}\n}\n\nfunc TestReset(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.AddTime(time.Second)\n\tta.AddTime(time.Second)\n\tta.AddTime(time.Second)\n\tta.Reset()\n\n\tif ta.Count != 0 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestAddTime(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.AddTime(time.Millisecond)\n\n\tif ta.Times[0] != time.Millisecond {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestSetWallTime(t *testing.T) {\n\tta := tachymeter.New(&tachymeter.Config{Size: 3})\n\n\tta.SetWallTime(time.Millisecond)\n\n\tif ta.WallTime != time.Millisecond {\n\t\tt.Fail()\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"os\"\n\t\"testing\"\n)\n\nconst PlaybookFilename = \"test-playbook.yml\"\nconst ManifestFilename = \"test-manifest.yml\"\nconst PlaybookContents string = `---\nname: The Project \nmeta:\n team: Project Devs\n email: devs@project.com\n slack: devs\nvars:\n - version\n - assets_version\n - owner\ntasks:\n - name: Deploy Postgres\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - name: Deploy Redis\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - name: Database Setup\n pod_manifest: test-manifest.yml\n wait_for:\n - success\n when: new_deployment\n - name: Database Migration\n pod_manifest: test-manifest.yml\n wait_for:\n - success\n - name: Deploy Project\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - test-manifest.yml\n`\n\nvar PlaybookBytes = []byte(PlaybookContents)\n\nconst PlaybookContentsIncomplete = `---\nname: The Project \n`\n\nvar IncompletePlaybookBytes = []byte(PlaybookContentsIncomplete)\n\nfunc TestMain(m *testing.M) {\n\tf, _ := os.Create(PlaybookFilename)\n\tf.Write(PlaybookBytes)\n\tf.Close()\n\n\tf, _ = os.Create(ManifestFilename)\n\tf.Close()\n\n\ttestresult := m.Run()\n\tteardown()\n\tos.Exit(testresult)\n}\nfunc teardown() {\n\tos.Remove(PlaybookFilename)\n\tos.Remove(ManifestFilename)\n}\n\nfunc TestReadPlaybookFromDisk(t *testing.T) {\n\tplaybook, err := ReadPlaybookFromDisk(PlaybookFilename)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !bytes.Equal(playbook, PlaybookBytes) {\n\t\tt.Error(errors.New(\"Playbook read from disk differs from Playbook written to disk\"))\n\t}\n}\n\nfunc TestParsePlaybook(t *testing.T) {\n\tvar err error\n\tParsedPlaybook, err := ParsePlaybook(PlaybookBytes)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif ParsedPlaybook.Name != \"The Project\" {\n\t\tt.Error(errors.New(\"Parsed Playbook has incorrect Name field\"))\n\t}\n}\n\nfunc TestParsePlaybookMalformed(t *testing.T) {\n\t_, err := ParsePlaybook([]byte(\"asdf\"))\n\tif err == nil {\n\t\tt.Error(errors.New(\"Parsing asdf succeeded, expected failure\"))\n\t}\n}\n\nfunc TestParsePlaybookIncomplete(t *testing.T) {\n\t_, err := ParsePlaybook(IncompletePlaybookBytes)\n\tif err != nil {\n\t\tt.Error(errors.New(\"Parsing well-formed, incomplete playbook failed, expected success\"))\n\t}\n}\n\nfunc TestValidatePlaybook(t *testing.T) {\n\tParsedPlaybook1, _ := ParsePlaybook(PlaybookBytes)\n\tif err := ParsedPlaybook1.Validate(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tParsedPlaybook2, _ := ParsePlaybook(IncompletePlaybookBytes)\n\tif err := ParsedPlaybook2.Validate(); err == nil {\n\t\tt.Errorf(\"Validation of incomplete playbook succeeded, expected error\")\n\t}\n\n\tParsedPlaybook3 := ParsedPlaybook1\n\tParsedPlaybook3.Tasks = []Task{\n\t\t{\n\t\t\tManifests: []string{ManifestFilename},\n\t\t},\n\t}\n\tif err := ParsedPlaybook3.Validate(); err == nil {\n\t\tt.Errorf(\"Validation of playbook with a task missing a name succeeded, expected error\")\n\t}\n}\n\nfunc TestTaskManifestsPresent(t *testing.T) {\n\ttestcases := []struct {\n\t\tscenario string\n\t\ttask Task\n\t\terrExpected bool\n\t}{\n\t\t{\n\t\t\t\"Task With Missing Manifests\",\n\t\t\tTask{\n\t\t\t\tName: \"task 1\",\n\t\t\t\tManifests: []string{\"pod0\"},\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Task With Existing Manifests\",\n\t\t\tTask{\n\t\t\t\tName: \"task 2\",\n\t\t\t\tManifests: []string{ManifestFilename},\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Task With Only Pod Manifest\",\n\t\t\tTask{\n\t\t\t\tName: \"task 2\",\n\t\t\t\tPodManifest: ManifestFilename,\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, testcase := range testcases {\n\t\ttask := testcase.task\n\t\terr := task.ManifestsPresent()\n\t\tif testcase.errExpected {\n\t\t\tif !os.IsNotExist(err) { \/\/ it was the wrong error!\n\t\t\t\tt.Errorf(\"Scenario %s: Got %s, expected 'not found'\", testcase.scenario, err)\n\t\t\t}\n\t\t} else if err != nil {\n\t\t\tt.Errorf(\"Scenario %s: Got %s, expected success\", testcase.scenario, err)\n\t\t}\n\t}\n}\nAdd testcases for playbook validationpackage main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"os\"\n\t\"testing\"\n)\n\nconst PlaybookFilename = \"test-playbook.yml\"\nconst ManifestFilename = \"test-manifest.yml\"\nconst PlaybookContents string = `---\nname: The Project \nmeta:\n team: Project Devs\n email: devs@project.com\n slack: devs\nvars:\n - version\n - assets_version\n - owner\ntasks:\n - name: Deploy Postgres\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - name: Deploy Redis\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - name: Database Setup\n pod_manifest: test-manifest.yml\n wait_for:\n - success\n when: new_deployment\n - name: Database Migration\n pod_manifest: test-manifest.yml\n wait_for:\n - success\n - name: Deploy Project\n manifests:\n - test-manifest.yml\n - test-manifest.yml\n - test-manifest.yml\n`\n\nvar PlaybookBytes = []byte(PlaybookContents)\n\nconst PlaybookContentsIncomplete = `---\nname: The Project \n`\n\nvar IncompletePlaybookBytes = []byte(PlaybookContentsIncomplete)\n\nfunc TestMain(m *testing.M) {\n\tf, _ := os.Create(PlaybookFilename)\n\tf.Write(PlaybookBytes)\n\tf.Close()\n\n\tf, _ = os.Create(ManifestFilename)\n\tf.Close()\n\n\ttestresult := m.Run()\n\tteardown()\n\tos.Exit(testresult)\n}\nfunc teardown() {\n\tos.Remove(PlaybookFilename)\n\tos.Remove(ManifestFilename)\n}\n\nfunc TestReadPlaybookFromDisk(t *testing.T) {\n\tplaybook, err := ReadPlaybookFromDisk(PlaybookFilename)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !bytes.Equal(playbook, PlaybookBytes) {\n\t\tt.Error(errors.New(\"Playbook read from disk differs from Playbook written to disk\"))\n\t}\n}\n\nfunc TestParsePlaybook(t *testing.T) {\n\tvar err error\n\tParsedPlaybook, err := ParsePlaybook(PlaybookBytes)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif ParsedPlaybook.Name != \"The Project\" {\n\t\tt.Error(errors.New(\"Parsed Playbook has incorrect Name field\"))\n\t}\n}\n\nfunc TestParsePlaybookMalformed(t *testing.T) {\n\t_, err := ParsePlaybook([]byte(\"asdf\"))\n\tif err == nil {\n\t\tt.Error(errors.New(\"Parsing asdf succeeded, expected failure\"))\n\t}\n}\n\nfunc TestParsePlaybookIncomplete(t *testing.T) {\n\t_, err := ParsePlaybook(IncompletePlaybookBytes)\n\tif err != nil {\n\t\tt.Error(errors.New(\"Parsing well-formed, incomplete playbook failed, expected success\"))\n\t}\n}\n\nfunc TestValidatePlaybook(t *testing.T) {\n\tValidTask := Task{\n\t\tName: \"task\",\n\t\tManifests: []string{ManifestFilename},\n\t}\n\tInvalidTask1 := Task{\n\t\tManifests: []string{ManifestFilename},\n\t}\n\tInvalidTask2 := Task{\n\t\tName: \"task\",\n\t}\n\n\ttestcases := []struct {\n\t\tscenario string\n\t\tplaybook Playbook\n\t\terrExpected bool\n\t}{\n\t\t{\n\t\t\t\"Validate Valid Playbook\",\n\t\t\tPlaybook{\n\t\t\t\tName: \"playbook 1\",\n\t\t\t\tTasks: []Task{ValidTask},\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Validate Empty Playbook\",\n\t\t\tPlaybook{},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Validate Playbook With Tasks Missing Names\",\n\t\t\tPlaybook{\n\t\t\t\tName: \"playbook 1\",\n\t\t\t\tTasks: []Task{InvalidTask1},\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Validate Playbook With Tasks Missing Manifests\",\n\t\t\tPlaybook{\n\t\t\t\tName: \"playbook 1\",\n\t\t\t\tTasks: []Task{InvalidTask2},\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor _, testcase := range testcases {\n\t\tplaybook := testcase.playbook\n\t\terr := playbook.Validate()\n\t\tif testcase.errExpected && err != nil {\n\t\t\tcontinue\n\t\t} else if testcase.errExpected && err == nil {\n\t\t\tt.Errorf(\"Scenario %s: Succeeded, expected failure\", testcase.scenario)\n\t\t} else if err != nil {\n\t\t\tt.Errorf(\"Scenario %s: Failed with %s, expected success\", testcase.scenario, err)\n\t\t}\n\t}\n}\n\nfunc TestTaskManifestsPresent(t *testing.T) {\n\ttestcases := []struct {\n\t\tscenario string\n\t\ttask Task\n\t\terrExpected bool\n\t}{\n\t\t{\n\t\t\t\"Task With Missing Manifests\",\n\t\t\tTask{\n\t\t\t\tName: \"task 1\",\n\t\t\t\tManifests: []string{\"pod0\"},\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Task With Existing Manifests\",\n\t\t\tTask{\n\t\t\t\tName: \"task 2\",\n\t\t\t\tManifests: []string{ManifestFilename},\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Task With Only Pod Manifest\",\n\t\t\tTask{\n\t\t\t\tName: \"task 2\",\n\t\t\t\tPodManifest: ManifestFilename,\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, testcase := range testcases {\n\t\ttask := testcase.task\n\t\terr := task.ManifestsPresent()\n\t\tif testcase.errExpected {\n\t\t\tif !os.IsNotExist(err) { \/\/ it was the wrong error!\n\t\t\t\tt.Errorf(\"Scenario %s: Got %s, expected 'not found'\", testcase.scenario, err)\n\t\t\t}\n\t\t} else if err != nil {\n\t\t\tt.Errorf(\"Scenario %s: Got %s, expected success\", testcase.scenario, err)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\"\n\t\"github.com\/intelsdi-x\/pulse\/plugin\/helper\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nvar (\n\tPluginName = \"pulse-publisher-hana\"\n\tPluginType = \"publisher\"\n\tPulsePath = os.Getenv(\"PULSE_PATH\")\n\tPluginPath = path.Join(PulsePath, \"plugin\", PluginName)\n)\n\nfunc TestHANAPublisherLoad(t *testing.T) {\n\t\/\/ These tests only work if PULSE_PATH is known.\n\t\/\/ It is the responsibility of the testing framework to\n\t\/\/ build the plugins first into the build dir.\n\tif PulsePath != \"\" {\n\t\t\/\/ Helper plugin trigger build if possible for this plugin\n\t\thelper.BuildPlugin(PluginType, PluginName)\n\t\t\/\/\n\t\t\/\/TODO cannot test this locally. We need AMQP and integration tests.\n\t\tSkipConvey(\"ensure plugin loads and responds\", t, func() {\n\t\t\tc := control.New()\n\t\t\tc.Start()\n\t\t\t_, err := c.Load(PluginPath)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\t} else {\n\t\tfmt.Printf(\"PULSE_PATH not set. Cannot test %s plugin.\\n\", PluginName)\n\t}\n}\n\nfunc TestMain(t *testing.T) {\n\tConvey(\"ensure plugin loads and responds\", t, func() {\n\t\tos.Args = []string{\"\", \"{\\\"NoDaemon\\\": true}\"}\n\t\tSo(func() { main() }, ShouldNotPanic)\n\t})\n}\nUpdate main_test.go to align with other plugins\/\/ +build unit\n\npackage main\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestMain(t *testing.T) {\n\tConvey(\"ensure plugin loads and responds\", t, func() {\n\t\tos.Args = []string{\"\", \"{\\\"NoDaemon\\\": true}\"}\n\t\tSo(func() { main() }, ShouldNotPanic)\n\t})\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/gocql\/gocql\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc setup() {\n\tlog.Println(\"SETTING UP\")\n\n\t_, testSession := createTestConnection()\n\tsession = testSession\n\tconnectionEstablished = true\n}\n\nfunc tearDown() {\n\tlog.Println(\"TEARING DOWN\")\n\n\tdestroyTestConnection(session)\n}\n\nfunc TestMain(m *testing.M) {\n\tsetup()\n\n\tretCode := m.Run()\n\n\ttearDown()\n\n\tos.Exit(retCode)\n}\n\nvar test_keyspace = \"test_keyspace\"\n\nfunc testInitialQuery() string {\n\treturn `\n CREATE KEYSPACE IF NOT EXISTS ` + test_keyspace + ` WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };\n CREATE TABLE IF NOT EXISTS ` + test_keyspace + `.alert (\n id timeuuid PRIMARY KEY,\n name varchar,\n required_criteria text,\n nice_to_have_criteria text,\n excluded_criteria text,\n owner_id int,\n status int,\n threshold int\n );\n CREATE INDEX IF NOT EXISTS by_owner_id ON ` + test_keyspace + `.alert(\"owner_id\");`\n}\n\nfunc createTestConnection() (*gocql.ClusterConfig, *gocql.Session) {\n\tcassandraNodes := \"localhost:9042\"\n\tcluster := gocql.NewCluster(strings.Split(cassandraNodes, \",\")...)\n\n\tcluster.Timeout = cassandraConnectTimeout\n\tcluster.DisableInitialHostLookup = true\n\n\tvar sessionErr error\n\tinitSession, sessionErr := cluster.CreateSession()\n\n\tif sessionErr != nil {\n\t\tlog.Fatal(\"Could NOT create test Cassandra session: \" + sessionErr.Error())\n\t}\n\n\texecuteInitialQuery(initSession, testInitialQuery())\n\tinitSession.Close()\n\n\tcluster.Keyspace = test_keyspace\n\tsession, _ := cluster.CreateSession()\n\n\treturn cluster, session\n}\n\nfunc destroyTestConnection(session *gocql.Session) {\n\tdefer session.Close()\n\n\tsession.Query(\"truncate \" + test_keyspace + \".alert\").Exec()\n\tsession.Query(\"drop keyspace \" + test_keyspace).Exec()\n}\n#0 add env variable for cassandra nodes for testing (#13)package main\n\nimport (\n\t\"github.com\/gocql\/gocql\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc setup() {\n\tlog.Println(\"SETTING UP\")\n\n\t_, testSession := createTestConnection()\n\tsession = testSession\n\tconnectionEstablished = true\n}\n\nfunc TestMain(m *testing.M) {\n\tsetup()\n\n\tretCode := m.Run()\n\n\ttearDown()\n\n\tos.Exit(retCode)\n}\n\nfunc tearDown() {\n\tlog.Println(\"TEARING DOWN\")\n\n\tdestroyTestConnection(session)\n}\n\nvar test_keyspace = \"test_keyspace\"\n\nfunc testInitialQuery() string {\n\treturn `\n CREATE KEYSPACE IF NOT EXISTS ` + test_keyspace + ` WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };\n CREATE TABLE IF NOT EXISTS ` + test_keyspace + `.alert (\n id timeuuid PRIMARY KEY,\n name varchar,\n required_criteria text,\n nice_to_have_criteria text,\n excluded_criteria text,\n owner_id int,\n status int,\n threshold int\n );\n CREATE INDEX IF NOT EXISTS by_owner_id ON ` + test_keyspace + `.alert(\"owner_id\");`\n}\n\nfunc createTestConnection() (*gocql.ClusterConfig, *gocql.Session) {\n\tcassandraNodes := os.Getenv(\"CASSANDRA_NODES_TEST\")\n\n\tif cassandraNodes == \"\" {\n\t\tlog.Fatal(\"Please specify CASSANDRA_NODES_TEST env variable for testing\")\n\t}\n\n\tcluster := gocql.NewCluster(strings.Split(cassandraNodes, \",\")...)\n\n\tcluster.Timeout = cassandraConnectTimeout\n\tcluster.DisableInitialHostLookup = true\n\n\tvar sessionErr error\n\tinitSession, sessionErr := cluster.CreateSession()\n\n\tif sessionErr != nil {\n\t\tlog.Fatal(\"Could NOT create test Cassandra session: \" + sessionErr.Error())\n\t}\n\n\texecuteInitialQuery(initSession, testInitialQuery())\n\tinitSession.Close()\n\n\tcluster.Keyspace = test_keyspace\n\tsession, _ := cluster.CreateSession()\n\n\treturn cluster, session\n}\n\nfunc destroyTestConnection(session *gocql.Session) {\n\tdefer session.Close()\n\n\tsession.Query(\"truncate \" + test_keyspace + \".alert\").Exec()\n\tsession.Query(\"drop keyspace \" + test_keyspace).Exec()\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"testing\"\n)\n\nconst apigeecli = \".\/apigeecli\"\n\nvar token = os.Getenv(\"APIGEE_TOKEN\")\nvar env = os.Getenv(\"APIGEE_ENV\")\nvar org = os.Getenv(\"APIGEE_ORG\")\n\nconst email = \"test@gmail.com\"\nconst name = \"test\"\nconst attrs = \"\\\"foo1=bar1,foo2=bar2\\\"\"\nconst envs = \"test\"\n\nvar appID string\n\nfunc TestMain(t *testing.T) {\n\tcmd := exec.Command(apigeecli)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ orgs test\nfunc TestListOrgs(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"orgs\", \"list\", \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetOrg(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"orgs\", \"get\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ env tests\nfunc TestListEnvs(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"envs\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetEnv(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"envs\", \"get\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ developers test\nfunc TestCreateDeveloper(t *testing.T) {\n\tfirst := \"frstname\"\n\tlast := \"lastname\"\n\tuser := \"username\"\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"create\", \"-o\", org, \"-n\", email, \"-f\", first, \"-s\",\n\t\tlast, \"-u\", user, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"get\", \"-o\", org, \"-n\", email, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListExpandDeveloper(t *testing.T) {\n\texpand := \"true\"\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"list\", \"-o\", org, \"-x\", expand, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ kvm test\nfunc TestCreateKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"list\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ sync tests\nfunc TestGetSync(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"sync\", \"get\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestSetSync(t *testing.T) {\n\tity := \"test@gmail.com\"\n\tcmd := exec.Command(apigeecli, \"sync\", \"set\", \"-o\", org, \"-i\", ity, \"-t\", token)\n\terr := cmd.Run()\n\tif err == nil {\n\t\tt.Fatal(\"Invalid identity test should have failed\")\n\t}\n}\n\nfunc TestCreateProxy(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apis\", \"create\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateProductLegacy(t *testing.T) {\n\tproxy := \"test\"\n\tapproval := \"auto\"\n\n\tcmd := exec.Command(apigeecli, \"products\", \"create\", \"-o\", org, \"-n\", name+\"-legacy\", \"-e\", envs, \"-p\", proxy,\n\t\t\"-f\", approval, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateProductGroup(t *testing.T) {\n\tproxy := \"test\"\n\tapproval := \"auto\"\n\toperationGroupFile := \".\/test\/apiproduct-op-group.json\"\n\n\tcmd := exec.Command(apigeecli, \"products\", \"create\", \"-o\", org, \"-n\", name+\"-group\", \"-e\", envs,\n\t\t\"-g\", operationGroupFile, \"-f\", approval, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateApp(t *testing.T) {\n\tproduct := \"test\"\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"create\", \"-o\", org, \"-n\", name, \"-e\", email, \"-p\", product,\n\t\t\"--attrs\", attrs, \"-t\", token)\n\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar outputMap map[string]string\n\t_ = json.Unmarshal(out.Bytes(), &outputMap)\n\tappID = outputMap[\"appId\"]\n}\n\nfunc TestListApp(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestGetProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"get\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"delete\", \"-o\", org, \"-n\", email, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateTS(t *testing.T) {\n\thost := \"example.com\"\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"create\", \"-o\", org, \"-n\", name, \"-e\", env, \"-s\",\n\t\thost, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestGetTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"get\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestListTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"list\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestDeleteTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestExportProducts(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"export\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateEncKVM(t *testing.T) {\n\tname := \"testEnc\"\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-c\", \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteEncKVM(t *testing.T) {\n\tname := \"testEnc\"\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteProxy(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apis\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tresPath := \".\/test\/test.js\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType, \"-r\", resPath)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"get\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListResources(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"resources\", \"list\", \"-o\", org, \"-e\", env)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/*func TestCreateKeyStore(t *testing.T) {\n\tname := \"testkeystore\"\n\tcmd := exec.Command(apigeecli, \"keystores\", \"create\", \"-o\", org, \"-e\", env,\n\t\t\"-n\", name)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateKeyAliasSelfSigned(t *testing.T) {\n\tpayload := \"{\\\"alias\\\": \\\"self\\\",\\\"keySize\\\": \\\"2048\\\",\\\"sigAlg\\\": \\\"SHA256withRSA\\\",\\\"subject\\\"\" +\n\t\t\"{\\\"commonName\\\": \\\"nandan\\\",\\\"email\\\": \\\"test@test.com\\\"},\\\"certValidityInDays\\\": \\\"10\\\"}\"\n\tname := \"testkeystore\"\n\tkeyaliasname := \"selfkeyalias\"\n\tcmd := exec.Command(apigeecli, \"keyaliases\", \"create-self-signed\", \"-o\", org, \"-e\", env,\n\t\t\"-n\", name, \"-s\", keyaliasname, \"-c\", payload)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}*\/\n\n\/\/get requires an app id. run list and get an app id or get it from create\n\/*func TestGetApp(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apps\", \"get\", \"-o\", org, \"-i\", appID, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}*\/\n\n\/*func TestSetMart(t *testing.T) {\n\tmart := os.Getenv(\"MART\")\n\tif mart == \"\" {\n\t\tt.Log(\"MART not set, skipping\")\n\t} else {\n\t\tcmd := exec.Command(apigeecli, \"orgs\", \"setmart\", \"-o\", org, \"-m\", mart, \"-t\", token)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc TestSetMartWhiteList(t *testing.T) {\n\tmart := os.Getenv(\"MART\")\n\tif mart == \"\" {\n\t\tt.Log(\"MART not set, skipping\")\n\t} else {\n\t\tcmd := exec.Command(apigeecli, \"orgs\", \"setmart\", \"-o\", org, \"-m\", mart, \"-w\", \"false\", \"-t\", token)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc TestDeleteApp(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n*\/\nremove unused var\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"testing\"\n)\n\nconst apigeecli = \".\/apigeecli\"\n\nvar token = os.Getenv(\"APIGEE_TOKEN\")\nvar env = os.Getenv(\"APIGEE_ENV\")\nvar org = os.Getenv(\"APIGEE_ORG\")\n\nconst email = \"test@gmail.com\"\nconst name = \"test\"\nconst attrs = \"\\\"foo1=bar1,foo2=bar2\\\"\"\nconst envs = \"test\"\n\nvar appID string\n\nfunc TestMain(t *testing.T) {\n\tcmd := exec.Command(apigeecli)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ orgs test\nfunc TestListOrgs(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"orgs\", \"list\", \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetOrg(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"orgs\", \"get\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ env tests\nfunc TestListEnvs(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"envs\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetEnv(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"envs\", \"get\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ developers test\nfunc TestCreateDeveloper(t *testing.T) {\n\tfirst := \"frstname\"\n\tlast := \"lastname\"\n\tuser := \"username\"\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"create\", \"-o\", org, \"-n\", email, \"-f\", first, \"-s\",\n\t\tlast, \"-u\", user, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"get\", \"-o\", org, \"-n\", email, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListExpandDeveloper(t *testing.T) {\n\texpand := \"true\"\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"list\", \"-o\", org, \"-x\", expand, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ kvm test\nfunc TestCreateKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"list\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/\/ sync tests\nfunc TestGetSync(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"sync\", \"get\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestSetSync(t *testing.T) {\n\tity := \"test@gmail.com\"\n\tcmd := exec.Command(apigeecli, \"sync\", \"set\", \"-o\", org, \"-i\", ity, \"-t\", token)\n\terr := cmd.Run()\n\tif err == nil {\n\t\tt.Fatal(\"Invalid identity test should have failed\")\n\t}\n}\n\nfunc TestCreateProxy(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apis\", \"create\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateProductLegacy(t *testing.T) {\n\tproxy := \"test\"\n\tapproval := \"auto\"\n\n\tcmd := exec.Command(apigeecli, \"products\", \"create\", \"-o\", org, \"-n\", name+\"-legacy\", \"-e\", envs, \"-p\", proxy,\n\t\t\"-f\", approval, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateProductGroup(t *testing.T) {\n\tapproval := \"auto\"\n\toperationGroupFile := \".\/test\/apiproduct-op-group.json\"\n\n\tcmd := exec.Command(apigeecli, \"products\", \"create\", \"-o\", org, \"-n\", name+\"-group\", \"-e\", envs,\n\t\t\"-g\", operationGroupFile, \"-f\", approval, \"--attrs\", attrs, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateApp(t *testing.T) {\n\tproduct := \"test\"\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"create\", \"-o\", org, \"-n\", name, \"-e\", email, \"-p\", product,\n\t\t\"--attrs\", attrs, \"-t\", token)\n\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar outputMap map[string]string\n\t_ = json.Unmarshal(out.Bytes(), &outputMap)\n\tappID = outputMap[\"appId\"]\n}\n\nfunc TestListApp(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestGetProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"get\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"list\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteDeveloper(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"developers\", \"delete\", \"-o\", org, \"-n\", email, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateTS(t *testing.T) {\n\thost := \"example.com\"\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"create\", \"-o\", org, \"-n\", name, \"-e\", env, \"-s\",\n\t\thost, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestGetTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"get\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestListTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"list\", \"-o\", org, \"-e\", env, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestDeleteTS(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"targetservers\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc TestExportProducts(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"export\", \"-o\", org, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteKVM(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteProduct(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"products\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateEncKVM(t *testing.T) {\n\tname := \"testEnc\"\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-c\", \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteEncKVM(t *testing.T) {\n\tname := \"testEnc\"\n\n\tcmd := exec.Command(apigeecli, \"kvms\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteProxy(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apis\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tresPath := \".\/test\/test.js\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"create\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType, \"-r\", resPath)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"get\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestListResources(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"resources\", \"list\", \"-o\", org, \"-e\", env)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestDeleteResource(t *testing.T) {\n\tname := \"test.js\"\n\tresType := \"jsc\"\n\tcmd := exec.Command(apigeecli, \"resources\", \"delete\", \"-o\", org, \"-e\", env, \"-n\", name, \"-p\", resType)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\n\/*func TestCreateKeyStore(t *testing.T) {\n\tname := \"testkeystore\"\n\tcmd := exec.Command(apigeecli, \"keystores\", \"create\", \"-o\", org, \"-e\", env,\n\t\t\"-n\", name)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestCreateKeyAliasSelfSigned(t *testing.T) {\n\tpayload := \"{\\\"alias\\\": \\\"self\\\",\\\"keySize\\\": \\\"2048\\\",\\\"sigAlg\\\": \\\"SHA256withRSA\\\",\\\"subject\\\"\" +\n\t\t\"{\\\"commonName\\\": \\\"nandan\\\",\\\"email\\\": \\\"test@test.com\\\"},\\\"certValidityInDays\\\": \\\"10\\\"}\"\n\tname := \"testkeystore\"\n\tkeyaliasname := \"selfkeyalias\"\n\tcmd := exec.Command(apigeecli, \"keyaliases\", \"create-self-signed\", \"-o\", org, \"-e\", env,\n\t\t\"-n\", name, \"-s\", keyaliasname, \"-c\", payload)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}*\/\n\n\/\/get requires an app id. run list and get an app id or get it from create\n\/*func TestGetApp(t *testing.T) {\n\tcmd := exec.Command(apigeecli, \"apps\", \"get\", \"-o\", org, \"-i\", appID, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}*\/\n\n\/*func TestSetMart(t *testing.T) {\n\tmart := os.Getenv(\"MART\")\n\tif mart == \"\" {\n\t\tt.Log(\"MART not set, skipping\")\n\t} else {\n\t\tcmd := exec.Command(apigeecli, \"orgs\", \"setmart\", \"-o\", org, \"-m\", mart, \"-t\", token)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc TestSetMartWhiteList(t *testing.T) {\n\tmart := os.Getenv(\"MART\")\n\tif mart == \"\" {\n\t\tt.Log(\"MART not set, skipping\")\n\t} else {\n\t\tcmd := exec.Command(apigeecli, \"orgs\", \"setmart\", \"-o\", org, \"-m\", mart, \"-w\", \"false\", \"-t\", token)\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc TestDeleteApp(t *testing.T) {\n\n\tcmd := exec.Command(apigeecli, \"apps\", \"delete\", \"-o\", org, \"-n\", name, \"-t\", token)\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n*\/\n<|endoftext|>"} {"text":"package lfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/github\/git-lfs\/git\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tvalueRegexp = regexp.MustCompile(\"\\\\Agit[\\\\-\\\\s]media\")\n\tprePushHook = []byte(\"#!\/bin\/sh\\ngit lfs push --stdin $*\\n\")\n\tNotInARepositoryError = errors.New(\"Not in a repository\")\n)\n\ntype HookExists struct {\n\tName string\n\tPath string\n}\n\nfunc (e *HookExists) Error() string {\n\treturn fmt.Sprintf(\"Hook already exists: %s\", e.Name)\n}\n\nfunc InstallHooks(force bool) error {\n\tif !InRepo() {\n\t\treturn NotInARepositoryError\n\t}\n\n\tif err := os.MkdirAll(filepath.Join(LocalGitDir, \"hooks\"), 0755); err != nil {\n\t\treturn err\n\t}\n\n\thookPath := filepath.Join(LocalGitDir, \"hooks\", \"pre-push\")\n\tif _, err := os.Stat(hookPath); err == nil && !force {\n\t\treturn &HookExists{\"pre-push\", hookPath}\n\t} else {\n\t\treturn ioutil.WriteFile(hookPath, prePushHook, 0755)\n\t}\n}\n\nfunc InstallFilters() error {\n\tvar err error\n\terr = setFilter(\"clean\")\n\tif err == nil {\n\t\terr = setFilter(\"smudge\")\n\t}\n\tif err == nil {\n\t\terr = requireFilters()\n\t}\n\treturn err\n}\n\nfunc setFilter(filterName string) error {\n\tkey := fmt.Sprintf(\"filter.lfs.%s\", filterName)\n\tvalue := fmt.Sprintf(\"git lfs %s %%f\", filterName)\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn fmt.Errorf(\"The %s filter should be \\\"%s\\\" but is \\\"%s\\\"\", filterName, value, existing)\n\t}\n\n\treturn nil\n}\n\nfunc requireFilters() error {\n\tkey := \"filter.lfs.required\"\n\tvalue := \"true\"\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn errors.New(\"Git LFS filters should be required but are not.\")\n\t}\n\n\treturn nil\n}\n\nfunc shouldReset(value string) bool {\n\tif len(value) == 0 {\n\t\treturn true\n\t}\n\treturn valueRegexp.MatchString(value)\n}\nアー アアアア アーアーpackage lfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/github\/git-lfs\/git\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tvalueRegexp = regexp.MustCompile(\"\\\\Agit[\\\\-\\\\s]media\")\n\tprePushHook = []byte(\"#!\/bin\/sh\\ngit lfs push --stdin \\\"$@\\\"\\n\")\n\tNotInARepositoryError = errors.New(\"Not in a repository\")\n)\n\ntype HookExists struct {\n\tName string\n\tPath string\n}\n\nfunc (e *HookExists) Error() string {\n\treturn fmt.Sprintf(\"Hook already exists: %s\", e.Name)\n}\n\nfunc InstallHooks(force bool) error {\n\tif !InRepo() {\n\t\treturn NotInARepositoryError\n\t}\n\n\tif err := os.MkdirAll(filepath.Join(LocalGitDir, \"hooks\"), 0755); err != nil {\n\t\treturn err\n\t}\n\n\thookPath := filepath.Join(LocalGitDir, \"hooks\", \"pre-push\")\n\tif _, err := os.Stat(hookPath); err == nil && !force {\n\t\treturn &HookExists{\"pre-push\", hookPath}\n\t} else {\n\t\treturn ioutil.WriteFile(hookPath, prePushHook, 0755)\n\t}\n}\n\nfunc InstallFilters() error {\n\tvar err error\n\terr = setFilter(\"clean\")\n\tif err == nil {\n\t\terr = setFilter(\"smudge\")\n\t}\n\tif err == nil {\n\t\terr = requireFilters()\n\t}\n\treturn err\n}\n\nfunc setFilter(filterName string) error {\n\tkey := fmt.Sprintf(\"filter.lfs.%s\", filterName)\n\tvalue := fmt.Sprintf(\"git lfs %s %%f\", filterName)\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn fmt.Errorf(\"The %s filter should be \\\"%s\\\" but is \\\"%s\\\"\", filterName, value, existing)\n\t}\n\n\treturn nil\n}\n\nfunc requireFilters() error {\n\tkey := \"filter.lfs.required\"\n\tvalue := \"true\"\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn errors.New(\"Git LFS filters should be required but are not.\")\n\t}\n\n\treturn nil\n}\n\nfunc shouldReset(value string) bool {\n\tif len(value) == 0 {\n\t\treturn true\n\t}\n\treturn valueRegexp.MatchString(value)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"text\/template\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/avelino\/slugify\"\n)\n\ntype Link struct {\n\tTitle string\n\tUrl string\n\tDescription string\n}\n\ntype Object struct {\n\tTitle string\n\tSlug string\n\tDescription string\n\tItems []Link\n}\n\nfunc main() {\n\tGenerateHTML()\n\tinput, err := ioutil.ReadFile(\".\/tmpl\/index.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbuf := bytes.NewBuffer(input)\n\tquery, err := goquery.NewDocumentFromReader(buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tobjs := []Object{}\n\tquery.Find(\"body #content ul ul\").First().Each(func(_ int, s *goquery.Selection) {\n\n\t\ts.Find(\"li a\").Each(func(_ int, s *goquery.Selection) {\n\t\t\tselector, _ := s.Attr(\"href\")\n\t\t\tobj := makeObjById(selector, query.Find(\"body\"))\n\t\t\tobjs = append(objs, obj)\n\t\t})\n\t})\n\n\tmakeSiteStruct(objs)\n\tmakeSitemap(objs)\n}\n\nfunc makeSiteStruct(objs []Object) {\n\tfor _, obj := range objs {\n\t\tfolder := fmt.Sprintf(\"tmpl\/%s\", obj.Slug)\n\t\tfmt.Println(folder)\n\n\t\terr := os.Mkdir(folder, 0755)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tt := template.Must(template.ParseFiles(\"tmpl\/cat-tmpl.html\"))\n\t\tf, _ := os.Create(fmt.Sprintf(\"%s\/index.html\", folder))\n\t\tt.Execute(f, obj)\n\t}\n}\n\nfunc makeSitemap(objs []Object) {\n\tt := template.Must(template.ParseFiles(\"tmpl\/sitemap-tmpl.xml\"))\n\tf, _ := os.Create(\"tmpl\/sitemap.xml\")\n\tt.Execute(f, objs)\n}\n\nfunc makeObjById(selector string, s *goquery.Selection) (obj Object) {\n\ts.Find(selector).Each(func(_ int, s *goquery.Selection) {\n\t\tdesc := s.NextFiltered(\"p\")\n\t\tul := desc.NextFiltered(\"ul\")\n\n\t\tlinks := []Link{}\n\t\tul.Find(\"li\").Each(func(_ int, s *goquery.Selection) {\n\t\t\turl, _ := s.Find(\"a\").Attr(\"href\")\n\t\t\tlink := Link{\n\t\t\t\tTitle: s.Find(\"a\").Text(),\n\t\t\t\tDescription: s.Text(),\n\t\t\t\tUrl: url,\n\t\t\t}\n\t\t\tlinks = append(links, link)\n\t\t})\n\t\tobj = Object{\n\t\t\tSlug: slugify.Slugify(s.Text()),\n\t\t\tTitle: s.Text(),\n\t\t\tDescription: desc.Text(),\n\t\t\tItems: links,\n\t\t}\n\t})\n\treturn\n}\nremove debug\/printpackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"text\/template\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/avelino\/slugify\"\n)\n\ntype Link struct {\n\tTitle string\n\tUrl string\n\tDescription string\n}\n\ntype Object struct {\n\tTitle string\n\tSlug string\n\tDescription string\n\tItems []Link\n}\n\nfunc main() {\n\tGenerateHTML()\n\tinput, err := ioutil.ReadFile(\".\/tmpl\/index.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbuf := bytes.NewBuffer(input)\n\tquery, err := goquery.NewDocumentFromReader(buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tobjs := []Object{}\n\tquery.Find(\"body #content ul ul\").First().Each(func(_ int, s *goquery.Selection) {\n\n\t\ts.Find(\"li a\").Each(func(_ int, s *goquery.Selection) {\n\t\t\tselector, _ := s.Attr(\"href\")\n\t\t\tobj := makeObjById(selector, query.Find(\"body\"))\n\t\t\tobjs = append(objs, obj)\n\t\t})\n\t})\n\n\tmakeSiteStruct(objs)\n\tmakeSitemap(objs)\n}\n\nfunc makeSiteStruct(objs []Object) {\n\tfor _, obj := range objs {\n\t\tfolder := fmt.Sprintf(\"tmpl\/%s\", obj.Slug)\n\t\terr := os.Mkdir(folder, 0755)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tt := template.Must(template.ParseFiles(\"tmpl\/cat-tmpl.html\"))\n\t\tf, _ := os.Create(fmt.Sprintf(\"%s\/index.html\", folder))\n\t\tt.Execute(f, obj)\n\t}\n}\n\nfunc makeSitemap(objs []Object) {\n\tt := template.Must(template.ParseFiles(\"tmpl\/sitemap-tmpl.xml\"))\n\tf, _ := os.Create(\"tmpl\/sitemap.xml\")\n\tt.Execute(f, objs)\n}\n\nfunc makeObjById(selector string, s *goquery.Selection) (obj Object) {\n\ts.Find(selector).Each(func(_ int, s *goquery.Selection) {\n\t\tdesc := s.NextFiltered(\"p\")\n\t\tul := desc.NextFiltered(\"ul\")\n\n\t\tlinks := []Link{}\n\t\tul.Find(\"li\").Each(func(_ int, s *goquery.Selection) {\n\t\t\turl, _ := s.Find(\"a\").Attr(\"href\")\n\t\t\tlink := Link{\n\t\t\t\tTitle: s.Find(\"a\").Text(),\n\t\t\t\tDescription: s.Text(),\n\t\t\t\tUrl: url,\n\t\t\t}\n\t\t\tlinks = append(links, link)\n\t\t})\n\t\tobj = Object{\n\t\t\tSlug: slugify.Slugify(s.Text()),\n\t\t\tTitle: s.Text(),\n\t\t\tDescription: desc.Text(),\n\t\t\tItems: links,\n\t\t}\n\t})\n\treturn\n}\n<|endoftext|>"} {"text":"package srcgraph\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/buildstore\"\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/util2\"\n\n\t\"testing\"\n\n\t\"github.com\/aybabtme\/color\/brush\"\n)\n\nvar mode = flag.String(\"test.mode\", \"test\", \"[test|keep|gen] 'test' runs test as normal; keep keeps around generated test files for inspection after tests complete; 'gen' generates new expected test data\")\nvar repoMatch = flag.String(\"test.repo\", \"\", \"only test `srcgraph make` for repos that contain this string\")\n\nfunc TestMakeCmd(t *testing.T) {\n\t\/\/ Since we exec `srcgraph`, make sure it's up-to-date.\n\tif out, err := exec.Command(\"make\", \"-C\", \"..\", \"srcgraph\").CombinedOutput(); err != nil {\n\t\tt.Errorf(\"Failed to build srcgraph for `srcgraph make` tests: %s.\\n\\nOutput was:\\n%s\", err, out)\n\t\treturn\n\t}\n\n\tcmd := exec.Command(\"git\", \"submodule\", \"update\", \"--init\", \"srcgraph\/testdata\/repos\")\n\tcmd.Dir = \"..\"\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tt.Errorf(\"Failed to update or init git submodules: %s.\\n\\nOutput was:\\n%s\", err, out)\n\t\treturn\n\t}\n\n\tconst testReposDir = \"testdata\/repos\"\n\tfis, err := ioutil.ReadDir(\"testdata\/repos\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := 0\n\tvar wg sync.WaitGroup\n\tfor _, fi := range fis {\n\t\tif repoDir := fi.Name(); strings.Contains(repoDir, *repoMatch) {\n\t\t\tfullRepoDir := filepath.Join(testReposDir, repoDir)\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\ttestMakeCmd(t, fullRepoDir)\n\t\t\t}()\n\t\t\tn++\n\t\t}\n\t}\n\twg.Wait()\n\tif n == 0 {\n\t\tt.Errorf(\"No TestMakeCmd cases were run. Did none match your constraint -test.match=%q?\", *repoMatch)\n\t}\n}\n\nfunc testMakeCmd(t *testing.T, repoDir string) {\n\trepoName := filepath.Base(repoDir)\n\n\t\/\/ Directories for the actual (\"got\") and expected (\"want\") outputs.\n\tgotOutputDir := filepath.Join(repoDir, \"..\/..\/repos-output\/got\", repoName)\n\twantOutputDir := filepath.Join(repoDir, \"..\/..\/repos-output\/want\", repoName)\n\n\t\/\/ Determine and wipe the desired output dir.\n\tvar outputDir string\n\tif *mode == \"gen\" {\n\t\toutputDir = wantOutputDir\n\t} else {\n\t\toutputDir = gotOutputDir\n\t}\n\toutputDir, _ = filepath.Abs(outputDir)\n\tif err := os.RemoveAll(outputDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Symlink ${repoDir}\/.sourcegraph-data\/${commitID} to the desired output dir.\n\torigOutputDestDir := filepath.Join(repoDir, buildstore.BuildDataDirName, getHEADOrTipCommitID(t, repoDir))\n\tif err := os.Mkdir(filepath.Dir(origOutputDestDir), 0755); err != nil && !os.IsExist(err) {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Remove(origOutputDestDir); err != nil && !os.IsNotExist(err) {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Symlink(outputDir, origOutputDestDir); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\t\/\/ Remove the symlink when we're done so the repo doesn't have\n\t\t\/\/ uncommitted changes.\n\t\tif err := os.Remove(origOutputDestDir); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t\/\/ Run `srcgraph make`.\n\tvar w io.Writer\n\tvar buf bytes.Buffer\n\tif testing.Verbose() {\n\t\tw = io.MultiWriter(&buf, os.Stderr)\n\t} else {\n\t\tw = &buf\n\t}\n\tcmd := exec.Command(\"srcgraph\", \"-v\", \"make\")\n\tcmd.Stderr, cmd.Stdout = w, w\n\tcmd.Dir = repoDir\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Errorf(\"Command %v in %s failed: %s.\\n\\nOutput was:\\n%s\", cmd.Args, repoDir, err, buf.String())\n\t\treturn\n\t}\n\n\tif *mode == \"gen\" {\n\t\tt.Errorf(\"Successfully generated expected output for %s in %s. (Triggering test error so you won't mistakenly interpret a 0 return code as a test success. Run without -test.mode=gen to run the test.)\", repoName, wantOutputDir)\n\t} else {\n\t\tcheckResults(t, buf, repoName, gotOutputDir, wantOutputDir)\n\t}\n}\n\nfunc checkResults(t *testing.T, output bytes.Buffer, repoName, gotOutputDir, wantOutputDir string) {\n\tout, err := exec.Command(\"diff\", \"-ur\", wantOutputDir, gotOutputDir).CombinedOutput()\n\tif err != nil || len(out) > 0 {\n\t\tt.Logf(brush.Red(repoName + \" FAIL\").String())\n\t\tt.Errorf(\"Diff failed for %s: %s.\", repoName, err)\n\t\tif len(out) > 0 {\n\t\t\tfmt.Println(brush.Red(repoName + \"FAIL\"))\n\t\t\tfmt.Println(output.String())\n\t\t\tfmt.Println(string(util2.ColorizeDiff(out)))\n\t\t\tt.Errorf(\"Output for %s differed from expected.\", repoName)\n\t\t}\n\t} else {\n\t\tt.Logf(brush.Green(repoName + \" PASS\").String())\n\t}\n}\n\nfunc getHEADOrTipCommitID(t *testing.T, repoDir string) string {\n\t\/\/ TODO(sqs): assumes git\n\tcmd := exec.Command(\"git\", \"rev-parse\", \"HEAD\")\n\tcmd.Dir = repoDir\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn string(bytes.TrimSpace(out))\n}\nskip srcgraph make tests if -test.short is setpackage srcgraph\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/buildstore\"\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/util2\"\n\n\t\"testing\"\n\n\t\"github.com\/aybabtme\/color\/brush\"\n)\n\nvar mode = flag.String(\"test.mode\", \"test\", \"[test|keep|gen] 'test' runs test as normal; keep keeps around generated test files for inspection after tests complete; 'gen' generates new expected test data\")\nvar repoMatch = flag.String(\"test.repo\", \"\", \"only test `srcgraph make` for repos that contain this string\")\n\nfunc TestMakeCmd(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"srcgraph make tests take a long time; skipping for -test.short\")\n\t}\n\n\t\/\/ Since we exec `srcgraph`, make sure it's up-to-date.\n\tif out, err := exec.Command(\"make\", \"-C\", \"..\", \"srcgraph\").CombinedOutput(); err != nil {\n\t\tt.Errorf(\"Failed to build srcgraph for `srcgraph make` tests: %s.\\n\\nOutput was:\\n%s\", err, out)\n\t\treturn\n\t}\n\n\tcmd := exec.Command(\"git\", \"submodule\", \"update\", \"--init\", \"srcgraph\/testdata\/repos\")\n\tcmd.Dir = \"..\"\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tt.Errorf(\"Failed to update or init git submodules: %s.\\n\\nOutput was:\\n%s\", err, out)\n\t\treturn\n\t}\n\n\tconst testReposDir = \"testdata\/repos\"\n\tfis, err := ioutil.ReadDir(\"testdata\/repos\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn := 0\n\tvar wg sync.WaitGroup\n\tfor _, fi := range fis {\n\t\tif repoDir := fi.Name(); strings.Contains(repoDir, *repoMatch) {\n\t\t\tfullRepoDir := filepath.Join(testReposDir, repoDir)\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\ttestMakeCmd(t, fullRepoDir)\n\t\t\t}()\n\t\t\tn++\n\t\t}\n\t}\n\twg.Wait()\n\tif n == 0 {\n\t\tt.Errorf(\"No TestMakeCmd cases were run. Did none match your constraint -test.match=%q?\", *repoMatch)\n\t}\n}\n\nfunc testMakeCmd(t *testing.T, repoDir string) {\n\trepoName := filepath.Base(repoDir)\n\n\t\/\/ Directories for the actual (\"got\") and expected (\"want\") outputs.\n\tgotOutputDir := filepath.Join(repoDir, \"..\/..\/repos-output\/got\", repoName)\n\twantOutputDir := filepath.Join(repoDir, \"..\/..\/repos-output\/want\", repoName)\n\n\t\/\/ Determine and wipe the desired output dir.\n\tvar outputDir string\n\tif *mode == \"gen\" {\n\t\toutputDir = wantOutputDir\n\t} else {\n\t\toutputDir = gotOutputDir\n\t}\n\toutputDir, _ = filepath.Abs(outputDir)\n\tif err := os.RemoveAll(outputDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Symlink ${repoDir}\/.sourcegraph-data\/${commitID} to the desired output dir.\n\torigOutputDestDir := filepath.Join(repoDir, buildstore.BuildDataDirName, getHEADOrTipCommitID(t, repoDir))\n\tif err := os.Mkdir(filepath.Dir(origOutputDestDir), 0755); err != nil && !os.IsExist(err) {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Remove(origOutputDestDir); err != nil && !os.IsNotExist(err) {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Symlink(outputDir, origOutputDestDir); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\t\/\/ Remove the symlink when we're done so the repo doesn't have\n\t\t\/\/ uncommitted changes.\n\t\tif err := os.Remove(origOutputDestDir); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t\/\/ Run `srcgraph make`.\n\tvar w io.Writer\n\tvar buf bytes.Buffer\n\tif testing.Verbose() {\n\t\tw = io.MultiWriter(&buf, os.Stderr)\n\t} else {\n\t\tw = &buf\n\t}\n\tcmd := exec.Command(\"srcgraph\", \"-v\", \"make\")\n\tcmd.Stderr, cmd.Stdout = w, w\n\tcmd.Dir = repoDir\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tt.Errorf(\"Command %v in %s failed: %s.\\n\\nOutput was:\\n%s\", cmd.Args, repoDir, err, buf.String())\n\t\treturn\n\t}\n\n\tif *mode == \"gen\" {\n\t\tt.Errorf(\"Successfully generated expected output for %s in %s. (Triggering test error so you won't mistakenly interpret a 0 return code as a test success. Run without -test.mode=gen to run the test.)\", repoName, wantOutputDir)\n\t} else {\n\t\tcheckResults(t, buf, repoName, gotOutputDir, wantOutputDir)\n\t}\n}\n\nfunc checkResults(t *testing.T, output bytes.Buffer, repoName, gotOutputDir, wantOutputDir string) {\n\tout, err := exec.Command(\"diff\", \"-ur\", wantOutputDir, gotOutputDir).CombinedOutput()\n\tif err != nil || len(out) > 0 {\n\t\tt.Logf(brush.Red(repoName + \" FAIL\").String())\n\t\tt.Errorf(\"Diff failed for %s: %s.\", repoName, err)\n\t\tif len(out) > 0 {\n\t\t\tfmt.Println(brush.Red(repoName + \"FAIL\"))\n\t\t\tfmt.Println(output.String())\n\t\t\tfmt.Println(string(util2.ColorizeDiff(out)))\n\t\t\tt.Errorf(\"Output for %s differed from expected.\", repoName)\n\t\t}\n\t} else {\n\t\tt.Logf(brush.Green(repoName + \" PASS\").String())\n\t}\n}\n\nfunc getHEADOrTipCommitID(t *testing.T, repoDir string) string {\n\t\/\/ TODO(sqs): assumes git\n\tcmd := exec.Command(\"git\", \"rev-parse\", \"HEAD\")\n\tcmd.Dir = repoDir\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn string(bytes.TrimSpace(out))\n}\n<|endoftext|>"} {"text":"package bot\n\nimport (\n\t\"bitbucket.org\/mrd0ll4r\/tbotapi\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype command string\n\nconst (\n\tcmdStart = command(\"start\")\n\tcmdStop = command(\"stop\")\n\tcmdNew = command(\"new\")\n\tcmdJoin = command(\"join\")\n\tcmdAbort = command(\"abort\")\n\tcmdUnknown = command(\"unknown\")\n)\n\nfunc parseCommand(text string) command {\n\ttext = strings.ToLower(text)\n\tif !strings.HasPrefix(text, \"\/\") {\n\t\treturn cmdUnknown\n\t}\n\n\ttext = text[1:]\n\tswitch text {\n\tcase \"new\", \"n\", \"new@\" + api.Username:\n\t\treturn cmdNew\n\tcase \"join\", \"j\", \"join@\" + api.Username:\n\t\treturn cmdJoin\n\tcase \"abort\", \"a\", \"abort@\" + api.Username:\n\t\treturn cmdAbort\n\tcase \"start\", \"start@\" + api.Username:\n\t\treturn cmdStart\n\tcase \"stop\", \"stop@\" + api.Username:\n\t\treturn cmdStop\n\tdefault:\n\t\treturn cmdUnknown\n\t}\n}\n\ntype choice string\n\nconst (\n\tchoiceRock = choice(\"rock\")\n\tchoicePaper = choice(\"paper\")\n\tchoiceScissors = choice(\"scissors\")\n\tchoiceUnknown = choice(\"unknown\")\n)\n\nfunc parseChoice(text string) choice {\n\ttext = strings.ToLower(text)\n\tswitch text {\n\tcase \"rock\", \"r\":\n\t\treturn choiceRock\n\tcase \"paper\", \"p\":\n\t\treturn choicePaper\n\tcase \"scissors\", \"s\":\n\t\treturn choiceScissors\n\tdefault:\n\t\treturn choiceUnknown\n\t}\n}\n\nvar api *tbotapi.TelegramBotAPI\n\n\/\/ RunBot runs a bot.\n\/\/ It will block until either something very bad happens or closing is closed.\nfunc RunBot(apiKey string, closing chan struct{}) {\n\tfmt.Println(\"Starting...\")\n\tif fileExists(\"chats.json\") {\n\t\tfmt.Println(\"Loading chats...\")\n\t\terr := loadChatsFromFile(\"chats.json\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not load:\", err.Error())\n\t\t}\n\t}\n\n\tfmt.Println(\"Starting bot...\")\n\tapi, err := tbotapi.New(apiKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ just to show its working\n\tfmt.Printf(\"User ID: %d\\n\", api.ID)\n\tfmt.Printf(\"Bot Name: %s\\n\", api.Name)\n\tfmt.Printf(\"Bot Username: %s\\n\", api.Username)\n\n\tclosed := make(chan struct{})\n\twg := &sync.WaitGroup{}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\tcase update := <-api.Updates:\n\t\t\t\tif update.Error() != nil {\n\t\t\t\t\tfmt.Printf(\"Update error: %s\\n\", update.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tupd := update.Update()\n\t\t\t\tswitch upd.Type() {\n\t\t\t\tcase tbotapi.MessageUpdate:\n\t\t\t\t\thandleMessage(*update.Update().Message, api)\n\t\t\t\tcase tbotapi.InlineQueryUpdate, tbotapi.ChosenInlineResultUpdate:\n\t\t\t\t\/\/ ignore\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Printf(\"Ignoring unknown Update type.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\tcase <-time.After(10 * time.Minute):\n\t\t\t\tfmt.Println(\"Saving db...\")\n\t\t\t\terr = dumpChatsToFile(\"chats.json\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Could not save:\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ wait for the signal\n\t<-closing\n\tfmt.Println(\"Closing...\")\n\n\tfmt.Println(\"Saving db...\")\n\terr = dumpChatsToFile(\"chats.json\")\n\tif err != nil {\n\t\tfmt.Println(\"Could not save:\", err.Error())\n\t}\n\n\tfmt.Println(\"Closing bot...\")\n\t\/\/ always close the API first, let it clean up the update loop\n\tapi.Close() \/\/this might take a while\n\tclose(closed)\n\twg.Wait()\n}\n\nfunc fileExists(filename string) bool {\n\tfi, err := os.Lstat(filename)\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc handleMessage(msg tbotapi.Message, api *tbotapi.TelegramBotAPI) {\n\ttyp := msg.Type()\n\tif typ != tbotapi.TextMessage {\n\t\t\/\/ignore non-text messages for now\n\t\treturn\n\t}\n\ttext := *msg.Text\n\tif msg.Chat.IsPrivateChat() {\n\t\tfmt.Printf(\"<-%d, %s,\\t%q\\n\", msg.ID, msg.Chat, text)\n\t} else {\n\t\tfmt.Printf(\"<-%d, %s(%s),\\t%q\\n\", msg.ID, msg.Chat, msg.From, text)\n\t}\n\n\tif msg.Chat.IsPrivateChat() {\n\t\t\/\/always update the list of private chats\n\t\tputChat(msg.From.ID, msg.Chat.ID)\n\t}\n\n\tif strings.HasPrefix(text, \"\/\") {\n\t\t\/\/command\n\t\tcmd := parseCommand(text)\n\t\tif cmd == cmdNew {\n\t\t\tgame(msg, api)\n\t\t\treturn\n\t\t}\n\n\t\tgroupsLock.RLock()\n\t\tif c, ok := groups[msg.Chat.ID]; ok {\n\t\t\tc <- msg\n\t\t}\n\t\tgroupsLock.RUnlock()\n\t} else {\n\t\tif msg.Chat.IsPrivateChat() {\n\t\t\tuid := msg.From.ID\n\t\t\texpectsLock.Lock()\n\t\t\tif expect, ok := expects[uid]; ok {\n\t\t\t\tswitch parseChoice(text) {\n\t\t\t\tcase choiceRock, choicePaper, choiceScissors:\n\t\t\t\t\texpect <- parseChoice(text)\n\t\t\t\t\tdelete(expects, uid)\n\t\t\t\tdefault:\n\t\t\t\t\treply(msg, api, \"No understand\")\n\t\t\t\t}\n\t\t\t}\n\t\t\texpectsLock.Unlock()\n\t\t}\n\t}\n}\n\nfunc game(msg tbotapi.Message, api *tbotapi.TelegramBotAPI) {\n\tif hasExpect(msg.From.ID) {\n\t\treply(msg, api, \"You are already in a game right now\")\n\t\treturn\n\t}\n\n\tif msg.Chat.IsPrivateChat() {\n\t\treply(msg, api, \"You will play against the bot. Make your choice! ([r]ock, [p]aper or [s]cissors)\")\n\n\t\teChan := make(chan choice)\n\t\texpectsLock.Lock()\n\t\texpects[msg.From.ID] = eChan\n\t\texpectsLock.Unlock()\n\n\t\tgo func(original tbotapi.Message, api *tbotapi.TelegramBotAPI, expected chan choice) {\n\t\t\tchoice := <-eChan\n\n\t\t\tbotChoice := rand.Float64()\n\n\t\t\tvar resp string\n\t\t\tif botChoice < (float64(1) \/ float64(3)) {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choiceRock, choice)\n\t\t\t} else if botChoice < (float64(2) \/ float64(3)) {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choicePaper, choice)\n\t\t\t} else {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choiceScissors, choice)\n\t\t\t}\n\n\t\t\treply(original, api, resp)\n\t\t}(msg, api, eChan)\n\n\t} else {\n\t\t\/\/group mode\n\n\t\tif !hasChat(msg.From.ID) {\n\t\t\treply(msg, api, \"I have lost track of our private chat. Please write me personally and try again\")\n\t\t\treturn\n\t\t}\n\n\t\tif hasGroup(msg.Chat.ID) {\n\t\t\treply(msg, api, \"This group already has an open game.\")\n\t\t\treturn\n\t\t}\n\n\t\tmessages := make(chan tbotapi.Message)\n\t\tgroups[msg.Chat.ID] = messages\n\t\treply(msg, api, \"Game opened. Join with \/join, abort with \/abort\")\n\n\t\tgo func(original tbotapi.Message, api *tbotapi.TelegramBotAPI, messages chan tbotapi.Message) {\n\t\t\tvar p1, p2 chan choice\n\t\t\tvar partner tbotapi.User\n\n\t\tloop:\n\t\t\tfor {\n\t\t\t\tmsg := <-messages\n\t\t\t\tif msg.Type() != tbotapi.TextMessage {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttext := *msg.Text\n\t\t\t\tswitch parseCommand(text) {\n\t\t\t\tcase cmdJoin:\n\t\t\t\t\tif msg.From.ID == original.From.ID {\n\t\t\t\t\t\treply(original, api, \"The creator is already in the game, idiot\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\texpectsLock.Lock()\n\t\t\t\t\t\tif _, ok := expects[original.From.ID]; ok {\n\t\t\t\t\t\t\treply(msg, api, \"The creator is already in a game right now, game will remain open...\")\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif _, ok := expects[msg.From.ID]; ok {\n\t\t\t\t\t\t\treply(msg, api, \"You are already in a game right now, game will remain open...\")\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif !hasChat(msg.From.ID) {\n\t\t\t\t\t\t\treply(msg, api, \"I have lost track of our private chat. Please write me personally and try again\")\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgroupsLock.Lock()\n\t\t\t\t\t\tdelete(groups, original.Chat.ID)\n\t\t\t\t\t\tgroupsLock.Unlock()\n\t\t\t\t\t\tp1 = make(chan choice)\n\t\t\t\t\t\texpects[original.From.ID] = p1\n\t\t\t\t\t\tp2 = make(chan choice)\n\t\t\t\t\t\texpects[msg.From.ID] = p2\n\t\t\t\t\t\texpectsLock.Unlock()\n\n\t\t\t\t\t\tp1Chat := chats[original.From.ID]\n\t\t\t\t\t\tp2Chat := chats[msg.From.ID]\n\n\t\t\t\t\t\tpartner = msg.From\n\n\t\t\t\t\t\tsendTo(p1Chat, api, \"Waiting for your choice. ([r]ock, [p]aper, [s]cissors)\")\n\t\t\t\t\t\tsendTo(p2Chat, api, \"Waiting for your choice. ([r]ock, [p]aper, [s]cissors)\")\n\t\t\t\t\t\treply(original, api, \"Game started, send me your choices in a private chat.\")\n\n\t\t\t\t\t\tbreak loop\n\t\t\t\t\t}\n\t\t\t\tcase cmdAbort:\n\t\t\t\t\tif msg.From.ID == original.From.ID {\n\t\t\t\t\t\tgroupsLock.Lock()\n\t\t\t\t\t\tdelete(groups, original.Chat.ID)\n\t\t\t\t\t\tgroupsLock.Unlock()\n\t\t\t\t\t\treply(original, api, \"Game aborted.\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\treply(original, api, \"Only the creator can abort a game\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ game running\n\n\t\t\tvar choice1, choice2 choice\n\n\t\tnextloop:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase choice1 = <-p1:\n\t\t\t\t\tif choice2 != \"\" {\n\t\t\t\t\t\tbreak nextloop\n\t\t\t\t\t}\n\t\t\t\tcase choice2 = <-p2:\n\t\t\t\t\tif choice1 != \"\" {\n\t\t\t\t\t\tbreak nextloop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresp := formatResponse(original.From.String(), partner.String(), choice1, choice2)\n\n\t\t\treply(original, api, resp)\n\n\t\t}(msg, api, messages)\n\t}\n}\n\nfunc formatResponse(part1, part2 string, choice1, choice2 choice) string {\n\tvar res string\n\tswitch choice1 {\n\tcase choiceRock:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = \"tie\"\n\t\tcase choicePaper:\n\t\t\tres = part2 + \" wins\"\n\t\tcase choiceScissors:\n\t\t\tres = part1 + \" wins\"\n\t\t}\n\tcase choicePaper:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = part1 + \" wins\"\n\t\tcase choicePaper:\n\t\t\tres = \"tie\"\n\t\tcase choiceScissors:\n\t\t\tres = part2 + \" wins\"\n\t\t}\n\tcase choiceScissors:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = part2 + \" wins\"\n\t\tcase choicePaper:\n\t\t\tres = part1 + \" wins\"\n\t\tcase choiceScissors:\n\t\t\tres = \"tie\"\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%s chose %s, %s chose %s: %s\", part1, choice1, part2, choice2, res)\n}\n\nfunc sendTo(chat int, api *tbotapi.TelegramBotAPI, text string) error {\n\toutMsg, err := api.NewOutgoingMessage(tbotapi.NewChatRecipient(chat), text).Send()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"->%d, %s,\\t%q\\n\", outMsg.Message.ID, outMsg.Message.Chat, *outMsg.Message.Text)\n\treturn nil\n}\n\nfunc reply(msg tbotapi.Message, api *tbotapi.TelegramBotAPI, text string) error {\n\treturn sendTo(msg.Chat.ID, api, text)\n}\nmore constantspackage bot\n\nimport (\n\t\"bitbucket.org\/mrd0ll4r\/tbotapi\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tmsgChoices = \"([r]ock, [p]aper or [s]cissors)\"\n\tmsgChoose = \"Make your choice! \" + msgChoices\n\tmsgNoPrivateChat = \"I have lost track of our private chat. Please write me in a private chat and try again\"\n\tmsgAlreadyIngame = \"You are already in a game right now, finish that first.\"\n\tmsgAlreadyIngameWillRemainOpen = msgAlreadyIngame + \" Game will remain open...\"\n\tmsgGameOpened = \"Game opened! Join with \/join, abort with \/abort\"\n\tmsgGameStarted = \"Game started! Waiting for your choices in our private chats...\"\n\tmsgGameAborted = \"Game aborted\"\n\tmsgOnlyCreatorCanAbort = \"Only the creator can abort a game\"\n\tmsgCreatorAlreadyInGame = \"The creator is already in the game, idiot\"\n)\n\ntype command string\n\nconst (\n\tcmdStart = command(\"start\")\n\tcmdStop = command(\"stop\")\n\tcmdNew = command(\"new\")\n\tcmdJoin = command(\"join\")\n\tcmdAbort = command(\"abort\")\n\tcmdUnknown = command(\"unknown\")\n)\n\nfunc parseCommand(text string) command {\n\ttext = strings.ToLower(text)\n\tif !strings.HasPrefix(text, \"\/\") {\n\t\treturn cmdUnknown\n\t}\n\n\ttext = text[1:]\n\tswitch text {\n\tcase \"new\", \"n\", \"new@\" + api.Username:\n\t\treturn cmdNew\n\tcase \"join\", \"j\", \"join@\" + api.Username:\n\t\treturn cmdJoin\n\tcase \"abort\", \"a\", \"abort@\" + api.Username:\n\t\treturn cmdAbort\n\tcase \"start\", \"start@\" + api.Username:\n\t\treturn cmdStart\n\tcase \"stop\", \"stop@\" + api.Username:\n\t\treturn cmdStop\n\tdefault:\n\t\treturn cmdUnknown\n\t}\n}\n\ntype choice string\n\nconst (\n\tchoiceRock = choice(\"rock\")\n\tchoicePaper = choice(\"paper\")\n\tchoiceScissors = choice(\"scissors\")\n\tchoiceUnknown = choice(\"unknown\")\n)\n\nfunc parseChoice(text string) choice {\n\ttext = strings.ToLower(text)\n\tswitch text {\n\tcase \"rock\", \"r\":\n\t\treturn choiceRock\n\tcase \"paper\", \"p\":\n\t\treturn choicePaper\n\tcase \"scissors\", \"s\":\n\t\treturn choiceScissors\n\tdefault:\n\t\treturn choiceUnknown\n\t}\n}\n\nvar api *tbotapi.TelegramBotAPI\n\n\/\/ RunBot runs a bot.\n\/\/ It will block until either something very bad happens or closing is closed.\nfunc RunBot(apiKey string, closing chan struct{}) {\n\tfmt.Println(\"Starting...\")\n\tif fileExists(\"chats.json\") {\n\t\tfmt.Println(\"Loading chats...\")\n\t\terr := loadChatsFromFile(\"chats.json\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not load:\", err.Error())\n\t\t}\n\t}\n\n\tfmt.Println(\"Starting bot...\")\n\tapi, err := tbotapi.New(apiKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ just to show its working\n\tfmt.Printf(\"User ID: %d\\n\", api.ID)\n\tfmt.Printf(\"Bot Name: %s\\n\", api.Name)\n\tfmt.Printf(\"Bot Username: %s\\n\", api.Username)\n\n\tclosed := make(chan struct{})\n\twg := &sync.WaitGroup{}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\tcase update := <-api.Updates:\n\t\t\t\tif update.Error() != nil {\n\t\t\t\t\tfmt.Printf(\"Update error: %s\\n\", update.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tupd := update.Update()\n\t\t\t\tswitch upd.Type() {\n\t\t\t\tcase tbotapi.MessageUpdate:\n\t\t\t\t\thandleMessage(*update.Update().Message, api)\n\t\t\t\tcase tbotapi.InlineQueryUpdate, tbotapi.ChosenInlineResultUpdate:\n\t\t\t\t\/\/ ignore\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Printf(\"Ignoring unknown Update type.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\tcase <-time.After(10 * time.Minute):\n\t\t\t\tfmt.Println(\"Saving db...\")\n\t\t\t\terr = dumpChatsToFile(\"chats.json\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Could not save:\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ wait for the signal\n\t<-closing\n\tfmt.Println(\"Closing...\")\n\n\tfmt.Println(\"Saving db...\")\n\terr = dumpChatsToFile(\"chats.json\")\n\tif err != nil {\n\t\tfmt.Println(\"Could not save:\", err.Error())\n\t}\n\n\tfmt.Println(\"Closing bot...\")\n\t\/\/ always close the API first, let it clean up the update loop\n\tapi.Close() \/\/this might take a while\n\tclose(closed)\n\twg.Wait()\n}\n\nfunc fileExists(filename string) bool {\n\tfi, err := os.Lstat(filename)\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc handleMessage(msg tbotapi.Message, api *tbotapi.TelegramBotAPI) {\n\ttyp := msg.Type()\n\tif typ != tbotapi.TextMessage {\n\t\t\/\/ignore non-text messages for now\n\t\treturn\n\t}\n\ttext := *msg.Text\n\tif msg.Chat.IsPrivateChat() {\n\t\tfmt.Printf(\"<-%d, %s,\\t%q\\n\", msg.ID, msg.Chat, text)\n\t} else {\n\t\tfmt.Printf(\"<-%d, %s(%s),\\t%q\\n\", msg.ID, msg.Chat, msg.From, text)\n\t}\n\n\tif msg.Chat.IsPrivateChat() {\n\t\t\/\/always update the list of private chats\n\t\tputChat(msg.From.ID, msg.Chat.ID)\n\t}\n\n\tif strings.HasPrefix(text, \"\/\") {\n\t\t\/\/command\n\t\tcmd := parseCommand(text)\n\t\tif cmd == cmdNew {\n\t\t\tgame(msg, api)\n\t\t\treturn\n\t\t}\n\n\t\tgroupsLock.RLock()\n\t\tif c, ok := groups[msg.Chat.ID]; ok {\n\t\t\tc <- msg\n\t\t}\n\t\tgroupsLock.RUnlock()\n\t} else {\n\t\tif msg.Chat.IsPrivateChat() {\n\t\t\tuid := msg.From.ID\n\t\t\texpectsLock.Lock()\n\t\t\tif expect, ok := expects[uid]; ok {\n\t\t\t\tswitch parseChoice(text) {\n\t\t\t\tcase choiceRock, choicePaper, choiceScissors:\n\t\t\t\t\texpect <- parseChoice(text)\n\t\t\t\t\tdelete(expects, uid)\n\t\t\t\tdefault:\n\t\t\t\t\treply(msg, api, \"No understand\")\n\t\t\t\t}\n\t\t\t}\n\t\t\texpectsLock.Unlock()\n\t\t}\n\t}\n}\n\nfunc game(msg tbotapi.Message, api *tbotapi.TelegramBotAPI) {\n\tif hasExpect(msg.From.ID) {\n\t\treply(msg, api, msgAlreadyIngame)\n\t\treturn\n\t}\n\n\tif msg.Chat.IsPrivateChat() {\n\t\treply(msg, api, \"You will play against the bot. \"+msgChoose)\n\n\t\teChan := make(chan choice)\n\t\texpectsLock.Lock()\n\t\texpects[msg.From.ID] = eChan\n\t\texpectsLock.Unlock()\n\n\t\tgo func(original tbotapi.Message, api *tbotapi.TelegramBotAPI, expected chan choice) {\n\t\t\tchoice := <-eChan\n\n\t\t\tbotChoice := rand.Float64()\n\n\t\t\tvar resp string\n\t\t\tif botChoice < (float64(1) \/ float64(3)) {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choiceRock, choice)\n\t\t\t} else if botChoice < (float64(2) \/ float64(3)) {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choicePaper, choice)\n\t\t\t} else {\n\t\t\t\tresp = formatResponse(\"the bot\", \"you\", choiceScissors, choice)\n\t\t\t}\n\n\t\t\treply(original, api, resp)\n\t\t}(msg, api, eChan)\n\n\t} else {\n\t\t\/\/group mode\n\n\t\tif !hasChat(msg.From.ID) {\n\t\t\treply(msg, api, msgNoPrivateChat)\n\t\t\treturn\n\t\t}\n\n\t\tif hasGroup(msg.Chat.ID) {\n\t\t\treply(msg, api, \"This group already has an open game.\")\n\t\t\treturn\n\t\t}\n\n\t\tmessages := make(chan tbotapi.Message)\n\t\tgroups[msg.Chat.ID] = messages\n\t\treply(msg, api, msgGameOpened)\n\n\t\tgo func(original tbotapi.Message, api *tbotapi.TelegramBotAPI, messages chan tbotapi.Message) {\n\t\t\tvar p1, p2 chan choice\n\t\t\tvar partner tbotapi.User\n\n\t\tloop:\n\t\t\tfor {\n\t\t\t\tmsg := <-messages\n\t\t\t\tif msg.Type() != tbotapi.TextMessage {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttext := *msg.Text\n\t\t\t\tswitch parseCommand(text) {\n\t\t\t\tcase cmdJoin:\n\t\t\t\t\tif msg.From.ID == original.From.ID {\n\t\t\t\t\t\treply(original, api, msgCreatorAlreadyInGame)\n\t\t\t\t\t} else {\n\t\t\t\t\t\texpectsLock.Lock()\n\t\t\t\t\t\tif _, ok := expects[original.From.ID]; ok {\n\t\t\t\t\t\t\treply(msg, api, msgAlreadyIngameWillRemainOpen)\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif _, ok := expects[msg.From.ID]; ok {\n\t\t\t\t\t\t\treply(msg, api, msgAlreadyIngameWillRemainOpen)\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif !hasChat(msg.From.ID) {\n\t\t\t\t\t\t\treply(msg, api, msgNoPrivateChat)\n\t\t\t\t\t\t\texpectsLock.Unlock()\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgroupsLock.Lock()\n\t\t\t\t\t\tdelete(groups, original.Chat.ID)\n\t\t\t\t\t\tgroupsLock.Unlock()\n\t\t\t\t\t\tp1 = make(chan choice)\n\t\t\t\t\t\texpects[original.From.ID] = p1\n\t\t\t\t\t\tp2 = make(chan choice)\n\t\t\t\t\t\texpects[msg.From.ID] = p2\n\t\t\t\t\t\texpectsLock.Unlock()\n\n\t\t\t\t\t\tp1Chat := chats[original.From.ID]\n\t\t\t\t\t\tp2Chat := chats[msg.From.ID]\n\n\t\t\t\t\t\tpartner = msg.From\n\n\t\t\t\t\t\tsendTo(p1Chat, api, msgChoose)\n\t\t\t\t\t\tsendTo(p2Chat, api, msgChoose)\n\t\t\t\t\t\treply(original, api, msgGameStarted)\n\n\t\t\t\t\t\tbreak loop\n\t\t\t\t\t}\n\t\t\t\tcase cmdAbort:\n\t\t\t\t\tif msg.From.ID == original.From.ID {\n\t\t\t\t\t\tgroupsLock.Lock()\n\t\t\t\t\t\tdelete(groups, original.Chat.ID)\n\t\t\t\t\t\tgroupsLock.Unlock()\n\t\t\t\t\t\treply(original, api, msgGameAborted)\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\treply(original, api, msgOnlyCreatorCanAbort)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ game running\n\n\t\t\tvar choice1, choice2 choice\n\n\t\tnextloop:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase choice1 = <-p1:\n\t\t\t\t\tif choice2 != \"\" {\n\t\t\t\t\t\tbreak nextloop\n\t\t\t\t\t}\n\t\t\t\tcase choice2 = <-p2:\n\t\t\t\t\tif choice1 != \"\" {\n\t\t\t\t\t\tbreak nextloop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresp := formatResponse(original.From.String(), partner.String(), choice1, choice2)\n\n\t\t\treply(original, api, resp)\n\n\t\t}(msg, api, messages)\n\t}\n}\n\nfunc formatResponse(part1, part2 string, choice1, choice2 choice) string {\n\tvar res string\n\tswitch choice1 {\n\tcase choiceRock:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = \"tie\"\n\t\tcase choicePaper:\n\t\t\tres = part2 + \" wins\"\n\t\tcase choiceScissors:\n\t\t\tres = part1 + \" wins\"\n\t\t}\n\tcase choicePaper:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = part1 + \" wins\"\n\t\tcase choicePaper:\n\t\t\tres = \"tie\"\n\t\tcase choiceScissors:\n\t\t\tres = part2 + \" wins\"\n\t\t}\n\tcase choiceScissors:\n\t\tswitch choice2 {\n\t\tcase choiceRock:\n\t\t\tres = part2 + \" wins\"\n\t\tcase choicePaper:\n\t\t\tres = part1 + \" wins\"\n\t\tcase choiceScissors:\n\t\t\tres = \"tie\"\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%s chose %s, %s chose %s: %s\", part1, choice1, part2, choice2, res)\n}\n\nfunc sendTo(chat int, api *tbotapi.TelegramBotAPI, text string) error {\n\toutMsg, err := api.NewOutgoingMessage(tbotapi.NewChatRecipient(chat), text).Send()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"->%d, %s,\\t%q\\n\", outMsg.Message.ID, outMsg.Message.Chat, *outMsg.Message.Text)\n\treturn nil\n}\n\nfunc reply(msg tbotapi.Message, api *tbotapi.TelegramBotAPI, text string) error {\n\treturn sendTo(msg.Chat.ID, api, text)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 xgfone\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package execution executes a command line program in a new process and returns a output.\npackage execution\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"os\/exec\"\n\t\"time\"\n)\n\n\/\/ ErrDeny is returned when the hook denies the cmd.\nvar ErrDeny = errors.New(\"the cmd is denied\")\n\n\/\/ Hook is used to filter or handle the cmd `name` with the arguments `args`.\n\/\/\n\/\/ If returning true, it will continue to run it, or do nothing.\ntype Hook func(name string, args ...string) bool\n\n\/\/ Cmd represents a command executor.\ntype Cmd struct {\n\thooks []Hook\n\n\t\/\/ Timeout is used to produce the timeout context based on the context\n\t\/\/ argument if not 0 when executing the command.\n\tTimeout time.Duration\n\n\t\/\/ SetCmd allows the user to customize exec.Cmd.\n\t\/\/\n\t\/\/ Notice: You should not modify the fields `Stdout` and `Stderr`.\n\tSetCmd func(*exec.Cmd)\n}\n\n\/\/ NewCmd returns a new executor Cmd.\nfunc NewCmd() *Cmd {\n\treturn new(Cmd)\n}\n\n\/\/ AppendHooks appends some hooks.\nfunc (c *Cmd) AppendHooks(hooks ...Hook) *Cmd {\n\tfor _, hook := range hooks {\n\t\tif hook != nil {\n\t\t\tc.hooks = append(c.hooks, hook)\n\t\t}\n\t}\n\treturn c\n}\n\nfunc geterr(stdout, stderr []byte, err error) error {\n\tif err != nil {\n\t\tif len(stderr) > 0 {\n\t\t\terr = errors.New(string(stderr))\n\t\t} else if len(stdout) > 0 {\n\t\t\terr = errors.New(string(stdout))\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ RunCmd executes the command, name, with its arguments, args,\n\/\/ then returns stdout, stderr and error.\nfunc (c *Cmd) RunCmd(cxt context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\n\tfor _, hook := range c.hooks {\n\t\tif ok := hook(name, args...); !ok {\n\t\t\treturn nil, nil, ErrDeny\n\t\t}\n\t}\n\n\tvar cancel func()\n\tif c.Timeout > 0 {\n\t\tcxt, cancel = context.WithTimeout(cxt, c.Timeout)\n\t\tdefer cancel()\n\t}\n\n\tcmd := exec.CommandContext(cxt, name, args...)\n\tif c.SetCmd != nil {\n\t\tc.SetCmd(cmd)\n\t}\n\n\tvar output bytes.Buffer\n\tvar errput bytes.Buffer\n\tcmd.Stdout = &output\n\tcmd.Stderr = &errput\n\terr = cmd.Run()\n\tstdout = output.Bytes()\n\tstderr = errput.Bytes()\n\terr = geterr(stdout, stderr, err)\n\treturn\n}\n\n\/\/ Run is the alias of RunCmd.\nfunc (c *Cmd) Run(ctx context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\treturn c.RunCmd(ctx, name, args...)\n}\n\n\/\/ RetryRunCmd is the same as RunCmd, but try to run once again if failed.\nfunc (c *Cmd) RetryRunCmd(ctx context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\tstdout, stderr, err = c.RunCmd(ctx, name, args...)\n\tif err != nil {\n\t\tstdout, stderr, err = c.RunCmd(ctx, name, args...)\n\t}\n\treturn\n}\n\n\/\/ Execute is the same as RunCmd, but only returns the error.\nfunc (c *Cmd) Execute(cxt context.Context, name string, args ...string) error {\n\t_, _, err := c.RunCmd(cxt, name, args...)\n\treturn err\n}\n\n\/\/ Output is the same as RunCmd, but only returns the stdout and the error.\nfunc (c *Cmd) Output(cxt context.Context, name string, args ...string) (string, error) {\n\tstdout, _, err := c.RunCmd(cxt, name, args...)\n\treturn string(stdout), err\n}\n\n\/\/ Executes is equal to Execute(cxt, cmds[0], cmds[1:]...)\nfunc (c *Cmd) Executes(cxt context.Context, cmds []string) error {\n\t_, _, err := c.RunCmd(cxt, cmds[0], cmds[1:]...)\n\treturn err\n}\n\n\/\/ Outputs is equal to Output(cxt, cmds[0], cmds[1:]...).\nfunc (c *Cmd) Outputs(cxt context.Context, cmds []string) (string, error) {\n\tstdout, _, err := c.RunCmd(cxt, cmds[0], cmds[1:]...)\n\treturn string(stdout), err\n}\nexport the field Hooks of Cmd\/\/ Copyright 2019 xgfone\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package execution executes a command line program in a new process and returns a output.\npackage execution\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"os\/exec\"\n\t\"time\"\n)\n\n\/\/ ErrDeny is returned when the hook denies the cmd.\nvar ErrDeny = errors.New(\"the cmd is denied\")\n\n\/\/ Hook is used to filter or handle the cmd `name` with the arguments `args`.\n\/\/\n\/\/ If returning true, it will continue to run it, or do nothing.\ntype Hook func(name string, args ...string) bool\n\n\/\/ Cmd represents a command executor.\ntype Cmd struct {\n\tHooks []Hook\n\n\t\/\/ Timeout is used to produce the timeout context based on the context\n\t\/\/ argument if not 0 when executing the command.\n\tTimeout time.Duration\n\n\t\/\/ SetCmd allows the user to customize exec.Cmd.\n\t\/\/\n\t\/\/ Notice: You should not modify the fields `Stdout` and `Stderr`.\n\tSetCmd func(*exec.Cmd)\n}\n\n\/\/ NewCmd returns a new executor Cmd.\nfunc NewCmd() *Cmd {\n\treturn new(Cmd)\n}\n\n\/\/ AppendHooks appends some hooks.\nfunc (c *Cmd) AppendHooks(hooks ...Hook) *Cmd {\n\tfor _, hook := range hooks {\n\t\tif hook != nil {\n\t\t\tc.Hooks = append(c.Hooks, hook)\n\t\t}\n\t}\n\treturn c\n}\n\nfunc geterr(stdout, stderr []byte, err error) error {\n\tif err != nil {\n\t\tif len(stderr) > 0 {\n\t\t\terr = errors.New(string(stderr))\n\t\t} else if len(stdout) > 0 {\n\t\t\terr = errors.New(string(stdout))\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ RunCmd executes the command, name, with its arguments, args,\n\/\/ then returns stdout, stderr and error.\nfunc (c *Cmd) RunCmd(cxt context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\n\tfor _, hook := range c.Hooks {\n\t\tif ok := hook(name, args...); !ok {\n\t\t\treturn nil, nil, ErrDeny\n\t\t}\n\t}\n\n\tvar cancel func()\n\tif c.Timeout > 0 {\n\t\tcxt, cancel = context.WithTimeout(cxt, c.Timeout)\n\t\tdefer cancel()\n\t}\n\n\tcmd := exec.CommandContext(cxt, name, args...)\n\tif c.SetCmd != nil {\n\t\tc.SetCmd(cmd)\n\t}\n\n\tvar output bytes.Buffer\n\tvar errput bytes.Buffer\n\tcmd.Stdout = &output\n\tcmd.Stderr = &errput\n\terr = cmd.Run()\n\tstdout = output.Bytes()\n\tstderr = errput.Bytes()\n\terr = geterr(stdout, stderr, err)\n\treturn\n}\n\n\/\/ Run is the alias of RunCmd.\nfunc (c *Cmd) Run(ctx context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\treturn c.RunCmd(ctx, name, args...)\n}\n\n\/\/ RetryRunCmd is the same as RunCmd, but try to run once again if failed.\nfunc (c *Cmd) RetryRunCmd(ctx context.Context, name string, args ...string) (\n\tstdout, stderr []byte, err error) {\n\tstdout, stderr, err = c.RunCmd(ctx, name, args...)\n\tif err != nil {\n\t\tstdout, stderr, err = c.RunCmd(ctx, name, args...)\n\t}\n\treturn\n}\n\n\/\/ Execute is the same as RunCmd, but only returns the error.\nfunc (c *Cmd) Execute(cxt context.Context, name string, args ...string) error {\n\t_, _, err := c.RunCmd(cxt, name, args...)\n\treturn err\n}\n\n\/\/ Output is the same as RunCmd, but only returns the stdout and the error.\nfunc (c *Cmd) Output(cxt context.Context, name string, args ...string) (string, error) {\n\tstdout, _, err := c.RunCmd(cxt, name, args...)\n\treturn string(stdout), err\n}\n\n\/\/ Executes is equal to Execute(cxt, cmds[0], cmds[1:]...)\nfunc (c *Cmd) Executes(cxt context.Context, cmds []string) error {\n\t_, _, err := c.RunCmd(cxt, cmds[0], cmds[1:]...)\n\treturn err\n}\n\n\/\/ Outputs is equal to Output(cxt, cmds[0], cmds[1:]...).\nfunc (c *Cmd) Outputs(cxt context.Context, cmds []string) (string, error) {\n\tstdout, _, err := c.RunCmd(cxt, cmds[0], cmds[1:]...)\n\treturn string(stdout), err\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017, OpenCensus Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage grpc-stats-collectionDeleted not used directories<|endoftext|>"} {"text":"package nca\n\nimport (\n\tlog \"gopkg.in\/inconshreveable\/log15.v2\"\n\t\"os\"\n\t\"os\/signal\"\n)\n\n\/\/ Runner is the main component of the application. It runs the Checker and\n\/\/ Publisher subcomponents and facilitates communication between them.\ntype Runner struct {\n\tconfig Config\n\tchecker *checker\n\tpublishers map[string]Publisher\n\tpublishChan chan *CheckResult \/\/ The cchannel check results are received from\n\tlog log.Logger\n\tdone chan struct{} \/\/ Used for signalling goroutines that we're shutting down\n}\n\n\/\/ NewRunner creates a new Runner with the given configuration.\nfunc NewRunner(cfg Config) (*Runner, error) {\n\tr := &Runner{}\n\tif err := r.Init(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ NewRunnerFromFile creates a new Runner using the configuration loaded\n\/\/ from the given file.\nfunc NewRunnerFromFile(filename string) (*Runner, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tcfg, err := ReadConfig(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := NewRunner(*cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ Init initializes the Runner with the given configuration.\nfunc (r *Runner) Init(cfg Config) error {\n\tr.config = cfg\n\tr.log = Log.New(\"component\", \"runner\")\n\tr.checker = &checker{}\n\tr.checker.RegisterChecks(r.config.Checks)\n\n\tr.publishers = make(map[string]Publisher)\n\tfor label, config := range cfg.Publishers {\n\t\tptype := config[\"type\"].(string)\n\t\tp := newPublisher(ptype)\n\t\tif err := p.Configure(config); err != nil {\n\t\t\tr.log.Error(\"Invalid publisher configuration\", \"publisher\", label, \"error\", err)\n\t\t\treturn err\n\t\t}\n\t\tr.publishers[label] = p\n\t}\n\n\treturn nil\n}\n\n\/\/ Start starts the Runner and begins running checks, publishing them as they\n\/\/ complete.\nfunc (r *Runner) Start() error {\n\tr.log.Info(\"Runner starting\")\n\tr.done = make(chan struct{})\n\n\tr.publishChan, _ = r.checker.Start()\n\tfor _, publisher := range r.publishers {\n\t\tpublisher.Start()\n\t}\n\tgo r.process()\n\treturn nil\n}\n\n\/\/ process reads results produced by the checker and distributes them\n\/\/ to the publishers.\nfunc (r *Runner) process() {\n\tr.log.Debug(\"process() loop start\")\n\tfor {\n\t\tselect {\n\t\tcase result := <-r.publishChan:\n\t\t\tif result == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor label, publisher := range r.publishers {\n\t\t\t\tl := r.log.New(\"check\", result.Name, \"publisher\", label)\n\t\t\t\tl.Debug(\"Publishing check result to publisher\")\n\t\t\t\tif err := publisher.Publish(result); err != nil {\n\t\t\t\t\tl.Warn(\"Error publishing check result\", \"error\", err)\n\t\t\t\t} else {\n\t\t\t\t\tl.Debug(\"Check result published\")\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-r.done:\n\t\t\treturn\n\t\t}\n\t}\n\tr.log.Debug(\"process() loop end\")\n}\n\n\/\/ Stop stops and shuts down the Runner.\nfunc (r *Runner) Stop() error {\n\tr.log.Info(\"Runner stopping\")\n\tr.checker.Stop()\n\tfor _, publisher := range r.publishers {\n\t\tpublisher.Stop()\n\t}\n\treturn nil\n}\n\n\/\/ Run starts the runner and blocks until an interrupt signal is received.\nfunc (r *Runner) Run() error {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\tr.Start()\n\tfor sig := range c {\n\t\tif sig == os.Interrupt {\n\t\t\tr.log.Info(\"Received interrupt, shutting down\")\n\t\t\tr.Stop()\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\nPublish results in seperate goroutinespackage nca\n\nimport (\n\tlog \"gopkg.in\/inconshreveable\/log15.v2\"\n\t\"os\"\n\t\"os\/signal\"\n)\n\n\/\/ Runner is the main component of the application. It runs the Checker and\n\/\/ Publisher subcomponents and facilitates communication between them.\ntype Runner struct {\n\tconfig Config\n\tchecker *checker\n\tpublishers map[string]Publisher\n\tpublishChan chan *CheckResult \/\/ The cchannel check results are received from\n\tlog log.Logger\n\tdone chan struct{} \/\/ Used for signalling goroutines that we're shutting down\n}\n\n\/\/ NewRunner creates a new Runner with the given configuration.\nfunc NewRunner(cfg Config) (*Runner, error) {\n\tr := &Runner{}\n\tif err := r.Init(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ NewRunnerFromFile creates a new Runner using the configuration loaded\n\/\/ from the given file.\nfunc NewRunnerFromFile(filename string) (*Runner, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tcfg, err := ReadConfig(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := NewRunner(*cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ Init initializes the Runner with the given configuration.\nfunc (r *Runner) Init(cfg Config) error {\n\tr.config = cfg\n\tr.log = Log.New(\"component\", \"runner\")\n\tr.checker = &checker{}\n\tr.checker.RegisterChecks(r.config.Checks)\n\n\tr.publishers = make(map[string]Publisher)\n\tfor label, config := range cfg.Publishers {\n\t\tptype := config[\"type\"].(string)\n\t\tp := newPublisher(ptype)\n\t\tif err := p.Configure(config); err != nil {\n\t\t\tr.log.Error(\"Invalid publisher configuration\", \"publisher\", label, \"error\", err)\n\t\t\treturn err\n\t\t}\n\t\tr.publishers[label] = p\n\t}\n\n\treturn nil\n}\n\n\/\/ Start starts the Runner and begins running checks, publishing them as they\n\/\/ complete.\nfunc (r *Runner) Start() error {\n\tr.log.Info(\"Runner starting\")\n\tr.done = make(chan struct{})\n\n\tr.publishChan, _ = r.checker.Start()\n\tfor _, publisher := range r.publishers {\n\t\tpublisher.Start()\n\t}\n\tgo r.process()\n\treturn nil\n}\n\n\/\/ process reads results produced by the checker and distributes them\n\/\/ to the publishers.\nfunc (r *Runner) process() {\n\tr.log.Debug(\"process() loop start\")\n\tfor {\n\t\tselect {\n\t\tcase result := <-r.publishChan:\n\t\t\tif result == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor label, publisher := range r.publishers {\n\t\t\t\tgo func() {\n\t\t\t\t\tl := r.log.New(\"check\", result.Name, \"publisher\", label)\n\t\t\t\t\tl.Debug(\"Publishing check result to publisher\")\n\t\t\t\t\tif err := publisher.Publish(result); err != nil {\n\t\t\t\t\t\tl.Warn(\"Error publishing check result\", \"error\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tl.Debug(\"Check result published\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\tcase <-r.done:\n\t\t\treturn\n\t\t}\n\t}\n\tr.log.Debug(\"process() loop end\")\n}\n\n\/\/ Stop stops and shuts down the Runner.\nfunc (r *Runner) Stop() error {\n\tr.log.Info(\"Runner stopping\")\n\tr.checker.Stop()\n\tfor _, publisher := range r.publishers {\n\t\tpublisher.Stop()\n\t}\n\treturn nil\n}\n\n\/\/ Run starts the runner and blocks until an interrupt signal is received.\nfunc (r *Runner) Run() error {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\tr.Start()\n\tfor sig := range c {\n\t\tif sig == os.Interrupt {\n\t\t\tr.log.Info(\"Received interrupt, shutting down\")\n\t\t\tr.Stop()\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"gopkg.in\/h2non\/gock.v1\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\nfunc TestRouter(t *testing.T) {\n\tapp := App()\n\n\tConvey(\"the index page\", t, func() {\n\n\t\tConvey(\"should return OK\", func() {\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusOK)\n\t\t\tSo(res.Body.String(), ShouldEqual, \"Welcome!\")\n\t\t})\n\n\t})\n\n\tConvey(\"CAS authentication\", t, func() {\n\n\t\tConvey(\"should redirect to CAS when not logged in\", func() {\n\t\t\tgock.New(\"https:\/\/fed.princeton.edu\").\n\t\t\t\tGet(\"\/cas\/validate\").\n\t\t\t\tReply(200).\n\t\t\t\tBodyString(\"no\\n\\n\")\n\t\t\tdefer gock.Off()\n\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/login\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusFound)\n\t\t})\n\n\t\t\/\/ TODO: Figure out why this test doesn't work\n\t\tSkipConvey(\"should return the proper user when logged in\", func() {\n\t\t\tgock.New(\"https:\/\/fed.princeton.edu\").\n\t\t\t\tGet(\"\/cas\/validate\").\n\t\t\t\tReply(200).\n\t\t\t\tBodyString(\"yes\\ntestuser\\n\")\n\t\t\tdefer gock.Off()\n\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/login\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusOK)\n\t\t\tSo(res.Body.String(), ShouldEqual, \"testuser\")\n\t\t})\n\n\t})\n}\nadd CORS testspackage server\n\nimport (\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"gopkg.in\/h2non\/gock.v1\"\n\t\"net\/http\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestRouter(t *testing.T) {\n\tapp := App()\n\n\tConvey(\"the index page\", t, func() {\n\n\t\tConvey(\"should return OK\", func() {\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusOK)\n\t\t\tSo(res.Body.String(), ShouldEqual, \"Welcome!\")\n\t\t})\n\n\t\tConvey(\"should have CORS headers\", func() {\n\t\t\torigin := os.Getenv(\"CLIENT_ROOT\")\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\t\t\treq.Header.Add(\"Origin\", origin)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Header().Get(\"Access-Control-Allow-Origin\"), ShouldEqual, origin)\n\t\t})\n\n\t\tConvey(\"should not have global CORS headers\", func() {\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\t\t\treq.Header.Add(\"Origin\", \"http:\/\/example.com\/\")\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Header().Get(\"Access-Control-Allow-Origin\"), ShouldEqual, \"\")\n\t\t})\n\n\t})\n\n\tConvey(\"CAS authentication\", t, func() {\n\n\t\tConvey(\"should redirect to CAS when not logged in\", func() {\n\t\t\tgock.New(\"https:\/\/fed.princeton.edu\").\n\t\t\t\tGet(\"\/cas\/validate\").\n\t\t\t\tReply(200).\n\t\t\t\tBodyString(\"no\\n\\n\")\n\t\t\tdefer gock.Off()\n\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/login\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusFound)\n\t\t})\n\n\t\t\/\/ TODO: Figure out why this test doesn't work\n\t\tSkipConvey(\"should return the proper user when logged in\", func() {\n\t\t\tgock.New(\"https:\/\/fed.princeton.edu\").\n\t\t\t\tGet(\"\/cas\/validate\").\n\t\t\t\tReply(200).\n\t\t\t\tBodyString(\"yes\\ntestuser\\n\")\n\t\t\tdefer gock.Off()\n\n\t\t\treq, _ := http.NewRequest(\"GET\", \"\/login\", nil)\n\t\t\tres := executeRequest(app, req)\n\n\t\t\tSo(res.Code, ShouldEqual, http.StatusOK)\n\t\t\tSo(res.Body.String(), ShouldEqual, \"testuser\")\n\t\t})\n\n\t})\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n \"bytes\"\n \"strings\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/pebbe\/util\"\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n . \"gopkg.in\/check.v1\"\n)\n\ntype ServerSuite struct {\n\tSession *mgo.Session\n\tRouter *mux.Router\n\tServer *httptest.Server\n\tFixtureId string\n}\n\nfunc Test(t *testing.T) { TestingT(t) }\n\nvar _ = Suite(&ServerSuite{})\n\nfunc (s *ServerSuite) SetUpSuite(c *C) {\n\n\t\/\/ Set up the database\n var err error\n\ts.Session, err = mgo.Dial(\"localhost\")\n\tutil.CheckErr(err)\n\tDatabase = s.Session.DB(\"fhir-test\")\n\n\t\/\/ Build routes for testing\n\ts.Router = mux.NewRouter()\n\ts.Router.StrictSlash(true)\n\ts.Router.KeepContext = true\n\tRegisterRoutes(s.Router, make(map[string][]negroni.Handler))\n\n\t\/\/ Create httptest server\n\ts.Server = httptest.NewServer(s.Router)\n\n\t\/\/ Add patient fixture\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := LoadPatientFromFixture(\"..\/fixtures\/patient-example-a.json\")\n\ti := bson.NewObjectId()\n\ts.FixtureId = i.Hex()\n\tpatient.Id = s.FixtureId\n\terr = patientCollection.Insert(patient)\n\tutil.CheckErr(err)\n}\n\nfunc (s *ServerSuite) TearDownSuite(c *C) {\n Database.DropDatabase()\n s.Session.Close()\n\ts.Server.Close()\n}\n\nfunc (s *ServerSuite) TestGetPatient(c *C) {\n\tres, err := http.Get(s.Server.URL + \"\/Patient\/\" + s.FixtureId)\n\tutil.CheckErr(err)\n\n decoder := json.NewDecoder(res.Body)\n patient := &models.Patient{}\n err = decoder.Decode(patient)\n util.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Donald\")\n}\n\nfunc (s *ServerSuite) TestShowPatient(c *C) {\n res, err := http.Get(s.Server.URL + \"\/Patient\")\n util.CheckErr(err)\n\n decoder := json.NewDecoder(res.Body)\n patientBundle := &models.PatientBundle{}\n err = decoder.Decode(patientBundle)\n util.CheckErr(err)\n\n var result []models.Patient\n collection := Database.C(\"patients\")\n iter := collection.Find(nil).Iter()\n err = iter.All(&result)\n util.CheckErr(err)\n\n c.Assert(patientBundle.TotalResults, Equals, len(result))\n c.Assert(patientBundle.Title, Equals, \"Patient Index\")\n}\n\nfunc (s *ServerSuite) TestCreatePatient(c *C) {\n createPatient := LoadPatientFromFixture(\"..\/fixtures\/patient-example-b.json\")\n var buf bytes.Buffer\n encoder := json.NewEncoder(&buf)\n encoder.Encode(createPatient)\n res, err := http.Post(s.Server.URL + \"\/Patient\", \"application\/json\", &buf)\n util.CheckErr(err)\n\n splitLocation := strings.Split(res.Header[\"Location\"][0], \"\/\")\n createdPatientId := splitLocation[len(splitLocation)-1]\n\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := models.Patient{}\n\terr = patientCollection.Find(bson.M{\"_id\": createdPatientId}).One(&patient)\n\tutil.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Daffy\")\n}\n\nfunc (s *ServerSuite) TestUpdatePatient(c *C) {\n updatePatient := LoadPatientFromFixture(\"..\/fixtures\/patient-example-c.json\")\n var buf bytes.Buffer\n encoder := json.NewEncoder(&buf)\n encoder.Encode(updatePatient)\n\n client := &http.Client{}\n req, err := http.NewRequest(\"PUT\", s.Server.URL + \"\/Patient\/\" + s.FixtureId, &buf)\n util.CheckErr(err)\n _, err = client.Do(req)\n\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := models.Patient{}\n\terr = patientCollection.Find(bson.M{\"_id\": s.FixtureId}).One(&patient)\n\tutil.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Darkwing\")\n}\n\nfunc (s *ServerSuite) TestDeletePatient(c *C) {\n\n createPatient := LoadPatientFromFixture(\"..\/fixtures\/patient-example-d.json\")\n var buf bytes.Buffer\n encoder := json.NewEncoder(&buf)\n encoder.Encode(createPatient)\n res, err := http.Post(s.Server.URL + \"\/Patient\", \"application\/json\", &buf)\n util.CheckErr(err)\n\n splitLocation := strings.Split(res.Header[\"Location\"][0], \"\/\")\n createdPatientId := splitLocation[len(splitLocation)-1]\n\n client := &http.Client{}\n req, err := http.NewRequest(\"DELETE\", s.Server.URL + \"\/Patient\/\" + createdPatientId, nil)\n util.CheckErr(err)\n _, err = client.Do(req)\n\n patientCollection := Database.C(\"patients\")\n\n count, err := patientCollection.Find(bson.M{\"_id\": createdPatientId}).Count()\n c.Assert(count, Equals, 0)\n}\n\nfunc LoadPatientFromFixture(fileName string) *models.Patient {\n\tdata, err := os.Open(fileName)\n\tdefer data.Close()\n\tutil.CheckErr(err)\n\tdecoder := json.NewDecoder(data)\n\tpatient := &models.Patient{}\n\terr = decoder.Decode(patient)\n\tutil.CheckErr(err)\n\treturn patient\n}\nrefactored test suite to avoid creating patient structs and re-encoding them to json. http tests now use raw json from fixturespackage server\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n \"strings\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/pebbe\/util\"\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n . \"gopkg.in\/check.v1\"\n)\n\ntype ServerSuite struct {\n\tSession *mgo.Session\n\tRouter *mux.Router\n\tServer *httptest.Server\n\tFixtureId string\n}\n\nfunc Test(t *testing.T) { TestingT(t) }\n\nvar _ = Suite(&ServerSuite{})\n\nfunc (s *ServerSuite) SetUpSuite(c *C) {\n\n\t\/\/ Set up the database\n var err error\n\ts.Session, err = mgo.Dial(\"localhost\")\n\tutil.CheckErr(err)\n\tDatabase = s.Session.DB(\"fhir-test\")\n\n\t\/\/ Build routes for testing\n\ts.Router = mux.NewRouter()\n\ts.Router.StrictSlash(true)\n\ts.Router.KeepContext = true\n\tRegisterRoutes(s.Router, make(map[string][]negroni.Handler))\n\n\t\/\/ Create httptest server\n\ts.Server = httptest.NewServer(s.Router)\n\n\t\/\/ Add patient fixture\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := LoadPatientFromFixture(\"..\/fixtures\/patient-example-a.json\")\n\ti := bson.NewObjectId()\n\ts.FixtureId = i.Hex()\n\tpatient.Id = s.FixtureId\n\terr = patientCollection.Insert(patient)\n\tutil.CheckErr(err)\n}\n\nfunc (s *ServerSuite) TearDownSuite(c *C) {\n Database.DropDatabase()\n s.Session.Close()\n\ts.Server.Close()\n}\n\nfunc (s *ServerSuite) TestGetPatient(c *C) {\n\tres, err := http.Get(s.Server.URL + \"\/Patient\/\" + s.FixtureId)\n\tutil.CheckErr(err)\n\n decoder := json.NewDecoder(res.Body)\n patient := &models.Patient{}\n err = decoder.Decode(patient)\n util.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Donald\")\n}\n\nfunc (s *ServerSuite) TestShowPatient(c *C) {\n res, err := http.Get(s.Server.URL + \"\/Patient\")\n util.CheckErr(err)\n\n decoder := json.NewDecoder(res.Body)\n patientBundle := &models.PatientBundle{}\n err = decoder.Decode(patientBundle)\n util.CheckErr(err)\n\n var result []models.Patient\n collection := Database.C(\"patients\")\n iter := collection.Find(nil).Iter()\n err = iter.All(&result)\n util.CheckErr(err)\n\n c.Assert(patientBundle.TotalResults, Equals, len(result))\n c.Assert(patientBundle.Title, Equals, \"Patient Index\")\n}\n\nfunc (s *ServerSuite) TestCreatePatient(c *C) {\n\tdata, err := os.Open(\"..\/fixtures\/patient-example-b.json\")\n\tdefer data.Close()\n\tutil.CheckErr(err)\n res, err := http.Post(s.Server.URL + \"\/Patient\", \"application\/json\", data)\n util.CheckErr(err)\n\n splitLocation := strings.Split(res.Header[\"Location\"][0], \"\/\")\n createdPatientId := splitLocation[len(splitLocation)-1]\n\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := models.Patient{}\n\terr = patientCollection.Find(bson.M{\"_id\": createdPatientId}).One(&patient)\n\tutil.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Daffy\")\n}\n\nfunc (s *ServerSuite) TestUpdatePatient(c *C) {\n\tdata, err := os.Open(\"..\/fixtures\/patient-example-c.json\")\n\tdefer data.Close()\n\tutil.CheckErr(err)\n\n client := &http.Client{}\n req, err := http.NewRequest(\"PUT\", s.Server.URL + \"\/Patient\/\" + s.FixtureId, data)\n util.CheckErr(err)\n _, err = client.Do(req)\n\n\tpatientCollection := Database.C(\"patients\")\n\tpatient := models.Patient{}\n\terr = patientCollection.Find(bson.M{\"_id\": s.FixtureId}).One(&patient)\n\tutil.CheckErr(err)\n c.Assert(patient.Name[0].Family[0], Equals, \"Darkwing\")\n}\n\nfunc (s *ServerSuite) TestDeletePatient(c *C) {\n\n\tdata, err := os.Open(\"..\/fixtures\/patient-example-d.json\")\n\tdefer data.Close()\n\tutil.CheckErr(err)\n res, err := http.Post(s.Server.URL + \"\/Patient\", \"application\/json\", data)\n util.CheckErr(err)\n\n splitLocation := strings.Split(res.Header[\"Location\"][0], \"\/\")\n createdPatientId := splitLocation[len(splitLocation)-1]\n\n client := &http.Client{}\n req, err := http.NewRequest(\"DELETE\", s.Server.URL + \"\/Patient\/\" + createdPatientId, nil)\n util.CheckErr(err)\n _, err = client.Do(req)\n\n patientCollection := Database.C(\"patients\")\n\n count, err := patientCollection.Find(bson.M{\"_id\": createdPatientId}).Count()\n c.Assert(count, Equals, 0)\n}\n\nfunc LoadPatientFromFixture(fileName string) *models.Patient {\n\tdata, err := os.Open(fileName)\n\tdefer data.Close()\n\tutil.CheckErr(err)\n\tdecoder := json.NewDecoder(data)\n\tpatient := &models.Patient{}\n\terr = decoder.Decode(patient)\n\tutil.CheckErr(err)\n\treturn patient\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Xing Xing .\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a commercial\n\/\/ license that can be found in the LICENSE file.\n\npackage iptpool\n\nimport (\n\t\"sync\"\n)\n\nvar (\n\tDefaultMaxIdle = 32\n)\n\ntype CreateFunc func() ScriptIpt\ntype EventFunc func(ScriptIpt) error\n\ntype ScriptIpt interface {\n\tExec(name string, params interface{}) error\n\tInit(path string) error\n\tFinal() error\n\tBind(name string, item interface{}) error\n\tState() interface{}\n}\n\ntype IptPool struct {\n\tp sync.Pool\n\tOnCreate EventFunc\n}\n\nfunc NewIptPool(create CreateFunc) *IptPool {\n\tiptPool := &IptPool{}\n\tf := func() interface{} {\n\t\tipt := create()\n\t\tif iptPool.OnCreate != nil {\n\t\t\tiptPool.OnCreate(ipt)\n\t\t}\n\t\treturn ipt\n\t}\n\tiptPool.p = sync.Pool{New: f}\n\treturn iptPool\n}\n\nfunc (pool *IptPool) Get() (ipt ScriptIpt) {\n\treturn pool.p.Get().(ScriptIpt)\n}\n\nfunc (pool *IptPool) Put(ipt ScriptIpt) {\n\tpool.p.Put(ipt)\n}\nno need to expose\/\/ Copyright 2013 Xing Xing .\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a commercial\n\/\/ license that can be found in the LICENSE file.\n\npackage iptpool\n\nimport (\n\t\"sync\"\n)\n\nvar (\n\tDefaultMaxIdle = 32\n)\n\ntype CreateFunc func() ScriptIpt\ntype EventFunc func(ScriptIpt) error\n\ntype ScriptIpt interface {\n\tExec(name string, params interface{}) error\n\tInit(path string) error\n\tFinal() error\n\tBind(name string, item interface{}) error\n}\n\ntype IptPool struct {\n\tp sync.Pool\n\tOnCreate EventFunc\n}\n\nfunc NewIptPool(create CreateFunc) *IptPool {\n\tiptPool := &IptPool{}\n\tf := func() interface{} {\n\t\tipt := create()\n\t\tif iptPool.OnCreate != nil {\n\t\t\tiptPool.OnCreate(ipt)\n\t\t}\n\t\treturn ipt\n\t}\n\tiptPool.p = sync.Pool{New: f}\n\treturn iptPool\n}\n\nfunc (pool *IptPool) Get() (ipt ScriptIpt) {\n\treturn pool.p.Get().(ScriptIpt)\n}\n\nfunc (pool *IptPool) Put(ipt ScriptIpt) {\n\tpool.p.Put(ipt)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Google, Inc. All rights reserved.\n\/\/ Copyright 2009-2011 Andreas Krennmair. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\npackage layers\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/google\/gopacket\"\n\t\"net\"\n)\n\n\/\/ EthernetBroadcast is the broadcast MAC address used by Ethernet.\nvar EthernetBroadcast = net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}\n\n\/\/ Ethernet is the layer for Ethernet frame headers.\ntype Ethernet struct {\n\tBaseLayer\n\tSrcMAC, DstMAC net.HardwareAddr\n\tEthernetType EthernetType\n\t\/\/ Length is only set if a length field exists within this header. Ethernet\n\t\/\/ headers follow two different standards, one that uses an EthernetType, the\n\t\/\/ other which defines a length the follows with a LLC header (802.3). If the\n\t\/\/ former is the case, we set EthernetType and Length stays 0. In the latter\n\t\/\/ case, we set Length and EthernetType = EthernetTypeLLC.\n\tLength uint16\n}\n\n\/\/ LayerType returns LayerTypeEthernet\nfunc (e *Ethernet) LayerType() gopacket.LayerType { return LayerTypeEthernet }\n\nfunc (e *Ethernet) LinkFlow() gopacket.Flow {\n\treturn gopacket.NewFlow(EndpointMAC, e.SrcMAC, e.DstMAC)\n}\n\nfunc (eth *Ethernet) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {\n\tif len(data) < 14 {\n\t\treturn errors.New(\"Ethernet packet too small\")\n\t}\n\teth.DstMAC = net.HardwareAddr(data[0:6])\n\teth.SrcMAC = net.HardwareAddr(data[6:12])\n\teth.EthernetType = EthernetType(binary.BigEndian.Uint16(data[12:14]))\n\teth.BaseLayer = BaseLayer{data[:14], data[14:]}\n\tif eth.EthernetType < 0x0600 {\n\t\teth.Length = uint16(eth.EthernetType)\n\t\teth.EthernetType = EthernetTypeLLC\n\t\tif cmp := len(eth.Payload) - int(eth.Length); cmp < 0 {\n\t\t\tdf.SetTruncated()\n\t\t} else if cmp > 0 {\n\t\t\t\/\/ Strip off bytes at the end, since we have too many bytes\n\t\t\teth.Payload = eth.Payload[:len(eth.Payload)-cmp]\n\t\t}\n\t\t\/\/\tfmt.Println(eth)\n\t}\n\treturn nil\n}\n\n\/\/ SerializeTo writes the serialized form of this layer into the\n\/\/ SerializationBuffer, implementing gopacket.SerializableLayer.\n\/\/ See the docs for gopacket.SerializableLayer for more info.\nfunc (eth *Ethernet) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {\n\tif len(eth.DstMAC) != 6 {\n\t\treturn fmt.Errorf(\"invalid dst MAC: %v\", eth.DstMAC)\n\t}\n\tif len(eth.SrcMAC) != 6 {\n\t\treturn fmt.Errorf(\"invalid src MAC: %v\", eth.SrcMAC)\n\t}\n\tpayload := b.Bytes()\n\tbytes, err := b.PrependBytes(14)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcopy(bytes, eth.DstMAC)\n\tcopy(bytes[6:], eth.SrcMAC)\n\tif eth.Length != 0 || eth.EthernetType == EthernetTypeLLC {\n\t\tif opts.FixLengths {\n\t\t\teth.Length = uint16(len(payload))\n\t\t}\n\t\tif eth.EthernetType != EthernetTypeLLC {\n\t\t\treturn fmt.Errorf(\"ethernet type %v not compatible with length value %v\", eth.EthernetType, eth.Length)\n\t\t} else if eth.Length > 0x0600 {\n\t\t\treturn fmt.Errorf(\"invalid ethernet length %v\", eth.Length)\n\t\t}\n\t\tbinary.BigEndian.PutUint16(bytes[12:], eth.Length)\n\t} else {\n\t\tbinary.BigEndian.PutUint16(bytes[12:], uint16(eth.EthernetType))\n\t}\n\tlength := len(b.Bytes())\n\tif length < 60 {\n\t\t\/\/ Pad out to 60 bytes.\n\t\tpadding, err := b.AppendBytes(60 - length)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcopy(padding, lotsOfZeros[:])\n\t}\n\treturn nil\n}\n\nfunc (eth *Ethernet) CanDecode() gopacket.LayerClass {\n\treturn LayerTypeEthernet\n}\n\nfunc (eth *Ethernet) NextLayerType() gopacket.LayerType {\n\treturn eth.EthernetType.LayerType()\n}\n\nfunc decodeEthernet(data []byte, p gopacket.PacketBuilder) error {\n\teth := &Ethernet{}\n\terr := eth.DecodeFromBytes(data, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.AddLayer(eth)\n\tp.SetLinkLayer(eth)\n\treturn p.NextDecoder(eth.EthernetType)\n}\nReset Length field in Ethernet.DecodeFromBytes\/\/ Copyright 2012 Google, Inc. All rights reserved.\n\/\/ Copyright 2009-2011 Andreas Krennmair. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\npackage layers\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/google\/gopacket\"\n\t\"net\"\n)\n\n\/\/ EthernetBroadcast is the broadcast MAC address used by Ethernet.\nvar EthernetBroadcast = net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}\n\n\/\/ Ethernet is the layer for Ethernet frame headers.\ntype Ethernet struct {\n\tBaseLayer\n\tSrcMAC, DstMAC net.HardwareAddr\n\tEthernetType EthernetType\n\t\/\/ Length is only set if a length field exists within this header. Ethernet\n\t\/\/ headers follow two different standards, one that uses an EthernetType, the\n\t\/\/ other which defines a length the follows with a LLC header (802.3). If the\n\t\/\/ former is the case, we set EthernetType and Length stays 0. In the latter\n\t\/\/ case, we set Length and EthernetType = EthernetTypeLLC.\n\tLength uint16\n}\n\n\/\/ LayerType returns LayerTypeEthernet\nfunc (e *Ethernet) LayerType() gopacket.LayerType { return LayerTypeEthernet }\n\nfunc (e *Ethernet) LinkFlow() gopacket.Flow {\n\treturn gopacket.NewFlow(EndpointMAC, e.SrcMAC, e.DstMAC)\n}\n\nfunc (eth *Ethernet) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {\n\tif len(data) < 14 {\n\t\treturn errors.New(\"Ethernet packet too small\")\n\t}\n\teth.DstMAC = net.HardwareAddr(data[0:6])\n\teth.SrcMAC = net.HardwareAddr(data[6:12])\n\teth.EthernetType = EthernetType(binary.BigEndian.Uint16(data[12:14]))\n\teth.BaseLayer = BaseLayer{data[:14], data[14:]}\n\teth.Length = 0\n\tif eth.EthernetType < 0x0600 {\n\t\teth.Length = uint16(eth.EthernetType)\n\t\teth.EthernetType = EthernetTypeLLC\n\t\tif cmp := len(eth.Payload) - int(eth.Length); cmp < 0 {\n\t\t\tdf.SetTruncated()\n\t\t} else if cmp > 0 {\n\t\t\t\/\/ Strip off bytes at the end, since we have too many bytes\n\t\t\teth.Payload = eth.Payload[:len(eth.Payload)-cmp]\n\t\t}\n\t\t\/\/\tfmt.Println(eth)\n\t}\n\treturn nil\n}\n\n\/\/ SerializeTo writes the serialized form of this layer into the\n\/\/ SerializationBuffer, implementing gopacket.SerializableLayer.\n\/\/ See the docs for gopacket.SerializableLayer for more info.\nfunc (eth *Ethernet) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {\n\tif len(eth.DstMAC) != 6 {\n\t\treturn fmt.Errorf(\"invalid dst MAC: %v\", eth.DstMAC)\n\t}\n\tif len(eth.SrcMAC) != 6 {\n\t\treturn fmt.Errorf(\"invalid src MAC: %v\", eth.SrcMAC)\n\t}\n\tpayload := b.Bytes()\n\tbytes, err := b.PrependBytes(14)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcopy(bytes, eth.DstMAC)\n\tcopy(bytes[6:], eth.SrcMAC)\n\tif eth.Length != 0 || eth.EthernetType == EthernetTypeLLC {\n\t\tif opts.FixLengths {\n\t\t\teth.Length = uint16(len(payload))\n\t\t}\n\t\tif eth.EthernetType != EthernetTypeLLC {\n\t\t\treturn fmt.Errorf(\"ethernet type %v not compatible with length value %v\", eth.EthernetType, eth.Length)\n\t\t} else if eth.Length > 0x0600 {\n\t\t\treturn fmt.Errorf(\"invalid ethernet length %v\", eth.Length)\n\t\t}\n\t\tbinary.BigEndian.PutUint16(bytes[12:], eth.Length)\n\t} else {\n\t\tbinary.BigEndian.PutUint16(bytes[12:], uint16(eth.EthernetType))\n\t}\n\tlength := len(b.Bytes())\n\tif length < 60 {\n\t\t\/\/ Pad out to 60 bytes.\n\t\tpadding, err := b.AppendBytes(60 - length)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcopy(padding, lotsOfZeros[:])\n\t}\n\treturn nil\n}\n\nfunc (eth *Ethernet) CanDecode() gopacket.LayerClass {\n\treturn LayerTypeEthernet\n}\n\nfunc (eth *Ethernet) NextLayerType() gopacket.LayerType {\n\treturn eth.EthernetType.LayerType()\n}\n\nfunc decodeEthernet(data []byte, p gopacket.PacketBuilder) error {\n\teth := &Ethernet{}\n\terr := eth.DecodeFromBytes(data, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.AddLayer(eth)\n\tp.SetLinkLayer(eth)\n\treturn p.NextDecoder(eth.EthernetType)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\n\t\"github.com\/sdboyer\/gps\"\n)\n\ntype lock struct {\n\tMemo []byte\n\tP []gps.LockedProject\n}\n\ntype rawLock struct {\n\tMemo string `json:\"memo\"`\n\tP []lockedDep `json:\"projects\"`\n}\n\ntype lockedDep struct {\n\tName string `json:\"name\"`\n\tVersion string `json:\"version,omitempty\"`\n\tBranch string `json:\"branch,omitempty\"`\n\tRevision string `json:\"revision\"`\n\tRepository string `json:\"repo,omitempty\"`\n\tPackages []string `json:\"packages\"`\n}\n\nfunc readLock(r io.Reader) (*lock, error) {\n\trl := rawLock{}\n\terr := json.NewDecoder(r).Decode(&rl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb, err := hex.DecodeString(rl.Memo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid hash digest in lock's memo field\")\n\t}\n\tl := &lock{\n\t\tMemo: b,\n\t\tP: make([]gps.LockedProject, len(rl.P)),\n\t}\n\n\tfor i, ld := range rl.P {\n\t\tr := gps.Revision(ld.Revision)\n\n\t\tvar v gps.Version\n\t\tif ld.Version != \"\" {\n\t\t\tif ld.Branch != \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"lock file specified both a branch (%s) and version (%s) for %s\", ld.Branch, ld.Version, ld.Name)\n\t\t\t}\n\t\t\tv = gps.NewVersion(ld.Version).Is(r)\n\t\t} else if ld.Branch != \"\" {\n\t\t\tv = gps.NewBranch(ld.Branch).Is(r)\n\t\t} else if r == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"lock file has entry for %s, but specifies no version\", ld.Name)\n\t\t} else {\n\t\t\tv = r\n\t\t}\n\n\t\tid := gps.ProjectIdentifier{\n\t\t\tProjectRoot: gps.ProjectRoot(ld.Name),\n\t\t\tSource: ld.Repository,\n\t\t}\n\t\tl.P[i] = gps.NewLockedProject(id, v, ld.Packages)\n\t}\n\n\treturn l, nil\n}\n\nfunc (l *lock) InputHash() []byte {\n\treturn l.Memo\n}\n\nfunc (l *lock) Projects() []gps.LockedProject {\n\treturn l.P\n}\n\nfunc (l *lock) MarshalJSON() ([]byte, error) {\n\traw := rawLock{\n\t\tMemo: hex.EncodeToString(l.Memo),\n\t\tP: make([]lockedDep, len(l.P)),\n\t}\n\n\tsort.Sort(sortedLockedProjects(l.P))\n\n\tfor k, lp := range l.P {\n\t\tid := lp.Ident()\n\t\tld := lockedDep{\n\t\t\tName: string(id.ProjectRoot),\n\t\t\tRepository: id.Source,\n\t\t\tPackages: lp.Packages(),\n\t\t}\n\n\t\tv := lp.Version()\n\t\t\/\/ Figure out how to get the underlying revision\n\t\tswitch tv := v.(type) {\n\t\tcase gps.UnpairedVersion:\n\t\t\t\/\/ TODO we could error here, if we want to be very defensive about not\n\t\t\t\/\/ allowing a lock to be written if without an immmutable revision\n\t\tcase gps.Revision:\n\t\t\tld.Revision = tv.String()\n\t\tcase gps.PairedVersion:\n\t\t\tld.Revision = tv.Underlying().String()\n\t\t}\n\n\t\tswitch v.Type() {\n\t\tcase gps.IsBranch:\n\t\t\tld.Branch = v.String()\n\t\tcase gps.IsSemver, gps.IsVersion:\n\t\t\tld.Version = v.String()\n\t\t}\n\n\t\traw.P[k] = ld\n\t}\n\n\t\/\/ TODO sort output - #15\n\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\tenc.SetIndent(\"\", \" \")\n\tenc.SetEscapeHTML(false)\n\terr := enc.Encode(raw)\n\n\treturn buf.Bytes(), err\n}\n\n\/\/ lockFromInterface converts an arbitrary gps.Lock to dep's representation of a\n\/\/ lock. If the input is already dep's *lock, the input is returned directly.\n\/\/\n\/\/ Data is defensively copied wherever necessary to ensure the resulting *lock\n\/\/ shares no memory with the original lock.\n\/\/\n\/\/ As gps.Solution is a superset of gps.Lock, this can also be used to convert\n\/\/ solutions to dep's lock form.\nfunc lockFromInterface(in gps.Lock) *lock {\n\tif in == nil {\n\t\treturn nil\n\t} else if l, ok := in.(*lock); ok {\n\t\treturn l\n\t}\n\n\th, p := in.InputHash(), in.Projects()\n\n\tl := &lock{\n\t\tMemo: make([]byte, len(h)),\n\t\tP: make([]gps.LockedProject, len(p)),\n\t}\n\n\tcopy(l.Memo, h)\n\tcopy(l.P, p)\n\treturn l\n}\n\ntype sortedLockedProjects []gps.LockedProject\n\nfunc (s sortedLockedProjects) Len() int { return len(s) }\nfunc (s sortedLockedProjects) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s sortedLockedProjects) Less(i, j int) bool {\n\tl, r := s[i].Ident(), s[j].Ident()\n\n\tif l.ProjectRoot < r.ProjectRoot {\n\t\treturn true\n\t}\n\tif r.ProjectRoot < l.ProjectRoot {\n\t\treturn false\n\t}\n\n\treturn l.Source < r.Source\n}\nAdd locksAreEquivalent()\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\n\t\"github.com\/sdboyer\/gps\"\n)\n\ntype lock struct {\n\tMemo []byte\n\tP []gps.LockedProject\n}\n\ntype rawLock struct {\n\tMemo string `json:\"memo\"`\n\tP []lockedDep `json:\"projects\"`\n}\n\ntype lockedDep struct {\n\tName string `json:\"name\"`\n\tVersion string `json:\"version,omitempty\"`\n\tBranch string `json:\"branch,omitempty\"`\n\tRevision string `json:\"revision\"`\n\tRepository string `json:\"repo,omitempty\"`\n\tPackages []string `json:\"packages\"`\n}\n\nfunc readLock(r io.Reader) (*lock, error) {\n\trl := rawLock{}\n\terr := json.NewDecoder(r).Decode(&rl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb, err := hex.DecodeString(rl.Memo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid hash digest in lock's memo field\")\n\t}\n\tl := &lock{\n\t\tMemo: b,\n\t\tP: make([]gps.LockedProject, len(rl.P)),\n\t}\n\n\tfor i, ld := range rl.P {\n\t\tr := gps.Revision(ld.Revision)\n\n\t\tvar v gps.Version\n\t\tif ld.Version != \"\" {\n\t\t\tif ld.Branch != \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"lock file specified both a branch (%s) and version (%s) for %s\", ld.Branch, ld.Version, ld.Name)\n\t\t\t}\n\t\t\tv = gps.NewVersion(ld.Version).Is(r)\n\t\t} else if ld.Branch != \"\" {\n\t\t\tv = gps.NewBranch(ld.Branch).Is(r)\n\t\t} else if r == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"lock file has entry for %s, but specifies no version\", ld.Name)\n\t\t} else {\n\t\t\tv = r\n\t\t}\n\n\t\tid := gps.ProjectIdentifier{\n\t\t\tProjectRoot: gps.ProjectRoot(ld.Name),\n\t\t\tSource: ld.Repository,\n\t\t}\n\t\tl.P[i] = gps.NewLockedProject(id, v, ld.Packages)\n\t}\n\n\treturn l, nil\n}\n\nfunc (l *lock) InputHash() []byte {\n\treturn l.Memo\n}\n\nfunc (l *lock) Projects() []gps.LockedProject {\n\treturn l.P\n}\n\nfunc (l *lock) MarshalJSON() ([]byte, error) {\n\traw := rawLock{\n\t\tMemo: hex.EncodeToString(l.Memo),\n\t\tP: make([]lockedDep, len(l.P)),\n\t}\n\n\tsort.Sort(sortedLockedProjects(l.P))\n\n\tfor k, lp := range l.P {\n\t\tid := lp.Ident()\n\t\tld := lockedDep{\n\t\t\tName: string(id.ProjectRoot),\n\t\t\tRepository: id.Source,\n\t\t\tPackages: lp.Packages(),\n\t\t}\n\n\t\tv := lp.Version()\n\t\t\/\/ Figure out how to get the underlying revision\n\t\tswitch tv := v.(type) {\n\t\tcase gps.UnpairedVersion:\n\t\t\t\/\/ TODO we could error here, if we want to be very defensive about not\n\t\t\t\/\/ allowing a lock to be written if without an immmutable revision\n\t\tcase gps.Revision:\n\t\t\tld.Revision = tv.String()\n\t\tcase gps.PairedVersion:\n\t\t\tld.Revision = tv.Underlying().String()\n\t\t}\n\n\t\tswitch v.Type() {\n\t\tcase gps.IsBranch:\n\t\t\tld.Branch = v.String()\n\t\tcase gps.IsSemver, gps.IsVersion:\n\t\t\tld.Version = v.String()\n\t\t}\n\n\t\traw.P[k] = ld\n\t}\n\n\t\/\/ TODO sort output - #15\n\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\tenc.SetIndent(\"\", \" \")\n\tenc.SetEscapeHTML(false)\n\terr := enc.Encode(raw)\n\n\treturn buf.Bytes(), err\n}\n\n\/\/ lockFromInterface converts an arbitrary gps.Lock to dep's representation of a\n\/\/ lock. If the input is already dep's *lock, the input is returned directly.\n\/\/\n\/\/ Data is defensively copied wherever necessary to ensure the resulting *lock\n\/\/ shares no memory with the original lock.\n\/\/\n\/\/ As gps.Solution is a superset of gps.Lock, this can also be used to convert\n\/\/ solutions to dep's lock form.\nfunc lockFromInterface(in gps.Lock) *lock {\n\tif in == nil {\n\t\treturn nil\n\t} else if l, ok := in.(*lock); ok {\n\t\treturn l\n\t}\n\n\th, p := in.InputHash(), in.Projects()\n\n\tl := &lock{\n\t\tMemo: make([]byte, len(h)),\n\t\tP: make([]gps.LockedProject, len(p)),\n\t}\n\n\tcopy(l.Memo, h)\n\tcopy(l.P, p)\n\treturn l\n}\n\ntype sortedLockedProjects []gps.LockedProject\n\nfunc (s sortedLockedProjects) Len() int { return len(s) }\nfunc (s sortedLockedProjects) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s sortedLockedProjects) Less(i, j int) bool {\n\tl, r := s[i].Ident(), s[j].Ident()\n\n\tif l.ProjectRoot < r.ProjectRoot {\n\t\treturn true\n\t}\n\tif r.ProjectRoot < l.ProjectRoot {\n\t\treturn false\n\t}\n\n\treturn l.Source < r.Source\n}\n\n\/\/ locksAreEquivalent compares two locks to see if they differ. If EITHER lock\n\/\/ is nil, or their memos do not match, or any projects differ, then false is\n\/\/ returned.\nfunc locksAreEquivalent(l, r *lock) bool {\n\tif l == nil || r == nil {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(l.Memo, r.Memo) {\n\t\treturn false\n\t}\n\n\tif len(l.P) != len(r.P) {\n\t\treturn false\n\t}\n\n\tsort.Sort(sortedLockedProjects(l.P))\n\tsort.Sort(sortedLockedProjects(r.P))\n\n\tfor k, lp := range l.P {\n\t\t\/\/ TODO(sdboyer) gps will be adding a func to compare LockedProjects in the next\n\t\t\/\/ version; we can swap that in here when it lands\n\t\trp := r.P[k]\n\t\tif lp.Ident() != rp.Ident() {\n\t\t\treturn false\n\t\t}\n\n\t\tlpkg, rpkg := lp.Packages(), rp.Packages()\n\t\tif !reflect.DeepEqual(lpkg, rpkg) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n<|endoftext|>"} {"text":"package export\n\nimport (\n\tcc \"github.com\/pivotalservices\/cf-mgmt\/cloudcontroller\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/config\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/organization\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/space\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/uaac\"\n\t\"github.com\/xchapter7x\/lo\"\n)\n\n\/\/NewExportManager Creates a new instance of the ImportConfig manager\nfunc NewExportManager(\n\tconfigDir string,\n\tuaacMgr uaac.Manager,\n\tcloudController cc.Manager) Manager {\n\treturn &DefaultImportManager{\n\t\tConfigDir: configDir,\n\t\tUAACMgr: uaacMgr,\n\t\tCloudController: cloudController,\n\t}\n}\n\n\/\/ExportConfig Imports org and space configuration from an existing CF instance\n\/\/Entries part of excludedOrgs and excludedSpaces are not included in the import\nfunc (im *DefaultImportManager) ExportConfig(excludedOrgs map[string]string, excludedSpaces map[string]string) error {\n\t\/\/Get all the users from the foundation\n\tuserIDToUserMap, err := im.UAACMgr.UsersByID()\n\tif err != nil {\n\t\tlo.G.Error(\"Unable to retrieve users\")\n\t\treturn err\n\t}\n\t\/\/Get all the orgs\n\torgs, err := im.CloudController.ListOrgs()\n\tif err != nil {\n\t\tlo.G.Errorf(\"Unable to retrieve orgs. Error : %s\", err)\n\t\treturn err\n\t}\n\tconfigMgr := config.NewManager(im.ConfigDir)\n\tlo.G.Info(\"Trying to delete existing config directory\")\n\t\/\/Delete existing config directory\n\terr = configMgr.DeleteConfigIfExists()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/Create a brand new directory\n\tlo.G.Info(\"Trying to create new config folder\")\n\n\tvar uaaUserOrigin string\n\tfor _, usr := range userIDToUserMap {\n\t\tif usr.Origin != \"\" {\n\t\t\tuaaUserOrigin = usr.Origin\n\t\t\tbreak\n\t\t}\n\t}\n\tlo.G.Infof(\"Using UAA user origin: %s\", uaaUserOrigin)\n\terr = configMgr.CreateConfigIfNotExists(uaaUserOrigin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlo.G.Debugf(\"Orgs to process: %s\", orgs)\n\n\tfor _, org := range orgs {\n\t\tif _, ok := excludedOrgs[org.Entity.Name]; ok {\n\t\t\tlo.G.Infof(\"Skipping org: %s as it is ignored from import\", org.Entity.Name)\n\t\t\tcontinue\n\t\t}\n\t\tlo.G.Infof(\"Processing org: %s \", org.Entity.Name)\n\t\torgConfig := &config.OrgConfig{Org: org.Entity.Name}\n\t\t\/\/Add users\n\t\taddOrgUsers(orgConfig, im.CloudController, userIDToUserMap, org.MetaData.GUID)\n\t\t\/\/Add Quota definition if applicable\n\t\tif org.Entity.QuotaDefinitionGUID != \"\" {\n\t\t\tquota := quotaDefinition(im.CloudController, org.Entity.QuotaDefinitionGUID, organization.ORGS)\n\t\t\torgConfig.EnableOrgQuota = quota.IsQuotaEnabled()\n\t\t\torgConfig.MemoryLimit = quota.GetMemoryLimit()\n\t\t\torgConfig.InstanceMemoryLimit = quota.GetInstanceMemoryLimit()\n\t\t\torgConfig.TotalRoutes = quota.GetTotalRoutes()\n\t\t\torgConfig.TotalServices = quota.GetTotalServices()\n\t\t\torgConfig.PaidServicePlansAllowed = quota.IsPaidServicesAllowed()\n\t\t\torgConfig.TotalPrivateDomains = quota.TotalPrivateDomains\n\t\t\torgConfig.TotalReservedRoutePorts = quota.TotalReservedRoutePorts\n\t\t\torgConfig.TotalServiceKeys = quota.TotalServiceKeys\n\t\t\torgConfig.AppInstanceLimit = quota.AppInstanceLimit\n\t\t}\n\t\tconfigMgr.AddOrgToConfig(orgConfig)\n\n\t\tlo.G.Infof(\"Done creating org %s\", orgConfig.Org)\n\t\tlo.G.Infof(\"Listing spaces for org %s\", orgConfig.Org)\n\t\tspaces, _ := im.CloudController.ListSpaces(org.MetaData.GUID)\n\t\tlo.G.Infof(\"Found %d Spaces for org %s\", len(spaces), orgConfig.Org)\n\t\tfor _, orgSpace := range spaces {\n\t\t\tif _, ok := excludedSpaces[orgSpace.Entity.Name]; ok {\n\t\t\t\tlo.G.Infof(\"Skipping space: %s as it is ignored from import\", orgSpace.Entity.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlo.G.Infof(\"Processing space: %s\", orgSpace.Entity.Name)\n\n\t\t\tspaceConfig := &config.SpaceConfig{Org: org.Entity.Name, Space: orgSpace.Entity.Name}\n\t\t\t\/\/Add users\n\t\t\taddSpaceUsers(spaceConfig, im.CloudController, userIDToUserMap, orgSpace.MetaData.GUID)\n\t\t\t\/\/Add Quota definition if applicable\n\t\t\tif orgSpace.Entity.QuotaDefinitionGUID != \"\" {\n\t\t\t\tquota := quotaDefinition(im.CloudController, orgSpace.Entity.QuotaDefinitionGUID, space.SPACES)\n\t\t\t\tspaceConfig.EnableSpaceQuota = quota.IsQuotaEnabled()\n\t\t\t\tspaceConfig.MemoryLimit = quota.GetMemoryLimit()\n\t\t\t\tspaceConfig.InstanceMemoryLimit = quota.GetInstanceMemoryLimit()\n\t\t\t\tspaceConfig.TotalRoutes = quota.GetTotalRoutes()\n\t\t\t\tspaceConfig.TotalServices = quota.GetTotalServices()\n\t\t\t\tspaceConfig.PaidServicePlansAllowed = quota.IsPaidServicesAllowed()\n\t\t\t\tspaceConfig.TotalPrivateDomains = quota.TotalPrivateDomains\n\t\t\t\tspaceConfig.TotalReservedRoutePorts = quota.TotalReservedRoutePorts\n\t\t\t\tspaceConfig.TotalServiceKeys = quota.TotalServiceKeys\n\t\t\t\tspaceConfig.AppInstanceLimit = quota.AppInstanceLimit\n\t\t\t}\n\t\t\tif orgSpace.Entity.AllowSSH {\n\t\t\t\tspaceConfig.AllowSSH = true\n\t\t\t}\n\t\t\tconfigMgr.AddSpaceToConfig(spaceConfig)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc quotaDefinition(controller cc.Manager, quotaDefinitionGUID, entityType string) cc.QuotaEntity {\n\tquotaDef, _ := controller.QuotaDef(quotaDefinitionGUID, entityType)\n\tif quotaDef.Entity.Name != \"default\" {\n\t\treturn quotaDef.Entity\n\t}\n\treturn cc.QuotaEntity{}\n}\n\nfunc addOrgUsers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\taddOrgManagers(orgConfig, controller, userIDToUserMap, orgGUID)\n\taddBillingManagers(orgConfig, controller, userIDToUserMap, orgGUID)\n\taddOrgAuditors(orgConfig, controller, userIDToUserMap, orgGUID)\n}\n\nfunc addSpaceUsers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\taddSpaceDevelopers(spaceConfig, controller, userIDToUserMap, spaceGUID)\n\taddSpaceManagers(spaceConfig, controller, userIDToUserMap, spaceGUID)\n\taddSpaceAuditors(spaceConfig, controller, userIDToUserMap, spaceGUID)\n}\n\nfunc addOrgManagers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgMgrs, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_MANAGERS)\n\tlo.G.Debugf(\"Found %d Org Managers for Org: %s\", len(orgMgrs), orgConfig.Org)\n\tdoAddUsers(orgMgrs, &orgConfig.Manager.Users, &orgConfig.Manager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addBillingManagers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgBillingMgrs, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_BILLING_MANAGERS)\n\tlo.G.Debugf(\"Found %d Org Billing Managers for Org: %s\", len(orgBillingMgrs), orgConfig.Org)\n\tdoAddUsers(orgBillingMgrs, &orgConfig.BillingManager.Users, &orgConfig.BillingManager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addOrgAuditors(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgAuditors, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_AUDITORS)\n\tlo.G.Debugf(\"Found %d Org Auditors for Org: %s\", len(orgAuditors), orgConfig.Org)\n\tdoAddUsers(orgAuditors, &orgConfig.Auditor.Users, &orgConfig.Auditor.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceManagers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceMgrs, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_MANAGERS)\n\tlo.G.Debugf(\"Found %d Space Managers for Org: %s and Space: %s\", len(spaceMgrs), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceMgrs, &spaceConfig.Manager.Users, &spaceConfig.Manager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceDevelopers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceDevs, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_DEVELOPERS)\n\tlo.G.Debugf(\"Found %d Space Developers for Org: %s and Space: %s\", len(spaceDevs), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceDevs, &spaceConfig.Developer.Users, &spaceConfig.Developer.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceAuditors(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceAuditors, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_AUDITORS)\n\tlo.G.Debugf(\"Found %d Space Auditors for Org: %s and Space: %s\", len(spaceAuditors), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceAuditors, &spaceConfig.Auditor.Users, &spaceConfig.Auditor.LDAPUsers, userIDToUserMap)\n}\n\nfunc doAddUsers(cfUsers map[string]string, uaaUsers *[]string, ldapUsers *[]string, userIDToUserMap map[string]uaac.User) {\n\tfor cfUser := range cfUsers {\n\t\tif usr, ok := userIDToUserMap[cfUser]; ok {\n\t\t\tif usr.Origin == \"uaa\" {\n\t\t\t\t*uaaUsers = append(*uaaUsers, usr.UserName)\n\t\t\t} else {\n\t\t\t\t*ldapUsers = append(*ldapUsers, usr.UserName)\n\t\t\t}\n\t\t} else {\n\t\t\tlo.G.Infof(\"CFUser [%s] not found in uaa user list\", cfUser)\n\t\t}\n\t}\n}\n\nfunc getCFUsers(cc cc.Manager, entityGUID, entityType, role string) (map[string]string, error) {\n\treturn cc.GetCFUsers(entityGUID, entityType, role)\n}\nadding logging to help triage issue with exportConfig not populating all userspackage export\n\nimport (\n\tcc \"github.com\/pivotalservices\/cf-mgmt\/cloudcontroller\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/config\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/organization\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/space\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/uaac\"\n\t\"github.com\/xchapter7x\/lo\"\n)\n\n\/\/NewExportManager Creates a new instance of the ImportConfig manager\nfunc NewExportManager(\n\tconfigDir string,\n\tuaacMgr uaac.Manager,\n\tcloudController cc.Manager) Manager {\n\treturn &DefaultImportManager{\n\t\tConfigDir: configDir,\n\t\tUAACMgr: uaacMgr,\n\t\tCloudController: cloudController,\n\t}\n}\n\n\/\/ExportConfig Imports org and space configuration from an existing CF instance\n\/\/Entries part of excludedOrgs and excludedSpaces are not included in the import\nfunc (im *DefaultImportManager) ExportConfig(excludedOrgs map[string]string, excludedSpaces map[string]string) error {\n\t\/\/Get all the users from the foundation\n\tuserIDToUserMap, err := im.UAACMgr.UsersByID()\n\tif err != nil {\n\t\tlo.G.Error(\"Unable to retrieve users\")\n\t\treturn err\n\t}\n\tlo.G.Debugf(\"uaa user id map %v\", userIDToUserMap)\n\t\/\/Get all the orgs\n\torgs, err := im.CloudController.ListOrgs()\n\tif err != nil {\n\t\tlo.G.Errorf(\"Unable to retrieve orgs. Error : %s\", err)\n\t\treturn err\n\t}\n\tconfigMgr := config.NewManager(im.ConfigDir)\n\tlo.G.Info(\"Trying to delete existing config directory\")\n\t\/\/Delete existing config directory\n\terr = configMgr.DeleteConfigIfExists()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/Create a brand new directory\n\tlo.G.Info(\"Trying to create new config folder\")\n\n\tvar uaaUserOrigin string\n\tfor _, usr := range userIDToUserMap {\n\t\tif usr.Origin != \"\" {\n\t\t\tuaaUserOrigin = usr.Origin\n\t\t\tbreak\n\t\t}\n\t}\n\tlo.G.Infof(\"Using UAA user origin: %s\", uaaUserOrigin)\n\terr = configMgr.CreateConfigIfNotExists(uaaUserOrigin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlo.G.Debugf(\"Orgs to process: %s\", orgs)\n\n\tfor _, org := range orgs {\n\t\tif _, ok := excludedOrgs[org.Entity.Name]; ok {\n\t\t\tlo.G.Infof(\"Skipping org: %s as it is ignored from import\", org.Entity.Name)\n\t\t\tcontinue\n\t\t}\n\t\tlo.G.Infof(\"Processing org: %s \", org.Entity.Name)\n\t\torgConfig := &config.OrgConfig{Org: org.Entity.Name}\n\t\t\/\/Add users\n\t\taddOrgUsers(orgConfig, im.CloudController, userIDToUserMap, org.MetaData.GUID)\n\t\t\/\/Add Quota definition if applicable\n\t\tif org.Entity.QuotaDefinitionGUID != \"\" {\n\t\t\tquota := quotaDefinition(im.CloudController, org.Entity.QuotaDefinitionGUID, organization.ORGS)\n\t\t\torgConfig.EnableOrgQuota = quota.IsQuotaEnabled()\n\t\t\torgConfig.MemoryLimit = quota.GetMemoryLimit()\n\t\t\torgConfig.InstanceMemoryLimit = quota.GetInstanceMemoryLimit()\n\t\t\torgConfig.TotalRoutes = quota.GetTotalRoutes()\n\t\t\torgConfig.TotalServices = quota.GetTotalServices()\n\t\t\torgConfig.PaidServicePlansAllowed = quota.IsPaidServicesAllowed()\n\t\t\torgConfig.TotalPrivateDomains = quota.TotalPrivateDomains\n\t\t\torgConfig.TotalReservedRoutePorts = quota.TotalReservedRoutePorts\n\t\t\torgConfig.TotalServiceKeys = quota.TotalServiceKeys\n\t\t\torgConfig.AppInstanceLimit = quota.AppInstanceLimit\n\t\t}\n\t\tconfigMgr.AddOrgToConfig(orgConfig)\n\n\t\tlo.G.Infof(\"Done creating org %s\", orgConfig.Org)\n\t\tlo.G.Infof(\"Listing spaces for org %s\", orgConfig.Org)\n\t\tspaces, _ := im.CloudController.ListSpaces(org.MetaData.GUID)\n\t\tlo.G.Infof(\"Found %d Spaces for org %s\", len(spaces), orgConfig.Org)\n\t\tfor _, orgSpace := range spaces {\n\t\t\tif _, ok := excludedSpaces[orgSpace.Entity.Name]; ok {\n\t\t\t\tlo.G.Infof(\"Skipping space: %s as it is ignored from import\", orgSpace.Entity.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlo.G.Infof(\"Processing space: %s\", orgSpace.Entity.Name)\n\n\t\t\tspaceConfig := &config.SpaceConfig{Org: org.Entity.Name, Space: orgSpace.Entity.Name}\n\t\t\t\/\/Add users\n\t\t\taddSpaceUsers(spaceConfig, im.CloudController, userIDToUserMap, orgSpace.MetaData.GUID)\n\t\t\t\/\/Add Quota definition if applicable\n\t\t\tif orgSpace.Entity.QuotaDefinitionGUID != \"\" {\n\t\t\t\tquota := quotaDefinition(im.CloudController, orgSpace.Entity.QuotaDefinitionGUID, space.SPACES)\n\t\t\t\tspaceConfig.EnableSpaceQuota = quota.IsQuotaEnabled()\n\t\t\t\tspaceConfig.MemoryLimit = quota.GetMemoryLimit()\n\t\t\t\tspaceConfig.InstanceMemoryLimit = quota.GetInstanceMemoryLimit()\n\t\t\t\tspaceConfig.TotalRoutes = quota.GetTotalRoutes()\n\t\t\t\tspaceConfig.TotalServices = quota.GetTotalServices()\n\t\t\t\tspaceConfig.PaidServicePlansAllowed = quota.IsPaidServicesAllowed()\n\t\t\t\tspaceConfig.TotalPrivateDomains = quota.TotalPrivateDomains\n\t\t\t\tspaceConfig.TotalReservedRoutePorts = quota.TotalReservedRoutePorts\n\t\t\t\tspaceConfig.TotalServiceKeys = quota.TotalServiceKeys\n\t\t\t\tspaceConfig.AppInstanceLimit = quota.AppInstanceLimit\n\t\t\t}\n\t\t\tif orgSpace.Entity.AllowSSH {\n\t\t\t\tspaceConfig.AllowSSH = true\n\t\t\t}\n\t\t\tconfigMgr.AddSpaceToConfig(spaceConfig)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc quotaDefinition(controller cc.Manager, quotaDefinitionGUID, entityType string) cc.QuotaEntity {\n\tquotaDef, _ := controller.QuotaDef(quotaDefinitionGUID, entityType)\n\tif quotaDef.Entity.Name != \"default\" {\n\t\treturn quotaDef.Entity\n\t}\n\treturn cc.QuotaEntity{}\n}\n\nfunc addOrgUsers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\taddOrgManagers(orgConfig, controller, userIDToUserMap, orgGUID)\n\taddBillingManagers(orgConfig, controller, userIDToUserMap, orgGUID)\n\taddOrgAuditors(orgConfig, controller, userIDToUserMap, orgGUID)\n}\n\nfunc addSpaceUsers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\taddSpaceDevelopers(spaceConfig, controller, userIDToUserMap, spaceGUID)\n\taddSpaceManagers(spaceConfig, controller, userIDToUserMap, spaceGUID)\n\taddSpaceAuditors(spaceConfig, controller, userIDToUserMap, spaceGUID)\n}\n\nfunc addOrgManagers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgMgrs, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_MANAGERS)\n\tlo.G.Debugf(\"Found %d Org Managers for Org: %s\", len(orgMgrs), orgConfig.Org)\n\tdoAddUsers(orgMgrs, &orgConfig.Manager.Users, &orgConfig.Manager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addBillingManagers(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgBillingMgrs, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_BILLING_MANAGERS)\n\tlo.G.Debugf(\"Found %d Org Billing Managers for Org: %s\", len(orgBillingMgrs), orgConfig.Org)\n\tdoAddUsers(orgBillingMgrs, &orgConfig.BillingManager.Users, &orgConfig.BillingManager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addOrgAuditors(orgConfig *config.OrgConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, orgGUID string) {\n\torgAuditors, _ := getCFUsers(controller, orgGUID, organization.ORGS, organization.ROLE_ORG_AUDITORS)\n\tlo.G.Debugf(\"Found %d Org Auditors for Org: %s\", len(orgAuditors), orgConfig.Org)\n\tdoAddUsers(orgAuditors, &orgConfig.Auditor.Users, &orgConfig.Auditor.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceManagers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceMgrs, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_MANAGERS)\n\tlo.G.Debugf(\"Found %d Space Managers for Org: %s and Space: %s\", len(spaceMgrs), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceMgrs, &spaceConfig.Manager.Users, &spaceConfig.Manager.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceDevelopers(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceDevs, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_DEVELOPERS)\n\tlo.G.Debugf(\"Found %d Space Developers for Org: %s and Space: %s\", len(spaceDevs), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceDevs, &spaceConfig.Developer.Users, &spaceConfig.Developer.LDAPUsers, userIDToUserMap)\n}\n\nfunc addSpaceAuditors(spaceConfig *config.SpaceConfig, controller cc.Manager, userIDToUserMap map[string]uaac.User, spaceGUID string) {\n\tspaceAuditors, _ := getCFUsers(controller, spaceGUID, space.SPACES, space.ROLE_SPACE_AUDITORS)\n\tlo.G.Debugf(\"Found %d Space Auditors for Org: %s and Space: %s\", len(spaceAuditors), spaceConfig.Org, spaceConfig.Space)\n\tdoAddUsers(spaceAuditors, &spaceConfig.Auditor.Users, &spaceConfig.Auditor.LDAPUsers, userIDToUserMap)\n}\n\nfunc doAddUsers(cfUsers map[string]string, uaaUsers *[]string, ldapUsers *[]string, userIDToUserMap map[string]uaac.User) {\n\tfor cfUser := range cfUsers {\n\t\tif usr, ok := userIDToUserMap[cfUser]; ok {\n\t\t\tif usr.Origin == \"uaa\" {\n\t\t\t\t*uaaUsers = append(*uaaUsers, usr.UserName)\n\t\t\t} else {\n\t\t\t\t*ldapUsers = append(*ldapUsers, usr.UserName)\n\t\t\t}\n\t\t} else {\n\t\t\tlo.G.Infof(\"CFUser [%s] not found in uaa user list\", cfUser)\n\t\t}\n\t}\n}\n\nfunc getCFUsers(cc cc.Manager, entityGUID, entityType, role string) (map[string]string, error) {\n\treturn cc.GetCFUsers(entityGUID, entityType, role)\n}\n<|endoftext|>"} {"text":"package ts\n\nimport \"io\"\nimport \"bytes\"\nimport \"github.com\/32bitkid\/mpeg\/util\"\n\ntype PayloadReader interface {\n\tio.Reader\n\tTransportStreamControl\n}\n\nfunc NewPayloadReader(source io.Reader, where PacketTester) PayloadReader {\n\treturn &payloadReader{\n\t\tcurrentPacket: new(Packet),\n\t\tbr: util.NewBitReader(source),\n\t\twhere: where,\n\t\tclosed: false,\n\t\tisAligned: false,\n\t\tskipUntil: alwaysTrueTester,\n\t\ttakeWhile: alwaysTrueTester,\n\t}\n}\n\ntype payloadReader struct {\n\tcurrentPacket *Packet\n\tbr util.BitReader32\n\twhere PacketTester\n\tskipUntil PacketTester\n\ttakeWhile PacketTester\n\tremainder bytes.Buffer\n\tclosed bool\n\tisAligned bool\n}\n\nfunc (r *payloadReader) SkipUntil(skipUntil PacketTester) {\n\tr.skipUntil = r.where.And(skipUntil)\n}\n\nfunc (r *payloadReader) TakeWhile(takeWhile PacketTester) {\n\tr.takeWhile = r.where.And(takeWhile)\n}\n\nfunc (r *payloadReader) Read(p []byte) (n int, err error) {\n\n\tif r.closed == true {\n\t\treturn 0, io.EOF\n\t}\n\n\tif r.isAligned == false {\n\t\terr = r.realign()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar remainder []byte\n\n\tif r.remainder.Len() > 0 {\n\t\tcopied, err := r.remainder.Read(p)\n\t\tif err != nil {\n\t\t\treturn copied, err\n\t\t}\n\t\tn = n + copied\n\t\tp = p[copied:]\n\t}\n\n\tfor len(p) > 0 {\n\t\terr = r.next()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif r.where(r.currentPacket) {\n\t\t\tcopied := copy(p, r.currentPacket.Payload)\n\t\t\tn = n + copied\n\t\t\tp = p[copied:]\n\t\t\tremainder = r.currentPacket.Payload[copied:]\n\t\t}\n\n\t\tcont := r.takeWhile(r.currentPacket)\n\t\tif cont == false {\n\t\t\tr.closed = true\n\t\t\treturn n, io.EOF\n\t\t}\n\t}\n\n\t_, err = r.remainder.Write(remainder)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (r *payloadReader) next() error {\n\treturn r.currentPacket.ReadFrom(r.br)\n}\n\nfunc (r *payloadReader) realign() (err error) {\n\tfor {\n\t\tr.next()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdone := r.skipUntil(r.currentPacket)\n\t\tif done {\n\t\t\tr.isAligned = true\n\t\t\tr.remainder.Write(r.currentPacket.Payload)\n\t\t\treturn nil\n\t\t}\n\t}\n}\nMake sure to drain the remainder before moving on.package ts\n\nimport \"io\"\nimport \"bytes\"\nimport \"github.com\/32bitkid\/mpeg\/util\"\n\ntype PayloadReader interface {\n\tio.Reader\n\tTransportStreamControl\n}\n\nfunc NewPayloadReader(source io.Reader, where PacketTester) PayloadReader {\n\treturn &payloadReader{\n\t\tcurrentPacket: new(Packet),\n\t\tbr: util.NewBitReader(source),\n\t\twhere: where,\n\t\tclosed: false,\n\t\tisAligned: false,\n\t\tskipUntil: alwaysTrueTester,\n\t\ttakeWhile: alwaysTrueTester,\n\t}\n}\n\ntype payloadReader struct {\n\tcurrentPacket *Packet\n\tbr util.BitReader32\n\twhere PacketTester\n\tskipUntil PacketTester\n\ttakeWhile PacketTester\n\tremainder bytes.Buffer\n\tclosed bool\n\tisAligned bool\n}\n\nfunc (r *payloadReader) SkipUntil(skipUntil PacketTester) {\n\tr.skipUntil = r.where.And(skipUntil)\n}\n\nfunc (r *payloadReader) TakeWhile(takeWhile PacketTester) {\n\tr.takeWhile = r.where.And(takeWhile)\n}\n\nfunc (r *payloadReader) Read(p []byte) (n int, err error) {\n\n\tif r.closed == true {\n\t\treturn 0, io.EOF\n\t}\n\n\tif r.isAligned == false {\n\t\terr = r.realign()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar remainder []byte\n\n\t\/\/ Drain remainder\n\tfor len(p) > 0 {\n\t\tcn, err := r.remainder.Read(p)\n\t\tn = n + cn\n\t\tp = p[cn:]\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tfor len(p) > 0 {\n\t\terr = r.next()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif r.where(r.currentPacket) {\n\t\t\tcopied := copy(p, r.currentPacket.Payload)\n\t\t\tn = n + copied\n\t\t\tp = p[copied:]\n\t\t\tremainder = r.currentPacket.Payload[copied:]\n\t\t}\n\n\t\tcont := r.takeWhile(r.currentPacket)\n\t\tif cont == false {\n\t\t\tr.closed = true\n\t\t\treturn n, io.EOF\n\t\t}\n\t}\n\n\t_, err = r.remainder.Write(remainder)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (r *payloadReader) next() error {\n\treturn r.currentPacket.ReadFrom(r.br)\n}\n\nfunc (r *payloadReader) realign() (err error) {\n\tfor {\n\t\tr.next()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdone := r.skipUntil(r.currentPacket)\n\t\tif done {\n\t\t\tr.isAligned = true\n\t\t\tr.remainder.Write(r.currentPacket.Payload)\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"Add comment to generated Msgsize function (#161)<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"math\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nvar (\n\tMemoryByteString = []byte(\"mem\") \/\/ heap optimization\n\n\t\/\/ Choices for modeling a host's memory capacity.\n\tMemoryMaxBytesChoices = []int64{8 << 30, 12 << 30, 16 << 30}\n\n\t\/\/ Field keys for 'mem' points.\n\tMemoryFieldKeys = [][]byte{\n\t\t[]byte(\"total\"),\n\t\t[]byte(\"available\"),\n\t\t[]byte(\"used\"),\n\t\t[]byte(\"free\"),\n\t\t[]byte(\"cached\"),\n\t\t[]byte(\"buffered\"),\n\t\t[]byte(\"used_percent\"),\n\t\t[]byte(\"available_percent\"),\n\t}\n)\n\ntype MemMeasurement struct {\n\t\/\/ this doesn't change:\n\tbytesTotal int64\n\n\t\/\/ these change:\n\ttimestamp time.Time\n\tbytesUsedDist, bytesCachedDist, bytesBufferedDist Distribution\n}\n\nfunc NewMemMeasurement(start time.Time) *MemMeasurement {\n\tbytesTotal := MemoryMaxBytesChoices[rand.Intn(len(MemoryMaxBytesChoices))]\n\tbytesUsedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\tbytesCachedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\tbytesBufferedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\treturn &MemMeasurement{\n\t\ttimestamp: start,\n\n\t\tbytesTotal: bytesTotal,\n\t\tbytesUsedDist: bytesUsedDist,\n\t\tbytesCachedDist: bytesCachedDist,\n\t\tbytesBufferedDist: bytesBufferedDist,\n\t}\n}\n\nfunc (m *MemMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\n\tm.bytesUsedDist.Advance()\n\tm.bytesCachedDist.Advance()\n\tm.bytesBufferedDist.Advance()\n}\n\nfunc (m *MemMeasurement) ToPoint(p *Point) {\n\tp.SetMeasurementName(MemoryByteString)\n\tp.SetTimestamp(&m.timestamp)\n\n\ttotal := m.bytesTotal\n\tused := m.bytesUsedDist.Get()\n\tcached := m.bytesCachedDist.Get()\n\tbuffered := m.bytesBufferedDist.Get()\n\n\tp.AppendField(MemoryFieldKeys[0], total)\n\tp.AppendField(MemoryFieldKeys[1], int(math.Floor(float64(total)-used)))\n\tp.AppendField(MemoryFieldKeys[2], int(math.Floor(used)))\n\tp.AppendField(MemoryFieldKeys[3], int(math.Floor(cached)))\n\tp.AppendField(MemoryFieldKeys[4], int(math.Floor(buffered)))\n\tp.AppendField(MemoryFieldKeys[5], int(math.Floor(used)))\n\tp.AppendField(MemoryFieldKeys[6], 100.0*(used\/float64(total)))\n\tp.AppendField(MemoryFieldKeys[7], 100.0*(float64(total)-used)\/float64(total))\n}\nadd one more metricpackage main\n\nimport (\n\t\"math\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nvar (\n\tMemoryByteString = []byte(\"mem\") \/\/ heap optimization\n\n\t\/\/ Choices for modeling a host's memory capacity.\n\tMemoryMaxBytesChoices = []int64{8 << 30, 12 << 30, 16 << 30}\n\n\t\/\/ Field keys for 'mem' points.\n\tMemoryFieldKeys = [][]byte{\n\t\t[]byte(\"total\"),\n\t\t[]byte(\"available\"),\n\t\t[]byte(\"used\"),\n\t\t[]byte(\"free\"),\n\t\t[]byte(\"cached\"),\n\t\t[]byte(\"buffered\"),\n\t\t[]byte(\"used_percent\"),\n\t\t[]byte(\"available_percent\"),\n\t\t[]byte(\"buffered_percent\"),\n\t}\n)\n\ntype MemMeasurement struct {\n\t\/\/ this doesn't change:\n\tbytesTotal int64\n\n\t\/\/ these change:\n\ttimestamp time.Time\n\tbytesUsedDist, bytesCachedDist, bytesBufferedDist Distribution\n}\n\nfunc NewMemMeasurement(start time.Time) *MemMeasurement {\n\tbytesTotal := MemoryMaxBytesChoices[rand.Intn(len(MemoryMaxBytesChoices))]\n\tbytesUsedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\tbytesCachedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\tbytesBufferedDist := &ClampedRandomWalkDistribution{\n\t\tState: rand.Float64() * float64(bytesTotal),\n\t\tMin: 0.0,\n\t\tMax: float64(bytesTotal),\n\t\tStep: &NormalDistribution{\n\t\t\tMean: 0.0,\n\t\t\tStdDev: float64(bytesTotal) \/ 64,\n\t\t},\n\t}\n\treturn &MemMeasurement{\n\t\ttimestamp: start,\n\n\t\tbytesTotal: bytesTotal,\n\t\tbytesUsedDist: bytesUsedDist,\n\t\tbytesCachedDist: bytesCachedDist,\n\t\tbytesBufferedDist: bytesBufferedDist,\n\t}\n}\n\nfunc (m *MemMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\n\tm.bytesUsedDist.Advance()\n\tm.bytesCachedDist.Advance()\n\tm.bytesBufferedDist.Advance()\n}\n\nfunc (m *MemMeasurement) ToPoint(p *Point) {\n\tp.SetMeasurementName(MemoryByteString)\n\tp.SetTimestamp(&m.timestamp)\n\n\ttotal := m.bytesTotal\n\tused := m.bytesUsedDist.Get()\n\tcached := m.bytesCachedDist.Get()\n\tbuffered := m.bytesBufferedDist.Get()\n\n\tp.AppendField(MemoryFieldKeys[0], total)\n\tp.AppendField(MemoryFieldKeys[1], int(math.Floor(float64(total)-used)))\n\tp.AppendField(MemoryFieldKeys[2], int(math.Floor(used)))\n\tp.AppendField(MemoryFieldKeys[3], int(math.Floor(cached)))\n\tp.AppendField(MemoryFieldKeys[4], int(math.Floor(buffered)))\n\tp.AppendField(MemoryFieldKeys[5], int(math.Floor(used)))\n\tp.AppendField(MemoryFieldKeys[6], 100.0*(used\/float64(total)))\n\tp.AppendField(MemoryFieldKeys[7], 100.0*(float64(total)-used)\/float64(total))\n\tp.AppendField(MemoryFieldKeys[8], 100.0*(float64(total)-buffered)\/float64(total))\n}\n<|endoftext|>"} {"text":"package redis\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"strings\"\n)\n\ntype scripter interface {\n\tEval(script string, keys []string, args ...interface{}) *Cmd\n\tEvalSha(sha1 string, keys []string, args ...interface{}) *Cmd\n\tScriptExists(scripts ...string) *BoolSliceCmd\n\tScriptLoad(script string) *StringCmd\n}\n\nvar _ scripter = (*Client)(nil)\nvar _ scripter = (*Ring)(nil)\nvar _ scripter = (*ClusterClient)(nil)\n\ntype Script struct {\n\tsrc, hash string\n}\n\nfunc NewScript(src string) *Script {\n\th := sha1.New()\n\tio.WriteString(h, src)\n\treturn &Script{\n\t\tsrc: src,\n\t\thash: hex.EncodeToString(h.Sum(nil)),\n\t}\n}\n\nfunc (s *Script) Load(c scripter) *StringCmd {\n\treturn c.ScriptLoad(s.src)\n}\n\nfunc (s *Script) Exists(c scripter) *BoolSliceCmd {\n\treturn c.ScriptExists(s.src)\n}\n\nfunc (s *Script) Eval(c scripter, keys []string, args ...interface{}) *Cmd {\n\treturn c.Eval(s.src, keys, args...)\n}\n\nfunc (s *Script) EvalSha(c scripter, keys []string, args ...interface{}) *Cmd {\n\treturn c.EvalSha(s.hash, keys, args...)\n}\n\n\/\/ Run optimistically uses EVALSHA to run the script. If script does not exist\n\/\/ it is retried using EVAL.\nfunc (s *Script) Run(c scripter, keys []string, args ...interface{}) *Cmd {\n\tr := s.EvalSha(c, keys, args...)\n\tif err := r.Err(); err != nil && strings.HasPrefix(err.Error(), \"NOSCRIPT \") {\n\t\treturn s.Eval(c, keys, args...)\n\t}\n\treturn r\n}\nAdd Script.Hashpackage redis\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"strings\"\n)\n\ntype scripter interface {\n\tEval(script string, keys []string, args ...interface{}) *Cmd\n\tEvalSha(sha1 string, keys []string, args ...interface{}) *Cmd\n\tScriptExists(scripts ...string) *BoolSliceCmd\n\tScriptLoad(script string) *StringCmd\n}\n\nvar _ scripter = (*Client)(nil)\nvar _ scripter = (*Ring)(nil)\nvar _ scripter = (*ClusterClient)(nil)\n\ntype Script struct {\n\tsrc, hash string\n}\n\nfunc NewScript(src string) *Script {\n\th := sha1.New()\n\tio.WriteString(h, src)\n\treturn &Script{\n\t\tsrc: src,\n\t\thash: hex.EncodeToString(h.Sum(nil)),\n\t}\n}\n\nfunc (s *Script) Hash() string {\n\treturn s.hash\n}\n\nfunc (s *Script) Load(c scripter) *StringCmd {\n\treturn c.ScriptLoad(s.src)\n}\n\nfunc (s *Script) Exists(c scripter) *BoolSliceCmd {\n\treturn c.ScriptExists(s.src)\n}\n\nfunc (s *Script) Eval(c scripter, keys []string, args ...interface{}) *Cmd {\n\treturn c.Eval(s.src, keys, args...)\n}\n\nfunc (s *Script) EvalSha(c scripter, keys []string, args ...interface{}) *Cmd {\n\treturn c.EvalSha(s.hash, keys, args...)\n}\n\n\/\/ Run optimistically uses EVALSHA to run the script. If script does not exist\n\/\/ it is retried using EVAL.\nfunc (s *Script) Run(c scripter, keys []string, args ...interface{}) *Cmd {\n\tr := s.EvalSha(c, keys, args...)\n\tif err := r.Err(); err != nil && strings.HasPrefix(err.Error(), \"NOSCRIPT \") {\n\t\treturn s.Eval(c, keys, args...)\n\t}\n\treturn r\n}\n<|endoftext|>"} {"text":"Always add date to slug<|endoftext|>"} {"text":"package collector\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/henrylee2cn\/pholcus\/common\/kafka\"\n\t\"github.com\/henrylee2cn\/pholcus\/common\/util\"\n)\n\n\/************************ Kafka 输出 ***************************\/\nfunc init() {\n\tvar (\n\t\tkafkaSenders = map[string]*kafka.KafkaSender{}\n\t\tkafkaSenderLock sync.RWMutex\n\t)\n\n\tvar getKafkaSender = func(name string) (*kafka.KafkaSender, bool) {\n\t\tkafkaSenderLock.RLock()\n\t\ttab, ok := kafkaSenders[name]\n\t\tkafkaSenderLock.RUnlock()\n\t\treturn tab, ok\n\t}\n\n\tvar setKafkaSender = func(name string, tab *kafka.KafkaSender) {\n\t\tkafkaSenderLock.Lock()\n\t\tkafkaSenders[name] = tab\n\t\tkafkaSenderLock.Unlock()\n\t}\n\n\tDataOutput[\"kafka\"] = func(self *Collector) error {\n\t\t_, err := kafka.GetProducer()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"kafka producer失败: %v\", err)\n\t\t}\n\t\tvar (\n\t\t\tkafkas = make(map[string]*kafka.KafkaSender)\n\t\t\tnamespace = util.FileNameReplace(self.namespace())\n\t\t)\n\t\tfor _, datacell := range self.dataDocker {\n\t\t\tsubNamespace := util.FileNameReplace(self.subNamespace(datacell))\n\t\t\ttopicName := joinNamespaces(namespace, subNamespace)\n\t\t\tsender, ok := kafkas[topicName]\n\t\t\tif !ok {\n\t\t\t\tsender, ok = getKafkaSender(topicName)\n\t\t\t\tif ok {\n\t\t\t\t\tkafkas[topicName] = sender\n\t\t\t\t} else {\n\t\t\t\t\tsender = kafka.New()\n\t\t\t\t\tsender.SetTopic(topicName)\n\t\t\t\t\tsetKafkaSender(topicName, sender)\n\t\t\t\t\tkafkas[topicName] = sender\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata := make(map[string]interface{})\n\t\t\tfor _, title := range self.MustGetRule(datacell[\"RuleName\"].(string)).ItemFields {\n\t\t\t\tvd := datacell[\"Data\"].(map[string]interface{})\n\t\t\t\tif v, ok := vd[title].(string); ok || vd[title] == nil {\n\t\t\t\t\tdata[title] = v\n\t\t\t\t} else {\n\t\t\t\t\tdata[title] = util.JsonString(vd[title])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif self.Spider.OutDefaultField() {\n\t\t\t\tdata[\"url\"] = datacell[\"Url\"].(string)\n\t\t\t\tdata[\"parent_url\"] = datacell[\"ParentUrl\"].(string)\n\t\t\t\tdata[\"download_time\"] = datacell[\"DownloadTime\"].(string)\n\t\t\t}\n\t\t\terr := sender.Push(data)\n\t\t\tutil.CheckErr(err)\n\t\t}\n\t\tkafkas = nil\n\t\treturn nil\n\t}\n}\nCompatible with Kafka v0.11.0.0package collector\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"sync\"\n\n\t\"github.com\/henrylee2cn\/pholcus\/common\/kafka\"\n\t\"github.com\/henrylee2cn\/pholcus\/common\/util\"\n\t\"github.com\/henrylee2cn\/pholcus\/logs\"\n)\n\n\/************************ Kafka 输出 ***************************\/\nfunc init() {\n\tvar (\n\t\tkafkaSenders = map[string]*kafka.KafkaSender{}\n\t\tkafkaSenderLock sync.RWMutex\n\t)\n\n\tvar getKafkaSender = func(name string) (*kafka.KafkaSender, bool) {\n\t\tkafkaSenderLock.RLock()\n\t\ttab, ok := kafkaSenders[name]\n\t\tkafkaSenderLock.RUnlock()\n\t\treturn tab, ok\n\t}\n\n\tvar setKafkaSender = func(name string, tab *kafka.KafkaSender) {\n\t\tkafkaSenderLock.Lock()\n\t\tkafkaSenders[name] = tab\n\t\tkafkaSenderLock.Unlock()\n\t}\n\n\tvar topic = regexp.MustCompile(\"^[0-9a-zA-Z_-]+$\")\n\n\tDataOutput[\"kafka\"] = func(self *Collector) error {\n\t\t_, err := kafka.GetProducer()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"kafka producer失败: %v\", err)\n\t\t}\n\t\tvar (\n\t\t\tkafkas = make(map[string]*kafka.KafkaSender)\n\t\t\tnamespace = util.FileNameReplace(self.namespace())\n\t\t)\n\t\tfor _, datacell := range self.dataDocker {\n\t\t\tsubNamespace := util.FileNameReplace(self.subNamespace(datacell))\n\t\t\ttopicName := joinNamespaces(namespace, subNamespace)\n\t\t\tif !topic.MatchString(topicName) {\n\t\t\t\tlogs.Log.Error(\"topic格式要求'^[0-9a-zA-Z_-]+$',当前为:%s\", topicName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsender, ok := kafkas[topicName]\n\t\t\tif !ok {\n\t\t\t\tsender, ok = getKafkaSender(topicName)\n\t\t\t\tif ok {\n\t\t\t\t\tkafkas[topicName] = sender\n\t\t\t\t} else {\n\t\t\t\t\tsender = kafka.New()\n\t\t\t\t\tsender.SetTopic(topicName)\n\t\t\t\t\tsetKafkaSender(topicName, sender)\n\t\t\t\t\tkafkas[topicName] = sender\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata := make(map[string]interface{})\n\t\t\tfor _, title := range self.MustGetRule(datacell[\"RuleName\"].(string)).ItemFields {\n\t\t\t\tvd := datacell[\"Data\"].(map[string]interface{})\n\t\t\t\tif v, ok := vd[title].(string); ok || vd[title] == nil {\n\t\t\t\t\tdata[title] = v\n\t\t\t\t} else {\n\t\t\t\t\tdata[title] = util.JsonString(vd[title])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif self.Spider.OutDefaultField() {\n\t\t\t\tdata[\"url\"] = datacell[\"Url\"].(string)\n\t\t\t\tdata[\"parent_url\"] = datacell[\"ParentUrl\"].(string)\n\t\t\t\tdata[\"download_time\"] = datacell[\"DownloadTime\"].(string)\n\t\t\t}\n\t\t\terr := sender.Push(data)\n\t\t\tutil.CheckErr(err)\n\t\t}\n\t\tkafkas = nil\n\t\treturn nil\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestTargetWorker(t *testing.T) {\n\ttype D1 struct {\n\t\tError string\n\t}\n\tf := func(bucket, object, localPath string) error {\n\t\tlog.Infof(\"f(%v, %v, %v)\\n\", bucket, object, localPath)\n\t\tif localPath == \"\" {\n\t\t\tlog.Infof(\"localPath is blank\\n\")\n\t\t\treturn fmt.Errorf(\"localPath is blank\")\n\t\t}\n\t\tlog.Infof(\"localPath is NOT blank\\n\")\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\treturn nil\n\t}\n\n\tworkers := TargetWorkers{\n\t\t&TargetWorker{name: \"w1\", impl: f, maxTries: 1, interval: 1 * time.Second},\n\t\t&TargetWorker{name: \"w2\", impl: f, maxTries: 1, interval: 1 * time.Second},\n\t\t&TargetWorker{name: \"w3\", impl: f, maxTries: 1, interval: 1 * time.Second},\n\t}\n\n\t\/\/ Empty targets\n\ttargets0 := Targets{}\n\terr := workers.process(targets0)\n\tassert.NoError(t, err)\n\n\t\/\/ 1 target\n\ttargets1 := Targets{\n\t\t&Target{LocalPath: \"foo\"},\n\t}\n\terr = workers.process(targets1)\n\tassert.NoError(t, err)\n\n\t\/\/ 1 error target\n\ttargets1Error := Targets{\n\t\t&Target{},\n\t}\n\terr = workers.process(targets1Error)\n\tassert.Equal(t, \"localPath is blank\", err.Error())\n\n\t\/\/ 1 success and 1 error\n\ttargets1Success1Error := Targets{\n\t\t&Target{LocalPath: \"foo\"},\n\t\t&Target{},\n\t}\n\terr = workers.process(targets1Success1Error)\n\tassert.Equal(t, \"localPath is blank\", err.Error())\n\n\t\/\/ 3 success and 2 error\n\ttargets3Success2Error := Targets{\n\t\t&Target{},\n\t\t&Target{LocalPath: \"foo\"},\n\t\t&Target{LocalPath: \"foo\"},\n\t\t&Target{},\n\t\t&Target{LocalPath: \"foo\"},\n\t}\n\terr = workers.process(targets3Success2Error)\n\tassert.Equal(t, \"localPath is blank\\nlocalPath is blank\", err.Error())\n\n\t\/\/ 3 success\n\ttargets3Success := Targets{\n\t\t&Target{LocalPath: \"foo\"},\n\t\t&Target{LocalPath: \"foo\"},\n\t\t&Target{LocalPath: \"foo\"},\n\t}\n\terr = workers.process(targets3Success)\n\tassert.NoError(t, err)\n}\n:shower: Remove test for TargetWorker<|endoftext|>"} {"text":"\/\/ Copyright 2020 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage executor\n\nimport (\n\t\"context\"\n\t\"sort\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/pingcap\/errors\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/parser\/model\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\t\"github.com\/pingcap\/tidb\/table\"\n\t\"github.com\/pingcap\/tidb\/tablecodec\"\n\t\"github.com\/pingcap\/tidb\/types\"\n\t\"github.com\/pingcap\/tidb\/util\/chunk\"\n\tdecoder \"github.com\/pingcap\/tidb\/util\/rowDecoder\"\n\t\"github.com\/tikv\/client-go\/v2\/tikv\"\n)\n\nvar _ Executor = &TableSampleExecutor{}\n\nconst sampleMethodRegionConcurrency = 5\n\n\/\/ TableSampleExecutor fetches a few rows through kv.Scan\n\/\/ according to the specific sample method.\ntype TableSampleExecutor struct {\n\tbaseExecutor\n\n\ttable table.Table\n\tstartTS uint64\n\n\tsampler rowSampler\n}\n\n\/\/ Open initializes necessary variables for using this executor.\nfunc (e *TableSampleExecutor) Open(ctx context.Context) error {\n\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\n\t\tspan1 := span.Tracer().StartSpan(\"TableSampleExecutor.Open\", opentracing.ChildOf(span.Context()))\n\t\tdefer span1.Finish()\n\t}\n\treturn nil\n}\n\n\/\/ Next fills data into the chunk passed by its caller.\n\/\/ The task was actually done by sampler.\nfunc (e *TableSampleExecutor) Next(ctx context.Context, req *chunk.Chunk) error {\n\treq.Reset()\n\tif e.sampler.finished() {\n\t\treturn nil\n\t}\n\t\/\/ TODO(tangenta): add runtime stat & memory tracing\n\treturn e.sampler.writeChunk(req)\n}\n\n\/\/ Close implements the Executor Close interface.\nfunc (e *TableSampleExecutor) Close() error {\n\treturn nil\n}\n\ntype rowSampler interface {\n\twriteChunk(req *chunk.Chunk) error\n\tfinished() bool\n}\n\ntype tableRegionSampler struct {\n\tctx sessionctx.Context\n\ttable table.Table\n\tstartTS uint64\n\tpartTables []table.PartitionedTable\n\tschema *expression.Schema\n\tfullSchema *expression.Schema\n\tisDesc bool\n\tretTypes []*types.FieldType\n\n\trowMap map[int64]types.Datum\n\trestKVRanges []kv.KeyRange\n\tisFinished bool\n}\n\nfunc newTableRegionSampler(ctx sessionctx.Context, t table.Table, startTs uint64, partTables []table.PartitionedTable,\n\tschema *expression.Schema, fullSchema *expression.Schema, retTypes []*types.FieldType, desc bool) *tableRegionSampler {\n\treturn &tableRegionSampler{\n\t\tctx: ctx,\n\t\ttable: t,\n\t\tstartTS: startTs,\n\t\tpartTables: partTables,\n\t\tschema: schema,\n\t\tfullSchema: fullSchema,\n\t\tisDesc: desc,\n\t\tretTypes: retTypes,\n\t\trowMap: make(map[int64]types.Datum),\n\t}\n}\n\nfunc (s *tableRegionSampler) writeChunk(req *chunk.Chunk) error {\n\terr := s.initRanges()\n\tif err != nil {\n\t\treturn err\n\t}\n\texpectedRowCount := req.RequiredRows()\n\tfor expectedRowCount > 0 && len(s.restKVRanges) > 0 {\n\t\tranges, err := s.pickRanges(expectedRowCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.writeChunkFromRanges(ranges, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\texpectedRowCount = req.RequiredRows() - req.NumRows()\n\t}\n\tif len(s.restKVRanges) == 0 {\n\t\ts.isFinished = true\n\t}\n\treturn nil\n}\n\nfunc (s *tableRegionSampler) initRanges() error {\n\tif s.restKVRanges == nil {\n\t\tvar err error\n\t\ts.restKVRanges, err = s.splitTableRanges()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsortRanges(s.restKVRanges, s.isDesc)\n\t}\n\treturn nil\n}\n\nfunc (s *tableRegionSampler) pickRanges(count int) ([]kv.KeyRange, error) {\n\tvar regionKeyRanges []kv.KeyRange\n\tcutPoint := count\n\tif len(s.restKVRanges) < cutPoint {\n\t\tcutPoint = len(s.restKVRanges)\n\t}\n\tregionKeyRanges, s.restKVRanges = s.restKVRanges[:cutPoint], s.restKVRanges[cutPoint:]\n\treturn regionKeyRanges, nil\n}\n\nfunc (s *tableRegionSampler) writeChunkFromRanges(ranges []kv.KeyRange, req *chunk.Chunk) error {\n\tdecLoc := s.ctx.GetSessionVars().Location()\n\tcols, decColMap, err := s.buildSampleColAndDecodeColMap()\n\tif err != nil {\n\t\treturn err\n\t}\n\trowDecoder := decoder.NewRowDecoder(s.table, cols, decColMap)\n\terr = s.scanFirstKVForEachRange(ranges, func(handle kv.Handle, value []byte) error {\n\t\t_, err := rowDecoder.DecodeAndEvalRowWithMap(s.ctx, handle, value, decLoc, s.rowMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcurrentRow := rowDecoder.CurrentRowWithDefaultVal()\n\t\tmutRow := chunk.MutRowFromTypes(s.retTypes)\n\t\tfor i, col := range s.schema.Columns {\n\t\t\toffset := decColMap[col.ID].Col.Offset\n\t\t\ttarget := currentRow.GetDatum(offset, s.retTypes[i])\n\t\t\tmutRow.SetDatum(i, target)\n\t\t}\n\t\treq.AppendRow(mutRow.ToRow())\n\t\ts.resetRowMap()\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (s *tableRegionSampler) splitTableRanges() ([]kv.KeyRange, error) {\n\tif len(s.partTables) != 0 {\n\t\tvar ranges []kv.KeyRange\n\t\tfor _, t := range s.partTables {\n\t\t\tfor _, pid := range t.GetAllPartitionIDs() {\n\t\t\t\tstart := tablecodec.GenTableRecordPrefix(pid)\n\t\t\t\tend := start.PrefixNext()\n\t\t\t\trs, err := splitIntoMultiRanges(s.ctx.GetStore(), start, end)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tranges = append(ranges, rs...)\n\t\t\t}\n\t\t}\n\t\treturn ranges, nil\n\t}\n\tstartKey, endKey := s.table.RecordPrefix(), s.table.RecordPrefix().PrefixNext()\n\treturn splitIntoMultiRanges(s.ctx.GetStore(), startKey, endKey)\n}\n\nfunc splitIntoMultiRanges(store kv.Storage, startKey, endKey kv.Key) ([]kv.KeyRange, error) {\n\tkvRange := kv.KeyRange{StartKey: startKey, EndKey: endKey}\n\n\ts, ok := store.(tikv.Storage)\n\tif !ok {\n\t\treturn []kv.KeyRange{kvRange}, nil\n\t}\n\n\tmaxSleep := 10000 \/\/ ms\n\tbo := tikv.NewBackofferWithVars(context.Background(), maxSleep, nil)\n\tregions, err := s.GetRegionCache().LoadRegionsInKeyRange(bo, startKey, endKey)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tvar ranges = make([]kv.KeyRange, 0, len(regions))\n\tfor _, r := range regions {\n\t\tstart, end := r.StartKey(), r.EndKey()\n\t\tif kv.Key(start).Cmp(startKey) < 0 {\n\t\t\tstart = startKey\n\t\t}\n\t\tif end == nil || kv.Key(end).Cmp(endKey) > 0 {\n\t\t\tend = endKey\n\t\t}\n\t\tranges = append(ranges, kv.KeyRange{StartKey: start, EndKey: end})\n\t}\n\tif len(ranges) == 0 {\n\t\treturn nil, errors.Trace(errors.Errorf(\"no regions found\"))\n\t}\n\treturn ranges, nil\n}\n\nfunc sortRanges(ranges []kv.KeyRange, isDesc bool) {\n\tsort.Slice(ranges, func(i, j int) bool {\n\t\tir, jr := ranges[i].StartKey, ranges[j].StartKey\n\t\tif !isDesc {\n\t\t\treturn ir.Cmp(jr) < 0\n\t\t}\n\t\treturn ir.Cmp(jr) > 0\n\t})\n}\n\nfunc (s *tableRegionSampler) buildSampleColAndDecodeColMap() ([]*table.Column, map[int64]decoder.Column, error) {\n\tschemaCols := s.schema.Columns\n\tcols := make([]*table.Column, 0, len(schemaCols))\n\tcolMap := make(map[int64]decoder.Column, len(schemaCols))\n\ttableCols := s.table.Cols()\n\n\tfor _, schemaCol := range schemaCols {\n\t\tfor _, tableCol := range tableCols {\n\t\t\tif tableCol.ID != schemaCol.ID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ The `MutRow` produced by `DecodeAndEvalRowWithMap` used `ColumnInfo.Offset` as indices.\n\t\t\t\/\/ To evaluate the columns in virtual generated expression properly,\n\t\t\t\/\/ indices of column(Column.Index) needs to be resolved against full column's schema.\n\t\t\tif schemaCol.VirtualExpr != nil {\n\t\t\t\tvar err error\n\t\t\t\tschemaCol.VirtualExpr, err = schemaCol.VirtualExpr.ResolveIndices(s.fullSchema)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tcolMap[tableCol.ID] = decoder.Column{\n\t\t\t\tCol: tableCol,\n\t\t\t\tGenExpr: schemaCol.VirtualExpr,\n\t\t\t}\n\t\t\tcols = append(cols, tableCol)\n\t\t}\n\t}\n\t\/\/ Schema columns contain _tidb_rowid, append extra handle column info.\n\tif len(cols) < len(schemaCols) && schemaCols[len(schemaCols)-1].ID == model.ExtraHandleID {\n\t\textraHandle := model.NewExtraHandleColInfo()\n\t\textraHandle.Offset = len(cols)\n\t\ttableCol := &table.Column{ColumnInfo: extraHandle}\n\t\tcolMap[model.ExtraHandleID] = decoder.Column{\n\t\t\tCol: tableCol,\n\t\t}\n\t\tcols = append(cols, tableCol)\n\t}\n\treturn cols, colMap, nil\n}\n\nfunc (s *tableRegionSampler) scanFirstKVForEachRange(ranges []kv.KeyRange,\n\tfn func(handle kv.Handle, value []byte) error) error {\n\tver := kv.Version{Ver: s.startTS}\n\tsnap := s.ctx.GetStore().GetSnapshot(ver)\n\tsetOptionForTopSQL(s.ctx.GetSessionVars().StmtCtx, snap)\n\tconcurrency := sampleMethodRegionConcurrency\n\tif len(ranges) < concurrency {\n\t\tconcurrency = len(ranges)\n\t}\n\n\tfetchers := make([]*sampleFetcher, concurrency)\n\tfor i := 0; i < concurrency; i++ {\n\t\tfetchers[i] = &sampleFetcher{\n\t\t\tworkerID: i,\n\t\t\tconcurrency: concurrency,\n\t\t\tkvChan: make(chan *sampleKV),\n\t\t\tsnapshot: snap,\n\t\t\tranges: ranges,\n\t\t}\n\t\tgo fetchers[i].run()\n\t}\n\tsyncer := sampleSyncer{\n\t\tfetchers: fetchers,\n\t\ttotalCount: len(ranges),\n\t\tconsumeFn: fn,\n\t}\n\treturn syncer.sync()\n}\n\nfunc (s *tableRegionSampler) resetRowMap() {\n\tif s.rowMap == nil {\n\t\tcolLen := len(s.schema.Columns)\n\t\ts.rowMap = make(map[int64]types.Datum, colLen)\n\t\treturn\n\t}\n\tfor id := range s.rowMap {\n\t\tdelete(s.rowMap, id)\n\t}\n}\n\nfunc (s *tableRegionSampler) finished() bool {\n\treturn s.isFinished\n}\n\ntype sampleKV struct {\n\thandle kv.Handle\n\tvalue []byte\n}\n\ntype sampleFetcher struct {\n\tworkerID int\n\tconcurrency int\n\tkvChan chan *sampleKV\n\terr error\n\tsnapshot kv.Snapshot\n\tranges []kv.KeyRange\n}\n\nfunc (s *sampleFetcher) run() {\n\tdefer close(s.kvChan)\n\tfor i, r := range s.ranges {\n\t\tif i%s.concurrency != s.workerID {\n\t\t\tcontinue\n\t\t}\n\t\tit, err := s.snapshot.Iter(r.StartKey, r.EndKey)\n\t\tif err != nil {\n\t\t\ts.err = err\n\t\t\treturn\n\t\t}\n\t\thasValue := false\n\t\tfor it.Valid() {\n\t\t\tif !tablecodec.IsRecordKey(it.Key()) {\n\t\t\t\tif err = it.Next(); err != nil {\n\t\t\t\t\ts.err = err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thandle, err := tablecodec.DecodeRowKey(it.Key())\n\t\t\tif err != nil {\n\t\t\t\ts.err = err\n\t\t\t\treturn\n\t\t\t}\n\t\t\thasValue = true\n\t\t\ts.kvChan <- &sampleKV{handle: handle, value: it.Value()}\n\t\t\tbreak\n\t\t}\n\t\tif !hasValue {\n\t\t\ts.kvChan <- nil\n\t\t}\n\t}\n}\n\ntype sampleSyncer struct {\n\tfetchers []*sampleFetcher\n\ttotalCount int\n\tconsumeFn func(handle kv.Handle, value []byte) error\n}\n\nfunc (s *sampleSyncer) sync() error {\n\tdefer func() {\n\t\tfor _, f := range s.fetchers {\n\t\t\t\/\/ Cleanup channels to terminate fetcher goroutines.\n\t\t\tfor _, ok := <-f.kvChan; ok; {\n\t\t\t}\n\t\t}\n\t}()\n\tfor i := 0; i < s.totalCount; i++ {\n\t\tf := s.fetchers[i%len(s.fetchers)]\n\t\tv, ok := <-f.kvChan\n\t\tif f.err != nil {\n\t\t\treturn f.err\n\t\t}\n\t\tif ok && v != nil {\n\t\t\terr := s.consumeFn(v.handle, v.value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\nexecutor: control the tablesample concurrency with system var (#34900)\/\/ Copyright 2020 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage executor\n\nimport (\n\t\"context\"\n\t\"sort\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/pingcap\/errors\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/parser\/model\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\t\"github.com\/pingcap\/tidb\/table\"\n\t\"github.com\/pingcap\/tidb\/tablecodec\"\n\t\"github.com\/pingcap\/tidb\/types\"\n\t\"github.com\/pingcap\/tidb\/util\/chunk\"\n\tdecoder \"github.com\/pingcap\/tidb\/util\/rowDecoder\"\n\t\"github.com\/tikv\/client-go\/v2\/tikv\"\n)\n\nvar _ Executor = &TableSampleExecutor{}\n\n\/\/ TableSampleExecutor fetches a few rows through kv.Scan\n\/\/ according to the specific sample method.\ntype TableSampleExecutor struct {\n\tbaseExecutor\n\n\ttable table.Table\n\tstartTS uint64\n\n\tsampler rowSampler\n}\n\n\/\/ Open initializes necessary variables for using this executor.\nfunc (e *TableSampleExecutor) Open(ctx context.Context) error {\n\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\n\t\tspan1 := span.Tracer().StartSpan(\"TableSampleExecutor.Open\", opentracing.ChildOf(span.Context()))\n\t\tdefer span1.Finish()\n\t}\n\treturn nil\n}\n\n\/\/ Next fills data into the chunk passed by its caller.\n\/\/ The task was actually done by sampler.\nfunc (e *TableSampleExecutor) Next(ctx context.Context, req *chunk.Chunk) error {\n\treq.Reset()\n\tif e.sampler.finished() {\n\t\treturn nil\n\t}\n\t\/\/ TODO(tangenta): add runtime stat & memory tracing\n\treturn e.sampler.writeChunk(req)\n}\n\n\/\/ Close implements the Executor Close interface.\nfunc (e *TableSampleExecutor) Close() error {\n\treturn nil\n}\n\ntype rowSampler interface {\n\twriteChunk(req *chunk.Chunk) error\n\tfinished() bool\n}\n\ntype tableRegionSampler struct {\n\tctx sessionctx.Context\n\ttable table.Table\n\tstartTS uint64\n\tpartTables []table.PartitionedTable\n\tschema *expression.Schema\n\tfullSchema *expression.Schema\n\tisDesc bool\n\tretTypes []*types.FieldType\n\n\trowMap map[int64]types.Datum\n\trestKVRanges []kv.KeyRange\n\tisFinished bool\n}\n\nfunc newTableRegionSampler(ctx sessionctx.Context, t table.Table, startTs uint64, partTables []table.PartitionedTable,\n\tschema *expression.Schema, fullSchema *expression.Schema, retTypes []*types.FieldType, desc bool) *tableRegionSampler {\n\treturn &tableRegionSampler{\n\t\tctx: ctx,\n\t\ttable: t,\n\t\tstartTS: startTs,\n\t\tpartTables: partTables,\n\t\tschema: schema,\n\t\tfullSchema: fullSchema,\n\t\tisDesc: desc,\n\t\tretTypes: retTypes,\n\t\trowMap: make(map[int64]types.Datum),\n\t}\n}\n\nfunc (s *tableRegionSampler) writeChunk(req *chunk.Chunk) error {\n\terr := s.initRanges()\n\tif err != nil {\n\t\treturn err\n\t}\n\texpectedRowCount := req.RequiredRows()\n\tfor expectedRowCount > 0 && len(s.restKVRanges) > 0 {\n\t\tranges, err := s.pickRanges(expectedRowCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.writeChunkFromRanges(ranges, req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\texpectedRowCount = req.RequiredRows() - req.NumRows()\n\t}\n\tif len(s.restKVRanges) == 0 {\n\t\ts.isFinished = true\n\t}\n\treturn nil\n}\n\nfunc (s *tableRegionSampler) initRanges() error {\n\tif s.restKVRanges == nil {\n\t\tvar err error\n\t\ts.restKVRanges, err = s.splitTableRanges()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsortRanges(s.restKVRanges, s.isDesc)\n\t}\n\treturn nil\n}\n\nfunc (s *tableRegionSampler) pickRanges(count int) ([]kv.KeyRange, error) {\n\tvar regionKeyRanges []kv.KeyRange\n\tcutPoint := count\n\tif len(s.restKVRanges) < cutPoint {\n\t\tcutPoint = len(s.restKVRanges)\n\t}\n\tregionKeyRanges, s.restKVRanges = s.restKVRanges[:cutPoint], s.restKVRanges[cutPoint:]\n\treturn regionKeyRanges, nil\n}\n\nfunc (s *tableRegionSampler) writeChunkFromRanges(ranges []kv.KeyRange, req *chunk.Chunk) error {\n\tdecLoc := s.ctx.GetSessionVars().Location()\n\tcols, decColMap, err := s.buildSampleColAndDecodeColMap()\n\tif err != nil {\n\t\treturn err\n\t}\n\trowDecoder := decoder.NewRowDecoder(s.table, cols, decColMap)\n\terr = s.scanFirstKVForEachRange(ranges, func(handle kv.Handle, value []byte) error {\n\t\t_, err := rowDecoder.DecodeAndEvalRowWithMap(s.ctx, handle, value, decLoc, s.rowMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcurrentRow := rowDecoder.CurrentRowWithDefaultVal()\n\t\tmutRow := chunk.MutRowFromTypes(s.retTypes)\n\t\tfor i, col := range s.schema.Columns {\n\t\t\toffset := decColMap[col.ID].Col.Offset\n\t\t\ttarget := currentRow.GetDatum(offset, s.retTypes[i])\n\t\t\tmutRow.SetDatum(i, target)\n\t\t}\n\t\treq.AppendRow(mutRow.ToRow())\n\t\ts.resetRowMap()\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (s *tableRegionSampler) splitTableRanges() ([]kv.KeyRange, error) {\n\tif len(s.partTables) != 0 {\n\t\tvar ranges []kv.KeyRange\n\t\tfor _, t := range s.partTables {\n\t\t\tfor _, pid := range t.GetAllPartitionIDs() {\n\t\t\t\tstart := tablecodec.GenTableRecordPrefix(pid)\n\t\t\t\tend := start.PrefixNext()\n\t\t\t\trs, err := splitIntoMultiRanges(s.ctx.GetStore(), start, end)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tranges = append(ranges, rs...)\n\t\t\t}\n\t\t}\n\t\treturn ranges, nil\n\t}\n\tstartKey, endKey := s.table.RecordPrefix(), s.table.RecordPrefix().PrefixNext()\n\treturn splitIntoMultiRanges(s.ctx.GetStore(), startKey, endKey)\n}\n\nfunc splitIntoMultiRanges(store kv.Storage, startKey, endKey kv.Key) ([]kv.KeyRange, error) {\n\tkvRange := kv.KeyRange{StartKey: startKey, EndKey: endKey}\n\n\ts, ok := store.(tikv.Storage)\n\tif !ok {\n\t\treturn []kv.KeyRange{kvRange}, nil\n\t}\n\n\tmaxSleep := 10000 \/\/ ms\n\tbo := tikv.NewBackofferWithVars(context.Background(), maxSleep, nil)\n\tregions, err := s.GetRegionCache().LoadRegionsInKeyRange(bo, startKey, endKey)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tvar ranges = make([]kv.KeyRange, 0, len(regions))\n\tfor _, r := range regions {\n\t\tstart, end := r.StartKey(), r.EndKey()\n\t\tif kv.Key(start).Cmp(startKey) < 0 {\n\t\t\tstart = startKey\n\t\t}\n\t\tif end == nil || kv.Key(end).Cmp(endKey) > 0 {\n\t\t\tend = endKey\n\t\t}\n\t\tranges = append(ranges, kv.KeyRange{StartKey: start, EndKey: end})\n\t}\n\tif len(ranges) == 0 {\n\t\treturn nil, errors.Trace(errors.Errorf(\"no regions found\"))\n\t}\n\treturn ranges, nil\n}\n\nfunc sortRanges(ranges []kv.KeyRange, isDesc bool) {\n\tsort.Slice(ranges, func(i, j int) bool {\n\t\tir, jr := ranges[i].StartKey, ranges[j].StartKey\n\t\tif !isDesc {\n\t\t\treturn ir.Cmp(jr) < 0\n\t\t}\n\t\treturn ir.Cmp(jr) > 0\n\t})\n}\n\nfunc (s *tableRegionSampler) buildSampleColAndDecodeColMap() ([]*table.Column, map[int64]decoder.Column, error) {\n\tschemaCols := s.schema.Columns\n\tcols := make([]*table.Column, 0, len(schemaCols))\n\tcolMap := make(map[int64]decoder.Column, len(schemaCols))\n\ttableCols := s.table.Cols()\n\n\tfor _, schemaCol := range schemaCols {\n\t\tfor _, tableCol := range tableCols {\n\t\t\tif tableCol.ID != schemaCol.ID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ The `MutRow` produced by `DecodeAndEvalRowWithMap` used `ColumnInfo.Offset` as indices.\n\t\t\t\/\/ To evaluate the columns in virtual generated expression properly,\n\t\t\t\/\/ indices of column(Column.Index) needs to be resolved against full column's schema.\n\t\t\tif schemaCol.VirtualExpr != nil {\n\t\t\t\tvar err error\n\t\t\t\tschemaCol.VirtualExpr, err = schemaCol.VirtualExpr.ResolveIndices(s.fullSchema)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tcolMap[tableCol.ID] = decoder.Column{\n\t\t\t\tCol: tableCol,\n\t\t\t\tGenExpr: schemaCol.VirtualExpr,\n\t\t\t}\n\t\t\tcols = append(cols, tableCol)\n\t\t}\n\t}\n\t\/\/ Schema columns contain _tidb_rowid, append extra handle column info.\n\tif len(cols) < len(schemaCols) && schemaCols[len(schemaCols)-1].ID == model.ExtraHandleID {\n\t\textraHandle := model.NewExtraHandleColInfo()\n\t\textraHandle.Offset = len(cols)\n\t\ttableCol := &table.Column{ColumnInfo: extraHandle}\n\t\tcolMap[model.ExtraHandleID] = decoder.Column{\n\t\t\tCol: tableCol,\n\t\t}\n\t\tcols = append(cols, tableCol)\n\t}\n\treturn cols, colMap, nil\n}\n\nfunc (s *tableRegionSampler) scanFirstKVForEachRange(ranges []kv.KeyRange,\n\tfn func(handle kv.Handle, value []byte) error) error {\n\tver := kv.Version{Ver: s.startTS}\n\tsnap := s.ctx.GetStore().GetSnapshot(ver)\n\tsetOptionForTopSQL(s.ctx.GetSessionVars().StmtCtx, snap)\n\tconcurrency := s.ctx.GetSessionVars().ExecutorConcurrency\n\tif len(ranges) < concurrency {\n\t\tconcurrency = len(ranges)\n\t}\n\n\tfetchers := make([]*sampleFetcher, concurrency)\n\tfor i := 0; i < concurrency; i++ {\n\t\tfetchers[i] = &sampleFetcher{\n\t\t\tworkerID: i,\n\t\t\tconcurrency: concurrency,\n\t\t\tkvChan: make(chan *sampleKV),\n\t\t\tsnapshot: snap,\n\t\t\tranges: ranges,\n\t\t}\n\t\tgo fetchers[i].run()\n\t}\n\tsyncer := sampleSyncer{\n\t\tfetchers: fetchers,\n\t\ttotalCount: len(ranges),\n\t\tconsumeFn: fn,\n\t}\n\treturn syncer.sync()\n}\n\nfunc (s *tableRegionSampler) resetRowMap() {\n\tif s.rowMap == nil {\n\t\tcolLen := len(s.schema.Columns)\n\t\ts.rowMap = make(map[int64]types.Datum, colLen)\n\t\treturn\n\t}\n\tfor id := range s.rowMap {\n\t\tdelete(s.rowMap, id)\n\t}\n}\n\nfunc (s *tableRegionSampler) finished() bool {\n\treturn s.isFinished\n}\n\ntype sampleKV struct {\n\thandle kv.Handle\n\tvalue []byte\n}\n\ntype sampleFetcher struct {\n\tworkerID int\n\tconcurrency int\n\tkvChan chan *sampleKV\n\terr error\n\tsnapshot kv.Snapshot\n\tranges []kv.KeyRange\n}\n\nfunc (s *sampleFetcher) run() {\n\tdefer close(s.kvChan)\n\tfor i, r := range s.ranges {\n\t\tif i%s.concurrency != s.workerID {\n\t\t\tcontinue\n\t\t}\n\t\tit, err := s.snapshot.Iter(r.StartKey, r.EndKey)\n\t\tif err != nil {\n\t\t\ts.err = err\n\t\t\treturn\n\t\t}\n\t\thasValue := false\n\t\tfor it.Valid() {\n\t\t\tif !tablecodec.IsRecordKey(it.Key()) {\n\t\t\t\tif err = it.Next(); err != nil {\n\t\t\t\t\ts.err = err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thandle, err := tablecodec.DecodeRowKey(it.Key())\n\t\t\tif err != nil {\n\t\t\t\ts.err = err\n\t\t\t\treturn\n\t\t\t}\n\t\t\thasValue = true\n\t\t\ts.kvChan <- &sampleKV{handle: handle, value: it.Value()}\n\t\t\tbreak\n\t\t}\n\t\tif !hasValue {\n\t\t\ts.kvChan <- nil\n\t\t}\n\t}\n}\n\ntype sampleSyncer struct {\n\tfetchers []*sampleFetcher\n\ttotalCount int\n\tconsumeFn func(handle kv.Handle, value []byte) error\n}\n\nfunc (s *sampleSyncer) sync() error {\n\tdefer func() {\n\t\tfor _, f := range s.fetchers {\n\t\t\t\/\/ Cleanup channels to terminate fetcher goroutines.\n\t\t\tfor _, ok := <-f.kvChan; ok; {\n\t\t\t}\n\t\t}\n\t}()\n\tfor i := 0; i < s.totalCount; i++ {\n\t\tf := s.fetchers[i%len(s.fetchers)]\n\t\tv, ok := <-f.kvChan\n\t\tif f.err != nil {\n\t\t\treturn f.err\n\t\t}\n\t\tif ok && v != nil {\n\t\t\terr := s.consumeFn(v.handle, v.value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package graphql_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/graphql-go\/graphql\"\n\t\"github.com\/graphql-go\/graphql\/testutil\"\n)\n\nfunc makeSubscribeToStringFunction(elements []string) func(p graphql.ResolveParams) (interface{}, error) {\n\treturn func(p graphql.ResolveParams) (interface{}, error) {\n\t\tc := make(chan interface{})\n\t\tgo func() {\n\t\t\tfor _, r := range elements {\n\t\t\t\tselect {\n\t\t\t\tcase <-p.Context.Done():\n\t\t\t\t\tclose(c)\n\t\t\t\t\treturn\n\t\t\t\tcase c <- r:\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(c)\n\t\t}()\n\t\treturn c, nil\n\t}\n}\n\nfunc makeSubscribeToMapFunction(elements []map[string]interface{}) func(p graphql.ResolveParams) (interface{}, error) {\n\treturn func(p graphql.ResolveParams) (interface{}, error) {\n\t\tc := make(chan interface{})\n\t\tgo func() {\n\t\t\tfor _, r := range elements {\n\t\t\t\tselect {\n\t\t\t\tcase <-p.Context.Done():\n\t\t\t\t\tclose(c)\n\t\t\t\t\treturn\n\t\t\t\tcase c <- r:\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(c)\n\t\t}()\n\t\treturn c, nil\n\t}\n}\n\nfunc makeSubscriptionSchema(t *testing.T, c graphql.ObjectConfig) graphql.Schema {\n\tschema, err := graphql.NewSchema(graphql.SchemaConfig{\n\t\tQuery: dummyQuery,\n\t\tSubscription: graphql.NewObject(c),\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"failed to create schema: %v\", err)\n\t}\n\treturn schema\n}\n\nfunc TestSchemaSubscribe(t *testing.T) {\n\n\ttestutil.RunSubscribes(t, []*testutil.TestSubscription{\n\t\t{\n\t\t\tName: \"subscribe without resolver\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_without_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\"}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) { \/\/ TODO remove dummy resolver\n\t\t\t\t\t\t\treturn p.Source, nil\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_without_resolver\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"a\" }`},\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"b\" }`},\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"c\" }`},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"receive query validation error\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_without_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\"}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_without_resolver\n\t\t\t\t\txxx\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Errors: []string{\"Cannot query field \\\"xxx\\\" on type \\\"Subscription\\\".\"}},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"subscribe with resolver changes output\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_with_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\", \"d\"}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\t\t\treturn fmt.Sprintf(\"result=%v\", p.Source), nil\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_with_resolver\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=a\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=b\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=c\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=d\" }`},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"subscribe to a nested object\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_with_object\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.NewObject(graphql.ObjectConfig{\n\t\t\t\t\t\t\tName: \"Obj\",\n\t\t\t\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\t\t\t\"field\": &graphql.Field{\n\t\t\t\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) { \/\/ TODO remove dummy resolver\n\t\t\t\t\t\t\treturn p.Source, nil\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSubscribe: makeSubscribeToMapFunction([]map[string]interface{}{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": \"hello\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": \"bye\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_with_object {\n\t\t\t\t\t\tfield\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": \"hello\" } }`},\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": \"bye\" } }`},\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": null } }`},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tName: \"subscription_resolver_can_error\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"should_error\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\t\t\treturn nil, errors.New(\"got a subscribe error\")\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription {\n\t\t\t\t\tshould_error\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{\n\t\t\t\t\tErrors: []string{\"got a subscribe error\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tName: \"schema_without_subscribe_errors\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"should_error\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription {\n\t\t\t\t\tshould_error\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{\n\t\t\t\t\tErrors: []string{\"the subscription function \\\"should_error\\\" is not defined\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n}\n\n\/\/ func TestRootOperations_invalidSubscriptionSchema(t *testing.T) {\n\/\/ \ttype args struct {\n\/\/ \t\tSchema string\n\/\/ \t}\n\/\/ \ttype want struct {\n\/\/ \t\tError string\n\/\/ \t}\n\/\/ \ttestTable := map[string]struct {\n\/\/ \t\tArgs args\n\/\/ \t\tWant want\n\/\/ \t}{\n\/\/ \t\t\"Subscription as incorrect type\": {\n\/\/ \t\t\tArgs: args{\n\/\/ \t\t\t\tSchema: `\n\/\/ \t\t\t\t\tschema {\n\/\/ \t\t\t\t\t\tquery: Query\n\/\/ \t\t\t\t\t\tsubscription: String\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\ttype Query {\n\/\/ \t\t\t\t\t\tthing: String\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t`,\n\/\/ \t\t\t},\n\/\/ \t\t\tWant: want{Error: `root operation \"subscription\" must be an OBJECT`},\n\/\/ \t\t},\n\/\/ \t\t\"Subscription declared by schema, but type not present\": {\n\/\/ \t\t\tArgs: args{\n\/\/ \t\t\t\tSchema: `\n\/\/ \t\t\t\t\tschema {\n\/\/ \t\t\t\t\t\tquery: Query\n\/\/ \t\t\t\t\t\tsubscription: Subscription\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t\ttype Query {\n\/\/ \t\t\t\t\t\thello: String!\n\/\/ \t\t\t\t\t}\n\/\/ \t\t\t\t`,\n\/\/ \t\t\t},\n\/\/ \t\t\tWant: want{Error: `graphql: type \"Subscription\" not found`},\n\/\/ \t\t},\n\/\/ \t}\n\n\/\/ \tfor name, tt := range testTable {\n\/\/ \t\ttt := tt\n\/\/ \t\tt.Run(name, func(t *testing.T) {\n\/\/ \t\t\tt.Log(tt.Args.Schema) \/\/ TODO do something\n\/\/ \t\t})\n\/\/ \t}\n\/\/ }\n\nvar dummyQuery = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"Query\",\n\tFields: graphql.Fields{\n\n\t\t\"hello\": &graphql.Field{Type: graphql.String},\n\t},\n})\nsubscription_test: refactored testspackage graphql_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/graphql-go\/graphql\"\n\t\"github.com\/graphql-go\/graphql\/testutil\"\n)\n\nfunc TestSchemaSubscribe(t *testing.T) {\n\n\ttestutil.RunSubscribes(t, []*testutil.TestSubscription{\n\t\t{\n\t\t\tName: \"subscribe without resolver\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_without_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\"}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) { \/\/ TODO remove dummy resolver\n\t\t\t\t\t\t\treturn p.Source, nil\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_without_resolver\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"a\" }`},\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"b\" }`},\n\t\t\t\t{Data: `{ \"sub_without_resolver\": \"c\" }`},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"receive query validation error\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_without_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\"}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_without_resolver\n\t\t\t\t\txxx\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Errors: []string{\"Cannot query field \\\"xxx\\\" on type \\\"Subscription\\\".\"}},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"subscribe with resolver changes output\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_with_resolver\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: makeSubscribeToStringFunction([]string{\"a\", \"b\", \"c\", \"d\"}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\t\t\treturn fmt.Sprintf(\"result=%v\", p.Source), nil\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_with_resolver\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=a\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=b\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=c\" }`},\n\t\t\t\t{Data: `{ \"sub_with_resolver\": \"result=d\" }`},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"subscribe to a nested object\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"sub_with_object\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.NewObject(graphql.ObjectConfig{\n\t\t\t\t\t\t\tName: \"Obj\",\n\t\t\t\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\t\t\t\"field\": &graphql.Field{\n\t\t\t\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) { \/\/ TODO remove dummy resolver\n\t\t\t\t\t\t\treturn p.Source, nil\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSubscribe: makeSubscribeToMapFunction([]map[string]interface{}{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": \"hello\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": \"bye\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"field\": nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription onHelloSaid {\n\t\t\t\t\tsub_with_object {\n\t\t\t\t\t\tfield\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": \"hello\" } }`},\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": \"bye\" } }`},\n\t\t\t\t{Data: `{ \"sub_with_object\": { \"field\": null } }`},\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tName: \"subscription_resolver_can_error\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"should_error\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t\tSubscribe: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\t\t\treturn nil, errors.New(\"got a subscribe error\")\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription {\n\t\t\t\t\tshould_error\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{\n\t\t\t\t\tErrors: []string{\"got a subscribe error\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"schema_without_subscribe_errors\",\n\t\t\tSchema: makeSubscriptionSchema(t, graphql.ObjectConfig{\n\t\t\t\tName: \"Subscription\",\n\t\t\t\tFields: graphql.Fields{\n\t\t\t\t\t\"should_error\": &graphql.Field{\n\t\t\t\t\t\tType: graphql.String,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\tQuery: `\n\t\t\t\tsubscription {\n\t\t\t\t\tshould_error\n\t\t\t\t}\n\t\t\t`,\n\t\t\tExpectedResults: []testutil.TestResponse{\n\t\t\t\t{\n\t\t\t\t\tErrors: []string{\"the subscription function \\\"should_error\\\" is not defined\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc makeSubscribeToStringFunction(elements []string) func(p graphql.ResolveParams) (interface{}, error) {\n\treturn func(p graphql.ResolveParams) (interface{}, error) {\n\t\tc := make(chan interface{})\n\t\tgo func() {\n\t\t\tfor _, r := range elements {\n\t\t\t\tselect {\n\t\t\t\tcase <-p.Context.Done():\n\t\t\t\t\tclose(c)\n\t\t\t\t\treturn\n\t\t\t\tcase c <- r:\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(c)\n\t\t}()\n\t\treturn c, nil\n\t}\n}\n\nfunc makeSubscribeToMapFunction(elements []map[string]interface{}) func(p graphql.ResolveParams) (interface{}, error) {\n\treturn func(p graphql.ResolveParams) (interface{}, error) {\n\t\tc := make(chan interface{})\n\t\tgo func() {\n\t\t\tfor _, r := range elements {\n\t\t\t\tselect {\n\t\t\t\tcase <-p.Context.Done():\n\t\t\t\t\tclose(c)\n\t\t\t\t\treturn\n\t\t\t\tcase c <- r:\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(c)\n\t\t}()\n\t\treturn c, nil\n\t}\n}\n\nfunc makeSubscriptionSchema(t *testing.T, c graphql.ObjectConfig) graphql.Schema {\n\tschema, err := graphql.NewSchema(graphql.SchemaConfig{\n\t\tQuery: dummyQuery,\n\t\tSubscription: graphql.NewObject(c),\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"failed to create schema: %v\", err)\n\t}\n\treturn schema\n}\n\nvar dummyQuery = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"Query\",\n\tFields: graphql.Fields{\n\n\t\t\"hello\": &graphql.Field{Type: graphql.String},\n\t},\n})\n<|endoftext|>"} {"text":"package cc_messages\n\nimport \"time\"\n\ntype LRPInstanceState string\n\nconst (\n\tLRPInstanceStateStarting LRPInstanceState = \"STARTING\"\n\tLRPInstanceStateRunning LRPInstanceState = \"RUNNING\"\n\tLRPInstanceStateCrashed LRPInstanceState = \"CRASHED\"\n\tLRPInstanceStateUnknown LRPInstanceState = \"UNKNOWN\"\n)\n\ntype LRPInstance struct {\n\tProcessGuid string `json:\"process_guid\"`\n\tInstanceGuid string `json:\"instance_guid\"`\n\tIndex uint `json:\"index\"`\n\tState LRPInstanceState `json:\"state\"`\n\tDetails string `json:\"details,omitempty\"`\n\tHost string `json:\"host,omitempty\"`\n\tPort uint16 `json:\"port,omitempty\"`\n\tUptime int64 `json:\"uptime\"`\n\tStats *LRPInstanceStats `json:\"stats,omitempty\"`\n}\n\ntype LRPInstanceStats struct {\n\tTime time.Time `json:\"time\"`\n\tCpuPercentage float64 `json:\"cpu\"`\n\tMemoryBytes uint64 `json:\"mem\"`\n\tDiskBytes uint64 `json:\"disk\"`\n}\nAdd Since to LRPInstance structpackage cc_messages\n\nimport \"time\"\n\ntype LRPInstanceState string\n\nconst (\n\tLRPInstanceStateStarting LRPInstanceState = \"STARTING\"\n\tLRPInstanceStateRunning LRPInstanceState = \"RUNNING\"\n\tLRPInstanceStateCrashed LRPInstanceState = \"CRASHED\"\n\tLRPInstanceStateUnknown LRPInstanceState = \"UNKNOWN\"\n)\n\ntype LRPInstance struct {\n\tProcessGuid string `json:\"process_guid\"`\n\tInstanceGuid string `json:\"instance_guid\"`\n\tIndex uint `json:\"index\"`\n\tState LRPInstanceState `json:\"state\"`\n\tDetails string `json:\"details,omitempty\"`\n\tHost string `json:\"host,omitempty\"`\n\tPort uint16 `json:\"port,omitempty\"`\n\tUptime int64 `json:\"uptime\"`\n\tSince int64 `json:\"since\"`\n\tStats *LRPInstanceStats `json:\"stats,omitempty\"`\n}\n\ntype LRPInstanceStats struct {\n\tTime time.Time `json:\"time\"`\n\tCpuPercentage float64 `json:\"cpu\"`\n\tMemoryBytes uint64 `json:\"mem\"`\n\tDiskBytes uint64 `json:\"disk\"`\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n \"github.com\/ricallinson\/forgery\"\n \"github.com\/spacedock-io\/index\/couch\/models\"\n)\n\nfunc CreateUser(req *f.Request, res *f.Response, next func()) {\n var username, email, password string\n\n if len(req.Body) > 0 {\n username, email, password = req.Body[\"username\"], req.Body[\"email\"],\n req.Body[\"password\"]\n } else if len(req.Request.Map) > 0 {\n username, _ = req.Map[\"username\"].(string)\n password, _ = req.Map[\"password\"].(string)\n email, _ = req.Map[\"email\"].(string)\n }\n\n \/\/ @TODO: Validate email format\n\n if len(password) < 5 {\n res.Send(\"Password too short\", 400)\n } else if len(username) < 4 {\n res.Send(\"Username too short\", 400)\n } else if len(username) > 30 {\n res.Send(\"Username too long\", 400)\n } else {\n \/\/ put user in couch, send confirm email\n u := models.NewUser()\n\n u.Username = username\n u.Email = append(u.Email, email)\n\n e := u.Create(password)\n if (e != nil) {\n \/\/ @TODO: Don't just send the whole error here\n res.Send(e.Error(), 400)\n }\n res.Send(\"User created successfully\", 201)\n \/\/ later on, send an async email\n \/\/go ConfirmEmail()\n }\n\n res.Send(\"Unknown error while trying to register user\", 400)\n}\n\nfunc Login(req *f.Request, res *f.Response, next func()) {\n \/\/ Because of middleware, execution only gets here on success.\n res.Send(\"OK\", 200)\n}\n\nfunc UpdateUser(req *f.Request, res *f.Response, next func()) {\n var username, email, newPass string\n\n username = req.Params[\"username\"]\n\n if len(req.Body) > 0 {\n email = req.Body[\"email\"]\n newPass = req.Body[\"password\"]\n } else if len(req.Map) > 0 {\n email = req.Map[\"email\"].(string)\n newPass = req.Map[\"password\"].(string)\n }\n\n u, e := models.GetUser(username)\n if e != nil {\n res.Send(e.Error(), 400)\n return\n }\n\n if len(newPass) > 5 {\n u.SetPassword(newPass)\n } else if len(newPass) > 0 {\n res.Send(\"Password too short\", 400)\n return\n }\n\n if len(email) > 0 { u.Email = append(u.Email, email) }\n\n e = u.Save(true)\n if e != nil {\n res.Send(e.Error(), 400)\n return\n }\n\n res.Send(\"User Updated\", 204)\n}\nreq.Map -> req.Map[\"json\"]package main\n\nimport (\n \"github.com\/ricallinson\/forgery\"\n \"github.com\/spacedock-io\/index\/couch\/models\"\n)\n\nfunc CreateUser(req *f.Request, res *f.Response, next func()) {\n var username, email, password string\n\n if len(req.Body) > 0 {\n username, email, password = req.Body[\"username\"], req.Body[\"email\"],\n req.Body[\"password\"]\n } else if len(req.Request.Map) > 0 {\n json := req.Map[\"json\"].(map[string]string)\n username, _ = json[\"username\"]\n password, _ = json[\"password\"]\n email, _ = json[\"email\"]\n }\n\n \/\/ @TODO: Validate email format\n\n if len(password) < 5 {\n res.Send(\"Password too short\", 400)\n } else if len(username) < 4 {\n res.Send(\"Username too short\", 400)\n } else if len(username) > 30 {\n res.Send(\"Username too long\", 400)\n } else {\n \/\/ put user in couch, send confirm email\n u := models.NewUser()\n\n u.Username = username\n u.Email = append(u.Email, email)\n\n e := u.Create(password)\n if (e != nil) {\n \/\/ @TODO: Don't just send the whole error here\n res.Send(e.Error(), 400)\n }\n res.Send(\"User created successfully\", 201)\n \/\/ later on, send an async email\n \/\/go ConfirmEmail()\n }\n\n res.Send(\"Unknown error while trying to register user\", 400)\n}\n\nfunc Login(req *f.Request, res *f.Response, next func()) {\n \/\/ Because of middleware, execution only gets here on success.\n res.Send(\"OK\", 200)\n}\n\nfunc UpdateUser(req *f.Request, res *f.Response, next func()) {\n var username, email, newPass string\n\n username = req.Params[\"username\"]\n\n if len(req.Body) > 0 {\n email = req.Body[\"email\"]\n newPass = req.Body[\"password\"]\n } else if len(req.Map) > 0 {\n email = req.Map[\"email\"].(string)\n newPass = req.Map[\"password\"].(string)\n }\n\n u, e := models.GetUser(username)\n if e != nil {\n res.Send(e.Error(), 400)\n return\n }\n\n if len(newPass) > 5 {\n u.SetPassword(newPass)\n } else if len(newPass) > 0 {\n res.Send(\"Password too short\", 400)\n return\n }\n\n if len(email) > 0 { u.Email = append(u.Email, email) }\n\n e = u.Save(true)\n if e != nil {\n res.Send(e.Error(), 400)\n return\n }\n\n res.Send(\"User Updated\", 204)\n}\n<|endoftext|>"} {"text":"package s3gof3r\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype putTest struct {\n\turl string\n\tfile_path string\n\theader string\n\tcheck bool\n\tout string\n}\n\ntype getTest struct {\n\tpath string\n\tconfig *Config\n\trSize int64\n\terr error\n}\n\nvar getTests = []getTest{\n\t{\"testfile\", nil, 22, nil},\n\t{\"NoKey\", nil, 0, &respError{StatusCode: 404, Message: \"The specified key does not exist.\"}},\n}\n\nfunc TestGetReader(t *testing.T) {\n\tb, err := testBucket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, tt := range getTests {\n\t\tr, h, err := b.GetReader(tt.path, tt.config)\n\t\tif !errorMatch(err, tt.err) {\n\t\t\tt.Errorf(\"GetReader called with %v\\n Expected: %v\\n Actual: %v\\n\", tt, tt.err, err)\n\t\t}\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tt.Logf(\"headers %v\\n\", h)\n\t\tw := ioutil.Discard\n\n\t\tn, err := io.Copy(w, r)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif n != tt.rSize {\n\t\t\tt.Errorf(\"Expected size: %d. Actual: %d\", tt.rSize, n)\n\n\t\t}\n\t\terr = r.Close()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t}\n}\n\nfunc testBucket() (*Bucket, error) {\n\tk, err := EnvKeys()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbucket := os.Getenv(\"TEST_BUCKET\")\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"TEST_BUCKET must be set in environment.\")\n\n\t}\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(bucket)\n\n\tw, err := b.PutWriter(\"testfile\", nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := bytes.NewReader([]byte(\"Test file content.....\"))\n\t_, err = io.Copy(w, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n\n}\n\nfunc errorMatch(expect, actual error) bool {\n\n\tif expect == nil && actual == nil {\n\t\treturn true\n\t}\n\n\tif expect == nil || actual == nil {\n\t\treturn false\n\t}\n\n\treturn expect.Error() == actual.Error()\n\n}\n\nfunc ExampleBucket_PutWriter() error {\n\n\tk, err := EnvKeys() \/\/ get S3 keys from environment\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ Open bucket to put file into\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(\"bucketName\")\n\n\t\/\/ open file to upload\n\tfile, err := os.Open(\"fileName\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open a PutWriter for upload\n\tw, err := b.PutWriter(file.Name(), nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = io.Copy(w, file); err != nil { \/\/ Copy into S3\n\t\treturn err\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ExampleBucket_GetReader() error {\n\n\tk, err := EnvKeys() \/\/ get S3 keys from environment\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open bucket to put file into\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(\"bucketName\")\n\n\tr, h, err := b.GetReader(\"keyName\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ stream to standard output\n\tif _, err = io.Copy(os.Stdout, r); err != nil {\n\t\treturn err\n\t}\n\terr = r.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(h) \/\/ print key header data\n\treturn nil\n}\nAdd header put test.package s3gof3r\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype getTest struct {\n\tpath string\n\tconfig *Config\n\trSize int64\n\terr error\n}\n\nvar getTests = []getTest{\n\t{\"testfile\", nil, 22, nil},\n\t{\"NoKey\", nil, 0, &respError{StatusCode: 404, Message: \"The specified key does not exist.\"}},\n}\n\nfunc TestGetReader(t *testing.T) {\n\tb, err := testBucket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, tt := range getTests {\n\t\tr, h, err := b.GetReader(tt.path, tt.config)\n\t\tif !errorMatch(err, tt.err) {\n\t\t\tt.Errorf(\"GetReader called with %v\\n Expected: %v\\n Actual: %v\\n\", tt, tt.err, err)\n\t\t}\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tt.Logf(\"headers %v\\n\", h)\n\t\tw := ioutil.Discard\n\n\t\tn, err := io.Copy(w, r)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif n != tt.rSize {\n\t\t\tt.Errorf(\"Expected size: %d. Actual: %d\", tt.rSize, n)\n\n\t\t}\n\t\terr = r.Close()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t}\n}\n\ntype putTest struct {\n\tpath string\n\tdata []byte\n\theader http.Header\n\tconfig *Config\n\twSize int64\n\terr error\n}\n\nvar putTests = []putTest{\n\t{\"testfile\", []byte(\"test_data\"), nil, nil, 9, nil},\n\t{\"\", []byte(\"test_data\"), nil, nil,\n\t\t9, &respError{StatusCode: 400, Message: \"A key must be specified\"}},\n\t{\"testfile\", []byte(\"\"), nil, nil, 1, nil}, \/\/bug?\n\t{\"testfile\", []byte(\"foo\"), correct_header(), nil, 3, nil},\n}\n\nfunc correct_header() http.Header {\n\theader := make(http.Header)\n\theader.Add(\"x-amz-server-side-encryption\", \"AES256\")\n\theader.Add(\"x-amz-meta-foometadata\", \"testmeta\")\n\n\treturn header\n}\n\nfunc TestPutWriter(t *testing.T) {\n\tb, err := testBucket()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, tt := range putTests {\n\t\tw, err := b.PutWriter(tt.path, tt.header, tt.config)\n\t\tif !errorMatch(err, tt.err) {\n\t\t\tt.Errorf(\"PutWriter called with %v\\n Expected: %v\\n Actual: %v\\n\", tt, tt.err, err)\n\t\t}\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tr := bytes.NewReader(tt.data)\n\n\t\tn, err := io.Copy(w, r)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif n != tt.wSize {\n\t\t\tt.Errorf(\"Expected size: %d. Actual: %d\", tt.wSize, n)\n\n\t\t}\n\t\terr = w.Close()\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t}\n}\n\nfunc testBucket() (*Bucket, error) {\n\tk, err := EnvKeys()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbucket := os.Getenv(\"TEST_BUCKET\")\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"TEST_BUCKET must be set in environment.\")\n\n\t}\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(bucket)\n\n\tw, err := b.PutWriter(\"testfile\", nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := bytes.NewReader([]byte(\"Test file content.....\"))\n\t_, err = io.Copy(w, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n\n}\n\nfunc errorMatch(expect, actual error) bool {\n\n\tif expect == nil && actual == nil {\n\t\treturn true\n\t}\n\n\tif expect == nil || actual == nil {\n\t\treturn false\n\t}\n\n\treturn expect.Error() == actual.Error()\n\n}\n\nfunc ExampleBucket_PutWriter() error {\n\n\tk, err := EnvKeys() \/\/ get S3 keys from environment\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ Open bucket to put file into\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(\"bucketName\")\n\n\t\/\/ open file to upload\n\tfile, err := os.Open(\"fileName\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open a PutWriter for upload\n\tw, err := b.PutWriter(file.Name(), nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = io.Copy(w, file); err != nil { \/\/ Copy into S3\n\t\treturn err\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ExampleBucket_GetReader() error {\n\n\tk, err := EnvKeys() \/\/ get S3 keys from environment\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open bucket to put file into\n\ts3 := New(\"\", k)\n\tb := s3.Bucket(\"bucketName\")\n\n\tr, h, err := b.GetReader(\"keyName\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ stream to standard output\n\tif _, err = io.Copy(os.Stdout, r); err != nil {\n\t\treturn err\n\t}\n\terr = r.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(h) \/\/ print key header data\n\treturn nil\n}\n<|endoftext|>"} {"text":"package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.536\"\nfnserver: 0.3.537 release [skip ci]package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.537\"\n<|endoftext|>"} {"text":"package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.610\"\nfnserver: 0.3.611 release [skip ci]package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.611\"\n<|endoftext|>"} {"text":"package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.383\"\nfnserver: 0.3.384 release [skip ci]package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.384\"\n<|endoftext|>"} {"text":"package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.313\"\nfnserver: 0.3.314 release [skip ci]package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.314\"\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"k8s.io\/kubernetes\/cmd\/libs\/go2idl\/client-gen\/test_apis\/testgroup.k8s.io\/v1\"\n\ttestgroupetcd \"k8s.io\/kubernetes\/examples\/apiserver\/rest\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/rest\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/apimachinery\/registered\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\/authorizer\"\n\tgenericoptions \"k8s.io\/kubernetes\/pkg\/genericapiserver\/options\"\n\tgenericvalidation \"k8s.io\/kubernetes\/pkg\/genericapiserver\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\"\n\t\"k8s.io\/kubernetes\/pkg\/storage\/storagebackend\"\n\n\t\/\/ Install the testgroup API\n\t_ \"k8s.io\/kubernetes\/cmd\/libs\/go2idl\/client-gen\/test_apis\/testgroup.k8s.io\/install\"\n)\n\nconst (\n\t\/\/ Ports on which to run the server.\n\t\/\/ Explicitly setting these to a different value than the default values, to prevent this from clashing with a local cluster.\n\tInsecurePort = 8081\n\tSecurePort = 6444\n)\n\nfunc newStorageFactory() genericapiserver.StorageFactory {\n\tconfig := storagebackend.Config{\n\t\tPrefix: genericoptions.DefaultEtcdPathPrefix,\n\t\tServerList: []string{\"http:\/\/127.0.0.1:2379\"},\n\t}\n\tstorageFactory := genericapiserver.NewDefaultStorageFactory(config, \"application\/json\", api.Codecs, genericapiserver.NewDefaultResourceEncodingConfig(), genericapiserver.NewResourceConfig())\n\n\treturn storageFactory\n}\n\nfunc NewServerRunOptions() *genericoptions.ServerRunOptions {\n\tserverOptions := genericoptions.NewServerRunOptions().WithEtcdOptions()\n\tserverOptions.InsecurePort = InsecurePort\n\treturn serverOptions\n}\n\nfunc Run(serverOptions *genericoptions.ServerRunOptions) error {\n\t\/\/ Set ServiceClusterIPRange\n\t_, serviceClusterIPRange, _ := net.ParseCIDR(\"10.0.0.0\/24\")\n\tserverOptions.ServiceClusterIPRange = *serviceClusterIPRange\n\tserverOptions.StorageConfig.ServerList = []string{\"http:\/\/127.0.0.1:2379\"}\n\tgenericvalidation.ValidateRunOptions(serverOptions)\n\tgenericvalidation.VerifyEtcdServersList(serverOptions)\n\tconfig := genericapiserver.NewConfig(serverOptions)\n\tconfig.Authorizer = authorizer.NewAlwaysAllowAuthorizer()\n\tconfig.Serializer = api.Codecs\n\ts, err := config.New()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error in bringing up the server: %v\", err)\n\t}\n\n\tgroupVersion := v1.SchemeGroupVersion\n\tgroupName := groupVersion.Group\n\tgroupMeta, err := registered.Group(groupName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v\", err)\n\t}\n\tstorageFactory := newStorageFactory()\n\tstorageConfig, err := storageFactory.NewConfig(unversioned.GroupResource{Group: groupName, Resource: \"testtype\"})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get storage config: %v\", err)\n\t}\n\n\trestStorageMap := map[string]rest.Storage{\n\t\t\"testtypes\": testgroupetcd.NewREST(storageConfig, generic.UndecoratedStorage),\n\t}\n\tapiGroupInfo := genericapiserver.APIGroupInfo{\n\t\tGroupMeta: *groupMeta,\n\t\tVersionedResourcesStorageMap: map[string]map[string]rest.Storage{\n\t\t\tgroupVersion.Version: restStorageMap,\n\t\t},\n\t\tScheme: api.Scheme,\n\t\tNegotiatedSerializer: api.Codecs,\n\t}\n\tif err := s.InstallAPIGroup(&apiGroupInfo); err != nil {\n\t\treturn fmt.Errorf(\"Error in installing API: %v\", err)\n\t}\n\ts.Run(serverOptions)\n\treturn nil\n}\nDecouple defaulting from genericapiserver and master\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"k8s.io\/kubernetes\/cmd\/libs\/go2idl\/client-gen\/test_apis\/testgroup.k8s.io\/v1\"\n\ttestgroupetcd \"k8s.io\/kubernetes\/examples\/apiserver\/rest\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/rest\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/apimachinery\/registered\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\/authorizer\"\n\tgenericoptions \"k8s.io\/kubernetes\/pkg\/genericapiserver\/options\"\n\tgenericvalidation \"k8s.io\/kubernetes\/pkg\/genericapiserver\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\"\n\t\"k8s.io\/kubernetes\/pkg\/storage\/storagebackend\"\n\n\t\/\/ Install the testgroup API\n\t_ \"k8s.io\/kubernetes\/cmd\/libs\/go2idl\/client-gen\/test_apis\/testgroup.k8s.io\/install\"\n)\n\nconst (\n\t\/\/ Ports on which to run the server.\n\t\/\/ Explicitly setting these to a different value than the default values, to prevent this from clashing with a local cluster.\n\tInsecurePort = 8081\n\tSecurePort = 6444\n)\n\nfunc newStorageFactory() genericapiserver.StorageFactory {\n\tconfig := storagebackend.Config{\n\t\tPrefix: genericoptions.DefaultEtcdPathPrefix,\n\t\tServerList: []string{\"http:\/\/127.0.0.1:2379\"},\n\t}\n\tstorageFactory := genericapiserver.NewDefaultStorageFactory(config, \"application\/json\", api.Codecs, genericapiserver.NewDefaultResourceEncodingConfig(), genericapiserver.NewResourceConfig())\n\n\treturn storageFactory\n}\n\nfunc NewServerRunOptions() *genericoptions.ServerRunOptions {\n\tserverOptions := genericoptions.NewServerRunOptions().WithEtcdOptions()\n\tserverOptions.InsecurePort = InsecurePort\n\treturn serverOptions\n}\n\nfunc Run(serverOptions *genericoptions.ServerRunOptions) error {\n\t\/\/ Set ServiceClusterIPRange\n\t_, serviceClusterIPRange, _ := net.ParseCIDR(\"10.0.0.0\/24\")\n\tserverOptions.ServiceClusterIPRange = *serviceClusterIPRange\n\tserverOptions.StorageConfig.ServerList = []string{\"http:\/\/127.0.0.1:2379\"}\n\tgenericvalidation.ValidateRunOptions(serverOptions)\n\tgenericvalidation.VerifyEtcdServersList(serverOptions)\n\tconfig := genericapiserver.NewConfig(serverOptions)\n\tconfig.Authorizer = authorizer.NewAlwaysAllowAuthorizer()\n\tconfig.Serializer = api.Codecs\n\ts, err := config.Complete().New()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error in bringing up the server: %v\", err)\n\t}\n\n\tgroupVersion := v1.SchemeGroupVersion\n\tgroupName := groupVersion.Group\n\tgroupMeta, err := registered.Group(groupName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v\", err)\n\t}\n\tstorageFactory := newStorageFactory()\n\tstorageConfig, err := storageFactory.NewConfig(unversioned.GroupResource{Group: groupName, Resource: \"testtype\"})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get storage config: %v\", err)\n\t}\n\n\trestStorageMap := map[string]rest.Storage{\n\t\t\"testtypes\": testgroupetcd.NewREST(storageConfig, generic.UndecoratedStorage),\n\t}\n\tapiGroupInfo := genericapiserver.APIGroupInfo{\n\t\tGroupMeta: *groupMeta,\n\t\tVersionedResourcesStorageMap: map[string]map[string]rest.Storage{\n\t\t\tgroupVersion.Version: restStorageMap,\n\t\t},\n\t\tScheme: api.Scheme,\n\t\tNegotiatedSerializer: api.Codecs,\n\t}\n\tif err := s.InstallAPIGroup(&apiGroupInfo); err != nil {\n\t\treturn fmt.Errorf(\"Error in installing API: %v\", err)\n\t}\n\ts.Run(serverOptions)\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage apiserver\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/juju\/errors\"\n\tcharmresource \"gopkg.in\/juju\/charm.v6-unstable\/resource\"\n\n\t\"github.com\/juju\/juju\/state\"\n)\n\n\/\/ XXX needs tests\n\n\/\/ resourceUploadHandler handles resources uploads for model migrations.\ntype resourceUploadHandler struct {\n\tctxt httpContext\n\tstateAuthFunc func(*http.Request) (*state.State, error)\n}\n\nfunc (h *resourceUploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Validate before authenticate because the authentication is dependent\n\t\/\/ on the state connection that is determined during the validation.\n\tst, err := h.stateAuthFunc(r)\n\tif err != nil {\n\t\tif err := sendError(w, err); err != nil {\n\t\t\tlogger.Errorf(\"%v\", err)\n\t\t}\n\t\treturn\n\t}\n\tdefer h.ctxt.release(st)\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tif err := h.processPost(r, st); err != nil {\n\t\t\tif err := sendError(w, err); err != nil {\n\t\t\t\tlogger.Errorf(\"%v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t\/\/ XXX this should send a JSON result (resource\/api.CharmResource)\n\t\tw.WriteHeader(http.StatusOK)\n\tdefault:\n\t\tif err := sendError(w, errors.MethodNotAllowedf(\"unsupported method: %q\", r.Method)); err != nil {\n\t\t\tlogger.Errorf(\"%v\", err)\n\t\t}\n\t}\n}\n\n\/\/ processPost handles a tools upload POST request after authentication.\nfunc (h *resourceUploadHandler) processPost(r *http.Request, st *state.State) error {\n\tquery := r.URL.Query()\n\n\tapplicationID := query.Get(\"application\")\n\tif applicationID == \"\" {\n\t\treturn errors.NotValidf(\"missing application\")\n\t}\n\tuserID := query.Get(\"user\")\n\tif userID == \"\" {\n\t\treturn errors.NotValidf(\"missing user\")\n\t}\n\tres, err := queryToResource(query)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\trSt, err := st.Resources()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\t_, err = rSt.SetResource(applicationID, userID, res, r.Body)\n\treturn errors.Annotate(err, \"resource upload failed\")\n}\n\nfunc queryToResource(query url.Values) (charmresource.Resource, error) {\n\tvar err error\n\tempty := charmresource.Resource{}\n\n\tres := charmresource.Resource{\n\t\tMeta: charmresource.Meta{\n\t\t\tName: query.Get(\"name\"),\n\t\t\tPath: query.Get(\"path\"),\n\t\t\tDescription: query.Get(\"description\"),\n\t\t},\n\t}\n\tif res.Name == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing name\")\n\t}\n\tif res.Path == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing path\")\n\t}\n\tif res.Description == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing description\")\n\t}\n\tres.Type, err = charmresource.ParseType(query.Get(\"type\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"type\")\n\t}\n\tres.Origin, err = charmresource.ParseOrigin(query.Get(\"origin\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"origin\")\n\t}\n\tres.Revision, err = strconv.Atoi(query.Get(\"revision\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"revision\")\n\t}\n\tres.Size, err = strconv.ParseInt(query.Get(\"size\"), 10, 64)\n\tif err != nil {\n\t\treturn empty, errors.Trace(err)\n\t}\n\tres.Fingerprint, err = charmresource.ParseFingerprint(query.Get(\"fingerprint\"))\n\tif err != nil {\n\t\treturn empty, errors.Annotate(err, \"invalid fingerprint\")\n\t}\n\treturn res, nil\n}\napiserver: Allow blank resource username\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage apiserver\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/juju\/errors\"\n\tcharmresource \"gopkg.in\/juju\/charm.v6-unstable\/resource\"\n\n\t\"github.com\/juju\/juju\/state\"\n)\n\n\/\/ XXX needs tests\n\n\/\/ resourceUploadHandler handles resources uploads for model migrations.\ntype resourceUploadHandler struct {\n\tctxt httpContext\n\tstateAuthFunc func(*http.Request) (*state.State, error)\n}\n\nfunc (h *resourceUploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Validate before authenticate because the authentication is dependent\n\t\/\/ on the state connection that is determined during the validation.\n\tst, err := h.stateAuthFunc(r)\n\tif err != nil {\n\t\tif err := sendError(w, err); err != nil {\n\t\t\tlogger.Errorf(\"%v\", err)\n\t\t}\n\t\treturn\n\t}\n\tdefer h.ctxt.release(st)\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tif err := h.processPost(r, st); err != nil {\n\t\t\tif err := sendError(w, err); err != nil {\n\t\t\t\tlogger.Errorf(\"%v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t\/\/ XXX this should send a JSON result (resource\/api.CharmResource)\n\t\tw.WriteHeader(http.StatusOK)\n\tdefault:\n\t\tif err := sendError(w, errors.MethodNotAllowedf(\"unsupported method: %q\", r.Method)); err != nil {\n\t\t\tlogger.Errorf(\"%v\", err)\n\t\t}\n\t}\n}\n\n\/\/ processPost handles a tools upload POST request after authentication.\nfunc (h *resourceUploadHandler) processPost(r *http.Request, st *state.State) error {\n\tquery := r.URL.Query()\n\n\tapplicationID := query.Get(\"application\")\n\tif applicationID == \"\" {\n\t\treturn errors.NotValidf(\"missing application\")\n\t}\n\tuserID := query.Get(\"user\") \/\/ Is allowed to be blank\n\tres, err := queryToResource(query)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\trSt, err := st.Resources()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\t_, err = rSt.SetResource(applicationID, userID, res, r.Body)\n\treturn errors.Annotate(err, \"resource upload failed\")\n}\n\nfunc queryToResource(query url.Values) (charmresource.Resource, error) {\n\tvar err error\n\tempty := charmresource.Resource{}\n\n\tres := charmresource.Resource{\n\t\tMeta: charmresource.Meta{\n\t\t\tName: query.Get(\"name\"),\n\t\t\tPath: query.Get(\"path\"),\n\t\t\tDescription: query.Get(\"description\"),\n\t\t},\n\t}\n\tif res.Name == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing name\")\n\t}\n\tif res.Path == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing path\")\n\t}\n\tif res.Description == \"\" {\n\t\treturn empty, errors.NotValidf(\"missing description\")\n\t}\n\tres.Type, err = charmresource.ParseType(query.Get(\"type\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"type\")\n\t}\n\tres.Origin, err = charmresource.ParseOrigin(query.Get(\"origin\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"origin\")\n\t}\n\tres.Revision, err = strconv.Atoi(query.Get(\"revision\"))\n\tif err != nil {\n\t\treturn empty, errors.NotValidf(\"revision\")\n\t}\n\tres.Size, err = strconv.ParseInt(query.Get(\"size\"), 10, 64)\n\tif err != nil {\n\t\treturn empty, errors.Trace(err)\n\t}\n\tres.Fingerprint, err = charmresource.ParseFingerprint(query.Get(\"fingerprint\"))\n\tif err != nil {\n\t\treturn empty, errors.Annotate(err, \"invalid fingerprint\")\n\t}\n\treturn res, nil\n}\n<|endoftext|>"} {"text":"package sftp\n\nimport (\n\t\"github.com\/pkg\/sftp\"\n\t\"path\/filepath\"\n\t\"github.com\/pufferpanel\/pufferd\/utils\"\n\t\"strings\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"fmt\"\n)\n\ntype requestPrefix struct {\n\tprefix string\n}\n\nfunc CreateRequestPrefix(prefix string) sftp.Handlers {\n\th := requestPrefix{prefix: prefix}\n\n\treturn sftp.Handlers{h, h, h, h}\n}\n\nfunc (rp requestPrefix) Fileread(request sftp.Request) (io.ReaderAt, error) {\n\tfile, err := rp.getFile(request.Filepath, os.O_RDONLY, 0644)\n\treturn file, err\n}\n\nfunc (rp requestPrefix) Filewrite(request sftp.Request) (io.WriterAt, error) {\n\tfile, err := rp.getFile(request.Filepath, os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644)\n\treturn file, err\n}\n\nfunc (rp requestPrefix) Filecmd(request sftp.Request) error {\n\tsourceName, err := rp.validate(request.Filepath)\n\tif err != nil {\n\t\treturn rp.maskError(err)\n\t}\n\tvar targetName string\n\tif request.Target != \"\"\t{\n\t\ttargetName, err = rp.validate(request.Target)\n\t\tif err != nil {\n\t\t\treturn rp.maskError(err)\n\t\t}\n\t}\n\tswitch (request.Method) {\n\tcase \"SetStat\": {\n\t\treturn nil;\n\t}\n\tcase \"Rename\": {\n\t\terr = os.Rename(sourceName, targetName)\n\t\treturn err\n\t}\n\tcase \"Rmdir\": {\n\t\treturn os.RemoveAll(sourceName)\n\t}\n\tcase \"Symlink\": {\n\t\treturn nil;\n\t}\n\tcase \"Remove\": {\n\t\treturn os.Remove(sourceName)\n\t}\n\tdefault:\n\t\treturn errors.New(fmt.Sprint(\"Unknown request method: %s\", request.Method));\n\t}\n}\n\nfunc (rp requestPrefix) Fileinfo(request sftp.Request) ([]os.FileInfo, error) {\n\tsourceName, err := rp.validate(request.Filepath)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\tswitch (request.Method) {\n\tcase \"List\": {\n\t\tfile, err := os.Open(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn file.Readdir(0)\n\t}\n\tcase \"Stat\": {\n\t\tfile, err := os.Open(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn []os.FileInfo{fi}, nil\n\t}\n\tcase \"Readlink\": {\n\t\ttarget, err := os.Readlink(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfile, err := os.Open(target)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn []os.FileInfo{fi}, nil\n\t}\n\tdefault:\n\t\treturn nil, errors.New(fmt.Sprint(\"Unknown request method: %s\", request.Method));\n\t}\n}\n\nfunc (rp requestPrefix) getFile(path string, flags int, mode os.FileMode) (*os.File, error) {\n\tfilePath, err := rp.validate(path)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\tfile, err := os.OpenFile(filePath, flags, mode)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\treturn file, err\n}\n\nfunc (rp requestPrefix) validate(path string) (string, error) {\n\tok, path := rp.tryPrefix(path)\n\tif !ok {\n\t\treturn \"\", errors.New(\"Access denied\")\n\t}\n\treturn path, nil\n}\n\nfunc (rp requestPrefix) tryPrefix(path string) (bool, string) {\n\tnewPath := filepath.Clean(filepath.Join(rp.prefix, path))\n\tif utils.EnsureAccess(newPath, rp.prefix) {\n\t\treturn true, newPath\n\t} else {\n\t\treturn false, \"\"\n\t}\n}\n\nfunc (rp requestPrefix) stripPrefix(path string) string {\n\tnewStr := strings.Replace(path, rp.prefix, \"\", -1)\n\tif len(newStr) == 0 {\n\t\tnewStr = \"\/\"\n\t}\n\treturn newStr\n}\n\nfunc (rp requestPrefix) maskError(err error) error {\n\treturn errors.New(rp.stripPrefix(err.Error()))\n}\nAdd Mkdir to SFTP request prefixespackage sftp\n\nimport (\n\t\"github.com\/pkg\/sftp\"\n\t\"path\/filepath\"\n\t\"github.com\/pufferpanel\/pufferd\/utils\"\n\t\"strings\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"fmt\"\n)\n\ntype requestPrefix struct {\n\tprefix string\n}\n\nfunc CreateRequestPrefix(prefix string) sftp.Handlers {\n\th := requestPrefix{prefix: prefix}\n\n\treturn sftp.Handlers{h, h, h, h}\n}\n\nfunc (rp requestPrefix) Fileread(request sftp.Request) (io.ReaderAt, error) {\n\tfile, err := rp.getFile(request.Filepath, os.O_RDONLY, 0644)\n\treturn file, err\n}\n\nfunc (rp requestPrefix) Filewrite(request sftp.Request) (io.WriterAt, error) {\n\tfile, err := rp.getFile(request.Filepath, os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644)\n\treturn file, err\n}\n\nfunc (rp requestPrefix) Filecmd(request sftp.Request) error {\n\tsourceName, err := rp.validate(request.Filepath)\n\tif err != nil {\n\t\treturn rp.maskError(err)\n\t}\n\tvar targetName string\n\tif request.Target != \"\"\t{\n\t\ttargetName, err = rp.validate(request.Target)\n\t\tif err != nil {\n\t\t\treturn rp.maskError(err)\n\t\t}\n\t}\n\tswitch (request.Method) {\n\tcase \"SetStat\", \"Setstat\": {\n\t\treturn nil;\n\t}\n\tcase \"Rename\": {\n\t\terr = os.Rename(sourceName, targetName)\n\t\treturn err\n\t}\n\tcase \"Rmdir\": {\n\t\treturn os.RemoveAll(sourceName)\n\t}\n\tcase \"Mkdir\": {\n\t\terr = os.Mkdir(sourceName, 0644)\n\t\treturn err\n\t}\n\tcase \"Symlink\": {\n\t\treturn nil;\n\t}\n\tcase \"Remove\": {\n\t\treturn os.Remove(sourceName)\n\t}\n\tdefault:\n\t\treturn errors.New(fmt.Sprint(\"Unknown request method: %s\", request.Method));\n\t}\n}\n\nfunc (rp requestPrefix) Fileinfo(request sftp.Request) ([]os.FileInfo, error) {\n\tsourceName, err := rp.validate(request.Filepath)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\tswitch (request.Method) {\n\tcase \"List\": {\n\t\tfile, err := os.Open(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn file.Readdir(0)\n\t}\n\tcase \"Stat\": {\n\t\tfile, err := os.Open(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn []os.FileInfo{fi}, nil\n\t}\n\tcase \"Readlink\": {\n\t\ttarget, err := os.Readlink(sourceName)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfile, err := os.Open(target)\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn nil, rp.maskError(err)\n\t\t}\n\t\treturn []os.FileInfo{fi}, nil\n\t}\n\tdefault:\n\t\treturn nil, errors.New(fmt.Sprint(\"Unknown request method: %s\", request.Method));\n\t}\n}\n\nfunc (rp requestPrefix) getFile(path string, flags int, mode os.FileMode) (*os.File, error) {\n\tfilePath, err := rp.validate(path)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\tfile, err := os.OpenFile(filePath, flags, mode)\n\tif err != nil {\n\t\treturn nil, rp.maskError(err)\n\t}\n\treturn file, err\n}\n\nfunc (rp requestPrefix) validate(path string) (string, error) {\n\tok, path := rp.tryPrefix(path)\n\tif !ok {\n\t\treturn \"\", errors.New(\"Access denied\")\n\t}\n\treturn path, nil\n}\n\nfunc (rp requestPrefix) tryPrefix(path string) (bool, string) {\n\tnewPath := filepath.Clean(filepath.Join(rp.prefix, path))\n\tif utils.EnsureAccess(newPath, rp.prefix) {\n\t\treturn true, newPath\n\t} else {\n\t\treturn false, \"\"\n\t}\n}\n\nfunc (rp requestPrefix) stripPrefix(path string) string {\n\tnewStr := strings.Replace(path, rp.prefix, \"\", -1)\n\tif len(newStr) == 0 {\n\t\tnewStr = \"\/\"\n\t}\n\treturn newStr\n}\n\nfunc (rp requestPrefix) maskError(err error) error {\n\treturn errors.New(rp.stripPrefix(err.Error()))\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttps:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage safehttp\n\nimport (\n\t\"net\/http\"\n)\n\n\/\/ TODO: add the missing methods\nconst (\n\t\/\/ HTTP GET request\n\tMethodGet = \"GET\"\n\t\/\/ HTTP Post request\n\tMethodPost = \"POST\"\n)\n\n\/\/ ServeMux is a safe HTTP request multiplexer that wraps http.ServeMux.\n\/\/ It matches the URL of each incoming request against a list of registered\n\/\/ patterns and calls the handler for the pattern that most closely matches the\n\/\/ URL.\n\/\/\n\/\/ The multiplexer contains a list of allowed domains that will be matched\n\/\/ against each incoming request. A different handler can be specified for every\n\/\/ HTTP method supported at a registered pattern.\ntype ServeMux struct {\n\tmux *http.ServeMux\n\tdomains map[string]bool\n\tdispatcher Dispatcher\n\n\t\/\/ Maps user-provided patterns to combined handlers which encapsulate\n\t\/\/ multiple handlers, each one associated with an HTTP method.\n\thandlers map[string]methodHandler\n}\n\n\/\/ NewServeMux allocates and returns a new ServeMux\n\/\/ TODO(@mattias, @mara): make domains a variadic of string **literals**.\nfunc NewServeMux(dispatcher Dispatcher, domains ...string) *ServeMux {\n\td := map[string]bool{}\n\tfor _, host := range domains {\n\t\td[host] = true\n\t}\n\treturn &ServeMux{\n\t\tmux: http.NewServeMux(),\n\t\tdomains: d,\n\t\tdispatcher: dispatcher,\n\t\thandlers: map[string]methodHandler{},\n\t}\n}\n\n\/\/ Handle registers a handler for the given pattern and method. If another\n\/\/ handler is already registered for the same pattern and method, Handle panics.\nfunc (m *ServeMux) Handle(pattern string, method string, h Handler) {\n\tch, ok := m.handlers[pattern]\n\tif !ok {\n\t\tch := methodHandler{\n\t\t\th: make(map[string]Handler),\n\t\t\tdomains: m.domains,\n\t\t\td: m.dispatcher,\n\t\t}\n\t\tch.h[method] = h\n\n\t\tm.handlers[pattern] = ch\n\t\tm.mux.Handle(pattern, ch)\n\t\treturn\n\t}\n\n\tif _, ok := ch.h[method]; ok {\n\t\tpanic(\"method already registered\")\n\t}\n\tch.h[method] = h\n}\n\n\/\/ ServeHTTP dispatches the request to the handler whose method matches the\n\/\/ incoming request and whose pattern most closely matches the request URL.\nfunc (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tm.mux.ServeHTTP(w, r)\n}\n\n\/\/ methodHandler is collection of handlers based on the request method.\ntype methodHandler struct {\n\t\/\/ Maps an HTTP method to its handler\n\th map[string]Handler\n\tdomains map[string]bool\n\td Dispatcher\n}\n\n\/\/ ServeHTTP dispatches the request to the handler associated with\n\/\/ the incoming request's method.\nfunc (c methodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !c.domains[r.Host] {\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\th, ok := c.h[r.Method]\n\tif !ok {\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\th.ServeHTTP(newResponseWriter(c.d, w), newIncomingRequest(r))\n}\nRefactored creation of methodHandler\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttps:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage safehttp\n\nimport (\n\t\"net\/http\"\n)\n\n\/\/ TODO: add the missing methods\nconst (\n\t\/\/ HTTP GET request\n\tMethodGet = \"GET\"\n\t\/\/ HTTP Post request\n\tMethodPost = \"POST\"\n)\n\n\/\/ ServeMux is a safe HTTP request multiplexer that wraps http.ServeMux.\n\/\/ It matches the URL of each incoming request against a list of registered\n\/\/ patterns and calls the handler for the pattern that most closely matches the\n\/\/ URL.\n\/\/\n\/\/ The multiplexer contains a list of allowed domains that will be matched\n\/\/ against each incoming request. A different handler can be specified for every\n\/\/ HTTP method supported at a registered pattern.\ntype ServeMux struct {\n\tmux *http.ServeMux\n\tdomains map[string]bool\n\tdispatcher Dispatcher\n\n\t\/\/ Maps user-provided patterns to combined handlers which encapsulate\n\t\/\/ multiple handlers, each one associated with an HTTP method.\n\thandlers map[string]methodHandler\n}\n\n\/\/ NewServeMux allocates and returns a new ServeMux\n\/\/ TODO(@mattias, @mara): make domains a variadic of string **literals**.\nfunc NewServeMux(dispatcher Dispatcher, domains ...string) *ServeMux {\n\td := map[string]bool{}\n\tfor _, host := range domains {\n\t\td[host] = true\n\t}\n\treturn &ServeMux{\n\t\tmux: http.NewServeMux(),\n\t\tdomains: d,\n\t\tdispatcher: dispatcher,\n\t\thandlers: map[string]methodHandler{},\n\t}\n}\n\n\/\/ Handle registers a handler for the given pattern and method. If another\n\/\/ handler is already registered for the same pattern and method, Handle panics.\nfunc (m *ServeMux) Handle(pattern string, method string, h Handler) {\n\tch, ok := m.handlers[pattern]\n\tif !ok {\n\t\tch := methodHandler{\n\t\t\th: map[string]Handler{method: h},\n\t\t\tdomains: m.domains,\n\t\t\td: m.dispatcher,\n\t\t}\n\n\t\tm.handlers[pattern] = ch\n\t\tm.mux.Handle(pattern, ch)\n\t\treturn\n\t}\n\n\tif _, ok := ch.h[method]; ok {\n\t\tpanic(\"method already registered\")\n\t}\n\tch.h[method] = h\n}\n\n\/\/ ServeHTTP dispatches the request to the handler whose method matches the\n\/\/ incoming request and whose pattern most closely matches the request URL.\nfunc (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tm.mux.ServeHTTP(w, r)\n}\n\n\/\/ methodHandler is collection of handlers based on the request method.\ntype methodHandler struct {\n\t\/\/ Maps an HTTP method to its handler\n\th map[string]Handler\n\tdomains map[string]bool\n\td Dispatcher\n}\n\n\/\/ ServeHTTP dispatches the request to the handler associated with\n\/\/ the incoming request's method.\nfunc (c methodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !c.domains[r.Host] {\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\th, ok := c.h[r.Method]\n\tif !ok {\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\th.ServeHTTP(newResponseWriter(c.d, w), newIncomingRequest(r))\n}\n<|endoftext|>"} {"text":"package scrypt\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"encoding\/binary\"\n\t\"log\"\n\n\t\"code.google.com\/p\/go.crypto\/scrypt\"\n)\n\n\/\/ EncryptPassphrase returns a keylen_bytes+60 bytes of encrypted text\n\/\/ from the input passphrase.\n\/\/ It runs the scrypt function for this.\nfunc EncryptPassphrase(passphrase string, keylen_bytes int) (key []byte, err error) {\n\t\/\/ Generate salt\n\tsalt := generateSalt()\n\t\/\/ Set params\n\tvar N int32 = 16384\n\tvar r int32 = 8\n\tvar p int32 = 1\n\n\t\/\/ Generate key\n\tkey, err = scrypt.Key([]byte(passphrase),\n\t\tsalt,\n\t\tint(N), \/\/ Must be a power of 2 greater than 1\n\t\tint(r),\n\t\tint(p), \/\/ r*p must be < 2^30\n\t\tkeylen_bytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in encrypting passphrase: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Appending the salt\n\tkey = append(key, salt...)\n\n\t\/\/ Encoding the params to be stored\n\tbuf := new(bytes.Buffer)\n\tfor _, elem := range [3]int32{N, r, p} {\n\t\terr = binary.Write(buf, binary.LittleEndian, elem)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"binary.Write failed: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tkey = append(key, buf.Bytes()...)\n\t\tbuf.Reset()\n\t}\n\n\t\/\/ appending the sha-256 of the entire header at the end\n\thash_digest := sha256.New()\n\thash_digest.Write(key)\n\tif err != nil {\n\t\tlog.Fatalf(\"hash_digest.Write failed: %s\\n\", err)\n\t\treturn\n\t}\n\thash := hash_digest.Sum(nil)\n\tkey = append(key, hash...)\n\n\treturn\n}\n\n\/\/ VerifyPassphrase takes the passphrase and the target_key to match against.\n\/\/ And returns a boolean result whether it matched or not\nfunc VerifyPassphrase(passphrase string, keylen_bytes int, target_key []byte) (result bool, err error) {\n\t\/\/ Get the master_key\n\ttarget_master_key := target_key[:keylen_bytes]\n\t\/\/ Get the salt\n\tsalt := target_key[keylen_bytes:48]\n\t\/\/ Get the params\n\tvar N, r, p int32\n\n\terr = binary.Read(bytes.NewReader(target_key[48:52]), \/\/ byte 48:52 for N\n\t\tbinary.LittleEndian,\n\t\t&N)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for N: %s\\n\", err)\n\t\treturn\n\t}\n\n\terr = binary.Read(bytes.NewReader(target_key[52:56]), \/\/ byte 52:56 for r\n\t\tbinary.LittleEndian,\n\t\t&r)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for r: %s\\n\", err)\n\t\treturn\n\t}\n\n\terr = binary.Read(bytes.NewReader(target_key[56:60]), \/\/ byte 56:60 for p\n\t\tbinary.LittleEndian,\n\t\t&p)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for p: %s\\n\", err)\n\t\treturn\n\t}\n\tvar source_master_key []byte\n\tsource_master_key, err = scrypt.Key([]byte(passphrase),\n\t\tsalt,\n\t\tint(N), \/\/ Must be a power of 2 greater than 1\n\t\tint(r),\n\t\tint(p), \/\/ r*p must be < 2^30\n\t\tkeylen_bytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in encrypting passphrase: %s\\n\", err)\n\t\treturn\n\t}\n\n\ttarget_hash := target_key[60:]\n\t\/\/ Doing the sha-256 checksum at the last because we want the attacker\n\t\/\/ to spend as much time possible cracking\n\thash_digest := sha256.New()\n\t_, err = hash_digest.Write(target_key[:60])\n\tif err != nil {\n\t\tlog.Fatalf(\"hash_digest.Write failed: %s\\n\", err)\n\t\treturn\n\t}\n\tsource_hash := hash_digest.Sum(nil)\n\n\tresult = bytes.Equal(source_master_key, target_master_key) &&\n\t\tbytes.Equal(target_hash, source_hash)\n\treturn\n}\n\nfunc generateSalt() (salt []byte) {\n\tsalt = make([]byte, 16)\n\t_, err := rand.Read(salt)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in generating salt: %s\\n\", err)\n\t\treturn\n\t}\n\treturn\n}\nPreventing timing attackspackage scrypt\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"crypto\/subtle\"\n\t\"encoding\/binary\"\n\t\"log\"\n\n\t\"code.google.com\/p\/go.crypto\/scrypt\"\n)\n\n\/\/ EncryptPassphrase returns a keylen_bytes+60 bytes of encrypted text\n\/\/ from the input passphrase.\n\/\/ It runs the scrypt function for this.\nfunc EncryptPassphrase(passphrase string, keylen_bytes int) (key []byte, err error) {\n\t\/\/ Generate salt\n\tsalt := generateSalt()\n\t\/\/ Set params\n\tvar N int32 = 16384\n\tvar r int32 = 8\n\tvar p int32 = 1\n\n\t\/\/ Generate key\n\tkey, err = scrypt.Key([]byte(passphrase),\n\t\tsalt,\n\t\tint(N), \/\/ Must be a power of 2 greater than 1\n\t\tint(r),\n\t\tint(p), \/\/ r*p must be < 2^30\n\t\tkeylen_bytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in encrypting passphrase: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Appending the salt\n\tkey = append(key, salt...)\n\n\t\/\/ Encoding the params to be stored\n\tbuf := new(bytes.Buffer)\n\tfor _, elem := range [3]int32{N, r, p} {\n\t\terr = binary.Write(buf, binary.LittleEndian, elem)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"binary.Write failed: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tkey = append(key, buf.Bytes()...)\n\t\tbuf.Reset()\n\t}\n\n\t\/\/ appending the sha-256 of the entire header at the end\n\thash_digest := sha256.New()\n\thash_digest.Write(key)\n\tif err != nil {\n\t\tlog.Fatalf(\"hash_digest.Write failed: %s\\n\", err)\n\t\treturn\n\t}\n\thash := hash_digest.Sum(nil)\n\tkey = append(key, hash...)\n\n\treturn\n}\n\n\/\/ VerifyPassphrase takes the passphrase and the target_key to match against.\n\/\/ And returns a boolean result whether it matched or not\nfunc VerifyPassphrase(passphrase string, keylen_bytes int, target_key []byte) (result bool, err error) {\n\t\/\/ Get the master_key\n\ttarget_master_key := target_key[:keylen_bytes]\n\t\/\/ Get the salt\n\tsalt := target_key[keylen_bytes:48]\n\t\/\/ Get the params\n\tvar N, r, p int32\n\n\terr = binary.Read(bytes.NewReader(target_key[48:52]), \/\/ byte 48:52 for N\n\t\tbinary.LittleEndian,\n\t\t&N)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for N: %s\\n\", err)\n\t\treturn\n\t}\n\n\terr = binary.Read(bytes.NewReader(target_key[52:56]), \/\/ byte 52:56 for r\n\t\tbinary.LittleEndian,\n\t\t&r)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for r: %s\\n\", err)\n\t\treturn\n\t}\n\n\terr = binary.Read(bytes.NewReader(target_key[56:60]), \/\/ byte 56:60 for p\n\t\tbinary.LittleEndian,\n\t\t&p)\n\tif err != nil {\n\t\tlog.Fatalf(\"binary.Read failed for p: %s\\n\", err)\n\t\treturn\n\t}\n\tvar source_master_key []byte\n\tsource_master_key, err = scrypt.Key([]byte(passphrase),\n\t\tsalt,\n\t\tint(N), \/\/ Must be a power of 2 greater than 1\n\t\tint(r),\n\t\tint(p), \/\/ r*p must be < 2^30\n\t\tkeylen_bytes)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in encrypting passphrase: %s\\n\", err)\n\t\treturn\n\t}\n\n\ttarget_hash := target_key[60:]\n\t\/\/ Doing the sha-256 checksum at the last because we want the attacker\n\t\/\/ to spend as much time possible cracking\n\thash_digest := sha256.New()\n\t_, err = hash_digest.Write(target_key[:60])\n\tif err != nil {\n\t\tlog.Fatalf(\"hash_digest.Write failed: %s\\n\", err)\n\t\treturn\n\t}\n\tsource_hash := hash_digest.Sum(nil)\n\n\t\/\/ ConstantTimeCompare returns ints. Converting it to bool\n\tkey_comp := subtle.ConstantTimeCompare(source_master_key,\n\t\ttarget_master_key) != 0\n\thash_comp := subtle.ConstantTimeCompare(target_hash,\n\t\tsource_hash) != 0\n\tresult = key_comp && hash_comp\n\treturn\n}\n\nfunc generateSalt() (salt []byte) {\n\tsalt = make([]byte, 16)\n\t_, err := rand.Read(salt)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in generating salt: %s\\n\", err)\n\t\treturn\n\t}\n\treturn\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-ini\/ini\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\n\/\/ HTTPResponse Structure used to define response object of every route request\ntype HTTPResponse struct {\n\tStatus bool `json:\"status\"`\n\tContent string `json:\"content\"`\n}\n\n\/\/ ResponseType Constant\nconst ResponseType = \"application\/json\"\n\n\/\/ ContentType Constant\nconst ContentType = \"Content-Type\"\n\nvar db *sql.DB\nvar lag int\n\nfunc main() {\n\n\tvar portstring string\n\n\tflag.StringVar(&portstring, \"port\", \"3307\", \"Listening port\")\n\tflag.Parse()\n\n\tcfg, err := ini.Load(os.Getenv(\"HOME\") + \"\/.my.cnf\")\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdbUser := cfg.Section(\"client\").Key(\"user\").String()\n\tdbPass := cfg.Section(\"client\").Key(\"password\").String()\n\tdbHost := cfg.Section(\"client\").Key(\"hostname\").String()\n\n\tdb, err = sql.Open(\"mysql\", dbUser+\":\"+dbPass+\"@\"+dbHost+\"\/mysql\")\n\n\tif err := db.Ping(); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer db.Close()\n\n\trouter := http.NewServeMux()\n\n\trouter.HandleFunc(\"\/status\/ro\", RouteStatusReadOnly)\n\trouter.HandleFunc(\"\/status\/rw\", RouteStatusReadWritable)\n\trouter.HandleFunc(\"\/status\/single\", RouteStatusSingle)\n\trouter.HandleFunc(\"\/status\/leader\", RouteStatusLeader)\n\trouter.HandleFunc(\"\/status\/follower\", RouteStatusFollower)\n\trouter.HandleFunc(\"\/status\/topology\", RouteStatusTopology)\n\n\trouter.HandleFunc(\"\/role\/master\", RouteRoleMaster)\n\trouter.HandleFunc(\"\/role\/replica\", RouteRoleReplica)\n\trouter.HandleFunc(\"\/role\/replica\/\", RouteRoleReplicaByLag)\n\trouter.HandleFunc(\"\/role\/galera\", RouteRoleGalera)\n\n\trouter.HandleFunc(\"\/read\/galera\/state\", RouteReadGaleraState)\n\trouter.HandleFunc(\"\/read\/replication\/lag\", RouteReadReplicationLag)\n\trouter.HandleFunc(\"\/read\/replication\/master\", RouteReadReplicationMaster)\n\trouter.HandleFunc(\"\/read\/replication\/replicas_count\", RouteReadReplicasCounter)\n\n\tlog.Printf(\"Listening on port %s ...\", portstring)\n\n\terr2 := http.ListenAndServe(\":\"+portstring, LogRequests(CheckURL(router)))\n\tlog.Fatal(err2)\n}\n\n\/*\n *\tMiddleware layers\n *\/\n\n\/\/ LogRequests Middleware level to log API requests\nfunc LogRequests(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\n\t\tnext.ServeHTTP(w, r)\n\n\t\tlog.Printf(\n\t\t\t\"[%s]\\t%s\\t%s\",\n\t\t\tr.Method,\n\t\t\tr.URL.String(),\n\t\t\ttime.Since(start),\n\t\t)\n\t})\n}\n\n\/\/ CheckURL Middleware level to validate requested URI\nfunc CheckURL(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tpath := r.URL.String()\n\t\tpathLength := len(path)\n\t\tmatchPath := \"\/role\/replica\/\"\n\t\tmatchLength := len(matchPath)\n\n\t\tif strings.Contains(path, matchPath) && pathLength > matchLength {\n\t\t\tlag, _ = strconv.Atoi(strings.Trim(path, matchPath))\n\t\t} else if strings.Compare(path, strings.TrimRight(path, \"\/\")) != 0 {\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(ContentType, ResponseType)\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\/*\n *\tGeneral functions\n *\/\n\n\/\/ int2bool Convert integers to boolean\nfunc int2bool(value int) bool {\n\tif value != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ unknownColumns Used to get value from specific column of a range of unknown columns\nfunc unknownColumns(rows *sql.Rows, column string) string {\n\tcolumns, _ := rows.Columns()\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := range columns {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\n\t\tfor i, col := range columns {\n\n\t\t\tvar value interface{}\n\n\t\t\tval := values[i]\n\n\t\t\tb, ok := val.([]byte)\n\n\t\t\tif ok {\n\t\t\t\tvalue = string(b)\n\t\t\t} else {\n\t\t\t\tvalue = val\n\t\t\t}\n\n\t\t\tsNum := value.(string)\n\n\t\t\tif col == column {\n\t\t\t\treturn sNum\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\/\/ routeResponse Used to build response to API requests\nfunc routeResponse(w http.ResponseWriter, httpStatus bool, contents string) {\n\tres := new(HTTPResponse)\n\n\tif httpStatus {\n\t\tw.WriteHeader(200)\n\t} else {\n\t\tw.WriteHeader(404)\n\t}\n\n\tres.Status = httpStatus\n\tres.Content = contents\n\tresponse, _ := json.Marshal(res)\n\tfmt.Fprintf(w, \"%s\", response)\n}\n\n\/*\n *\tDatabase functions\n *\/\n\n\/\/ readOnly Check if database is in readonly mode, or not\nfunc readOnly() bool {\n\tvar state string\n\tvar key string\n\n\terr := db.QueryRow(\"show variables like 'read_only'\").Scan(&key, &state)\n\n\tif state == \"OFF\" || err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ replicaStatus Read database status if it is a replica\nfunc replicaStatus(lagCount int) (bool, int) {\n\tif lagCount == 0 {\n\t\tlagCount = 1<<63 - 1\n\t}\n\n\trows, err := db.Query(\"show slave status\")\n\n\tif err != nil {\n\t\treturn false, 0\n\t}\n\n\tdefer rows.Close()\n\n\tsecondsBehindMaster := unknownColumns(rows, \"Seconds_Behind_Master\")\n\n\tif secondsBehindMaster == \"\" {\n\t\tsecondsBehindMaster = \"0\"\n\t}\n\n\tlag, _ = strconv.Atoi(secondsBehindMaster)\n\n\tif lag > 0 {\n\t\tif lagCount > lag {\n\t\t\treturn true, lag\n\t\t}\n\n\t\treturn false, lag\n\t}\n\n\treturn false, 0\n}\n\n\/\/ isReplica Get database's master, in case it is a replica\nfunc isReplica() (bool, string) {\n\trows, err := db.Query(\"show slave status\")\n\n\tif err != nil {\n\t\treturn false, \"\"\n\t}\n\n\tdefer rows.Close()\n\n\tmasterHost := unknownColumns(rows, \"Master_Host\")\n\n\tif masterHost != \"\" {\n\t\treturn true, masterHost\n\t}\n\n\treturn false, \"\"\n}\n\n\/\/ servingBinlogs ...\nfunc servingBinlogs() int {\n\tvar count int\n\n\terr := db.QueryRow(\n\t\t\"select count(*) as n \" +\n\t\t\t\"from information_schema.processlist \" +\n\t\t\t\"where command = 'Binlog Dump'\").Scan(&count)\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn count\n}\n\n\/\/ galeraClusterState ...\nfunc galeraClusterState() (bool, string) {\n\tvar v string\n\n\terr := db.QueryRow(\n\t\t\"select variable_value as v \" +\n\t\t\t\"from information_schema.global_status \" +\n\t\t\t\"where variable_name like 'wsrep_local_state' = 4\").Scan(&v)\n\n\tif err == sql.ErrNoRows || err != nil {\n\t\treturn false, \"\"\n\t}\n\n\treturn true, v\n}\n\n\/*\n * Status routes\n *\/\n\n\/\/ RouteStatusReadOnly ...\nfunc RouteStatusReadOnly(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: readOnly...\")\n\tisReadonly := readOnly()\n\n\trouteResponse(w, isReadonly, \"\")\n}\n\n\/\/ RouteStatusReadWritable ...\nfunc RouteStatusReadWritable(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: readable and writable...\")\n\tisReadonly := readOnly()\n\n\trouteResponse(w, !isReadonly, \"\")\n}\n\n\/\/ RouteStatusSingle ...\nfunc RouteStatusSingle(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: single...\")\n\tisReadonly := readOnly()\n\tisReplica, _ := isReplica()\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, !isReadonly && !isReplica && !isServeLogs, \"\")\n}\n\n\/\/ RouteStatusLeader ...\nfunc RouteStatusLeader(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: leader...\")\n\tisReplica, _ := isReplica()\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, !isReplica && isServeLogs, \"\")\n}\n\n\/\/ RouteStatusFollower ...\nfunc RouteStatusFollower(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: follower...\")\n\tisReplica, _ := isReplica()\n\n\trouteResponse(w, isReplica, \"\")\n\n}\n\n\/\/ RouteStatusTopology ...\nfunc RouteStatusTopology(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: topology...\")\n\tisReplica, _ := isReplica()\n\treplicaStatus, _ := replicaStatus(0)\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, (!replicaStatus && isServeLogs) || isReplica, \"\")\n}\n\n\/*\n * Roles routes\n *\/\n\n\/\/ RouteRoleMaster ...\nfunc RouteRoleMaster(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: master...\")\n\tisReadonly := readOnly()\n\tisReplica, _ := isReplica()\n\n\trouteResponse(w, !isReadonly && !isReplica, \"\")\n}\n\n\/\/ RouteRoleReplica ...\nfunc RouteRoleReplica(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: replica...\")\n\tisReadonly := readOnly()\n\treplicaStatus, _ := replicaStatus(0)\n\n\trouteResponse(w, isReadonly && replicaStatus, \"\")\n}\n\n\/\/ RouteRoleReplicaByLag ...\nfunc RouteRoleReplicaByLag(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: replica by lag...\")\n\tisReadonly := readOnly()\n\treplicaStatus, _ := replicaStatus(lag)\n\n\trouteResponse(w, isReadonly && replicaStatus, \"\")\n}\n\n\/\/ RouteRoleGalera ...\nfunc RouteRoleGalera(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: galera...\")\n\tgaleraClusterState, _ := galeraClusterState()\n\n\trouteResponse(w, galeraClusterState, \"\")\n}\n\n\/*\n * Read routes\n *\/\n\n\/\/ RouteReadGaleraState ...\nfunc RouteReadGaleraState(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database state: galera...\")\n\tgaleraClusterState, varValue := galeraClusterState()\n\n\trouteResponse(w, galeraClusterState, varValue)\n}\n\n\/\/ RouteReadReplicationLag ...\nfunc RouteReadReplicationLag(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database replication: lag...\")\n\tlagString := \"\"\n\tisReplica, _ := isReplica()\n\t_, lagValue := replicaStatus(0)\n\n\tif isReplica {\n\t\tlagString = strconv.Itoa(lagValue)\n\t}\n\n\trouteResponse(w, isReplica, lagString)\n}\n\n\/\/ RouteReadReplicationMaster ...\nfunc RouteReadReplicationMaster(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database status: master...\")\n\tlagString := \"\"\n\tisReplica, _ := isReplica()\n\t_, lagValue := replicaStatus(0)\n\n\tif isReplica {\n\t\tlagString = strconv.Itoa(lagValue)\n\t}\n\n\trouteResponse(w, isReplica, lagString)\n}\n\n\/\/ RouteReadReplicasCounter ...\nfunc RouteReadReplicasCounter(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading counter of database replications...\")\n\tlagString := \"0\"\n\tisServeLogs := servingBinlogs()\n\n\tif int2bool(isServeLogs) {\n\t\tlagString = strconv.Itoa(isServeLogs)\n\t}\n\n\trouteResponse(w, int2bool(isServeLogs), lagString)\n\n}\nChanged http returned code on errorpackage main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-ini\/ini\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\n\/\/ HTTPResponse Structure used to define response object of every route request\ntype HTTPResponse struct {\n\tStatus bool `json:\"status\"`\n\tContent string `json:\"content\"`\n}\n\n\/\/ ResponseType Constant\nconst ResponseType = \"application\/json\"\n\n\/\/ ContentType Constant\nconst ContentType = \"Content-Type\"\n\nvar db *sql.DB\nvar lag int\n\nfunc main() {\n\n\tvar portstring string\n\n\tflag.StringVar(&portstring, \"port\", \"3307\", \"Listening port\")\n\tflag.Parse()\n\n\tcfg, err := ini.Load(os.Getenv(\"HOME\") + \"\/.my.cnf\")\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdbUser := cfg.Section(\"client\").Key(\"user\").String()\n\tdbPass := cfg.Section(\"client\").Key(\"password\").String()\n\tdbHost := cfg.Section(\"client\").Key(\"hostname\").String()\n\n\tdb, err = sql.Open(\"mysql\", dbUser+\":\"+dbPass+\"@\"+dbHost+\"\/mysql\")\n\n\tif err := db.Ping(); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer db.Close()\n\n\trouter := http.NewServeMux()\n\n\trouter.HandleFunc(\"\/status\/ro\", RouteStatusReadOnly)\n\trouter.HandleFunc(\"\/status\/rw\", RouteStatusReadWritable)\n\trouter.HandleFunc(\"\/status\/single\", RouteStatusSingle)\n\trouter.HandleFunc(\"\/status\/leader\", RouteStatusLeader)\n\trouter.HandleFunc(\"\/status\/follower\", RouteStatusFollower)\n\trouter.HandleFunc(\"\/status\/topology\", RouteStatusTopology)\n\n\trouter.HandleFunc(\"\/role\/master\", RouteRoleMaster)\n\trouter.HandleFunc(\"\/role\/replica\", RouteRoleReplica)\n\trouter.HandleFunc(\"\/role\/replica\/\", RouteRoleReplicaByLag)\n\trouter.HandleFunc(\"\/role\/galera\", RouteRoleGalera)\n\n\trouter.HandleFunc(\"\/read\/galera\/state\", RouteReadGaleraState)\n\trouter.HandleFunc(\"\/read\/replication\/lag\", RouteReadReplicationLag)\n\trouter.HandleFunc(\"\/read\/replication\/master\", RouteReadReplicationMaster)\n\trouter.HandleFunc(\"\/read\/replication\/replicas_count\", RouteReadReplicasCounter)\n\n\tlog.Printf(\"Listening on port %s ...\", portstring)\n\n\terr2 := http.ListenAndServe(\":\"+portstring, LogRequests(CheckURL(router)))\n\tlog.Fatal(err2)\n}\n\n\/*\n *\tMiddleware layers\n *\/\n\n\/\/ LogRequests Middleware level to log API requests\nfunc LogRequests(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\n\t\tnext.ServeHTTP(w, r)\n\n\t\tlog.Printf(\n\t\t\t\"[%s]\\t%s\\t%s\",\n\t\t\tr.Method,\n\t\t\tr.URL.String(),\n\t\t\ttime.Since(start),\n\t\t)\n\t})\n}\n\n\/\/ CheckURL Middleware level to validate requested URI\nfunc CheckURL(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tpath := r.URL.String()\n\t\tpathLength := len(path)\n\t\tmatchPath := \"\/role\/replica\/\"\n\t\tmatchLength := len(matchPath)\n\n\t\tif strings.Contains(path, matchPath) && pathLength > matchLength {\n\t\t\tlag, _ = strconv.Atoi(strings.Trim(path, matchPath))\n\t\t} else if strings.Compare(path, strings.TrimRight(path, \"\/\")) != 0 {\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(ContentType, ResponseType)\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\/*\n *\tGeneral functions\n *\/\n\n\/\/ int2bool Convert integers to boolean\nfunc int2bool(value int) bool {\n\tif value != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ unknownColumns Used to get value from specific column of a range of unknown columns\nfunc unknownColumns(rows *sql.Rows, column string) string {\n\tcolumns, _ := rows.Columns()\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := range columns {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\n\t\tfor i, col := range columns {\n\n\t\t\tvar value interface{}\n\n\t\t\tval := values[i]\n\n\t\t\tb, ok := val.([]byte)\n\n\t\t\tif ok {\n\t\t\t\tvalue = string(b)\n\t\t\t} else {\n\t\t\t\tvalue = val\n\t\t\t}\n\n\t\t\tsNum := value.(string)\n\n\t\t\tif col == column {\n\t\t\t\treturn sNum\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\/\/ routeResponse Used to build response to API requests\nfunc routeResponse(w http.ResponseWriter, httpStatus bool, contents string) {\n\tres := new(HTTPResponse)\n\n\tif httpStatus {\n\t\tw.WriteHeader(200)\n\t} else {\n\t\tw.WriteHeader(403)\n\t}\n\n\tres.Status = httpStatus\n\tres.Content = contents\n\tresponse, _ := json.Marshal(res)\n\tfmt.Fprintf(w, \"%s\", response)\n}\n\n\/*\n *\tDatabase functions\n *\/\n\n\/\/ readOnly Check if database is in readonly mode, or not\nfunc readOnly() bool {\n\tvar state string\n\tvar key string\n\n\terr := db.QueryRow(\"show variables like 'read_only'\").Scan(&key, &state)\n\n\tif state == \"OFF\" || err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ replicaStatus Read database status if it is a replica\nfunc replicaStatus(lagCount int) (bool, int) {\n\tif lagCount == 0 {\n\t\tlagCount = 1<<63 - 1\n\t}\n\n\trows, err := db.Query(\"show slave status\")\n\n\tif err != nil {\n\t\treturn false, 0\n\t}\n\n\tdefer rows.Close()\n\n\tsecondsBehindMaster := unknownColumns(rows, \"Seconds_Behind_Master\")\n\n\tif secondsBehindMaster == \"\" {\n\t\tsecondsBehindMaster = \"0\"\n\t}\n\n\tlag, _ = strconv.Atoi(secondsBehindMaster)\n\n\tif lag > 0 {\n\t\tif lagCount > lag {\n\t\t\treturn true, lag\n\t\t}\n\n\t\treturn false, lag\n\t}\n\n\treturn false, 0\n}\n\n\/\/ isReplica Get database's master, in case it is a replica\nfunc isReplica() (bool, string) {\n\trows, err := db.Query(\"show slave status\")\n\n\tif err != nil {\n\t\treturn false, \"\"\n\t}\n\n\tdefer rows.Close()\n\n\tmasterHost := unknownColumns(rows, \"Master_Host\")\n\n\tif masterHost != \"\" {\n\t\treturn true, masterHost\n\t}\n\n\treturn false, \"\"\n}\n\n\/\/ servingBinlogs ...\nfunc servingBinlogs() int {\n\tvar count int\n\n\terr := db.QueryRow(\n\t\t\"select count(*) as n \" +\n\t\t\t\"from information_schema.processlist \" +\n\t\t\t\"where command = 'Binlog Dump'\").Scan(&count)\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn count\n}\n\n\/\/ galeraClusterState ...\nfunc galeraClusterState() (bool, string) {\n\tvar v string\n\n\terr := db.QueryRow(\n\t\t\"select variable_value as v \" +\n\t\t\t\"from information_schema.global_status \" +\n\t\t\t\"where variable_name like 'wsrep_local_state' = 4\").Scan(&v)\n\n\tif err == sql.ErrNoRows || err != nil {\n\t\treturn false, \"\"\n\t}\n\n\treturn true, v\n}\n\n\/*\n * Status routes\n *\/\n\n\/\/ RouteStatusReadOnly ...\nfunc RouteStatusReadOnly(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: readOnly...\")\n\tisReadonly := readOnly()\n\n\trouteResponse(w, isReadonly, \"\")\n}\n\n\/\/ RouteStatusReadWritable ...\nfunc RouteStatusReadWritable(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: readable and writable...\")\n\tisReadonly := readOnly()\n\n\trouteResponse(w, !isReadonly, \"\")\n}\n\n\/\/ RouteStatusSingle ...\nfunc RouteStatusSingle(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: single...\")\n\tisReadonly := readOnly()\n\tisReplica, _ := isReplica()\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, !isReadonly && !isReplica && !isServeLogs, \"\")\n}\n\n\/\/ RouteStatusLeader ...\nfunc RouteStatusLeader(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: leader...\")\n\tisReplica, _ := isReplica()\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, !isReplica && isServeLogs, \"\")\n}\n\n\/\/ RouteStatusFollower ...\nfunc RouteStatusFollower(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: follower...\")\n\tisReplica, _ := isReplica()\n\n\trouteResponse(w, isReplica, \"\")\n\n}\n\n\/\/ RouteStatusTopology ...\nfunc RouteStatusTopology(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database status: topology...\")\n\tisReplica, _ := isReplica()\n\treplicaStatus, _ := replicaStatus(0)\n\tisServeLogs := int2bool(servingBinlogs())\n\n\trouteResponse(w, (!replicaStatus && isServeLogs) || isReplica, \"\")\n}\n\n\/*\n * Roles routes\n *\/\n\n\/\/ RouteRoleMaster ...\nfunc RouteRoleMaster(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: master...\")\n\tisReadonly := readOnly()\n\tisReplica, _ := isReplica()\n\n\trouteResponse(w, !isReadonly && !isReplica, \"\")\n}\n\n\/\/ RouteRoleReplica ...\nfunc RouteRoleReplica(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: replica...\")\n\tisReadonly := readOnly()\n\treplicaStatus, _ := replicaStatus(0)\n\n\trouteResponse(w, isReadonly && replicaStatus, \"\")\n}\n\n\/\/ RouteRoleReplicaByLag ...\nfunc RouteRoleReplicaByLag(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: replica by lag...\")\n\tisReadonly := readOnly()\n\treplicaStatus, _ := replicaStatus(lag)\n\n\trouteResponse(w, isReadonly && replicaStatus, \"\")\n}\n\n\/\/ RouteRoleGalera ...\nfunc RouteRoleGalera(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Checking database role: galera...\")\n\tgaleraClusterState, _ := galeraClusterState()\n\n\trouteResponse(w, galeraClusterState, \"\")\n}\n\n\/*\n * Read routes\n *\/\n\n\/\/ RouteReadGaleraState ...\nfunc RouteReadGaleraState(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database state: galera...\")\n\tgaleraClusterState, varValue := galeraClusterState()\n\n\trouteResponse(w, galeraClusterState, varValue)\n}\n\n\/\/ RouteReadReplicationLag ...\nfunc RouteReadReplicationLag(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database replication: lag...\")\n\tlagString := \"\"\n\tisReplica, _ := isReplica()\n\t_, lagValue := replicaStatus(0)\n\n\tif isReplica {\n\t\tlagString = strconv.Itoa(lagValue)\n\t}\n\n\trouteResponse(w, isReplica, lagString)\n}\n\n\/\/ RouteReadReplicationMaster ...\nfunc RouteReadReplicationMaster(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading database status: master...\")\n\tlagString := \"\"\n\tisReplica, _ := isReplica()\n\t_, lagValue := replicaStatus(0)\n\n\tif isReplica {\n\t\tlagString = strconv.Itoa(lagValue)\n\t}\n\n\trouteResponse(w, isReplica, lagString)\n}\n\n\/\/ RouteReadReplicasCounter ...\nfunc RouteReadReplicasCounter(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"Reading counter of database replications...\")\n\tlagString := \"0\"\n\tisServeLogs := servingBinlogs()\n\n\tif int2bool(isServeLogs) {\n\t\tlagString = strconv.Itoa(isServeLogs)\n\t}\n\n\trouteResponse(w, int2bool(isServeLogs), lagString)\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/kch42\/gomcmap\/mcmap\"\n\t\"github.com\/mattn\/go-gtk\/gdk\"\n\t\"github.com\/mattn\/go-gtk\/glib\"\n\t\"github.com\/mattn\/go-gtk\/gtk\"\n\t\"math\"\n\t\"unsafe\"\n)\n\nconst (\n\tzoom = 2\n\ttileSize = zoom * mcmap.ChunkSizeXZ\n\thalfChunkSize = mcmap.ChunkSizeXZ \/ 2\n)\n\ntype tileCmd int\n\nconst (\n\tcmdUpdateTiles tileCmd = iota\n\tcmdFlushTiles\n\tcmdSave\n)\n\nfunc renderTile(chunk *mcmap.Chunk) (maptile, biotile *gdk.Pixmap, biocache []mcmap.Biome) {\n\tmaptile = emptyPixmap(tileSize, tileSize, 24)\n\tmtDrawable := maptile.GetDrawable()\n\tmtGC := gdk.NewGC(mtDrawable)\n\n\tbiotile = emptyPixmap(tileSize, tileSize, 24)\n\tbtDrawable := biotile.GetDrawable()\n\tbtGC := gdk.NewGC(btDrawable)\n\n\tbiocache = make([]mcmap.Biome, mcmap.ChunkRectXZ)\n\n\ti := 0\n\tfor z := 0; z < mcmap.ChunkSizeXZ; z++ {\n\tscanX:\n\t\tfor x := 0; x < mcmap.ChunkSizeXZ; x++ {\n\t\t\tbio := chunk.Biome(x, z)\n\t\t\tbtGC.SetRgbFgColor(bioColors[bio])\n\t\t\tbtDrawable.DrawRectangle(btGC, true, x*zoom, z*zoom, zoom, zoom)\n\n\t\t\tbiocache[i] = bio\n\t\t\ti++\n\n\t\t\tfor y := chunk.Height(x, z); y >= 0; y-- {\n\t\t\t\tif col, ok := blockColors[chunk.Block(x, y, z).ID]; ok {\n\t\t\t\t\tmtGC.SetRgbFgColor(col)\n\t\t\t\t\tmtDrawable.DrawRectangle(mtGC, true, x*zoom, z*zoom, zoom, zoom)\n\t\t\t\t\tcontinue scanX\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmtGC.SetRgbFgColor(gdk.NewColor(\"#ffffff\"))\n\t\t\tmtDrawable.DrawRectangle(mtGC, true, x*zoom, z*zoom, zoom, zoom)\n\t\t}\n\t}\n\n\treturn\n}\n\ntype MapWidget struct {\n\tdArea *gtk.DrawingArea\n\tw, h int\n\n\treportFail func(msg string)\n\tupdateInfo func(x, z int, bio mcmap.Biome)\n\n\tisInit bool\n\n\tshowBiomes bool\n\n\toffX, offZ int\n\tmx1, mx2, my1, my2 int\n\n\tpixmap *gdk.Pixmap\n\tpixmapGC *gdk.GC\n\tgdkwin *gdk.Window\n\n\tbg *gdk.Pixmap\n\n\tregion *mcmap.Region\n\n\tmaptiles map[XZPos]*gdk.Pixmap\n\tbiotiles map[XZPos]*gdk.Pixmap\n\tbioCache map[XZPos][]mcmap.Biome\n\n\tredraw chan bool\n\ttileCmds chan tileCmd\n}\n\nvar (\n\tchecker1 = gdk.NewColor(\"#222222\")\n\tchecker2 = gdk.NewColor(\"#444444\")\n)\n\nfunc emptyPixmap(w, h, depth int) *gdk.Pixmap {\n\treturn gdk.NewPixmap(new(gdk.Drawable), w, h, depth)\n}\n\nfunc (mw *MapWidget) SetShowBiomes(b bool) {\n\tmw.showBiomes = b\n\tmw.redraw <- true\n}\n\nfunc (mw *MapWidget) DArea() *gtk.DrawingArea { return mw.dArea }\n\nfunc (mw *MapWidget) doTileCmds() {\n\tfor cmd := range mw.tileCmds {\n\t\tswitch cmd {\n\t\tcase cmdSave:\n\t\t\tmw.region.Save()\n\t\tcase cmdFlushTiles:\n\t\t\tgdk.ThreadsEnter()\n\t\t\tfor _, mt := range mw.maptiles {\n\t\t\t\tmt.Unref()\n\t\t\t}\n\t\t\tfor _, bt := range mw.biotiles {\n\t\t\t\tbt.Unref()\n\t\t\t}\n\t\t\tgdk.ThreadsLeave()\n\n\t\t\tmw.maptiles = make(map[XZPos]*gdk.Pixmap)\n\t\t\tmw.biotiles = make(map[XZPos]*gdk.Pixmap)\n\t\t\tmw.bioCache = make(map[XZPos][]mcmap.Biome)\n\t\tcase cmdUpdateTiles:\n\t\t\ttodelete := make(map[XZPos]bool)\n\n\t\t\tstartX := int(math.Floor(float64(mw.offX) \/ tileSize))\n\t\t\tstartZ := int(math.Floor(float64(mw.offZ) \/ tileSize))\n\t\t\tendX := int(math.Ceil(float64(mw.offX+mw.w) \/ tileSize))\n\t\t\tendZ := int(math.Ceil(float64(mw.offZ+mw.h) \/ tileSize))\n\n\t\t\tfor pos := range mw.maptiles {\n\t\t\t\tif (pos.X < startX) || (pos.Z < startZ) || (pos.X >= endX) || (pos.Z >= endZ) {\n\t\t\t\t\ttodelete[pos] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgdk.ThreadsEnter()\n\t\t\tfor pos := range todelete {\n\t\t\t\tif tile, ok := mw.maptiles[pos]; ok {\n\t\t\t\t\ttile.Unref()\n\t\t\t\t\tdelete(mw.maptiles, pos)\n\t\t\t\t}\n\n\t\t\t\tif tile, ok := mw.biotiles[pos]; ok {\n\t\t\t\t\ttile.Unref()\n\t\t\t\t\tdelete(mw.biotiles, pos)\n\t\t\t\t}\n\n\t\t\t\tif _, ok := mw.bioCache[pos]; ok {\n\t\t\t\t\tdelete(mw.bioCache, pos)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor z := startZ; z < endZ; z++ {\n\t\t\tscanX:\n\t\t\t\tfor x := startX; x < endX; x++ {\n\t\t\t\t\tpos := XZPos{x, z}\n\n\t\t\t\t\tif _, ok := mw.biotiles[pos]; ok {\n\t\t\t\t\t\tcontinue scanX\n\t\t\t\t\t}\n\n\t\t\t\t\tchunk, err := mw.region.Chunk(x, z)\n\t\t\t\t\tswitch err {\n\t\t\t\t\tcase nil:\n\t\t\t\t\tcase mcmap.NotAvailable:\n\t\t\t\t\t\tcontinue scanX\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmw.reportFail(fmt.Sprintf(\"Could not get chunk %d, %d: %s\", x, z, err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tmw.maptiles[pos], mw.biotiles[pos], mw.bioCache[pos] = renderTile(chunk)\n\t\t\t\t\tchunk.MarkUnused()\n\n\t\t\t\t\tgdk.ThreadsLeave()\n\t\t\t\t\tmw.redraw <- true\n\t\t\t\t\tgdk.ThreadsEnter()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgdk.ThreadsLeave()\n\t\t}\n\t}\n}\n\nfunc (mw *MapWidget) configure() {\n\tif mw.pixmap != nil {\n\t\tmw.pixmap.Unref()\n\t}\n\n\talloc := mw.dArea.GetAllocation()\n\tmw.w = alloc.Width\n\tmw.h = alloc.Height\n\n\tif !mw.isInit {\n\t\tmw.offX = -(mw.w \/ 2)\n\t\tmw.offZ = -(mw.h \/ 2)\n\t\tmw.isInit = true\n\t}\n\n\tmw.pixmap = gdk.NewPixmap(mw.dArea.GetWindow().GetDrawable(), mw.w, mw.h, 24)\n\tmw.pixmapGC = gdk.NewGC(mw.pixmap.GetDrawable())\n\n\tmw.drawBg()\n\tgdk.ThreadsLeave()\n\tmw.redraw <- true\n\tgdk.ThreadsEnter()\n}\n\nfunc (mw *MapWidget) drawBg() {\n\tif mw.bg != nil {\n\t\tmw.bg.Unref()\n\t}\n\n\tmw.bg = emptyPixmap(mw.w, mw.h, 24)\n\tdrawable := mw.bg.GetDrawable()\n\tgc := gdk.NewGC(drawable)\n\n\tw := (mw.w + 16) \/ 32\n\th := (mw.h + 16) \/ 32\n\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tif (x % 2) == (y % 2) {\n\t\t\t\tgc.SetRgbFgColor(checker1)\n\t\t\t} else {\n\t\t\t\tgc.SetRgbFgColor(checker2)\n\t\t\t}\n\t\t\tdrawable.DrawRectangle(gc, true, x*32, y*32, 32, 32)\n\t\t}\n\t}\n}\n\nfunc (mw *MapWidget) compose() {\n\tdrawable := mw.pixmap.GetDrawable()\n\tgc := mw.pixmapGC\n\n\tdrawable.DrawDrawable(gc, mw.bg.GetDrawable(), 0, 0, 0, 0, -1, -1)\n\n\tvar tiles map[XZPos]*gdk.Pixmap\n\tif mw.showBiomes {\n\t\ttiles = mw.biotiles\n\t} else {\n\t\ttiles = mw.maptiles\n\t}\n\n\tfor pos, tile := range tiles {\n\t\tx := (pos.X * tileSize) - mw.offX\n\t\ty := (pos.Z * tileSize) - mw.offZ\n\n\t\tdrawable.DrawDrawable(gc, tile.GetDrawable(), 0, 0, x, y, tileSize, tileSize)\n\t}\n}\n\nfunc (mw *MapWidget) movement(ctx *glib.CallbackContext) {\n\tif mw.gdkwin == nil {\n\t\tmw.gdkwin = mw.dArea.GetWindow()\n\t}\n\targ := ctx.Args(0)\n\tmev := *(**gdk.EventMotion)(unsafe.Pointer(&arg))\n\tvar mt gdk.ModifierType\n\tif mev.IsHint != 0 {\n\t\tmw.gdkwin.GetPointer(&(mw.mx2), &(mw.my2), &mt)\n\t} else {\n\t\tmw.mx2, mw.my2 = int(mev.X), int(mev.Y)\n\t}\n\n\tx := (mw.offX + mw.mx2) \/ zoom\n\tz := (mw.offZ + mw.my2) \/ zoom\n\tcx, cz, cbx, cbz := mcmap.BlockToChunk(x, z)\n\tbio := mcmap.Biome(mcmap.BioUncalculated)\n\tif bc, ok := mw.bioCache[XZPos{cx, cz}]; ok {\n\t\tbio = bc[cbz*mcmap.ChunkSizeXZ+cbx]\n\t}\n\tmw.updateInfo(x, z, bio)\n\n\tswitch {\n\tcase mt&gdk.BUTTON1_MASK != 0:\n\tcase mt&gdk.BUTTON2_MASK != 0:\n\t\tif (mw.mx1 != -1) && (mw.my1 != -1) {\n\t\t\tmw.offX += mw.mx1 - mw.mx2\n\t\t\tmw.offZ += mw.my1 - mw.my2\n\n\t\t\tgdk.ThreadsLeave()\n\t\t\tmw.tileCmds <- cmdUpdateTiles\n\t\t\tgdk.ThreadsEnter()\n\t\t}\n\t}\n\n\tmw.mx1, mw.my1 = mw.mx2, mw.my2\n}\n\nfunc (mw *MapWidget) expose() {\n\tmw.dArea.GetWindow().GetDrawable().DrawDrawable(mw.pixmapGC, mw.pixmap.GetDrawable(), 0, 0, 0, 0, -1, -1)\n}\n\nfunc (mw *MapWidget) guiUpdater() {\n\tfor _ = range mw.redraw {\n\t\tgdk.ThreadsEnter()\n\t\tmw.compose()\n\t\tmw.expose()\n\t\tmw.dArea.GetWindow().Invalidate(nil, false)\n\t\tgdk.ThreadsLeave()\n\t}\n}\n\nfunc (mw *MapWidget) init() {\n\tmw.redraw = make(chan bool)\n\tmw.tileCmds = make(chan tileCmd)\n\n\tmw.maptiles = make(map[XZPos]*gdk.Pixmap)\n\tmw.biotiles = make(map[XZPos]*gdk.Pixmap)\n\tmw.bioCache = make(map[XZPos][]mcmap.Biome)\n\n\tmw.showBiomes = true\n\n\tmw.mx1, mw.my1 = -1, -1\n\n\tgo mw.doTileCmds()\n\tgo mw.guiUpdater()\n\n\tmw.dArea = gtk.NewDrawingArea()\n\tmw.dArea.Connect(\"configure-event\", mw.configure)\n\tmw.dArea.Connect(\"expose-event\", mw.expose)\n\tmw.dArea.Connect(\"motion-notify-event\", mw.movement)\n\n\tmw.dArea.SetEvents(int(gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.BUTTON_PRESS_MASK))\n}\n\nfunc (mw *MapWidget) setRegion(region *mcmap.Region) {\n\tmw.tileCmds <- cmdFlushTiles\n\tmw.region = region\n\tmw.tileCmds <- cmdUpdateTiles\n}\n\nfunc NewMapWidget(reportFail func(msg string), updateInfo func(x, z int, bio mcmap.Biome)) *MapWidget {\n\tmw := &MapWidget{reportFail: reportFail, updateInfo: updateInfo}\n\tmw.init()\n\treturn mw\n}\nFixing checkerboard backgroundpackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/kch42\/gomcmap\/mcmap\"\n\t\"github.com\/mattn\/go-gtk\/gdk\"\n\t\"github.com\/mattn\/go-gtk\/glib\"\n\t\"github.com\/mattn\/go-gtk\/gtk\"\n\t\"math\"\n\t\"unsafe\"\n)\n\nconst (\n\tzoom = 2\n\ttileSize = zoom * mcmap.ChunkSizeXZ\n\thalfChunkSize = mcmap.ChunkSizeXZ \/ 2\n)\n\ntype tileCmd int\n\nconst (\n\tcmdUpdateTiles tileCmd = iota\n\tcmdFlushTiles\n\tcmdSave\n)\n\nfunc renderTile(chunk *mcmap.Chunk) (maptile, biotile *gdk.Pixmap, biocache []mcmap.Biome) {\n\tmaptile = emptyPixmap(tileSize, tileSize, 24)\n\tmtDrawable := maptile.GetDrawable()\n\tmtGC := gdk.NewGC(mtDrawable)\n\n\tbiotile = emptyPixmap(tileSize, tileSize, 24)\n\tbtDrawable := biotile.GetDrawable()\n\tbtGC := gdk.NewGC(btDrawable)\n\n\tbiocache = make([]mcmap.Biome, mcmap.ChunkRectXZ)\n\n\ti := 0\n\tfor z := 0; z < mcmap.ChunkSizeXZ; z++ {\n\tscanX:\n\t\tfor x := 0; x < mcmap.ChunkSizeXZ; x++ {\n\t\t\tbio := chunk.Biome(x, z)\n\t\t\tbtGC.SetRgbFgColor(bioColors[bio])\n\t\t\tbtDrawable.DrawRectangle(btGC, true, x*zoom, z*zoom, zoom, zoom)\n\n\t\t\tbiocache[i] = bio\n\t\t\ti++\n\n\t\t\tfor y := chunk.Height(x, z); y >= 0; y-- {\n\t\t\t\tif col, ok := blockColors[chunk.Block(x, y, z).ID]; ok {\n\t\t\t\t\tmtGC.SetRgbFgColor(col)\n\t\t\t\t\tmtDrawable.DrawRectangle(mtGC, true, x*zoom, z*zoom, zoom, zoom)\n\t\t\t\t\tcontinue scanX\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmtGC.SetRgbFgColor(gdk.NewColor(\"#ffffff\"))\n\t\t\tmtDrawable.DrawRectangle(mtGC, true, x*zoom, z*zoom, zoom, zoom)\n\t\t}\n\t}\n\n\treturn\n}\n\ntype MapWidget struct {\n\tdArea *gtk.DrawingArea\n\tw, h int\n\n\treportFail func(msg string)\n\tupdateInfo func(x, z int, bio mcmap.Biome)\n\n\tisInit bool\n\n\tshowBiomes bool\n\n\toffX, offZ int\n\tmx1, mx2, my1, my2 int\n\n\tpixmap *gdk.Pixmap\n\tpixmapGC *gdk.GC\n\tgdkwin *gdk.Window\n\n\tbg *gdk.Pixmap\n\n\tregion *mcmap.Region\n\n\tmaptiles map[XZPos]*gdk.Pixmap\n\tbiotiles map[XZPos]*gdk.Pixmap\n\tbioCache map[XZPos][]mcmap.Biome\n\n\tredraw chan bool\n\ttileCmds chan tileCmd\n}\n\nvar (\n\tchecker1 = gdk.NewColor(\"#222222\")\n\tchecker2 = gdk.NewColor(\"#444444\")\n)\n\nfunc emptyPixmap(w, h, depth int) *gdk.Pixmap {\n\treturn gdk.NewPixmap(new(gdk.Drawable), w, h, depth)\n}\n\nfunc (mw *MapWidget) SetShowBiomes(b bool) {\n\tmw.showBiomes = b\n\tmw.redraw <- true\n}\n\nfunc (mw *MapWidget) DArea() *gtk.DrawingArea { return mw.dArea }\n\nfunc (mw *MapWidget) doTileCmds() {\n\tfor cmd := range mw.tileCmds {\n\t\tswitch cmd {\n\t\tcase cmdSave:\n\t\t\tmw.region.Save()\n\t\tcase cmdFlushTiles:\n\t\t\tgdk.ThreadsEnter()\n\t\t\tfor _, mt := range mw.maptiles {\n\t\t\t\tmt.Unref()\n\t\t\t}\n\t\t\tfor _, bt := range mw.biotiles {\n\t\t\t\tbt.Unref()\n\t\t\t}\n\t\t\tgdk.ThreadsLeave()\n\n\t\t\tmw.maptiles = make(map[XZPos]*gdk.Pixmap)\n\t\t\tmw.biotiles = make(map[XZPos]*gdk.Pixmap)\n\t\t\tmw.bioCache = make(map[XZPos][]mcmap.Biome)\n\t\tcase cmdUpdateTiles:\n\t\t\ttodelete := make(map[XZPos]bool)\n\n\t\t\tstartX := int(math.Floor(float64(mw.offX) \/ tileSize))\n\t\t\tstartZ := int(math.Floor(float64(mw.offZ) \/ tileSize))\n\t\t\tendX := int(math.Ceil(float64(mw.offX+mw.w) \/ tileSize))\n\t\t\tendZ := int(math.Ceil(float64(mw.offZ+mw.h) \/ tileSize))\n\n\t\t\tfor pos := range mw.maptiles {\n\t\t\t\tif (pos.X < startX) || (pos.Z < startZ) || (pos.X >= endX) || (pos.Z >= endZ) {\n\t\t\t\t\ttodelete[pos] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgdk.ThreadsEnter()\n\t\t\tfor pos := range todelete {\n\t\t\t\tif tile, ok := mw.maptiles[pos]; ok {\n\t\t\t\t\ttile.Unref()\n\t\t\t\t\tdelete(mw.maptiles, pos)\n\t\t\t\t}\n\n\t\t\t\tif tile, ok := mw.biotiles[pos]; ok {\n\t\t\t\t\ttile.Unref()\n\t\t\t\t\tdelete(mw.biotiles, pos)\n\t\t\t\t}\n\n\t\t\t\tif _, ok := mw.bioCache[pos]; ok {\n\t\t\t\t\tdelete(mw.bioCache, pos)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor z := startZ; z < endZ; z++ {\n\t\t\tscanX:\n\t\t\t\tfor x := startX; x < endX; x++ {\n\t\t\t\t\tpos := XZPos{x, z}\n\n\t\t\t\t\tif _, ok := mw.biotiles[pos]; ok {\n\t\t\t\t\t\tcontinue scanX\n\t\t\t\t\t}\n\n\t\t\t\t\tchunk, err := mw.region.Chunk(x, z)\n\t\t\t\t\tswitch err {\n\t\t\t\t\tcase nil:\n\t\t\t\t\tcase mcmap.NotAvailable:\n\t\t\t\t\t\tcontinue scanX\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tmw.reportFail(fmt.Sprintf(\"Could not get chunk %d, %d: %s\", x, z, err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tmw.maptiles[pos], mw.biotiles[pos], mw.bioCache[pos] = renderTile(chunk)\n\t\t\t\t\tchunk.MarkUnused()\n\n\t\t\t\t\tgdk.ThreadsLeave()\n\t\t\t\t\tmw.redraw <- true\n\t\t\t\t\tgdk.ThreadsEnter()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgdk.ThreadsLeave()\n\t\t}\n\t}\n}\n\nfunc (mw *MapWidget) configure() {\n\tif mw.pixmap != nil {\n\t\tmw.pixmap.Unref()\n\t}\n\n\talloc := mw.dArea.GetAllocation()\n\tmw.w = alloc.Width\n\tmw.h = alloc.Height\n\n\tif !mw.isInit {\n\t\tmw.offX = -(mw.w \/ 2)\n\t\tmw.offZ = -(mw.h \/ 2)\n\t\tmw.isInit = true\n\t}\n\n\tmw.pixmap = gdk.NewPixmap(mw.dArea.GetWindow().GetDrawable(), mw.w, mw.h, 24)\n\tmw.pixmapGC = gdk.NewGC(mw.pixmap.GetDrawable())\n\n\tmw.drawBg()\n\tgdk.ThreadsLeave()\n\tmw.redraw <- true\n\tgdk.ThreadsEnter()\n}\n\nfunc (mw *MapWidget) drawBg() {\n\tif mw.bg != nil {\n\t\tmw.bg.Unref()\n\t}\n\n\tmw.bg = emptyPixmap(mw.w, mw.h, 24)\n\tdrawable := mw.bg.GetDrawable()\n\tgc := gdk.NewGC(drawable)\n\n\tw := int(math.Ceil(float64(mw.w) \/ 32))\n\th := int(math.Ceil(float64(mw.h) \/ 32))\n\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tif (x % 2) == (y % 2) {\n\t\t\t\tgc.SetRgbFgColor(checker1)\n\t\t\t} else {\n\t\t\t\tgc.SetRgbFgColor(checker2)\n\t\t\t}\n\t\t\tdrawable.DrawRectangle(gc, true, x*32, y*32, 32, 32)\n\t\t}\n\t}\n}\n\nfunc (mw *MapWidget) compose() {\n\tdrawable := mw.pixmap.GetDrawable()\n\tgc := mw.pixmapGC\n\n\tdrawable.DrawDrawable(gc, mw.bg.GetDrawable(), 0, 0, 0, 0, -1, -1)\n\n\tvar tiles map[XZPos]*gdk.Pixmap\n\tif mw.showBiomes {\n\t\ttiles = mw.biotiles\n\t} else {\n\t\ttiles = mw.maptiles\n\t}\n\n\tfor pos, tile := range tiles {\n\t\tx := (pos.X * tileSize) - mw.offX\n\t\ty := (pos.Z * tileSize) - mw.offZ\n\n\t\tdrawable.DrawDrawable(gc, tile.GetDrawable(), 0, 0, x, y, tileSize, tileSize)\n\t}\n}\n\nfunc (mw *MapWidget) movement(ctx *glib.CallbackContext) {\n\tif mw.gdkwin == nil {\n\t\tmw.gdkwin = mw.dArea.GetWindow()\n\t}\n\targ := ctx.Args(0)\n\tmev := *(**gdk.EventMotion)(unsafe.Pointer(&arg))\n\tvar mt gdk.ModifierType\n\tif mev.IsHint != 0 {\n\t\tmw.gdkwin.GetPointer(&(mw.mx2), &(mw.my2), &mt)\n\t} else {\n\t\tmw.mx2, mw.my2 = int(mev.X), int(mev.Y)\n\t}\n\n\tx := (mw.offX + mw.mx2) \/ zoom\n\tz := (mw.offZ + mw.my2) \/ zoom\n\tcx, cz, cbx, cbz := mcmap.BlockToChunk(x, z)\n\tbio := mcmap.Biome(mcmap.BioUncalculated)\n\tif bc, ok := mw.bioCache[XZPos{cx, cz}]; ok {\n\t\tbio = bc[cbz*mcmap.ChunkSizeXZ+cbx]\n\t}\n\tmw.updateInfo(x, z, bio)\n\n\tswitch {\n\tcase mt&gdk.BUTTON1_MASK != 0:\n\tcase mt&gdk.BUTTON2_MASK != 0:\n\t\tif (mw.mx1 != -1) && (mw.my1 != -1) {\n\t\t\tmw.offX += mw.mx1 - mw.mx2\n\t\t\tmw.offZ += mw.my1 - mw.my2\n\n\t\t\tgdk.ThreadsLeave()\n\t\t\tmw.tileCmds <- cmdUpdateTiles\n\t\t\tgdk.ThreadsEnter()\n\t\t}\n\t}\n\n\tmw.mx1, mw.my1 = mw.mx2, mw.my2\n}\n\nfunc (mw *MapWidget) expose() {\n\tmw.dArea.GetWindow().GetDrawable().DrawDrawable(mw.pixmapGC, mw.pixmap.GetDrawable(), 0, 0, 0, 0, -1, -1)\n}\n\nfunc (mw *MapWidget) guiUpdater() {\n\tfor _ = range mw.redraw {\n\t\tgdk.ThreadsEnter()\n\t\tmw.compose()\n\t\tmw.expose()\n\t\tmw.dArea.GetWindow().Invalidate(nil, false)\n\t\tgdk.ThreadsLeave()\n\t}\n}\n\nfunc (mw *MapWidget) init() {\n\tmw.redraw = make(chan bool)\n\tmw.tileCmds = make(chan tileCmd)\n\n\tmw.maptiles = make(map[XZPos]*gdk.Pixmap)\n\tmw.biotiles = make(map[XZPos]*gdk.Pixmap)\n\tmw.bioCache = make(map[XZPos][]mcmap.Biome)\n\n\tmw.showBiomes = true\n\n\tmw.mx1, mw.my1 = -1, -1\n\n\tgo mw.doTileCmds()\n\tgo mw.guiUpdater()\n\n\tmw.dArea = gtk.NewDrawingArea()\n\tmw.dArea.Connect(\"configure-event\", mw.configure)\n\tmw.dArea.Connect(\"expose-event\", mw.expose)\n\tmw.dArea.Connect(\"motion-notify-event\", mw.movement)\n\n\tmw.dArea.SetEvents(int(gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.BUTTON_PRESS_MASK))\n}\n\nfunc (mw *MapWidget) setRegion(region *mcmap.Region) {\n\tmw.tileCmds <- cmdFlushTiles\n\tmw.region = region\n\tmw.tileCmds <- cmdUpdateTiles\n}\n\nfunc NewMapWidget(reportFail func(msg string), updateInfo func(x, z int, bio mcmap.Biome)) *MapWidget {\n\tmw := &MapWidget{reportFail: reportFail, updateInfo: updateInfo}\n\tmw.init()\n\treturn mw\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 Couchbase, Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n\/\/ except in compliance with the License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software distributed under the\n\/\/ License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n\/\/ either express or implied. See the License for the specific language governing permissions\n\/\/ and limitations under the License.\n\npackage bleve\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/blevesearch\/bleve\/analysis\"\n\t\"github.com\/blevesearch\/bleve\/search\"\n)\n\ntype numericRange struct {\n\tName string `json:\"name,omitempty\"`\n\tMin *float64 `json:\"min,omitempty\"`\n\tMax *float64 `json:\"max,omitempty\"`\n}\n\ntype dateTimeRange struct {\n\tName string `json:\"name,omitempty\"`\n\tStart time.Time `json:\"start,omitempty\"`\n\tEnd time.Time `json:\"end,omitempty\"`\n\tstartString *string\n\tendString *string\n}\n\nfunc (dr *dateTimeRange) ParseDates(dateTimeParser analysis.DateTimeParser) {\n\tif dr.Start.IsZero() && dr.startString != nil {\n\t\tstart, err := dateTimeParser.ParseDateTime(*dr.startString)\n\t\tif err == nil {\n\t\t\tdr.Start = start\n\t\t}\n\t}\n\tif dr.End.IsZero() && dr.endString != nil {\n\t\tend, err := dateTimeParser.ParseDateTime(*dr.endString)\n\t\tif err == nil {\n\t\t\tdr.End = end\n\t\t}\n\t}\n}\n\nfunc (dr *dateTimeRange) UnmarshalJSON(input []byte) error {\n\tvar temp struct {\n\t\tName string `json:\"name,omitempty\"`\n\t\tStart *string `json:\"start,omitempty\"`\n\t\tEnd *string `json:\"end,omitempty\"`\n\t}\n\n\terr := json.Unmarshal(input, &temp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdr.Name = temp.Name\n\tif temp.Start != nil {\n\t\tdr.startString = temp.Start\n\t}\n\tif temp.End != nil {\n\t\tdr.endString = temp.End\n\t}\n\n\treturn nil\n}\n\n\/\/ A FacetRequest describes a facet or aggregation\n\/\/ of the result document set you would like to be\n\/\/ built.\ntype FacetRequest struct {\n\tSize int\n\tField string\n\tNumericRanges []*numericRange `json:\"numeric_ranges,omitempty\"`\n\tDateTimeRanges []*dateTimeRange `json:\"date_ranges,omitempty\"`\n}\n\n\/\/ NewFacetRequest creates a facet on the specified\n\/\/ field that limits the number of entries to the\n\/\/ specified size.\nfunc NewFacetRequest(field string, size int) *FacetRequest {\n\treturn &FacetRequest{\n\t\tField: field,\n\t\tSize: size,\n\t}\n}\n\n\/\/ AddDateTimeRange adds a bucket to a field\n\/\/ containing date values. Documents with a\n\/\/ date value falling into this range are tabulated\n\/\/ as part of this bucket\/range.\nfunc (fr *FacetRequest) AddDateTimeRange(name string, start, end time.Time) {\n\tif fr.DateTimeRanges == nil {\n\t\tfr.DateTimeRanges = make([]*dateTimeRange, 0, 1)\n\t}\n\tfr.DateTimeRanges = append(fr.DateTimeRanges, &dateTimeRange{Name: name, Start: start, End: end})\n}\n\n\/\/ AddNumericRange adds a bucket to a field\n\/\/ containing numeric values. Documents with a\n\/\/ numeric value falling into this range are\n\/\/ tabulated as part of this bucket\/range.\nfunc (fr *FacetRequest) AddNumericRange(name string, min, max *float64) {\n\tif fr.NumericRanges == nil {\n\t\tfr.NumericRanges = make([]*numericRange, 0, 1)\n\t}\n\tfr.NumericRanges = append(fr.NumericRanges, &numericRange{Name: name, Min: min, Max: max})\n}\n\n\/\/ FacetsRequest groups together all the\n\/\/ FacetRequest objects for a single query.\ntype FacetsRequest map[string]*FacetRequest\n\n\/\/ HighlightRequest describes how field matches\n\/\/ should be highlighted.\ntype HighlightRequest struct {\n\tStyle *string `json:\"style\"`\n\tFields []string `json:\"fields\"`\n}\n\n\/\/ NewHighlight creates a default\n\/\/ HighlightRequest.\nfunc NewHighlight() *HighlightRequest {\n\treturn &HighlightRequest{}\n}\n\n\/\/ NewHighlightWithStyle creates a HighlightRequest\n\/\/ with an alternate style.\nfunc NewHighlightWithStyle(style string) *HighlightRequest {\n\treturn &HighlightRequest{\n\t\tStyle: &style,\n\t}\n}\n\nfunc (h *HighlightRequest) AddField(field string) {\n\tif h.Fields == nil {\n\t\th.Fields = make([]string, 0, 1)\n\t}\n\th.Fields = append(h.Fields, field)\n}\n\n\/\/ A SearchRequest describes all the parameters\n\/\/ needed to search the index.\n\/\/ Query is required.\n\/\/ Size\/From describe how much and which part of the\n\/\/ result set to return.\n\/\/ Highlight describes optional search result\n\/\/ highlighting.\n\/\/ Fields describes a list of field values which\n\/\/ should be retrieved for result documents.\n\/\/ Facets describe the set of facets to be computed.\n\/\/ Explain triggers inclusion of additional search\n\/\/ result score explanations.\n\/\/\n\/\/ A special field named \"*\" can be used to return all fields.\ntype SearchRequest struct {\n\tQuery Query `json:\"query\"`\n\tSize int `json:\"size\"`\n\tFrom int `json:\"from\"`\n\tHighlight *HighlightRequest `json:\"highlight\"`\n\tFields []string `json:\"fields\"`\n\tFacets FacetsRequest `json:\"facets\"`\n\tExplain bool `json:\"explain\"`\n}\n\n\/\/ AddFacet adds a FacetRequest to this SearchRequest\nfunc (r *SearchRequest) AddFacet(facetName string, f *FacetRequest) {\n\tif r.Facets == nil {\n\t\tr.Facets = make(FacetsRequest, 1)\n\t}\n\tr.Facets[facetName] = f\n}\n\n\/\/ UnmarshalJSON deserializes a JSON representation of\n\/\/ a SearchRequest\nfunc (r *SearchRequest) UnmarshalJSON(input []byte) error {\n\tvar temp struct {\n\t\tQ json.RawMessage `json:\"query\"`\n\t\tSize int `json:\"size\"`\n\t\tFrom int `json:\"from\"`\n\t\tHighlight *HighlightRequest `json:\"highlight\"`\n\t\tFields []string `json:\"fields\"`\n\t\tFacets FacetsRequest `json:\"facets\"`\n\t\tExplain bool `json:\"explain\"`\n\t}\n\n\terr := json.Unmarshal(input, &temp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Size = temp.Size\n\tr.From = temp.From\n\tr.Explain = temp.Explain\n\tr.Highlight = temp.Highlight\n\tr.Fields = temp.Fields\n\tr.Facets = temp.Facets\n\tr.Query, err = ParseQuery(temp.Q)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.Size < 0 {\n\t\tr.Size = 10\n\t}\n\tif r.From < 0 {\n\t\tr.From = 0\n\t}\n\n\treturn nil\n\n}\n\n\/\/ NewSearchRequest creates a new SearchRequest\n\/\/ for the Query, using default values for all\n\/\/ other search parameters.\nfunc NewSearchRequest(q Query) *SearchRequest {\n\treturn NewSearchRequestOptions(q, 10, 0, false)\n}\n\n\/\/ NewSearchRequestOptions creates a new SearchRequest\n\/\/ for the Query, with the requested size, from\n\/\/ and explanation search parameters.\nfunc NewSearchRequestOptions(q Query, size, from int, explain bool) *SearchRequest {\n\treturn &SearchRequest{\n\t\tQuery: q,\n\t\tSize: size,\n\t\tFrom: from,\n\t\tExplain: explain,\n\t}\n}\n\n\/\/ A SearchResult describes the results of executing\n\/\/ a SearchRequest.\ntype SearchResult struct {\n\tRequest *SearchRequest `json:\"request\"`\n\tHits search.DocumentMatchCollection `json:\"hits\"`\n\tTotal uint64 `json:\"total_hits\"`\n\tMaxScore float64 `json:\"max_score\"`\n\tTook time.Duration `json:\"took\"`\n\tFacets search.FacetResults `json:\"facets\"`\n}\n\nfunc (sr *SearchResult) String() string {\n\trv := \"\"\n\tif sr.Total > 0 {\n\t\tif sr.Request.Size > 0 {\n\t\t\trv = fmt.Sprintf(\"%d matches, showing %d through %d, took %s\\n\", sr.Total, sr.Request.From+1, sr.Request.From+len(sr.Hits), sr.Took)\n\t\t\tfor i, hit := range sr.Hits {\n\t\t\t\trv += fmt.Sprintf(\"%5d. %s (%f)\\n\", i+sr.Request.From+1, hit.ID, hit.Score)\n\t\t\t\tfor fragmentField, fragments := range hit.Fragments {\n\t\t\t\t\trv += fmt.Sprintf(\"\\t%s\\n\", fragmentField)\n\t\t\t\t\tfor _, fragment := range fragments {\n\t\t\t\t\t\trv += fmt.Sprintf(\"\\t\\t%s\\n\", fragment)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\trv = fmt.Sprintf(\"%d matches, took %s\\n\", sr.Total, sr.Took)\n\t\t}\n\t} else {\n\t\trv = \"No matches\"\n\t}\n\treturn rv\n}\n\nfunc (sr *SearchResult) Merge(other *SearchResult) {\n\tsr.Hits = append(sr.Hits, other.Hits...)\n\tsr.Total += other.Total\n\tsr.Took += other.Took\n\tif other.MaxScore > sr.MaxScore {\n\t\tsr.MaxScore = other.MaxScore\n\t}\n\tsr.Facets.Merge(other.Facets)\n}\nalso print out the requested stored fields\/\/ Copyright (c) 2014 Couchbase, Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n\/\/ except in compliance with the License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software distributed under the\n\/\/ License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n\/\/ either express or implied. See the License for the specific language governing permissions\n\/\/ and limitations under the License.\n\npackage bleve\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/blevesearch\/bleve\/analysis\"\n\t\"github.com\/blevesearch\/bleve\/search\"\n)\n\ntype numericRange struct {\n\tName string `json:\"name,omitempty\"`\n\tMin *float64 `json:\"min,omitempty\"`\n\tMax *float64 `json:\"max,omitempty\"`\n}\n\ntype dateTimeRange struct {\n\tName string `json:\"name,omitempty\"`\n\tStart time.Time `json:\"start,omitempty\"`\n\tEnd time.Time `json:\"end,omitempty\"`\n\tstartString *string\n\tendString *string\n}\n\nfunc (dr *dateTimeRange) ParseDates(dateTimeParser analysis.DateTimeParser) {\n\tif dr.Start.IsZero() && dr.startString != nil {\n\t\tstart, err := dateTimeParser.ParseDateTime(*dr.startString)\n\t\tif err == nil {\n\t\t\tdr.Start = start\n\t\t}\n\t}\n\tif dr.End.IsZero() && dr.endString != nil {\n\t\tend, err := dateTimeParser.ParseDateTime(*dr.endString)\n\t\tif err == nil {\n\t\t\tdr.End = end\n\t\t}\n\t}\n}\n\nfunc (dr *dateTimeRange) UnmarshalJSON(input []byte) error {\n\tvar temp struct {\n\t\tName string `json:\"name,omitempty\"`\n\t\tStart *string `json:\"start,omitempty\"`\n\t\tEnd *string `json:\"end,omitempty\"`\n\t}\n\n\terr := json.Unmarshal(input, &temp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdr.Name = temp.Name\n\tif temp.Start != nil {\n\t\tdr.startString = temp.Start\n\t}\n\tif temp.End != nil {\n\t\tdr.endString = temp.End\n\t}\n\n\treturn nil\n}\n\n\/\/ A FacetRequest describes a facet or aggregation\n\/\/ of the result document set you would like to be\n\/\/ built.\ntype FacetRequest struct {\n\tSize int\n\tField string\n\tNumericRanges []*numericRange `json:\"numeric_ranges,omitempty\"`\n\tDateTimeRanges []*dateTimeRange `json:\"date_ranges,omitempty\"`\n}\n\n\/\/ NewFacetRequest creates a facet on the specified\n\/\/ field that limits the number of entries to the\n\/\/ specified size.\nfunc NewFacetRequest(field string, size int) *FacetRequest {\n\treturn &FacetRequest{\n\t\tField: field,\n\t\tSize: size,\n\t}\n}\n\n\/\/ AddDateTimeRange adds a bucket to a field\n\/\/ containing date values. Documents with a\n\/\/ date value falling into this range are tabulated\n\/\/ as part of this bucket\/range.\nfunc (fr *FacetRequest) AddDateTimeRange(name string, start, end time.Time) {\n\tif fr.DateTimeRanges == nil {\n\t\tfr.DateTimeRanges = make([]*dateTimeRange, 0, 1)\n\t}\n\tfr.DateTimeRanges = append(fr.DateTimeRanges, &dateTimeRange{Name: name, Start: start, End: end})\n}\n\n\/\/ AddNumericRange adds a bucket to a field\n\/\/ containing numeric values. Documents with a\n\/\/ numeric value falling into this range are\n\/\/ tabulated as part of this bucket\/range.\nfunc (fr *FacetRequest) AddNumericRange(name string, min, max *float64) {\n\tif fr.NumericRanges == nil {\n\t\tfr.NumericRanges = make([]*numericRange, 0, 1)\n\t}\n\tfr.NumericRanges = append(fr.NumericRanges, &numericRange{Name: name, Min: min, Max: max})\n}\n\n\/\/ FacetsRequest groups together all the\n\/\/ FacetRequest objects for a single query.\ntype FacetsRequest map[string]*FacetRequest\n\n\/\/ HighlightRequest describes how field matches\n\/\/ should be highlighted.\ntype HighlightRequest struct {\n\tStyle *string `json:\"style\"`\n\tFields []string `json:\"fields\"`\n}\n\n\/\/ NewHighlight creates a default\n\/\/ HighlightRequest.\nfunc NewHighlight() *HighlightRequest {\n\treturn &HighlightRequest{}\n}\n\n\/\/ NewHighlightWithStyle creates a HighlightRequest\n\/\/ with an alternate style.\nfunc NewHighlightWithStyle(style string) *HighlightRequest {\n\treturn &HighlightRequest{\n\t\tStyle: &style,\n\t}\n}\n\nfunc (h *HighlightRequest) AddField(field string) {\n\tif h.Fields == nil {\n\t\th.Fields = make([]string, 0, 1)\n\t}\n\th.Fields = append(h.Fields, field)\n}\n\n\/\/ A SearchRequest describes all the parameters\n\/\/ needed to search the index.\n\/\/ Query is required.\n\/\/ Size\/From describe how much and which part of the\n\/\/ result set to return.\n\/\/ Highlight describes optional search result\n\/\/ highlighting.\n\/\/ Fields describes a list of field values which\n\/\/ should be retrieved for result documents.\n\/\/ Facets describe the set of facets to be computed.\n\/\/ Explain triggers inclusion of additional search\n\/\/ result score explanations.\n\/\/\n\/\/ A special field named \"*\" can be used to return all fields.\ntype SearchRequest struct {\n\tQuery Query `json:\"query\"`\n\tSize int `json:\"size\"`\n\tFrom int `json:\"from\"`\n\tHighlight *HighlightRequest `json:\"highlight\"`\n\tFields []string `json:\"fields\"`\n\tFacets FacetsRequest `json:\"facets\"`\n\tExplain bool `json:\"explain\"`\n}\n\n\/\/ AddFacet adds a FacetRequest to this SearchRequest\nfunc (r *SearchRequest) AddFacet(facetName string, f *FacetRequest) {\n\tif r.Facets == nil {\n\t\tr.Facets = make(FacetsRequest, 1)\n\t}\n\tr.Facets[facetName] = f\n}\n\n\/\/ UnmarshalJSON deserializes a JSON representation of\n\/\/ a SearchRequest\nfunc (r *SearchRequest) UnmarshalJSON(input []byte) error {\n\tvar temp struct {\n\t\tQ json.RawMessage `json:\"query\"`\n\t\tSize int `json:\"size\"`\n\t\tFrom int `json:\"from\"`\n\t\tHighlight *HighlightRequest `json:\"highlight\"`\n\t\tFields []string `json:\"fields\"`\n\t\tFacets FacetsRequest `json:\"facets\"`\n\t\tExplain bool `json:\"explain\"`\n\t}\n\n\terr := json.Unmarshal(input, &temp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Size = temp.Size\n\tr.From = temp.From\n\tr.Explain = temp.Explain\n\tr.Highlight = temp.Highlight\n\tr.Fields = temp.Fields\n\tr.Facets = temp.Facets\n\tr.Query, err = ParseQuery(temp.Q)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.Size < 0 {\n\t\tr.Size = 10\n\t}\n\tif r.From < 0 {\n\t\tr.From = 0\n\t}\n\n\treturn nil\n\n}\n\n\/\/ NewSearchRequest creates a new SearchRequest\n\/\/ for the Query, using default values for all\n\/\/ other search parameters.\nfunc NewSearchRequest(q Query) *SearchRequest {\n\treturn NewSearchRequestOptions(q, 10, 0, false)\n}\n\n\/\/ NewSearchRequestOptions creates a new SearchRequest\n\/\/ for the Query, with the requested size, from\n\/\/ and explanation search parameters.\nfunc NewSearchRequestOptions(q Query, size, from int, explain bool) *SearchRequest {\n\treturn &SearchRequest{\n\t\tQuery: q,\n\t\tSize: size,\n\t\tFrom: from,\n\t\tExplain: explain,\n\t}\n}\n\n\/\/ A SearchResult describes the results of executing\n\/\/ a SearchRequest.\ntype SearchResult struct {\n\tRequest *SearchRequest `json:\"request\"`\n\tHits search.DocumentMatchCollection `json:\"hits\"`\n\tTotal uint64 `json:\"total_hits\"`\n\tMaxScore float64 `json:\"max_score\"`\n\tTook time.Duration `json:\"took\"`\n\tFacets search.FacetResults `json:\"facets\"`\n}\n\nfunc (sr *SearchResult) String() string {\n\trv := \"\"\n\tif sr.Total > 0 {\n\t\tif sr.Request.Size > 0 {\n\t\t\trv = fmt.Sprintf(\"%d matches, showing %d through %d, took %s\\n\", sr.Total, sr.Request.From+1, sr.Request.From+len(sr.Hits), sr.Took)\n\t\t\tfor i, hit := range sr.Hits {\n\t\t\t\trv += fmt.Sprintf(\"%5d. %s (%f)\\n\", i+sr.Request.From+1, hit.ID, hit.Score)\n\t\t\t\tfor fragmentField, fragments := range hit.Fragments {\n\t\t\t\t\trv += fmt.Sprintf(\"\\t%s\\n\", fragmentField)\n\t\t\t\t\tfor _, fragment := range fragments {\n\t\t\t\t\t\trv += fmt.Sprintf(\"\\t\\t%s\\n\", fragment)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor otherFieldName, otherFieldValue := range hit.Fields {\n\t\t\t\t\tif _, ok := hit.Fragments[otherFieldName]; !ok {\n\t\t\t\t\t\trv += fmt.Sprintf(\"\\t%s\\n\", otherFieldName)\n\t\t\t\t\t\trv += fmt.Sprintf(\"\\t\\t%s\\n\", otherFieldValue)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\trv = fmt.Sprintf(\"%d matches, took %s\\n\", sr.Total, sr.Took)\n\t\t}\n\t} else {\n\t\trv = \"No matches\"\n\t}\n\treturn rv\n}\n\nfunc (sr *SearchResult) Merge(other *SearchResult) {\n\tsr.Hits = append(sr.Hits, other.Hits...)\n\tsr.Total += other.Total\n\tsr.Took += other.Took\n\tif other.MaxScore > sr.MaxScore {\n\t\tsr.MaxScore = other.MaxScore\n\t}\n\tsr.Facets.Merge(other.Facets)\n}\n<|endoftext|>"} {"text":"package search\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/mholt\/caddy\/middleware\"\n\t\"github.com\/pedronasser\/caddy-search\/indexer\"\n)\n\n\/\/ Handler creates a new handler for the search middleware\nfunc Handler(next middleware.Handler, config *Config, index indexer.Handler, pipeline *Pipeline) middleware.Handler {\n\treturn &Search{next, config, index, pipeline}\n}\n\n\/\/ Search represents this middleware structure\ntype Search struct {\n\tNext middleware.Handler\n\t*Config\n\tIndexer indexer.Handler\n\t*Pipeline\n}\n\n\/\/ ServerHTTP is the HTTP handler for this middleware\nfunc (s *Search) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {\n\tif middleware.Path(r.URL.Path).Matches(s.Config.Endpoint) {\n\t\tif r.Header.Get(\"Accept\") == \"application\/json\" {\n\t\t\treturn s.SearchJSON(w, r)\n\t\t}\n\t\treturn s.SearchJSON(w, r)\n\t}\n\n\trecord := s.Indexer.Record(r.URL.String())\n\tgo s.Pipeline.Pipe(record)\n\treturn s.Next.ServeHTTP(&searchResponseWriter{w, record}, r)\n}\n\n\/\/ Result is the structure for the search result\ntype Result struct {\n\tPath string\n\tTitle string\n\tBody string\n\tModified time.Time\n}\n\n\/\/ SearchJSON ...\nfunc (s *Search) SearchJSON(w http.ResponseWriter, r *http.Request) (status int, err error) {\n\tvar jresp []byte\n\n\tq := r.URL.Query().Get(\"q\")\n\tindexResult := s.Indexer.Search(q)\n\n\tresults := make([]Result, len(indexResult))\n\n\tfor i, result := range indexResult {\n\t\tbody := result.Body()\n\t\tresults[i] = Result{\n\t\t\tPath: result.Path(),\n\t\t\tTitle: result.Title(),\n\t\t\tModified: result.Modified(),\n\t\t\tBody: string(body),\n\t\t}\n\t}\n\n\tjresp, err = json.Marshal(results)\n\tif err != nil {\n\t\treturn 500, err\n\t}\n\n\tw.Write(jresp)\n\treturn 200, err\n}\n\ntype searchResponseWriter struct {\n\tw http.ResponseWriter\n\trecord indexer.Record\n}\n\nfunc (r *searchResponseWriter) Header() http.Header {\n\treturn r.w.Header()\n}\n\nfunc (r *searchResponseWriter) WriteHeader(code int) {\n\tif code != 200 {\n\t\tr.record.Ignore()\n\t}\n\tr.w.WriteHeader(code)\n}\n\nfunc (r *searchResponseWriter) Write(p []byte) (int, error) {\n\tdefer r.record.Write(p)\n\tn, err := r.w.Write(p)\n\treturn n, err\n}\nfix infinite loop if response code not 200package search\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/mholt\/caddy\/middleware\"\n\t\"github.com\/pedronasser\/caddy-search\/indexer\"\n)\n\n\/\/ Handler creates a new handler for the search middleware\nfunc Handler(next middleware.Handler, config *Config, index indexer.Handler, pipeline *Pipeline) middleware.Handler {\n\treturn &Search{next, config, index, pipeline}\n}\n\n\/\/ Search represents this middleware structure\ntype Search struct {\n\tNext middleware.Handler\n\t*Config\n\tIndexer indexer.Handler\n\t*Pipeline\n}\n\n\/\/ ServerHTTP is the HTTP handler for this middleware\nfunc (s *Search) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {\n\tif middleware.Path(r.URL.Path).Matches(s.Config.Endpoint) {\n\t\tif r.Header.Get(\"Accept\") == \"application\/json\" {\n\t\t\treturn s.SearchJSON(w, r)\n\t\t}\n\t\treturn s.SearchJSON(w, r)\n\t}\n\n\trecord := s.Indexer.Record(r.URL.String())\n\tgo s.Pipeline.Pipe(record)\n\n\tstatus, err := s.Next.ServeHTTP(&searchResponseWriter{w, record}, r)\n\tif status != 200 {\n\t\trecord.Ignore()\n\t}\n\n\treturn status, err\n}\n\n\/\/ Result is the structure for the search result\ntype Result struct {\n\tPath string\n\tTitle string\n\tBody string\n\tModified time.Time\n}\n\n\/\/ SearchJSON ...\nfunc (s *Search) SearchJSON(w http.ResponseWriter, r *http.Request) (status int, err error) {\n\tvar jresp []byte\n\n\tq := r.URL.Query().Get(\"q\")\n\tindexResult := s.Indexer.Search(q)\n\n\tresults := make([]Result, len(indexResult))\n\n\tfor i, result := range indexResult {\n\t\tbody := result.Body()\n\t\tresults[i] = Result{\n\t\t\tPath: result.Path(),\n\t\t\tTitle: result.Title(),\n\t\t\tModified: result.Modified(),\n\t\t\tBody: string(body),\n\t\t}\n\t}\n\n\tjresp, err = json.Marshal(results)\n\tif err != nil {\n\t\treturn 500, err\n\t}\n\n\tw.Write(jresp)\n\treturn 200, err\n}\n\ntype searchResponseWriter struct {\n\tw http.ResponseWriter\n\trecord indexer.Record\n}\n\nfunc (r *searchResponseWriter) Header() http.Header {\n\treturn r.w.Header()\n}\n\nfunc (r *searchResponseWriter) WriteHeader(code int) {\n\tif code != 200 {\n\t\tr.record.Ignore()\n\t}\n\tr.w.WriteHeader(code)\n}\n\nfunc (r *searchResponseWriter) Write(p []byte) (int, error) {\n\tdefer r.record.Write(p)\n\tn, err := r.w.Write(p)\n\treturn n, err\n}\n<|endoftext|>"} {"text":"package intarr\n\nimport \"encoding\/binary\"\n\nfunc Uint64ToBytes(i uint64) []byte {\n\tdata := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(data, i)\n\treturn data\n}\n\nfunc BytesToUint64(bts []byte) uint64 {\n\treturn binary.BigEndian.Uint64(bts)\n}\nadd utilpackage intarr\n\nimport \"encoding\/binary\"\n\nfunc Uint64ToBytes(i uint64) []byte {\n\tdata := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(data, i)\n\treturn data\n}\n\nfunc BytesToUint64(bts []byte) uint64 {\n\treturn binary.BigEndian.Uint64(bts)\n}\nfunc InArray(value int64, array []int64) bool {\n\tfor _, v := range array {\n\t\tif v == value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"} {"text":"package gopherneo\n\nimport \"regexp\"\n\nfunc EscapeStringForCypherRegex(in string) string {\n\t\/\/fmt.Printf(\"in: %v\\n\", in)\n\tr1 := regexp.MustCompile(\"(\\\\')\")\n\tr2 := regexp.MustCompile(\"(\\\\(|\\\\))\")\n\tr3 := regexp.MustCompile(\"(&)\")\n\tr4 := regexp.MustCompile(\"(\\\\*)\")\n\n\tout := in\n\tout = r1.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r2.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r3.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r4.ReplaceAllString(out, \"\\\\\\\\$1\")\n\t\/\/fmt.Printf(\"out: %v\\n\", out)\n\treturn out\n}\nMore improvements to unescaping for regex in cypherpackage gopherneo\n\nimport \"regexp\"\n\nfunc EscapeStringForCypherRegex(in string) string {\n\t\/\/fmt.Printf(\"in: %v\\n\", in)\n\tr1 := regexp.MustCompile(\"(\\\\')\")\n\tr2 := regexp.MustCompile(\"(\\\\(|\\\\))\")\n\tr3 := regexp.MustCompile(\"(&)\")\n\tr4 := regexp.MustCompile(\"(\\\\*)\")\n\tr5 := regexp.MustCompile(\"(\\\")\")\n\tr6 := regexp.MustCompile(\"(\\\\+)\")\n\n\tout := in\n\tout = r1.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r2.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r3.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r4.ReplaceAllString(out, \"\\\\\\\\$1\")\n\tout = r5.ReplaceAllString(out, \"\\\\$1\")\n\tout = r6.ReplaceAllString(out, \"\\\\\\\\$1\")\n\n\t\/\/fmt.Printf(\"out: %v\\n\", out)\n\treturn out\n}\n<|endoftext|>"} {"text":"package gg\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/draw\"\n\t_ \"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/golang\/freetype\/truetype\"\n\n\t\"golang.org\/x\/image\/font\"\n\t\"golang.org\/x\/image\/math\/fixed\"\n)\n\nfunc Radians(degrees float64) float64 {\n\treturn degrees * math.Pi \/ 180\n}\n\nfunc Degrees(radians float64) float64 {\n\treturn radians * 180 \/ math.Pi\n}\n\nfunc LoadImage(path string) (image.Image, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tim, _, err := image.Decode(file)\n\treturn im, err\n}\n\nfunc LoadPNG(path string) (image.Image, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn png.Decode(file)\n}\n\nfunc SavePNG(path string, im image.Image) error {\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn png.Encode(file, im)\n}\n\nfunc imageToRGBA(src image.Image) *image.RGBA {\n\tbounds := src.Bounds()\n\tdst := image.NewRGBA(bounds)\n\tdraw.Draw(dst, bounds, src, bounds.Min, draw.Src)\n\treturn dst\n}\n\nfunc parseHexColor(x string) (r, g, b, a int) {\n\tx = strings.TrimPrefix(x, \"#\")\n\ta = 255\n\tif len(x) == 3 {\n\t\tformat := \"%1x%1x%1x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b)\n\t\tr |= r << 4\n\t\tg |= g << 4\n\t\tb |= b << 4\n\t}\n\tif len(x) == 6 {\n\t\tformat := \"%02x%02x%02x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b)\n\t}\n\tif len(x) == 8 {\n\t\tformat := \"%02x%02x%02x%02x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b, &a)\n\t}\n\treturn\n}\n\nfunc fixp(x, y float64) fixed.Point26_6 {\n\treturn fixed.Point26_6{fix(x), fix(y)}\n}\n\nfunc fix(x float64) fixed.Int26_6 {\n\treturn fixed.Int26_6(x * 64)\n}\n\nfunc unfix(x fixed.Int26_6) float64 {\n\tconst shift, mask = 6, 1<<6 - 1\n\tif x >= 0 {\n\t\treturn float64(x>>shift) + float64(x&mask)\/64\n\t}\n\tx = -x\n\tif x >= 0 {\n\t\treturn -(float64(x>>shift) + float64(x&mask)\/64)\n\t}\n\treturn 0\n}\n\nfunc LoadFontFace(path string, points float64) (font.Face, error) {\n\tfontBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := truetype.Parse(fontBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tface := truetype.NewFace(f, &truetype.Options{\n\t\tSize: points,\n\t\t\/\/ Hinting: font.HintingFull,\n\t})\n\treturn face, nil\n}\nFix #23 via doc on gg.LoadFontFace function.package gg\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/draw\"\n\t_ \"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/golang\/freetype\/truetype\"\n\n\t\"golang.org\/x\/image\/font\"\n\t\"golang.org\/x\/image\/math\/fixed\"\n)\n\nfunc Radians(degrees float64) float64 {\n\treturn degrees * math.Pi \/ 180\n}\n\nfunc Degrees(radians float64) float64 {\n\treturn radians * 180 \/ math.Pi\n}\n\nfunc LoadImage(path string) (image.Image, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tim, _, err := image.Decode(file)\n\treturn im, err\n}\n\nfunc LoadPNG(path string) (image.Image, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn png.Decode(file)\n}\n\nfunc SavePNG(path string, im image.Image) error {\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn png.Encode(file, im)\n}\n\nfunc imageToRGBA(src image.Image) *image.RGBA {\n\tbounds := src.Bounds()\n\tdst := image.NewRGBA(bounds)\n\tdraw.Draw(dst, bounds, src, bounds.Min, draw.Src)\n\treturn dst\n}\n\nfunc parseHexColor(x string) (r, g, b, a int) {\n\tx = strings.TrimPrefix(x, \"#\")\n\ta = 255\n\tif len(x) == 3 {\n\t\tformat := \"%1x%1x%1x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b)\n\t\tr |= r << 4\n\t\tg |= g << 4\n\t\tb |= b << 4\n\t}\n\tif len(x) == 6 {\n\t\tformat := \"%02x%02x%02x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b)\n\t}\n\tif len(x) == 8 {\n\t\tformat := \"%02x%02x%02x%02x\"\n\t\tfmt.Sscanf(x, format, &r, &g, &b, &a)\n\t}\n\treturn\n}\n\nfunc fixp(x, y float64) fixed.Point26_6 {\n\treturn fixed.Point26_6{fix(x), fix(y)}\n}\n\nfunc fix(x float64) fixed.Int26_6 {\n\treturn fixed.Int26_6(x * 64)\n}\n\nfunc unfix(x fixed.Int26_6) float64 {\n\tconst shift, mask = 6, 1<<6 - 1\n\tif x >= 0 {\n\t\treturn float64(x>>shift) + float64(x&mask)\/64\n\t}\n\tx = -x\n\tif x >= 0 {\n\t\treturn -(float64(x>>shift) + float64(x&mask)\/64)\n\t}\n\treturn 0\n}\n\n\/\/ LoadFontFace is a helper function to load the specified font file with\n\/\/ the specified point size. Note that the returned `font.Face` objects\n\/\/ are not thread safe and cannot be used in parallel across goroutines.\n\/\/ You can usually just use the Context.LoadFontFace function instead of\n\/\/ this package-level function.\nfunc LoadFontFace(path string, points float64) (font.Face, error) {\n\tfontBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := truetype.Parse(fontBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tface := truetype.NewFace(f, &truetype.Options{\n\t\tSize: points,\n\t\t\/\/ Hinting: font.HintingFull,\n\t})\n\treturn face, nil\n}\n<|endoftext|>"} {"text":"package postgres\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"context\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/iron-io\/functions\/api\/models\"\n\t\"github.com\/lib\/pq\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nconst routesTableCreate = `\nCREATE TABLE IF NOT EXISTS routes (\n\tapp_name character varying(256) NOT NULL,\n\tpath text NOT NULL,\n\timage character varying(256) NOT NULL,\n\tformat character varying(16) NOT NULL,\n\tmaxc integer NOT NULL,\n\tmemory integer NOT NULL,\n\ttimeout integer NOT NULL,\n\ttype character varying(16) NOT NULL,\n\theaders text NOT NULL,\n\tconfig text NOT NULL,\n\tPRIMARY KEY (app_name, path)\n);`\n\nconst appsTableCreate = `CREATE TABLE IF NOT EXISTS apps (\n name character varying(256) NOT NULL PRIMARY KEY,\n\tconfig text NOT NULL\n);`\n\nconst extrasTableCreate = `CREATE TABLE IF NOT EXISTS extras (\n key character varying(256) NOT NULL PRIMARY KEY,\n\tvalue character varying(256) NOT NULL\n);`\n\nconst routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, headers, config FROM routes`\n\ntype rowScanner interface {\n\tScan(dest ...interface{}) error\n}\n\ntype rowQuerier interface {\n\tQueryRow(query string, args ...interface{}) *sql.Row\n}\n\ntype PostgresDatastore struct {\n\tdb *sql.DB\n}\n\nfunc New(url *url.URL) (models.Datastore, error) {\n\tdb, err := sql.Open(\"postgres\", url.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxIdleConns := 30 \/\/ c.MaxIdleConnections\n\tdb.SetMaxIdleConns(maxIdleConns)\n\tlogrus.WithFields(logrus.Fields{\"max_idle_connections\": maxIdleConns}).Info(\"Postgres dialed\")\n\n\tpg := &PostgresDatastore{\n\t\tdb: db,\n\t}\n\n\tfor _, v := range []string{routesTableCreate, appsTableCreate, extrasTableCreate} {\n\t\t_, err = db.Exec(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn pg, nil\n}\n\nfunc (ds *PostgresDatastore) InsertApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tvar cbyte []byte\n\tvar err error\n\n\tif app == nil {\n\t\treturn nil, models.ErrDatastoreEmptyApp\n\t}\n\n\tif app.Name == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\tif app.Config != nil {\n\t\tcbyte, err = json.Marshal(app.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t_, err = ds.db.Exec(`INSERT INTO apps (name, config) VALUES ($1, $2);`,\n\t\tapp.Name,\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\tpqErr := err.(*pq.Error)\n\t\tif pqErr.Code == \"23505\" {\n\t\t\treturn nil, models.ErrAppsAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\nfunc (ds *PostgresDatastore) UpdateApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tif app == nil {\n\t\treturn nil, models.ErrAppsNotFound\n\t}\n\n\tcbyte, err := json.Marshal(app.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := ds.db.Exec(`\n\t UPDATE apps SET\n\t\tconfig = $2\n\t WHERE name = $1\n\t RETURNING *;\n\t`,\n\t\tapp.Name,\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n == 0 {\n\t\treturn nil, models.ErrAppsNotFound\n\t}\n\n\treturn app, nil\n}\n\nfunc (ds *PostgresDatastore) RemoveApp(ctx context.Context, appName string) error {\n\tif appName == \"\" {\n\t\treturn models.ErrDatastoreEmptyAppName\n\t}\n\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = $1\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ds *PostgresDatastore) GetApp(ctx context.Context, name string) (*models.App, error) {\n\tif name == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\trow := ds.db.QueryRow(\"SELECT name, config FROM apps WHERE name=$1\", name)\n\n\tvar resName string\n\tvar config string\n\terr := row.Scan(&resName, &config)\n\n\tres := &models.App{\n\t\tName: resName,\n\t}\n\n\tjson.Unmarshal([]byte(config), &res.Config)\n\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, models.ErrAppsNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}\n\nfunc scanApp(scanner rowScanner, app *models.App) error {\n\tvar configStr string\n\n\terr := scanner.Scan(\n\t\t&app.Name,\n\t\t&configStr,\n\t)\n\n\tif configStr == \"\" {\n\t\treturn models.ErrAppsNotFound\n\t}\n\n\tjson.Unmarshal([]byte(configStr), &app.Config)\n\n\treturn err\n}\n\nfunc (ds *PostgresDatastore) GetApps(ctx context.Context, filter *models.AppFilter) ([]*models.App, error) {\n\tres := []*models.App{}\n\n\tfilterQuery := buildFilterAppQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"SELECT DISTINCT * FROM apps %s\", filterQuery))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar app models.App\n\t\terr := scanApp(rows, &app)\n\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\treturn res, nil\n\t\t\t}\n\t\t\treturn res, err\n\t\t}\n\t\tres = append(res, &app)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn res, err\n\t}\n\treturn res, nil\n}\n\nfunc (ds *PostgresDatastore) InsertRoute(ctx context.Context, route *models.Route) (*models.Route, error) {\n\tif route == nil {\n\t\treturn nil, models.ErrDatastoreEmptyRoute\n\t}\n\n\thbyte, err := json.Marshal(route.Headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcbyte, err := json.Marshal(route.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = ds.db.Exec(`\n\t\tINSERT INTO routes (\n\t\t\tapp_name,\n\t\t\tpath,\n\t\t\timage,\n\t\t\tformat,\n\t\t\tmaxc,\n\t\t\tmemory,\n\t\t\ttype,\n\t\t\ttimeout,\n\t\t\theaders,\n\t\t\tconfig\n\t\t)\n\t\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);`,\n\t\troute.AppName,\n\t\troute.Path,\n\t\troute.Image,\n\t\troute.Format,\n\t\troute.MaxConcurrency,\n\t\troute.Memory,\n\t\troute.Type,\n\t\troute.Timeout,\n\t\tstring(hbyte),\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\tpqErr := err.(*pq.Error)\n\t\tif pqErr.Code == \"23505\" {\n\t\t\treturn nil, models.ErrRoutesAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn route, nil\n}\n\nfunc (ds *PostgresDatastore) UpdateRoute(ctx context.Context, route *models.Route) (*models.Route, error) {\n\tif route == nil {\n\t\treturn nil, models.ErrDatastoreEmptyRoute\n\t}\n\n\thbyte, err := json.Marshal(route.Headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcbyte, err := json.Marshal(route.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := ds.db.Exec(`\n\t\tUPDATE routes SET\n\t\t\timage = $3,\n\t\t\tformat = $4,\n\t\t\tmemory = $5,\n\t\t\tmaxc = $6,\n\t\t\ttype = $7,\n\t\t\ttimeout = $8,\n\t\t\theaders = $9,\n\t\t\tconfig = $10\n\t\tWHERE app_name = $1 AND path = $2;`,\n\t\troute.AppName,\n\t\troute.Path,\n\t\troute.Image,\n\t\troute.Format,\n\t\troute.Memory,\n\t\troute.MaxConcurrency,\n\t\troute.Type,\n\t\troute.Timeout,\n\t\tstring(hbyte),\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n == 0 {\n\t\treturn nil, models.ErrRoutesNotFound\n\t}\n\n\treturn route, nil\n}\n\nfunc (ds *PostgresDatastore) RemoveRoute(ctx context.Context, appName, routePath string) error {\n\tif appName == \"\" {\n\t\treturn models.ErrDatastoreEmptyAppName\n\t}\n\n\tif routePath == \"\" {\n\t\treturn models.ErrDatastoreEmptyRoutePath\n\t}\n\n\tres, err := ds.db.Exec(`\n\t\tDELETE FROM routes\n\t\tWHERE path = $1 AND app_name = $2\n\t`, routePath, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n == 0 {\n\t\treturn models.ErrRoutesRemoving\n\t}\n\n\treturn nil\n}\n\nfunc scanRoute(scanner rowScanner, route *models.Route) error {\n\tvar headerStr string\n\tvar configStr string\n\n\terr := scanner.Scan(\n\t\t&route.AppName,\n\t\t&route.Path,\n\t\t&route.Image,\n\t\t&route.Format,\n\t\t&route.Memory,\n\t\t&route.MaxConcurrency,\n\t\t&route.Type,\n\t\t&route.Timeout,\n\t\t&headerStr,\n\t\t&configStr,\n\t)\n\n\tif headerStr == \"\" {\n\t\treturn models.ErrRoutesNotFound\n\t}\n\n\tjson.Unmarshal([]byte(headerStr), &route.Headers)\n\tjson.Unmarshal([]byte(configStr), &route.Config)\n\n\treturn err\n}\n\nfunc (ds *PostgresDatastore) GetRoute(ctx context.Context, appName, routePath string) (*models.Route, error) {\n\tif appName == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\tif routePath == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyRoutePath\n\t}\n\n\tvar route models.Route\n\n\trow := ds.db.QueryRow(fmt.Sprintf(\"%s WHERE app_name=$1 AND path=$2\", routeSelector), appName, routePath)\n\terr := scanRoute(row, &route)\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil, models.ErrRoutesNotFound\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn &route, nil\n}\n\nfunc (ds *PostgresDatastore) GetRoutes(ctx context.Context, filter *models.RouteFilter) ([]*models.Route, error) {\n\tres := []*models.Route{}\n\tfilterQuery := buildFilterRouteQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"%s %s\", routeSelector, filterQuery))\n\t\/\/ todo: check for no rows so we don't respond with a sql 500 err\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar route models.Route\n\t\terr := scanRoute(rows, &route)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &route)\n\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc (ds *PostgresDatastore) GetRoutesByApp(ctx context.Context, appName string, filter *models.RouteFilter) ([]*models.Route, error) {\n\tres := []*models.Route{}\n\tfilter.AppName = appName\n\tfilterQuery := buildFilterRouteQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"%s %s\", routeSelector, filterQuery))\n\t\/\/ todo: check for no rows so we don't respond with a sql 500 err\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar route models.Route\n\t\terr := scanRoute(rows, &route)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &route)\n\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc buildFilterAppQuery(filter *models.AppFilter) string {\n\tfilterQuery := \"\"\n\n\tif filter != nil {\n\t\tfilterQueries := []string{}\n\t\tif filter.Name != \"\" {\n\t\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"name LIKE '%s'\", filter.Name))\n\t\t}\n\n\t\tfor i, field := range filterQueries {\n\t\t\tif i == 0 {\n\t\t\t\tfilterQuery = fmt.Sprintf(\"WHERE %s \", field)\n\t\t\t} else {\n\t\t\t\tfilterQuery = fmt.Sprintf(\"%s AND %s\", filterQuery, field)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filterQuery\n}\n\nfunc buildFilterRouteQuery(filter *models.RouteFilter) string {\n\tfilterQuery := \"\"\n\n\tfilterQueries := []string{}\n\tif filter.Path != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"path = '%s'\", filter.Path))\n\t}\n\n\tif filter.AppName != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"app_name = '%s'\", filter.AppName))\n\t}\n\n\tif filter.Image != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"image = '%s'\", filter.Image))\n\t}\n\n\tfor i, field := range filterQueries {\n\t\tif i == 0 {\n\t\t\tfilterQuery = fmt.Sprintf(\"WHERE %s \", field)\n\t\t} else {\n\t\t\tfilterQuery = fmt.Sprintf(\"%s AND %s\", filterQuery, field)\n\t\t}\n\t}\n\n\treturn filterQuery\n}\n\nfunc (ds *PostgresDatastore) Put(ctx context.Context, key, value []byte) error {\n\t_, err := ds.db.Exec(`\n\t INSERT INTO extras (\n\t\t\tkey,\n\t\t\tvalue\n\t\t)\n\t\tVALUES ($1, $2)\n\t\tON CONFLICT (key) DO UPDATE SET\n\t\t\tvalue = $1;\n\t\t`, value)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ds *PostgresDatastore) Get(ctx context.Context, key []byte) ([]byte, error) {\n\trow := ds.db.QueryRow(\"SELECT value FROM extras WHERE key=$1\", key)\n\n\tvar value []byte\n\terr := row.Scan(&value)\n\tif err == sql.ErrNoRows {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn value, nil\n}\nminor postgres fix (#392)package postgres\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"context\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/iron-io\/functions\/api\/models\"\n\t\"github.com\/lib\/pq\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nconst routesTableCreate = `\nCREATE TABLE IF NOT EXISTS routes (\n\tapp_name character varying(256) NOT NULL,\n\tpath text NOT NULL,\n\timage character varying(256) NOT NULL,\n\tformat character varying(16) NOT NULL,\n\tmaxc integer NOT NULL,\n\tmemory integer NOT NULL,\n\ttimeout integer NOT NULL,\n\ttype character varying(16) NOT NULL,\n\theaders text NOT NULL,\n\tconfig text NOT NULL,\n\tPRIMARY KEY (app_name, path)\n);`\n\nconst appsTableCreate = `CREATE TABLE IF NOT EXISTS apps (\n name character varying(256) NOT NULL PRIMARY KEY,\n\tconfig text NOT NULL\n);`\n\nconst extrasTableCreate = `CREATE TABLE IF NOT EXISTS extras (\n key character varying(256) NOT NULL PRIMARY KEY,\n\tvalue character varying(256) NOT NULL\n);`\n\nconst routeSelector = `SELECT app_name, path, image, format, maxc, memory, type, timeout, headers, config FROM routes`\n\ntype rowScanner interface {\n\tScan(dest ...interface{}) error\n}\n\ntype rowQuerier interface {\n\tQueryRow(query string, args ...interface{}) *sql.Row\n}\n\ntype PostgresDatastore struct {\n\tdb *sql.DB\n}\n\nfunc New(url *url.URL) (models.Datastore, error) {\n\tdb, err := sql.Open(\"postgres\", url.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxIdleConns := 30 \/\/ c.MaxIdleConnections\n\tdb.SetMaxIdleConns(maxIdleConns)\n\tlogrus.WithFields(logrus.Fields{\"max_idle_connections\": maxIdleConns}).Info(\"Postgres dialed\")\n\n\tpg := &PostgresDatastore{\n\t\tdb: db,\n\t}\n\n\tfor _, v := range []string{routesTableCreate, appsTableCreate, extrasTableCreate} {\n\t\t_, err = db.Exec(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn pg, nil\n}\n\nfunc (ds *PostgresDatastore) InsertApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tvar cbyte []byte\n\tvar err error\n\n\tif app == nil {\n\t\treturn nil, models.ErrDatastoreEmptyApp\n\t}\n\n\tif app.Name == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\tif app.Config != nil {\n\t\tcbyte, err = json.Marshal(app.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t_, err = ds.db.Exec(`INSERT INTO apps (name, config) VALUES ($1, $2);`,\n\t\tapp.Name,\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\tpqErr := err.(*pq.Error)\n\t\tif pqErr.Code == \"23505\" {\n\t\t\treturn nil, models.ErrAppsAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn app, nil\n}\n\nfunc (ds *PostgresDatastore) UpdateApp(ctx context.Context, app *models.App) (*models.App, error) {\n\tif app == nil {\n\t\treturn nil, models.ErrAppsNotFound\n\t}\n\n\tcbyte, err := json.Marshal(app.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := ds.db.Exec(`\n\t UPDATE apps SET\n\t\tconfig = $2\n\t WHERE name = $1\n\t RETURNING *;\n\t`,\n\t\tapp.Name,\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n == 0 {\n\t\treturn nil, models.ErrAppsNotFound\n\t}\n\n\treturn app, nil\n}\n\nfunc (ds *PostgresDatastore) RemoveApp(ctx context.Context, appName string) error {\n\tif appName == \"\" {\n\t\treturn models.ErrDatastoreEmptyAppName\n\t}\n\n\t_, err := ds.db.Exec(`\n\t DELETE FROM apps\n\t WHERE name = $1\n\t`, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ds *PostgresDatastore) GetApp(ctx context.Context, name string) (*models.App, error) {\n\tif name == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\trow := ds.db.QueryRow(\"SELECT name, config FROM apps WHERE name=$1\", name)\n\n\tvar resName string\n\tvar config string\n\terr := row.Scan(&resName, &config)\n\n\tres := &models.App{\n\t\tName: resName,\n\t}\n\n\tjson.Unmarshal([]byte(config), &res.Config)\n\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, models.ErrAppsNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}\n\nfunc scanApp(scanner rowScanner, app *models.App) error {\n\tvar configStr string\n\n\terr := scanner.Scan(\n\t\t&app.Name,\n\t\t&configStr,\n\t)\n\n\tjson.Unmarshal([]byte(configStr), &app.Config)\n\n\treturn err\n}\n\nfunc (ds *PostgresDatastore) GetApps(ctx context.Context, filter *models.AppFilter) ([]*models.App, error) {\n\tres := []*models.App{}\n\n\tfilterQuery := buildFilterAppQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"SELECT DISTINCT * FROM apps %s\", filterQuery))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar app models.App\n\t\terr := scanApp(rows, &app)\n\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\treturn res, nil\n\t\t\t}\n\t\t\treturn res, err\n\t\t}\n\t\tres = append(res, &app)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn res, err\n\t}\n\treturn res, nil\n}\n\nfunc (ds *PostgresDatastore) InsertRoute(ctx context.Context, route *models.Route) (*models.Route, error) {\n\tif route == nil {\n\t\treturn nil, models.ErrDatastoreEmptyRoute\n\t}\n\n\thbyte, err := json.Marshal(route.Headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcbyte, err := json.Marshal(route.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = ds.db.Exec(`\n\t\tINSERT INTO routes (\n\t\t\tapp_name,\n\t\t\tpath,\n\t\t\timage,\n\t\t\tformat,\n\t\t\tmaxc,\n\t\t\tmemory,\n\t\t\ttype,\n\t\t\ttimeout,\n\t\t\theaders,\n\t\t\tconfig\n\t\t)\n\t\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);`,\n\t\troute.AppName,\n\t\troute.Path,\n\t\troute.Image,\n\t\troute.Format,\n\t\troute.MaxConcurrency,\n\t\troute.Memory,\n\t\troute.Type,\n\t\troute.Timeout,\n\t\tstring(hbyte),\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\tpqErr := err.(*pq.Error)\n\t\tif pqErr.Code == \"23505\" {\n\t\t\treturn nil, models.ErrRoutesAlreadyExists\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn route, nil\n}\n\nfunc (ds *PostgresDatastore) UpdateRoute(ctx context.Context, route *models.Route) (*models.Route, error) {\n\tif route == nil {\n\t\treturn nil, models.ErrDatastoreEmptyRoute\n\t}\n\n\thbyte, err := json.Marshal(route.Headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcbyte, err := json.Marshal(route.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := ds.db.Exec(`\n\t\tUPDATE routes SET\n\t\t\timage = $3,\n\t\t\tformat = $4,\n\t\t\tmemory = $5,\n\t\t\tmaxc = $6,\n\t\t\ttype = $7,\n\t\t\ttimeout = $8,\n\t\t\theaders = $9,\n\t\t\tconfig = $10\n\t\tWHERE app_name = $1 AND path = $2;`,\n\t\troute.AppName,\n\t\troute.Path,\n\t\troute.Image,\n\t\troute.Format,\n\t\troute.Memory,\n\t\troute.MaxConcurrency,\n\t\troute.Type,\n\t\troute.Timeout,\n\t\tstring(hbyte),\n\t\tstring(cbyte),\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n == 0 {\n\t\treturn nil, models.ErrRoutesNotFound\n\t}\n\n\treturn route, nil\n}\n\nfunc (ds *PostgresDatastore) RemoveRoute(ctx context.Context, appName, routePath string) error {\n\tif appName == \"\" {\n\t\treturn models.ErrDatastoreEmptyAppName\n\t}\n\n\tif routePath == \"\" {\n\t\treturn models.ErrDatastoreEmptyRoutePath\n\t}\n\n\tres, err := ds.db.Exec(`\n\t\tDELETE FROM routes\n\t\tWHERE path = $1 AND app_name = $2\n\t`, routePath, appName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n == 0 {\n\t\treturn models.ErrRoutesRemoving\n\t}\n\n\treturn nil\n}\n\nfunc scanRoute(scanner rowScanner, route *models.Route) error {\n\tvar headerStr string\n\tvar configStr string\n\n\terr := scanner.Scan(\n\t\t&route.AppName,\n\t\t&route.Path,\n\t\t&route.Image,\n\t\t&route.Format,\n\t\t&route.Memory,\n\t\t&route.MaxConcurrency,\n\t\t&route.Type,\n\t\t&route.Timeout,\n\t\t&headerStr,\n\t\t&configStr,\n\t)\n\n\tif headerStr == \"\" {\n\t\treturn models.ErrRoutesNotFound\n\t}\n\n\tjson.Unmarshal([]byte(headerStr), &route.Headers)\n\tjson.Unmarshal([]byte(configStr), &route.Config)\n\n\treturn err\n}\n\nfunc (ds *PostgresDatastore) GetRoute(ctx context.Context, appName, routePath string) (*models.Route, error) {\n\tif appName == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyAppName\n\t}\n\n\tif routePath == \"\" {\n\t\treturn nil, models.ErrDatastoreEmptyRoutePath\n\t}\n\n\tvar route models.Route\n\n\trow := ds.db.QueryRow(fmt.Sprintf(\"%s WHERE app_name=$1 AND path=$2\", routeSelector), appName, routePath)\n\terr := scanRoute(row, &route)\n\n\tif err == sql.ErrNoRows {\n\t\treturn nil, models.ErrRoutesNotFound\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn &route, nil\n}\n\nfunc (ds *PostgresDatastore) GetRoutes(ctx context.Context, filter *models.RouteFilter) ([]*models.Route, error) {\n\tres := []*models.Route{}\n\tfilterQuery := buildFilterRouteQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"%s %s\", routeSelector, filterQuery))\n\t\/\/ todo: check for no rows so we don't respond with a sql 500 err\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar route models.Route\n\t\terr := scanRoute(rows, &route)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &route)\n\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc (ds *PostgresDatastore) GetRoutesByApp(ctx context.Context, appName string, filter *models.RouteFilter) ([]*models.Route, error) {\n\tres := []*models.Route{}\n\tfilter.AppName = appName\n\tfilterQuery := buildFilterRouteQuery(filter)\n\trows, err := ds.db.Query(fmt.Sprintf(\"%s %s\", routeSelector, filterQuery))\n\t\/\/ todo: check for no rows so we don't respond with a sql 500 err\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar route models.Route\n\t\terr := scanRoute(rows, &route)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &route)\n\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n\nfunc buildFilterAppQuery(filter *models.AppFilter) string {\n\tfilterQuery := \"\"\n\n\tif filter != nil {\n\t\tfilterQueries := []string{}\n\t\tif filter.Name != \"\" {\n\t\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"name LIKE '%s'\", filter.Name))\n\t\t}\n\n\t\tfor i, field := range filterQueries {\n\t\t\tif i == 0 {\n\t\t\t\tfilterQuery = fmt.Sprintf(\"WHERE %s \", field)\n\t\t\t} else {\n\t\t\t\tfilterQuery = fmt.Sprintf(\"%s AND %s\", filterQuery, field)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filterQuery\n}\n\nfunc buildFilterRouteQuery(filter *models.RouteFilter) string {\n\tfilterQuery := \"\"\n\n\tfilterQueries := []string{}\n\tif filter.Path != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"path = '%s'\", filter.Path))\n\t}\n\n\tif filter.AppName != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"app_name = '%s'\", filter.AppName))\n\t}\n\n\tif filter.Image != \"\" {\n\t\tfilterQueries = append(filterQueries, fmt.Sprintf(\"image = '%s'\", filter.Image))\n\t}\n\n\tfor i, field := range filterQueries {\n\t\tif i == 0 {\n\t\t\tfilterQuery = fmt.Sprintf(\"WHERE %s \", field)\n\t\t} else {\n\t\t\tfilterQuery = fmt.Sprintf(\"%s AND %s\", filterQuery, field)\n\t\t}\n\t}\n\n\treturn filterQuery\n}\n\nfunc (ds *PostgresDatastore) Put(ctx context.Context, key, value []byte) error {\n\t_, err := ds.db.Exec(`\n\t INSERT INTO extras (\n\t\t\tkey,\n\t\t\tvalue\n\t\t)\n\t\tVALUES ($1, $2)\n\t\tON CONFLICT (key) DO UPDATE SET\n\t\t\tvalue = $1;\n\t\t`, string(key), string(value))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ds *PostgresDatastore) Get(ctx context.Context, key []byte) ([]byte, error) {\n\trow := ds.db.QueryRow(\"SELECT value FROM extras WHERE key=$1\", key)\n\n\tvar value string\n\terr := row.Scan(&value)\n\tif err == sql.ErrNoRows {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []byte(value), nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright ©2015 The gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage native\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/gonum\/lapack\/testlapack\"\n)\n\nvar impl = Implementation{}\n\nfunc TestDbdsqr(t *testing.T) {\n\ttestlapack.DbdsqrTest(t, impl)\n}\n\nfunc TestDgebd2(t *testing.T) {\n\ttestlapack.Dgebd2Test(t, impl)\n}\n\nfunc TestDgebrd(t *testing.T) {\n\ttestlapack.DgebrdTest(t, impl)\n}\n\nfunc TestDgecon(t *testing.T) {\n\ttestlapack.DgeconTest(t, impl)\n}\n\nfunc TestDgehd2(t *testing.T) {\n\ttestlapack.Dgehd2Test(t, impl)\n}\n\nfunc TestDgehrd(t *testing.T) {\n\ttestlapack.DgehrdTest(t, impl)\n}\n\nfunc TestDgelqf(t *testing.T) {\n\ttestlapack.DgelqfTest(t, impl)\n}\n\nfunc TestDgelq2(t *testing.T) {\n\ttestlapack.Dgelq2Test(t, impl)\n}\n\nfunc TestDgeql2(t *testing.T) {\n\ttestlapack.Dgeql2Test(t, impl)\n}\n\nfunc TestDgels(t *testing.T) {\n\ttestlapack.DgelsTest(t, impl)\n}\n\nfunc TestDgeqr2(t *testing.T) {\n\ttestlapack.Dgeqr2Test(t, impl)\n}\n\nfunc TestDgeqrf(t *testing.T) {\n\ttestlapack.DgeqrfTest(t, impl)\n}\n\nfunc TestDgesvd(t *testing.T) {\n\ttestlapack.DgesvdTest(t, impl)\n}\n\nfunc TestDgetri(t *testing.T) {\n\ttestlapack.DgetriTest(t, impl)\n}\n\nfunc TestDgetf2(t *testing.T) {\n\ttestlapack.Dgetf2Test(t, impl)\n}\n\nfunc TestDgetrf(t *testing.T) {\n\ttestlapack.DgetrfTest(t, impl)\n}\n\nfunc TestDgetrs(t *testing.T) {\n\ttestlapack.DgetrsTest(t, impl)\n}\n\nfunc TestDlabrd(t *testing.T) {\n\ttestlapack.DlabrdTest(t, impl)\n}\n\nfunc TestDlacpy(t *testing.T) {\n\ttestlapack.DlacpyTest(t, impl)\n}\n\nfunc TestDlae2(t *testing.T) {\n\ttestlapack.Dlae2Test(t, impl)\n}\n\nfunc TestDlaev2(t *testing.T) {\n\ttestlapack.Dlaev2Test(t, impl)\n}\n\nfunc TestDlaexc(t *testing.T) {\n\ttestlapack.DlaexcTest(t, impl)\n}\n\nfunc TestDlahqr(t *testing.T) {\n\ttestlapack.DlahqrTest(t, impl)\n}\n\nfunc TestDlahr2(t *testing.T) {\n\ttestlapack.Dlahr2Test(t, impl)\n}\n\nfunc TestDlaln2(t *testing.T) {\n\ttestlapack.Dlaln2Test(t, impl)\n}\n\nfunc TestDlange(t *testing.T) {\n\ttestlapack.DlangeTest(t, impl)\n}\n\nfunc TestDlas2(t *testing.T) {\n\ttestlapack.Dlas2Test(t, impl)\n}\n\nfunc TestDlasy2(t *testing.T) {\n\ttestlapack.Dlasy2Test(t, impl)\n}\n\nfunc TestDlanst(t *testing.T) {\n\ttestlapack.DlanstTest(t, impl)\n}\n\nfunc TestDlansy(t *testing.T) {\n\ttestlapack.DlansyTest(t, impl)\n}\n\nfunc TestDlantr(t *testing.T) {\n\ttestlapack.DlantrTest(t, impl)\n}\n\nfunc TestDlanv2(t *testing.T) {\n\ttestlapack.Dlanv2Test(t, impl)\n}\n\nfunc TestDlaqr1(t *testing.T) {\n\ttestlapack.Dlaqr1Test(t, impl)\n}\n\nfunc TestDlaqr5(t *testing.T) {\n\ttestlapack.Dlaqr5Test(t, impl)\n}\n\nfunc TestDlarf(t *testing.T) {\n\ttestlapack.DlarfTest(t, impl)\n}\n\nfunc TestDlarfb(t *testing.T) {\n\ttestlapack.DlarfbTest(t, impl)\n}\n\nfunc TestDlarfg(t *testing.T) {\n\ttestlapack.DlarfgTest(t, impl)\n}\n\nfunc TestDlarft(t *testing.T) {\n\ttestlapack.DlarftTest(t, impl)\n}\n\nfunc TestDlarfx(t *testing.T) {\n\ttestlapack.DlarfxTest(t, impl)\n}\n\nfunc TestDlartg(t *testing.T) {\n\ttestlapack.DlartgTest(t, impl)\n}\n\nfunc TestDlasq1(t *testing.T) {\n\ttestlapack.Dlasq1Test(t, impl)\n}\n\nfunc TestDlasq2(t *testing.T) {\n\ttestlapack.Dlasq2Test(t, impl)\n}\n\nfunc TestDlasq3(t *testing.T) {\n\ttestlapack.Dlasq3Test(t, impl)\n}\n\nfunc TestDlasq4(t *testing.T) {\n\ttestlapack.Dlasq4Test(t, impl)\n}\n\nfunc TestDlasq5(t *testing.T) {\n\ttestlapack.Dlasq5Test(t, impl)\n}\n\nfunc TestDlasr(t *testing.T) {\n\ttestlapack.DlasrTest(t, impl)\n}\n\nfunc TestDlasv2(t *testing.T) {\n\ttestlapack.Dlasv2Test(t, impl)\n}\n\nfunc TestDlatrd(t *testing.T) {\n\ttestlapack.DlatrdTest(t, impl)\n}\n\nfunc TestDorg2r(t *testing.T) {\n\ttestlapack.Dorg2rTest(t, impl)\n}\n\nfunc TestDorgbr(t *testing.T) {\n\ttestlapack.DorgbrTest(t, impl)\n}\n\nfunc TestDorghr(t *testing.T) {\n\ttestlapack.DorghrTest(t, impl)\n}\n\nfunc TestDorg2l(t *testing.T) {\n\ttestlapack.Dorg2lTest(t, impl)\n}\n\nfunc TestDorgl2(t *testing.T) {\n\ttestlapack.Dorgl2Test(t, impl)\n}\n\nfunc TestDorglq(t *testing.T) {\n\ttestlapack.DorglqTest(t, impl)\n}\n\nfunc TestDorgql(t *testing.T) {\n\ttestlapack.DorgqlTest(t, impl)\n}\n\nfunc TestDorgqr(t *testing.T) {\n\ttestlapack.DorgqrTest(t, impl)\n}\n\nfunc TestDorgtr(t *testing.T) {\n\ttestlapack.DorgtrTest(t, impl)\n}\n\nfunc TestDormbr(t *testing.T) {\n\ttestlapack.DormbrTest(t, impl)\n}\n\nfunc TestDormhr(t *testing.T) {\n\ttestlapack.DormhrTest(t, impl)\n}\n\nfunc TestDorml2(t *testing.T) {\n\ttestlapack.Dorml2Test(t, impl)\n}\n\nfunc TestDormlq(t *testing.T) {\n\ttestlapack.DormlqTest(t, impl)\n}\n\nfunc TestDormqr(t *testing.T) {\n\ttestlapack.DormqrTest(t, impl)\n}\n\nfunc TestDorm2r(t *testing.T) {\n\ttestlapack.Dorm2rTest(t, impl)\n}\n\nfunc TestDpocon(t *testing.T) {\n\ttestlapack.DpoconTest(t, impl)\n}\n\nfunc TestDpotf2(t *testing.T) {\n\ttestlapack.Dpotf2Test(t, impl)\n}\n\nfunc TestDpotrf(t *testing.T) {\n\ttestlapack.DpotrfTest(t, impl)\n}\n\nfunc TestDrscl(t *testing.T) {\n\ttestlapack.DrsclTest(t, impl)\n}\n\nfunc TestDsteqr(t *testing.T) {\n\ttestlapack.DsteqrTest(t, impl)\n}\n\nfunc TestDsterf(t *testing.T) {\n\ttestlapack.DsterfTest(t, impl)\n}\n\nfunc TestDsyev(t *testing.T) {\n\ttestlapack.DsyevTest(t, impl)\n}\n\nfunc TestDsytd2(t *testing.T) {\n\ttestlapack.Dsytd2Test(t, impl)\n}\n\nfunc TestDsytrd(t *testing.T) {\n\ttestlapack.DsytrdTest(t, impl)\n}\n\nfunc TestDtrcon(t *testing.T) {\n\ttestlapack.DtrconTest(t, impl)\n}\n\nfunc TestDtrexc(t *testing.T) {\n\ttestlapack.DtrexcTest(t, impl)\n}\n\nfunc TestDtrti2(t *testing.T) {\n\ttestlapack.Dtrti2Test(t, impl)\n}\n\nfunc TestDtrtri(t *testing.T) {\n\ttestlapack.DtrtriTest(t, impl)\n}\n\nfunc TestIladlc(t *testing.T) {\n\ttestlapack.IladlcTest(t, impl)\n}\n\nfunc TestIladlr(t *testing.T) {\n\ttestlapack.IladlrTest(t, impl)\n}\nnative: add test for Dlaqr2\/\/ Copyright ©2015 The gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage native\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/gonum\/lapack\/testlapack\"\n)\n\nvar impl = Implementation{}\n\nfunc TestDbdsqr(t *testing.T) {\n\ttestlapack.DbdsqrTest(t, impl)\n}\n\nfunc TestDgebd2(t *testing.T) {\n\ttestlapack.Dgebd2Test(t, impl)\n}\n\nfunc TestDgebrd(t *testing.T) {\n\ttestlapack.DgebrdTest(t, impl)\n}\n\nfunc TestDgecon(t *testing.T) {\n\ttestlapack.DgeconTest(t, impl)\n}\n\nfunc TestDgehd2(t *testing.T) {\n\ttestlapack.Dgehd2Test(t, impl)\n}\n\nfunc TestDgehrd(t *testing.T) {\n\ttestlapack.DgehrdTest(t, impl)\n}\n\nfunc TestDgelqf(t *testing.T) {\n\ttestlapack.DgelqfTest(t, impl)\n}\n\nfunc TestDgelq2(t *testing.T) {\n\ttestlapack.Dgelq2Test(t, impl)\n}\n\nfunc TestDgeql2(t *testing.T) {\n\ttestlapack.Dgeql2Test(t, impl)\n}\n\nfunc TestDgels(t *testing.T) {\n\ttestlapack.DgelsTest(t, impl)\n}\n\nfunc TestDgeqr2(t *testing.T) {\n\ttestlapack.Dgeqr2Test(t, impl)\n}\n\nfunc TestDgeqrf(t *testing.T) {\n\ttestlapack.DgeqrfTest(t, impl)\n}\n\nfunc TestDgesvd(t *testing.T) {\n\ttestlapack.DgesvdTest(t, impl)\n}\n\nfunc TestDgetri(t *testing.T) {\n\ttestlapack.DgetriTest(t, impl)\n}\n\nfunc TestDgetf2(t *testing.T) {\n\ttestlapack.Dgetf2Test(t, impl)\n}\n\nfunc TestDgetrf(t *testing.T) {\n\ttestlapack.DgetrfTest(t, impl)\n}\n\nfunc TestDgetrs(t *testing.T) {\n\ttestlapack.DgetrsTest(t, impl)\n}\n\nfunc TestDlabrd(t *testing.T) {\n\ttestlapack.DlabrdTest(t, impl)\n}\n\nfunc TestDlacpy(t *testing.T) {\n\ttestlapack.DlacpyTest(t, impl)\n}\n\nfunc TestDlae2(t *testing.T) {\n\ttestlapack.Dlae2Test(t, impl)\n}\n\nfunc TestDlaev2(t *testing.T) {\n\ttestlapack.Dlaev2Test(t, impl)\n}\n\nfunc TestDlaexc(t *testing.T) {\n\ttestlapack.DlaexcTest(t, impl)\n}\n\nfunc TestDlahqr(t *testing.T) {\n\ttestlapack.DlahqrTest(t, impl)\n}\n\nfunc TestDlahr2(t *testing.T) {\n\ttestlapack.Dlahr2Test(t, impl)\n}\n\nfunc TestDlaln2(t *testing.T) {\n\ttestlapack.Dlaln2Test(t, impl)\n}\n\nfunc TestDlange(t *testing.T) {\n\ttestlapack.DlangeTest(t, impl)\n}\n\nfunc TestDlas2(t *testing.T) {\n\ttestlapack.Dlas2Test(t, impl)\n}\n\nfunc TestDlasy2(t *testing.T) {\n\ttestlapack.Dlasy2Test(t, impl)\n}\n\nfunc TestDlanst(t *testing.T) {\n\ttestlapack.DlanstTest(t, impl)\n}\n\nfunc TestDlansy(t *testing.T) {\n\ttestlapack.DlansyTest(t, impl)\n}\n\nfunc TestDlantr(t *testing.T) {\n\ttestlapack.DlantrTest(t, impl)\n}\n\nfunc TestDlanv2(t *testing.T) {\n\ttestlapack.Dlanv2Test(t, impl)\n}\n\nfunc TestDlaqr1(t *testing.T) {\n\ttestlapack.Dlaqr1Test(t, impl)\n}\n\nfunc TestDlaqr2(t *testing.T) {\n\ttestlapack.Dlaqr2Test(t, impl)\n}\n\nfunc TestDlaqr5(t *testing.T) {\n\ttestlapack.Dlaqr5Test(t, impl)\n}\n\nfunc TestDlarf(t *testing.T) {\n\ttestlapack.DlarfTest(t, impl)\n}\n\nfunc TestDlarfb(t *testing.T) {\n\ttestlapack.DlarfbTest(t, impl)\n}\n\nfunc TestDlarfg(t *testing.T) {\n\ttestlapack.DlarfgTest(t, impl)\n}\n\nfunc TestDlarft(t *testing.T) {\n\ttestlapack.DlarftTest(t, impl)\n}\n\nfunc TestDlarfx(t *testing.T) {\n\ttestlapack.DlarfxTest(t, impl)\n}\n\nfunc TestDlartg(t *testing.T) {\n\ttestlapack.DlartgTest(t, impl)\n}\n\nfunc TestDlasq1(t *testing.T) {\n\ttestlapack.Dlasq1Test(t, impl)\n}\n\nfunc TestDlasq2(t *testing.T) {\n\ttestlapack.Dlasq2Test(t, impl)\n}\n\nfunc TestDlasq3(t *testing.T) {\n\ttestlapack.Dlasq3Test(t, impl)\n}\n\nfunc TestDlasq4(t *testing.T) {\n\ttestlapack.Dlasq4Test(t, impl)\n}\n\nfunc TestDlasq5(t *testing.T) {\n\ttestlapack.Dlasq5Test(t, impl)\n}\n\nfunc TestDlasr(t *testing.T) {\n\ttestlapack.DlasrTest(t, impl)\n}\n\nfunc TestDlasv2(t *testing.T) {\n\ttestlapack.Dlasv2Test(t, impl)\n}\n\nfunc TestDlatrd(t *testing.T) {\n\ttestlapack.DlatrdTest(t, impl)\n}\n\nfunc TestDorg2r(t *testing.T) {\n\ttestlapack.Dorg2rTest(t, impl)\n}\n\nfunc TestDorgbr(t *testing.T) {\n\ttestlapack.DorgbrTest(t, impl)\n}\n\nfunc TestDorghr(t *testing.T) {\n\ttestlapack.DorghrTest(t, impl)\n}\n\nfunc TestDorg2l(t *testing.T) {\n\ttestlapack.Dorg2lTest(t, impl)\n}\n\nfunc TestDorgl2(t *testing.T) {\n\ttestlapack.Dorgl2Test(t, impl)\n}\n\nfunc TestDorglq(t *testing.T) {\n\ttestlapack.DorglqTest(t, impl)\n}\n\nfunc TestDorgql(t *testing.T) {\n\ttestlapack.DorgqlTest(t, impl)\n}\n\nfunc TestDorgqr(t *testing.T) {\n\ttestlapack.DorgqrTest(t, impl)\n}\n\nfunc TestDorgtr(t *testing.T) {\n\ttestlapack.DorgtrTest(t, impl)\n}\n\nfunc TestDormbr(t *testing.T) {\n\ttestlapack.DormbrTest(t, impl)\n}\n\nfunc TestDormhr(t *testing.T) {\n\ttestlapack.DormhrTest(t, impl)\n}\n\nfunc TestDorml2(t *testing.T) {\n\ttestlapack.Dorml2Test(t, impl)\n}\n\nfunc TestDormlq(t *testing.T) {\n\ttestlapack.DormlqTest(t, impl)\n}\n\nfunc TestDormqr(t *testing.T) {\n\ttestlapack.DormqrTest(t, impl)\n}\n\nfunc TestDorm2r(t *testing.T) {\n\ttestlapack.Dorm2rTest(t, impl)\n}\n\nfunc TestDpocon(t *testing.T) {\n\ttestlapack.DpoconTest(t, impl)\n}\n\nfunc TestDpotf2(t *testing.T) {\n\ttestlapack.Dpotf2Test(t, impl)\n}\n\nfunc TestDpotrf(t *testing.T) {\n\ttestlapack.DpotrfTest(t, impl)\n}\n\nfunc TestDrscl(t *testing.T) {\n\ttestlapack.DrsclTest(t, impl)\n}\n\nfunc TestDsteqr(t *testing.T) {\n\ttestlapack.DsteqrTest(t, impl)\n}\n\nfunc TestDsterf(t *testing.T) {\n\ttestlapack.DsterfTest(t, impl)\n}\n\nfunc TestDsyev(t *testing.T) {\n\ttestlapack.DsyevTest(t, impl)\n}\n\nfunc TestDsytd2(t *testing.T) {\n\ttestlapack.Dsytd2Test(t, impl)\n}\n\nfunc TestDsytrd(t *testing.T) {\n\ttestlapack.DsytrdTest(t, impl)\n}\n\nfunc TestDtrcon(t *testing.T) {\n\ttestlapack.DtrconTest(t, impl)\n}\n\nfunc TestDtrexc(t *testing.T) {\n\ttestlapack.DtrexcTest(t, impl)\n}\n\nfunc TestDtrti2(t *testing.T) {\n\ttestlapack.Dtrti2Test(t, impl)\n}\n\nfunc TestDtrtri(t *testing.T) {\n\ttestlapack.DtrtriTest(t, impl)\n}\n\nfunc TestIladlc(t *testing.T) {\n\ttestlapack.IladlcTest(t, impl)\n}\n\nfunc TestIladlr(t *testing.T) {\n\ttestlapack.IladlrTest(t, impl)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/backend\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/server\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nconst (\n\tmaxPacketAge = 10\n)\n\nfunc openSock(path string) (net.Listener, error) {\n\tif err := syscall.Unlink(path); err != nil && err != syscall.EEXIST {\n\t\treturn nil, err\n\t}\n\tln, err := net.Listen(\"unix\", socket)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := syscall.Chmod(path, 0770); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ln, nil\n}\n\nfunc main() {\n\tif len(os.Args)%3 != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: seclab key [dest open closed [..]]\\n\")\n\t\treturn\n\t}\n\tkeypath := os.Args[1]\n\ts := server.New(keypath, maxPacketAge)\n\n\tfor i := 2; i+2 < len(os.Args); i += 3 {\n\t\tdest := os.Args[i]\n\t\topenfile := os.Args[i+1]\n\t\tclosedfile := os.Args[i+2]\n\t\ts.AddBackend(backend.New(dest, openfile, closedfile))\n\t}\n\n\tsyscall.Umask(0007)\n\n\tsocket := \"seclab.sock\"\n\tln, err := openSock(socket)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\t\/\/ Make sure the socket closes\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tln.Close()\n\t\t}\n\t}()\n\n\ts.Serve(ln)\n}\nFix typopackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/backend\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/server\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nconst (\n\tmaxPacketAge = 10\n)\n\nfunc openSock(path string) (net.Listener, error) {\n\tif err := syscall.Unlink(path); err != nil && err != syscall.EEXIST {\n\t\treturn nil, err\n\t}\n\tln, err := net.Listen(\"unix\", path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := syscall.Chmod(path, 0770); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ln, nil\n}\n\nfunc main() {\n\tif len(os.Args)%3 != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: seclab key [dest open closed [..]]\\n\")\n\t\treturn\n\t}\n\tkeypath := os.Args[1]\n\ts := server.New(keypath, maxPacketAge)\n\n\tfor i := 2; i+2 < len(os.Args); i += 3 {\n\t\tdest := os.Args[i]\n\t\topenfile := os.Args[i+1]\n\t\tclosedfile := os.Args[i+2]\n\t\ts.AddBackend(backend.New(dest, openfile, closedfile))\n\t}\n\n\tsyscall.Umask(0007)\n\n\tsocket := \"seclab.sock\"\n\tln, err := openSock(socket)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\t\/\/ Make sure the socket closes\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tln.Close()\n\t\t}\n\t}()\n\n\ts.Serve(ln)\n}\n<|endoftext|>"} {"text":"package psql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/lib\/pq\"\n)\n\n\/\/ Select creates a new SelectQuery using the expressions exprs to populate\n\/\/ the SELECT list, that is the portion of the query between the key words\n\/\/ \"SELECT\" and \"FROM\".\nfunc Select(exprs ...Expression) SelectQuery {\n\treturn SelectQuery{\n\t\tsel: selectClause{exprs},\n\t\tparams: newParams(),\n\t}\n}\n\n\/\/ A SelectQuery represents a SELECT query with all its clauses.\ntype SelectQuery struct {\n\tsel selectClause\n\torderBy orderByClause\n\tgroupBy groupByClause\n\n\tparams *Params\n}\n\n\/\/ OrderBy returns a copy of the SelectQuery s with an additional ORDER BY\n\/\/ clause containing the order expressions provided. If an ORDER BY clause\n\/\/ was already present, this operation will overwrite it.\nfunc (s SelectQuery) OrderBy(exprs ...OrderExpression) SelectQuery {\n\ts.orderBy = orderByClause{exprs}\n\treturn s\n}\n\n\/\/ GroupBy returns a copy of the SelectQuery s with an additional GROUP BY\n\/\/ clause containing the Expressions provided. If a GROUP BY clause was\n\/\/ already present, this operation will overwrite it.\nfunc (s SelectQuery) GroupBy(exprs ...Expression) SelectQuery {\n\ts.groupBy = groupByClause{exprs}\n\treturn s\n}\n\n\/\/ ToSQL returns a string containing the full SQL query version of the\n\/\/ SelectQuery. If the query is empty, an empty string is returned.\nfunc (s SelectQuery) ToSQL() string {\n\tvar parts []string\n\n\tfor _, clause := range s.clauses() {\n\t\tif part := clause.ToSQLClause(s.params); part != \"\" {\n\t\t\tparts = append(parts, part)\n\t\t}\n\t}\n\n\tif len(parts) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n\nfunc (s SelectQuery) clauses() []Clause {\n\treturn []Clause{\n\t\ts.sel,\n\t\ts.from(),\n\t\ts.groupBy,\n\t\ts.orderBy,\n\t}\n}\n\nfunc (s SelectQuery) from() Clause {\n\trels := make([]string, 0)\n\tset := make(map[string]struct{})\n\n\tfor _, rel := range s.relations() {\n\t\t\/\/ Have we seen this relation before?\n\t\tif _, ok := set[rel]; !ok {\n\t\t\tset[rel] = struct{}{}\n\t\t\trels = append(rels, rel)\n\t\t}\n\t}\n\n\treturn fromClause{rels}\n}\n\nfunc (s SelectQuery) relations() []string {\n\tvar rels []string\n\trels = append(rels, s.sel.Relations()...)\n\trels = append(rels, s.groupBy.Relations()...)\n\trels = append(rels, s.orderBy.Relations()...)\n\treturn rels\n}\n\n\/\/ Bindings returns a slice of arguments that can be unpacked and passed\n\/\/ into the Query and QueryRow methods of the database\/sql package.\n\/\/\n\/\/ Any variadic arguments passed into Bindings will be used to replace\n\/\/ user-supplied parameters in the SELECT query, in the same order as\n\/\/ they appear in the query.\nfunc (s SelectQuery) Bindings(inputs ...interface{}) []interface{} {\n\treturn s.params.Values(inputs)\n}\n\n\/\/ Clause is the interface that represents the individual components of\n\/\/ an SQL query.\n\/\/\n\/\/ ToSQLClause converts the clause to a string representation. If an empty\n\/\/ string is returned, the clause will be omitted from the final SQL query.\ntype Clause interface {\n\tToSQLClause(p *Params) string\n}\n\ntype selectClause struct {\n\texprs []Expression\n}\n\nfunc (s selectClause) ToSQLClause(p *Params) string {\n\tif len(s.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\targs := make([]string, len(s.exprs))\n\tfor i, expr := range s.exprs {\n\t\targs[i] = expr.ToSQLExpr(p)\n\t}\n\n\treturn fmt.Sprintf(\"SELECT %s\", strings.Join(args, \", \"))\n}\n\nfunc (s selectClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range s.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\ntype fromClause struct {\n\trels []string\n}\n\nfunc (f fromClause) ToSQLClause(*Params) string {\n\tif len(f.rels) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"FROM %s\", strings.Join(f.rels, \", \"))\n}\n\ntype groupByClause struct {\n\texprs []Expression\n}\n\nfunc (g groupByClause) ToSQLClause(p *Params) string {\n\tif len(g.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\tparts := make([]string, len(g.exprs))\n\tfor i, expr := range g.exprs {\n\t\tparts[i] = expr.ToSQLExpr(p)\n\t}\n\n\treturn fmt.Sprintf(\"GROUP BY %s\", strings.Join(parts, \", \"))\n}\n\nfunc (g groupByClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range g.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\ntype orderByClause struct {\n\texprs []OrderExpression\n}\n\nfunc (o orderByClause) ToSQLClause(p *Params) string {\n\tif len(o.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\tparts := make([]string, len(o.exprs))\n\tfor i, expr := range o.exprs {\n\t\tparts[i] = expr.ToSQLOrder(p)\n\t}\n\n\treturn fmt.Sprintf(\"ORDER BY %s\", strings.Join(parts, \", \"))\n}\n\nfunc (o orderByClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range o.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\n\/\/ Ascending returns a new OrderExpression specifying that the results\n\/\/ of the query must be ordered by the given Expression in ascending order.\nfunc Ascending(expr Expression) OrderExpression {\n\treturn OrderExpression{expr, asc}\n}\n\n\/\/ Descending returns a new OrderExpression specifying that the results\n\/\/ of the query must be ordered by the given Expression in descending order.\nfunc Descending(expr Expression) OrderExpression {\n\treturn OrderExpression{expr, desc}\n}\n\ntype orderDirection string\n\nconst (\n\tasc orderDirection = \"ASC\"\n\tdesc = \"DESC\"\n)\n\n\/\/ An OrderExpression is each individual component of a SELECT query's\n\/\/ ORDER BY clause, specifying that the results of the query must be\n\/\/ sorted by a given SQL expression.\ntype OrderExpression struct {\n\texpr Expression\n\tdirection orderDirection\n}\n\nfunc (o OrderExpression) ToSQLOrder(p *Params) string {\n\treturn fmt.Sprintf(\"%s %s\", o.expr.ToSQLExpr(p), o.direction)\n}\n\nfunc (o OrderExpression) Relations() []string {\n\treturn o.expr.Relations()\n}\n\n\/\/ Expression is the interface that represents any SQL expression that\n\/\/ can be used in the SELECT list of an SQL query.\n\/\/\n\/\/ ToSQLExpr converts the expression into a snippet of SQL that may be\n\/\/ safely embedded in a query. If the expression needs to be quoted or\n\/\/ otherwise escaped, ToSQLExpr must return the quoted version.\n\/\/\n\/\/ Relations returns a slice of strings corresponding to the (quoted)\n\/\/ names of all relations used by the Expression.\ntype Expression interface {\n\tToSQLExpr(*Params) string\n\tRelations() []string\n}\n\n\/\/ AllColumns returns an Expression representing all columns in the table.\nfunc AllColumns(table string) allColumns {\n\treturn allColumns{table}\n}\n\ntype allColumns struct {\n\ttable string\n}\n\nfunc (ac allColumns) ToSQLExpr(*Params) string {\n\treturn fmt.Sprintf(\"%s.*\", pq.QuoteIdentifier(ac.table))\n}\n\nfunc (ac allColumns) Relations() []string {\n\treturn []string{\n\t\tpq.QuoteIdentifier(ac.table),\n\t}\n}\n\n\/\/ TableColumn returns an Expression representing the column col of the\n\/\/ database table with the given name.\nfunc TableColumn(table, col string) tableColumn {\n\treturn tableColumn{table, col}\n}\n\ntype tableColumn struct {\n\ttable, column string\n}\n\nfunc (tc tableColumn) ToSQLExpr(*Params) string {\n\treturn pq.QuoteIdentifier(tc.column)\n}\n\nfunc (tc tableColumn) Relations() []string {\n\treturn []string{\n\t\tpq.QuoteIdentifier(tc.table),\n\t}\n}\n\nfunc newParams() *Params {\n\treturn &Params{\n\t\tvalues: make(map[int]interface{}),\n\t}\n}\n\ntype Params struct {\n\tcounter int\n\tvalues map[int]interface{}\n}\n\nfunc (p *Params) Add(value interface{}) string {\n\tmarker := p.next()\n\tp.values[p.counter] = value\n\treturn marker\n}\n\nfunc (p *Params) New() string {\n\treturn p.next()\n}\n\nfunc (p *Params) next() string {\n\tp.counter++\n\treturn fmt.Sprintf(\"$%d\", p.counter)\n}\n\nfunc (p *Params) Values(inputs []interface{}) []interface{} {\n\tvar values []interface{}\n\n\tfor i := 1; i <= p.counter; i++ {\n\t\tif val, ok := p.values[i]; ok {\n\t\t\tvalues = append(values, val)\n\t\t} else if len(inputs) > 0 {\n\t\t\tvalues = append(values, inputs[0])\n\t\t\tinputs = inputs[1:]\n\t\t}\n\t}\n\n\treturn values\n}\n\n\/\/ StringLiteral returns a text literal that will be replaced with str\n\/\/ when the query is executed. For security reasons, the contents of str\n\/\/ are not directly interpolated into the query's SQL representation.\n\/\/ Instead, a marker such as $1 is used, and the value of str is injected\n\/\/ into the appropriate position when the Bindings() method is called.\nfunc StringLiteral(str string) stringLiteral {\n\treturn stringLiteral(str)\n}\n\ntype stringLiteral string\n\nfunc (s stringLiteral) ToSQLExpr(params *Params) string {\n\tmarker := params.Add(string(s))\n\treturn fmt.Sprintf(\"%s::%s\", marker, TextDataType)\n}\n\nfunc (stringLiteral) Relations() []string {\n\treturn nil\n}\n\ntype DataType string\n\nconst (\n\tTextDataType DataType = \"text\"\n)\n\n\/\/ StringParam returns a free (unbound) parameter using the \"text\" type.\nfunc StringParam() freeParam {\n\treturn freeParam{TextDataType}\n}\n\ntype freeParam struct {\n\tType DataType\n}\n\nfunc (p freeParam) ToSQLExpr(params *Params) string {\n\treturn fmt.Sprintf(\"%s::%s\", params.New(), p.Type)\n}\n\nfunc (p freeParam) Relations() []string {\n\treturn nil\n}\nRename DataType to dataType since we don't need to export itpackage psql\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/lib\/pq\"\n)\n\n\/\/ Select creates a new SelectQuery using the expressions exprs to populate\n\/\/ the SELECT list, that is the portion of the query between the key words\n\/\/ \"SELECT\" and \"FROM\".\nfunc Select(exprs ...Expression) SelectQuery {\n\treturn SelectQuery{\n\t\tsel: selectClause{exprs},\n\t\tparams: newParams(),\n\t}\n}\n\n\/\/ A SelectQuery represents a SELECT query with all its clauses.\ntype SelectQuery struct {\n\tsel selectClause\n\torderBy orderByClause\n\tgroupBy groupByClause\n\n\tparams *Params\n}\n\n\/\/ OrderBy returns a copy of the SelectQuery s with an additional ORDER BY\n\/\/ clause containing the order expressions provided. If an ORDER BY clause\n\/\/ was already present, this operation will overwrite it.\nfunc (s SelectQuery) OrderBy(exprs ...OrderExpression) SelectQuery {\n\ts.orderBy = orderByClause{exprs}\n\treturn s\n}\n\n\/\/ GroupBy returns a copy of the SelectQuery s with an additional GROUP BY\n\/\/ clause containing the Expressions provided. If a GROUP BY clause was\n\/\/ already present, this operation will overwrite it.\nfunc (s SelectQuery) GroupBy(exprs ...Expression) SelectQuery {\n\ts.groupBy = groupByClause{exprs}\n\treturn s\n}\n\n\/\/ ToSQL returns a string containing the full SQL query version of the\n\/\/ SelectQuery. If the query is empty, an empty string is returned.\nfunc (s SelectQuery) ToSQL() string {\n\tvar parts []string\n\n\tfor _, clause := range s.clauses() {\n\t\tif part := clause.ToSQLClause(s.params); part != \"\" {\n\t\t\tparts = append(parts, part)\n\t\t}\n\t}\n\n\tif len(parts) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn strings.Join(parts, \" \")\n}\n\nfunc (s SelectQuery) clauses() []Clause {\n\treturn []Clause{\n\t\ts.sel,\n\t\ts.from(),\n\t\ts.groupBy,\n\t\ts.orderBy,\n\t}\n}\n\nfunc (s SelectQuery) from() Clause {\n\trels := make([]string, 0)\n\tset := make(map[string]struct{})\n\n\tfor _, rel := range s.relations() {\n\t\t\/\/ Have we seen this relation before?\n\t\tif _, ok := set[rel]; !ok {\n\t\t\tset[rel] = struct{}{}\n\t\t\trels = append(rels, rel)\n\t\t}\n\t}\n\n\treturn fromClause{rels}\n}\n\nfunc (s SelectQuery) relations() []string {\n\tvar rels []string\n\trels = append(rels, s.sel.Relations()...)\n\trels = append(rels, s.groupBy.Relations()...)\n\trels = append(rels, s.orderBy.Relations()...)\n\treturn rels\n}\n\n\/\/ Bindings returns a slice of arguments that can be unpacked and passed\n\/\/ into the Query and QueryRow methods of the database\/sql package.\n\/\/\n\/\/ Any variadic arguments passed into Bindings will be used to replace\n\/\/ user-supplied parameters in the SELECT query, in the same order as\n\/\/ they appear in the query.\nfunc (s SelectQuery) Bindings(inputs ...interface{}) []interface{} {\n\treturn s.params.Values(inputs)\n}\n\n\/\/ Clause is the interface that represents the individual components of\n\/\/ an SQL query.\n\/\/\n\/\/ ToSQLClause converts the clause to a string representation. If an empty\n\/\/ string is returned, the clause will be omitted from the final SQL query.\ntype Clause interface {\n\tToSQLClause(p *Params) string\n}\n\ntype selectClause struct {\n\texprs []Expression\n}\n\nfunc (s selectClause) ToSQLClause(p *Params) string {\n\tif len(s.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\targs := make([]string, len(s.exprs))\n\tfor i, expr := range s.exprs {\n\t\targs[i] = expr.ToSQLExpr(p)\n\t}\n\n\treturn fmt.Sprintf(\"SELECT %s\", strings.Join(args, \", \"))\n}\n\nfunc (s selectClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range s.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\ntype fromClause struct {\n\trels []string\n}\n\nfunc (f fromClause) ToSQLClause(*Params) string {\n\tif len(f.rels) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"FROM %s\", strings.Join(f.rels, \", \"))\n}\n\ntype groupByClause struct {\n\texprs []Expression\n}\n\nfunc (g groupByClause) ToSQLClause(p *Params) string {\n\tif len(g.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\tparts := make([]string, len(g.exprs))\n\tfor i, expr := range g.exprs {\n\t\tparts[i] = expr.ToSQLExpr(p)\n\t}\n\n\treturn fmt.Sprintf(\"GROUP BY %s\", strings.Join(parts, \", \"))\n}\n\nfunc (g groupByClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range g.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\ntype orderByClause struct {\n\texprs []OrderExpression\n}\n\nfunc (o orderByClause) ToSQLClause(p *Params) string {\n\tif len(o.exprs) == 0 {\n\t\treturn \"\"\n\t}\n\n\tparts := make([]string, len(o.exprs))\n\tfor i, expr := range o.exprs {\n\t\tparts[i] = expr.ToSQLOrder(p)\n\t}\n\n\treturn fmt.Sprintf(\"ORDER BY %s\", strings.Join(parts, \", \"))\n}\n\nfunc (o orderByClause) Relations() []string {\n\tvar rels []string\n\tfor _, expr := range o.exprs {\n\t\trels = append(rels, expr.Relations()...)\n\t}\n\treturn rels\n}\n\n\/\/ Ascending returns a new OrderExpression specifying that the results\n\/\/ of the query must be ordered by the given Expression in ascending order.\nfunc Ascending(expr Expression) OrderExpression {\n\treturn OrderExpression{expr, asc}\n}\n\n\/\/ Descending returns a new OrderExpression specifying that the results\n\/\/ of the query must be ordered by the given Expression in descending order.\nfunc Descending(expr Expression) OrderExpression {\n\treturn OrderExpression{expr, desc}\n}\n\ntype orderDirection string\n\nconst (\n\tasc orderDirection = \"ASC\"\n\tdesc = \"DESC\"\n)\n\n\/\/ An OrderExpression is each individual component of a SELECT query's\n\/\/ ORDER BY clause, specifying that the results of the query must be\n\/\/ sorted by a given SQL expression.\ntype OrderExpression struct {\n\texpr Expression\n\tdirection orderDirection\n}\n\nfunc (o OrderExpression) ToSQLOrder(p *Params) string {\n\treturn fmt.Sprintf(\"%s %s\", o.expr.ToSQLExpr(p), o.direction)\n}\n\nfunc (o OrderExpression) Relations() []string {\n\treturn o.expr.Relations()\n}\n\n\/\/ Expression is the interface that represents any SQL expression that\n\/\/ can be used in the SELECT list of an SQL query.\n\/\/\n\/\/ ToSQLExpr converts the expression into a snippet of SQL that may be\n\/\/ safely embedded in a query. If the expression needs to be quoted or\n\/\/ otherwise escaped, ToSQLExpr must return the quoted version.\n\/\/\n\/\/ Relations returns a slice of strings corresponding to the (quoted)\n\/\/ names of all relations used by the Expression.\ntype Expression interface {\n\tToSQLExpr(*Params) string\n\tRelations() []string\n}\n\n\/\/ AllColumns returns an Expression representing all columns in the table.\nfunc AllColumns(table string) allColumns {\n\treturn allColumns{table}\n}\n\ntype allColumns struct {\n\ttable string\n}\n\nfunc (ac allColumns) ToSQLExpr(*Params) string {\n\treturn fmt.Sprintf(\"%s.*\", pq.QuoteIdentifier(ac.table))\n}\n\nfunc (ac allColumns) Relations() []string {\n\treturn []string{\n\t\tpq.QuoteIdentifier(ac.table),\n\t}\n}\n\n\/\/ TableColumn returns an Expression representing the column col of the\n\/\/ database table with the given name.\nfunc TableColumn(table, col string) tableColumn {\n\treturn tableColumn{table, col}\n}\n\ntype tableColumn struct {\n\ttable, column string\n}\n\nfunc (tc tableColumn) ToSQLExpr(*Params) string {\n\treturn pq.QuoteIdentifier(tc.column)\n}\n\nfunc (tc tableColumn) Relations() []string {\n\treturn []string{\n\t\tpq.QuoteIdentifier(tc.table),\n\t}\n}\n\nfunc newParams() *Params {\n\treturn &Params{\n\t\tvalues: make(map[int]interface{}),\n\t}\n}\n\ntype Params struct {\n\tcounter int\n\tvalues map[int]interface{}\n}\n\nfunc (p *Params) Add(value interface{}) string {\n\tmarker := p.next()\n\tp.values[p.counter] = value\n\treturn marker\n}\n\nfunc (p *Params) New() string {\n\treturn p.next()\n}\n\nfunc (p *Params) next() string {\n\tp.counter++\n\treturn fmt.Sprintf(\"$%d\", p.counter)\n}\n\nfunc (p *Params) Values(inputs []interface{}) []interface{} {\n\tvar values []interface{}\n\n\tfor i := 1; i <= p.counter; i++ {\n\t\tif val, ok := p.values[i]; ok {\n\t\t\tvalues = append(values, val)\n\t\t} else if len(inputs) > 0 {\n\t\t\tvalues = append(values, inputs[0])\n\t\t\tinputs = inputs[1:]\n\t\t}\n\t}\n\n\treturn values\n}\n\n\/\/ StringLiteral returns a text literal that will be replaced with str\n\/\/ when the query is executed. For security reasons, the contents of str\n\/\/ are not directly interpolated into the query's SQL representation.\n\/\/ Instead, a marker such as $1 is used, and the value of str is injected\n\/\/ into the appropriate position when the Bindings() method is called.\nfunc StringLiteral(str string) stringLiteral {\n\treturn stringLiteral(str)\n}\n\ntype stringLiteral string\n\nfunc (s stringLiteral) ToSQLExpr(params *Params) string {\n\tmarker := params.Add(string(s))\n\treturn fmt.Sprintf(\"%s::%s\", marker, textType)\n}\n\nfunc (stringLiteral) Relations() []string {\n\treturn nil\n}\n\ntype dataType string\n\nconst (\n\ttextType dataType = \"text\"\n)\n\n\/\/ StringParam returns a free (unbound) parameter using the \"text\" type.\nfunc StringParam() freeParam {\n\treturn freeParam{textType}\n}\n\ntype freeParam struct {\n\tdataType dataType\n}\n\nfunc (p freeParam) ToSQLExpr(params *Params) string {\n\treturn fmt.Sprintf(\"%s::%s\", params.New(), p.dataType)\n}\n\nfunc (p freeParam) Relations() []string {\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright © 2017 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage lorawan\n\nimport (\n\t\"github.com\/TheThingsNetwork\/ttn\/api\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/types\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n)\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *DeviceIdentifier) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil || m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Device) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil || m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\tif err := api.NotEmptyAndValidID(m.AppId, \"AppId\"); err != nil {\n\t\treturn err\n\t}\n\tif err := api.NotEmptyAndValidID(m.DevId, \"DevId\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Metadata) Validate() error {\n\tswitch m.Modulation {\n\tcase Modulation_LORA:\n\t\tif m.DataRate == \"\" {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", \"can not be empty\")\n\t\t}\n\t\tif _, err := types.ParseDataRate(m.DataRate); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", err.Error())\n\t\t}\n\tcase Modulation_FSK:\n\t\tif m.BitRate == 0 {\n\t\t\treturn errors.NewErrInvalidArgument(\"BitRate\", \"can not be empty\")\n\t\t}\n\t}\n\tif m.CodingRate == \"\" {\n\t\treturn errors.NewErrInvalidArgument(\"CodingRate\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *TxConfiguration) Validate() error {\n\tswitch m.Modulation {\n\tcase Modulation_LORA:\n\t\tif m.DataRate == \"\" {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", \"can not be empty\")\n\t\t}\n\t\tif _, err := types.ParseDataRate(m.DataRate); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", err.Error())\n\t\t}\n\tcase Modulation_FSK:\n\t\tif m.BitRate == 0 {\n\t\t\treturn errors.NewErrInvalidArgument(\"BitRate\", \"can not be empty\")\n\t\t}\n\t}\n\tif m.CodingRate == \"\" {\n\t\treturn errors.NewErrInvalidArgument(\"CodingRate\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *ActivationMetadata) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil || m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\tif m.DevAddr != nil && m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\tif m.NwkSKey != nil && m.NwkSKey.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"NwkSKey\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Message) Validate() error {\n\tif m.Major != Major_LORAWAN_R1 {\n\t\treturn errors.NewErrInvalidArgument(\"Major\", \"invalid value \"+m.Major.String())\n\t}\n\tswitch m.MType {\n\tcase MType_JOIN_REQUEST:\n\t\tif m.GetJoinRequestPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinRequestPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetJoinRequestPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinRequestPayload\", err.Error())\n\t\t}\n\tcase MType_JOIN_ACCEPT:\n\t\tif m.GetJoinAcceptPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinAcceptPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetJoinAcceptPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinAcceptPayload\", err.Error())\n\t\t}\n\tcase MType_UNCONFIRMED_UP, MType_UNCONFIRMED_DOWN, MType_CONFIRMED_UP, MType_CONFIRMED_DOWN:\n\t\tif m.GetMacPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"MacPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetMacPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"MacPayload\", err.Error())\n\t\t}\n\tdefault:\n\t\treturn errors.NewErrInvalidArgument(\"MType\", \"unknown type \"+m.MType.String())\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *JoinRequestPayload) Validate() error {\n\tif m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *JoinAcceptPayload) Validate() error {\n\tif len(m.Encrypted) != 0 {\n\t\treturn nil\n\t}\n\n\tif m.CfList != nil && len(m.CfList.Freq) != 5 {\n\t\treturn errors.NewErrInvalidArgument(\"CfList.Freq\", \"length must be 5\")\n\t}\n\n\tif m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\tif m.NetId.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"NetId\", \"can not be empty\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *MACPayload) Validate() error {\n\tif m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\treturn nil\n}\nUpdate validation to allow on-join device registration\/\/ Copyright © 2017 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage lorawan\n\nimport (\n\t\"github.com\/TheThingsNetwork\/ttn\/api\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/types\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n)\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *DeviceIdentifier) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Device) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\tif err := api.NotEmptyAndValidID(m.AppId, \"AppId\"); err != nil {\n\t\treturn err\n\t}\n\tif err := api.NotEmptyAndValidID(m.DevId, \"DevId\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Metadata) Validate() error {\n\tswitch m.Modulation {\n\tcase Modulation_LORA:\n\t\tif m.DataRate == \"\" {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", \"can not be empty\")\n\t\t}\n\t\tif _, err := types.ParseDataRate(m.DataRate); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", err.Error())\n\t\t}\n\tcase Modulation_FSK:\n\t\tif m.BitRate == 0 {\n\t\t\treturn errors.NewErrInvalidArgument(\"BitRate\", \"can not be empty\")\n\t\t}\n\t}\n\tif m.CodingRate == \"\" {\n\t\treturn errors.NewErrInvalidArgument(\"CodingRate\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *TxConfiguration) Validate() error {\n\tswitch m.Modulation {\n\tcase Modulation_LORA:\n\t\tif m.DataRate == \"\" {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", \"can not be empty\")\n\t\t}\n\t\tif _, err := types.ParseDataRate(m.DataRate); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"DataRate\", err.Error())\n\t\t}\n\tcase Modulation_FSK:\n\t\tif m.BitRate == 0 {\n\t\t\treturn errors.NewErrInvalidArgument(\"BitRate\", \"can not be empty\")\n\t\t}\n\t}\n\tif m.CodingRate == \"\" {\n\t\treturn errors.NewErrInvalidArgument(\"CodingRate\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *ActivationMetadata) Validate() error {\n\tif m.AppEui == nil || m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui == nil || m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\tif m.DevAddr != nil && m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\tif m.NwkSKey != nil && m.NwkSKey.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"NwkSKey\", \"can not be empty\")\n\t}\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *Message) Validate() error {\n\tif m.Major != Major_LORAWAN_R1 {\n\t\treturn errors.NewErrInvalidArgument(\"Major\", \"invalid value \"+m.Major.String())\n\t}\n\tswitch m.MType {\n\tcase MType_JOIN_REQUEST:\n\t\tif m.GetJoinRequestPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinRequestPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetJoinRequestPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinRequestPayload\", err.Error())\n\t\t}\n\tcase MType_JOIN_ACCEPT:\n\t\tif m.GetJoinAcceptPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinAcceptPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetJoinAcceptPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"JoinAcceptPayload\", err.Error())\n\t\t}\n\tcase MType_UNCONFIRMED_UP, MType_UNCONFIRMED_DOWN, MType_CONFIRMED_UP, MType_CONFIRMED_DOWN:\n\t\tif m.GetMacPayload() == nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"MacPayload\", \"can not be empty\")\n\t\t}\n\t\tif err := m.GetMacPayload().Validate(); err != nil {\n\t\t\treturn errors.NewErrInvalidArgument(\"MacPayload\", err.Error())\n\t\t}\n\tdefault:\n\t\treturn errors.NewErrInvalidArgument(\"MType\", \"unknown type \"+m.MType.String())\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *JoinRequestPayload) Validate() error {\n\tif m.AppEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"AppEui\", \"can not be empty\")\n\t}\n\tif m.DevEui.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevEui\", \"can not be empty\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *JoinAcceptPayload) Validate() error {\n\tif len(m.Encrypted) != 0 {\n\t\treturn nil\n\t}\n\n\tif m.CfList != nil && len(m.CfList.Freq) != 5 {\n\t\treturn errors.NewErrInvalidArgument(\"CfList.Freq\", \"length must be 5\")\n\t}\n\n\tif m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\tif m.NetId.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"NetId\", \"can not be empty\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Validate implements the api.Validator interface\nfunc (m *MACPayload) Validate() error {\n\tif m.DevAddr.IsEmpty() {\n\t\treturn errors.NewErrInvalidArgument(\"DevAddr\", \"can not be empty\")\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ 4 march 2014\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/andlabs\/ui\"\n)\n\nconst (\n\tdefCmdLine = \"mpv -loop inf ~\/ring.wav\"\n\tdefTime = \"10:30 AM\"\n\ttimeFmt = \"3:04 PM\"\n)\n\n\/\/ If later hasn't happened yet, make it happen on the day of now; if not, the day after.\nfunc bestTime(now time.Time, later time.Time) time.Time {\n\tnow = now.Local() \/\/ use local time to make things make sense\n\tnowh, nowm, nows := now.Clock()\n\tlaterh, laterm, laters := later.Clock()\n\tadd := false\n\tif nowh > laterh {\n\t\tadd = true\n\t} else if (nowh == laterh) && (nowm > laterm) {\n\t\tadd = true\n\t} else if (nowh == laterh) && (nowm == laterm) && (nows >= laters) {\n\t\t\/\/ >= in the case we're on the exact second; add a day because the alarm should have gone off by now otherwise!\n\t\tadd = true\n\t}\n\tif add {\n\t\tnow = now.AddDate(0, 0, 1)\n\t}\n\treturn time.Date(now.Year(), now.Month(), now.Day(),\n\t\tlaterh, laterm, laters, 0,\n\t\tnow.Location())\n}\n\nfunc myMain() {\n\tvar cmd *exec.Cmd\n\tvar timer *time.Timer\n\tvar timerChan <-chan time.Time\n\tvar w *ui.Window\n\n\tstatus := ui.NewLabel(\"\")\n\n\tstop := func() {\n\t\tif cmd != nil { \/\/ stop the command if it's running\n\t\t\terr := cmd.Process.Kill()\n\t\t\tif err != nil {\n\t\t\t\tui.MsgBoxError(w,\n\t\t\t\t\tfmt.Sprintf(\"Error killing process: %v\", err),\n\t\t\t\t\t\"You may need to kill it manually.\")\n\t\t\t}\n\t\t\terr = cmd.Process.Release()\n\t\t\tif err != nil {\n\t\t\t\tui.MsgBoxError(w,\n\t\t\t\t\tfmt.Sprintf(\"Error releasing process: %v\", err),\n\t\t\t\t\t\"\")\n\t\t\t}\n\t\t\tcmd = nil\n\t\t}\n\t\tif timer != nil { \/\/ stop the timer if we started it\n\t\t\ttimer.Stop()\n\t\t\ttimer = nil\n\t\t\ttimerChan = nil\n\t\t}\n\t\tstatus.SetText(\"\")\n\t}\n\n\tw = ui.NewWindow(\"wakeup\", 400, 100)\n\tui.AppQuit = w.Closing \/\/ treat application close as main window close\n\tcmdbox := ui.NewLineEdit(defCmdLine)\n\ttimebox := ui.NewLineEdit(defTime)\n\tbStart := ui.NewButton(\"Start\")\n\tbStop := ui.NewButton(\"Stop\")\n\n\t\/\/ a Stack to keep both buttons at the same size\n\tbtnbox := ui.NewHorizontalStack(bStart, bStop)\n\tbtnbox.SetStretchy(0)\n\tbtnbox.SetStretchy(1)\n\t\/\/ and a Stack around that Stack to keep them at a reasonable size, with space to their right\n\tbtnbox = ui.NewHorizontalStack(btnbox, status)\n\n\t\/\/ the main layout\n\tgrid := ui.NewGrid(2,\n\t\tui.NewLabel(\"Command\"), cmdbox,\n\t\tui.NewLabel(\"Time\"), timebox,\n\t\tui.Space(), ui.Space(), \/\/ the Space on the right will consume the window blank space\n\t\tui.Space(), btnbox)\n\tgrid.SetStretchy(2, 1) \/\/ make the Space noted above consume\n\tgrid.SetFilling(0, 1) \/\/ make the two textboxes grow horizontally\n\tgrid.SetFilling(1, 1)\n\n\tw.Open(grid)\n\nmainloop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.Closing:\n\t\t\tbreak mainloop\n\t\tcase <-bStart.Clicked:\n\t\t\tstop() \/\/ only one alarm at a time\n\t\t\talarmTime, err := time.Parse(timeFmt, timebox.Text())\n\t\t\tif err != nil {\n\t\t\t\tui.MsgBoxError(w,\n\t\t\t\t\tfmt.Sprintf(\"Error parsing time %q: %v\", timebox.Text(), err),\n\t\t\t\t\tfmt.Sprintf(\"Make sure your time is in the form %q (without quotes).\", timeFmt))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnow := time.Now()\n\t\t\tlater := bestTime(now, alarmTime)\n\t\t\ttimer = time.NewTimer(later.Sub(now))\n\t\t\ttimerChan = timer.C\n\t\t\tstatus.SetText(\"Started\")\n\t\tcase <-timerChan:\n\t\t\tcmd = exec.Command(\"\/bin\/sh\", \"-c\", \"exec \"+cmdbox.Text())\n\t\t\t\/\/ keep stdin \/dev\/null in case user wants to run multiple alarms on one instance (TODO should I allow this program to act as a pipe?)\n\t\t\t\/\/ keep stdout \/dev\/null to avoid stty mucking\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\terr := cmd.Start()\n\t\t\tstatus.SetText(\"Firing\")\n\t\t\tif err != nil {\n\t\t\t\tui.MsgBoxError(w,\n\t\t\t\t\tfmt.Sprintf(\"Error running program: %v\", err),\n\t\t\t\t\t\"\")\n\t\t\t\tcmd = nil\n\t\t\t\tstatus.SetText(\"\")\n\t\t\t}\n\t\t\ttimer = nil\n\t\t\ttimerChan = nil\n\t\tcase <-bStop.Clicked:\n\t\t\tstop()\n\t\t}\n\t}\n\n\t\/\/ clean up\n\tstop()\n}\n\nfunc main() {\n\terr := ui.Go(myMain)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error initializing UI library: %v\", err))\n\t}\n}\nAnother MsgBox() API update.\/\/ 4 march 2014\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/andlabs\/ui\"\n)\n\nconst (\n\tdefCmdLine = \"mpv -loop inf ~\/ring.wav\"\n\tdefTime = \"10:30 AM\"\n\ttimeFmt = \"3:04 PM\"\n)\n\n\/\/ If later hasn't happened yet, make it happen on the day of now; if not, the day after.\nfunc bestTime(now time.Time, later time.Time) time.Time {\n\tnow = now.Local() \/\/ use local time to make things make sense\n\tnowh, nowm, nows := now.Clock()\n\tlaterh, laterm, laters := later.Clock()\n\tadd := false\n\tif nowh > laterh {\n\t\tadd = true\n\t} else if (nowh == laterh) && (nowm > laterm) {\n\t\tadd = true\n\t} else if (nowh == laterh) && (nowm == laterm) && (nows >= laters) {\n\t\t\/\/ >= in the case we're on the exact second; add a day because the alarm should have gone off by now otherwise!\n\t\tadd = true\n\t}\n\tif add {\n\t\tnow = now.AddDate(0, 0, 1)\n\t}\n\treturn time.Date(now.Year(), now.Month(), now.Day(),\n\t\tlaterh, laterm, laters, 0,\n\t\tnow.Location())\n}\n\nfunc myMain() {\n\tvar cmd *exec.Cmd\n\tvar timer *time.Timer\n\tvar timerChan <-chan time.Time\n\tvar w *ui.Window\n\n\tstatus := ui.NewLabel(\"\")\n\n\tstop := func() {\n\t\tif cmd != nil { \/\/ stop the command if it's running\n\t\t\terr := cmd.Process.Kill()\n\t\t\tif err != nil {\n\t\t\t\t<-w.MsgBoxError(\n\t\t\t\t\tfmt.Sprintf(\"Error killing process: %v\", err),\n\t\t\t\t\t\"You may need to kill it manually.\")\n\t\t\t}\n\t\t\terr = cmd.Process.Release()\n\t\t\tif err != nil {\n\t\t\t\t<-w.MsgBoxError(\n\t\t\t\t\tfmt.Sprintf(\"Error releasing process: %v\", err),\n\t\t\t\t\t\"\")\n\t\t\t}\n\t\t\tcmd = nil\n\t\t}\n\t\tif timer != nil { \/\/ stop the timer if we started it\n\t\t\ttimer.Stop()\n\t\t\ttimer = nil\n\t\t\ttimerChan = nil\n\t\t}\n\t\tstatus.SetText(\"\")\n\t}\n\n\tw = ui.NewWindow(\"wakeup\", 400, 100)\n\tui.AppQuit = w.Closing \/\/ treat application close as main window close\n\tcmdbox := ui.NewLineEdit(defCmdLine)\n\ttimebox := ui.NewLineEdit(defTime)\n\tbStart := ui.NewButton(\"Start\")\n\tbStop := ui.NewButton(\"Stop\")\n\n\t\/\/ a Stack to keep both buttons at the same size\n\tbtnbox := ui.NewHorizontalStack(bStart, bStop)\n\tbtnbox.SetStretchy(0)\n\tbtnbox.SetStretchy(1)\n\t\/\/ and a Stack around that Stack to keep them at a reasonable size, with space to their right\n\tbtnbox = ui.NewHorizontalStack(btnbox, status)\n\n\t\/\/ the main layout\n\tgrid := ui.NewGrid(2,\n\t\tui.NewLabel(\"Command\"), cmdbox,\n\t\tui.NewLabel(\"Time\"), timebox,\n\t\tui.Space(), ui.Space(), \/\/ the Space on the right will consume the window blank space\n\t\tui.Space(), btnbox)\n\tgrid.SetStretchy(2, 1) \/\/ make the Space noted above consume\n\tgrid.SetFilling(0, 1) \/\/ make the two textboxes grow horizontally\n\tgrid.SetFilling(1, 1)\n\n\tw.Open(grid)\n\nmainloop:\n\tfor {\n\t\tselect {\n\t\tcase <-w.Closing:\n\t\t\tbreak mainloop\n\t\tcase <-bStart.Clicked:\n\t\t\tstop() \/\/ only one alarm at a time\n\t\t\talarmTime, err := time.Parse(timeFmt, timebox.Text())\n\t\t\tif err != nil {\n\t\t\t\t<-w.MsgBoxError(\n\t\t\t\t\tfmt.Sprintf(\"Error parsing time %q: %v\", timebox.Text(), err),\n\t\t\t\t\tfmt.Sprintf(\"Make sure your time is in the form %q (without quotes).\", timeFmt))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnow := time.Now()\n\t\t\tlater := bestTime(now, alarmTime)\n\t\t\ttimer = time.NewTimer(later.Sub(now))\n\t\t\ttimerChan = timer.C\n\t\t\tstatus.SetText(\"Started\")\n\t\tcase <-timerChan:\n\t\t\tcmd = exec.Command(\"\/bin\/sh\", \"-c\", \"exec \"+cmdbox.Text())\n\t\t\t\/\/ keep stdin \/dev\/null in case user wants to run multiple alarms on one instance (TODO should I allow this program to act as a pipe?)\n\t\t\t\/\/ keep stdout \/dev\/null to avoid stty mucking\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\terr := cmd.Start()\n\t\t\tstatus.SetText(\"Firing\")\n\t\t\tif err != nil {\n\t\t\t\t<-w.MsgBoxError(\n\t\t\t\t\tfmt.Sprintf(\"Error running program: %v\", err),\n\t\t\t\t\t\"\")\n\t\t\t\tcmd = nil\n\t\t\t\tstatus.SetText(\"\")\n\t\t\t}\n\t\t\ttimer = nil\n\t\t\ttimerChan = nil\n\t\tcase <-bStop.Clicked:\n\t\t\tstop()\n\t\t}\n\t}\n\n\t\/\/ clean up\n\tstop()\n}\n\nfunc main() {\n\terr := ui.Go(myMain)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"error initializing UI library: %v\", err))\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nfunc main() {\n\tflags := ParseCmdArgs()\n\tif flags.Help {\n\t\tExitWithUsage()\n\t} else if flags.Version {\n\t\tExitWithVersion()\n\t}\n\n\tg := NewGenerator(\n\t\tTemplateDir(),\n\t\tNewRepositoryFromURL(RemoteURL(\"origin\")),\n\t)\n\tif flags.IssueOnly {\n\t\tg.GenerateIssueTemplate()\n\t} else if flags.PROnly {\n\t\tg.GeneratePRTemplate()\n\t} else if flags.ContributingOnly {\n\t\tg.GenerateContributingTemplate()\n\t} else {\n\t\tg.GenerateAllTemplates()\n\t}\n}\nallow multiple flagspackage main\n\nfunc main() {\n\tflags := ParseCmdArgs()\n\tif flags.Help {\n\t\tExitWithUsage()\n\t} else if flags.Version {\n\t\tExitWithVersion()\n\t}\n\n\tg := NewGenerator(\n\t\tTemplateDir(),\n\t\tNewRepositoryFromURL(RemoteURL(\"origin\")),\n\t)\n\tif flags.IssueOnly {\n\t\tg.GenerateIssueTemplate()\n\t}\n\tif flags.PROnly {\n\t\tg.GeneratePRTemplate()\n\t}\n\tif flags.ContributingOnly {\n\t\tg.GenerateContributingTemplate()\n\t}\n\tif !flags.IssueOnly && !flags.PROnly && !flags.ContributingOnly {\n\t\tg.GenerateAllTemplates()\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n)\n\nvar Cfg Config\nvar utl util.SomaUtil\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"somaadm\"\n\tapp.Usage = \"SOMA Administrative Interface\"\n\tapp.Version = \"0.2.0\"\n\n\tapp = registerCommands(*app)\n\tapp = registerFlags(*app)\n\n\tapp.Run(os.Args)\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n0.3.0: merged serviceprop branchpackage main\n\nimport (\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n)\n\nvar Cfg Config\nvar utl util.SomaUtil\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"somaadm\"\n\tapp.Usage = \"SOMA Administrative Interface\"\n\tapp.Version = \"0.3.0\"\n\n\tapp = registerCommands(*app)\n\tapp = registerFlags(*app)\n\n\tapp.Run(os.Args)\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n<|endoftext|>"} {"text":"\/\/ HttpDebugProxy is a HTTP proxy which dumps out the requests and responses.\npackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ CustomTransport replaces DefaultTransport for overriding RoundTrip.\ntype CustomTransport struct{}\n\nfunc main() {\n\t\/\/ TODO: improve flags.\n\tvar src, dst string\n\tflag.Parse()\n\targs := flag.Args()\n\t\/\/ First arg is destination.\n\tif len(args) >= 1 {\n\t\tdst = args[0]\n\t} else {\n\t\tdst = \"http:\/\/127.0.0.1:8080\"\n\t}\n\t\/\/ Second arg is source.\n\tif len(args) == 2 {\n\t\tsrc = args[1]\n\t} else {\n\t\tsrc = \":80\"\n\t}\n\n\t\/\/ Create destination url.\n\tu, err := url.Parse(dst)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing destination url:\", err)\n\t}\n\n\t\/\/ Create reverse proxy.\n\tproxy := httputil.NewSingleHostReverseProxy(u)\n\tproxy.Transport = &CustomTransport{}\n\n\t\/\/ Create server.\n\ts := &http.Server{\n\t\tAddr: src,\n\t\tHandler: proxy,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tlog.Fatal(s.ListenAndServe())\n}\n\n\/\/ RoundTrip replaces DefaultTransport RoundTrip, contains the Request and Response dumps.\nfunc (t *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ Read the Request, including body.\n\treqBody, err := httputil.DumpRequest(req, true)\n\tif err != nil {\n\t\tlog.Println(\"Error calling DumpRequest:\", err)\n\t}\n\tlog.Println(\">>>>> Request >>>>>\")\n\tlog.Println(\"\\n\\n\" + string(reqBody))\n\n\t\/\/ Send request and receive response.\n\tresponse, err := http.DefaultTransport.RoundTrip(req)\n\tif err != nil {\n\t\tlog.Println(\"Error calling RoundTrip:\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Read the Response, including body.\n\trespBody, err := httputil.DumpResponse(response, true)\n\tif err != nil {\n\t\tlog.Println(\"Error calling DumpResponse:\", err)\n\t\treturn nil, err\n\t}\n\tlog.Println(\"<<<<< Response <<<<<\")\n\tlog.Println(\"\\n\\n\" + string(respBody))\n\n\treturn response, err\n}\nRefactored.\/\/ HttpDebugProxy is a HTTP proxy which dumps out the requests and responses.\npackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ CustomTransport replaces DefaultTransport for overriding RoundTrip.\ntype CustomTransport struct{}\n\nfunc main() {\n\t\/\/ TODO: improve flags.\n\tvar src, dst string\n\tflag.Parse()\n\targs := flag.Args()\n\t\/\/ First arg is destination.\n\tif len(args) >= 1 {\n\t\tdst = args[0]\n\t} else {\n\t\tdst = \"http:\/\/127.0.0.1:8080\"\n\t}\n\t\/\/ Second arg is source.\n\tif len(args) == 2 {\n\t\tsrc = args[1]\n\t} else {\n\t\tsrc = \":80\"\n\t}\n\n\ts, err := buildServer(src, dst)\n\tif err != nil {\n\t\tlog.Fatal(\"Error building server:\", err)\n\t}\n\tlog.Fatal(s.ListenAndServe())\n}\nfunc buildServer(src string, dst string) (*http.Server, error) {\n\t\/\/ Create destination url.\n\tu, err := url.Parse(dst)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing destination url:\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create reverse proxy.\n\tproxy := httputil.NewSingleHostReverseProxy(u)\n\tproxy.Transport = &CustomTransport{}\n\n\t\/\/ Create server.\n\ts := &http.Server{\n\t\tAddr: src,\n\t\tHandler: proxy,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\treturn s, nil\n}\n\n\/\/ RoundTrip replaces DefaultTransport RoundTrip, contains the Request and Response dumps.\nfunc (t *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ Read the Request, including body.\n\treqBody, err := httputil.DumpRequest(req, true)\n\tif err != nil {\n\t\tlog.Println(\"Error calling DumpRequest:\", err)\n\t}\n\tlog.Println(\">>>>> Request >>>>>\")\n\tlog.Println(\"\\n\\n\" + string(reqBody))\n\n\t\/\/ Send request and receive response.\n\tresponse, err := http.DefaultTransport.RoundTrip(req)\n\tif err != nil {\n\t\tlog.Println(\"Error calling RoundTrip:\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Read the Response, including body.\n\trespBody, err := httputil.DumpResponse(response, true)\n\tif err != nil {\n\t\tlog.Println(\"Error calling DumpResponse:\", err)\n\t\treturn nil, err\n\t}\n\tlog.Println(\"<<<<< Response <<<<<\")\n\tlog.Println(\"\\n\\n\" + string(respBody))\n\n\treturn response, err\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"swan\"\n\tapp.Usage = \"terminal migrations\"\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tAliases: []string{\"r\"},\n\t\t\tUsage: \"run migrations\",\n\t\t\tDescription: \"run all migrations since the last migration\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"dir\",\n\t\t\t\t\tValue: \".\/migrations\",\n\t\t\t\t\tUsage: \"migration directory\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"last\",\n\t\t\t\t\tValue: \".swan\",\n\t\t\t\t\tUsage: \"last migration file\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tdir := c.String(\"dir\")\n\t\t\t\tlast := c.String(\"last\")\n\t\t\t\tif err := Run(last, dir); err != nil {\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"create\",\n\t\t\tAliases: []string{\"c\"},\n\t\t\tUsage: \"create a new migration: create [name] [ext]\",\n\t\t\tDescription: \"create a new migration in the provided migrations directory\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"dir\",\n\t\t\t\t\tValue: \".\/migrations\",\n\t\t\t\t\tUsage: \"migration directory\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tname := c.Args().First()\n\t\t\t\text := c.Args().Get(1)\n\t\t\t\tif ext == \"\" {\n\t\t\t\t\text = \"sh\"\n\t\t\t\t}\n\t\t\t\tdir := c.String(\"dir\")\n\n\t\t\t\tif err := Create(name, dir, ext, time.Now()); err != nil {\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\nUse constants for defaultspackage main\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n)\n\nconst (\n\tdefaultDir = \"migrations\"\n\tlastFile = \".swan\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"swan\"\n\tapp.Usage = \"terminal migrations\"\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tAliases: []string{\"r\"},\n\t\t\tUsage: \"run migrations\",\n\t\t\tDescription: \"run all migrations since the last migration\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"dir\",\n\t\t\t\t\tValue: defaultDir,\n\t\t\t\t\tUsage: \"migration directory\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"last\",\n\t\t\t\t\tValue: lastFile,\n\t\t\t\t\tUsage: \"last migration file\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tdir := c.String(\"dir\")\n\t\t\t\tlast := c.String(\"last\")\n\t\t\t\tif err := Run(last, dir); err != nil {\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"create\",\n\t\t\tAliases: []string{\"c\"},\n\t\t\tUsage: \"create a new migration: create [name] [ext]\",\n\t\t\tDescription: \"create a new migration in the provided migrations directory\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"dir\",\n\t\t\t\t\tValue: defaultDir,\n\t\t\t\t\tUsage: \"migration directory\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tname := c.Args().First()\n\t\t\t\text := c.Args().Get(1)\n\t\t\t\tif ext == \"\" {\n\t\t\t\t\text = \"sh\"\n\t\t\t\t}\n\t\t\t\tdir := c.String(\"dir\")\n\n\t\t\t\tif err := Create(name, dir, ext, time.Now()); err != nil {\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/artyom\/autoflags\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nfunc main() {\n\tconfig := struct {\n\t\tAddr string `flag:\"listen,address to listen at\"`\n\t\tQsize int `flag:\"qsize,job queue size\"`\n\t\tConfig string `flag:\"config,path to config (yaml)\"`\n\t\tCertFile string `flag:\"cert,path to ssl certificate\"`\n\t\tKeyFile string `flag:\"key,path to ssl certificate key\"`\n\t}{\n\t\tAddr: \"127.0.0.1:8080\",\n\t\tQsize: 10,\n\t}\n\tautoflags.Define(&config)\n\tflag.Parse()\n\tcfg, err := readConfig(config.Config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif config.Qsize < 1 {\n\t\tconfig.Qsize = 1\n\t}\n\th := hookHandler{cmds: make(chan execEnv, config.Qsize)}\n\tfor k, v := range cfg {\n\t\thttp.HandleFunc(k, h.endpointHandler(v))\n\t}\n\tgo h.run()\n\tserver := &http.Server{\n\t\tAddr: config.Addr,\n\t\tMaxHeaderBytes: 1 << 20,\n\t\tReadTimeout: 15 * time.Second,\n\t\tWriteTimeout: 15 * time.Second,\n\t}\n\tif len(config.CertFile) > 0 && len(config.KeyFile) > 0 {\n\t\tlog.Fatal(server.ListenAndServeTLS(config.CertFile, config.KeyFile))\n\t}\n\tlog.Fatal(server.ListenAndServe())\n}\n\n\/\/ hookHandler manages receiving\/dispatching hook requests and running\n\/\/ corresponding commands\ntype hookHandler struct {\n\tcmds chan execEnv\n}\n\n\/\/ run receives commands to run on channel and executes them\nfunc (hh hookHandler) run() {\n\tfor item := range hh.cmds {\n\t\tvar cmd *exec.Cmd\n\t\tc, ok := item.endpoint.Refs[item.payload.Ref]\n\t\tswitch {\n\t\tcase ok:\n\t\t\tlog.Print(\"found per-ref command\")\n\t\t\tcmd = exec.Command(c.Command, c.Args...)\n\t\tcase !ok && len(item.endpoint.Command) > 0:\n\t\t\tlog.Print(\"found global per-repo command\")\n\t\t\tcmd = exec.Command(\n\t\t\t\titem.endpoint.Command,\n\t\t\t\titem.endpoint.Args...)\n\t\tdefault:\n\t\t\tlog.Printf(\"no matching command for ref %q found, skipping\",\n\t\t\t\titem.payload.Ref)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"repo: %q, ref: %q, command: %v\",\n\t\t\titem.endpoint.RepoName, item.payload.Ref, cmd.Args)\n\t\tif err := cmd.Start(); err != nil {\n\t\t\tlog.Print(\"failed to start command:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo func(cmd *exec.Cmd) {\n\t\t\tif err := cmd.Wait(); err != nil {\n\t\t\t\tlog.Print(\"command finished with error:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Print(\"command finished ok\")\n\t\t}(cmd)\n\t}\n}\n\n\/\/ endpointHandler constructs http.HandlerFunc for particular endpoint\nfunc (hh hookHandler) endpointHandler(ep endpoint) http.HandlerFunc {\n\tsecret := []byte(ep.Secret)\n\twithSecret := len(ep.Secret) > 0\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"POST\" {\n\t\t\thttp.Error(w, \"unsupported method\",\n\t\t\t\thttp.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tswitch r.Header.Get(\"X-Github-Event\") {\n\t\tcase \"push\":\n\t\tcase \"ping\":\n\t\t\treturn \/\/ accept with code 200\n\t\tdefault:\n\t\t\thttp.Error(w, \"unsupported event type\",\n\t\t\t\thttp.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tif r.Header.Get(\"Content-Type\") != \"application\/json\" {\n\t\t\thttp.Error(w, \"unsupported content type\",\n\t\t\t\thttp.StatusUnsupportedMediaType)\n\t\t\treturn\n\t\t}\n\t\tvar sig string\n\t\tif n, err := fmt.Sscanf(\n\t\t\tr.Header.Get(\"X-Hub-Signature\"),\n\t\t\t\"sha1=%s\", &sig); n != 1 || err != nil {\n\t\t\thttp.Error(w, \"malformed signature\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tvar (\n\t\t\ttr io.Reader = r.Body\n\t\t\tmac hash.Hash\n\t\t\tpayload pushPayload\n\t\t)\n\t\tif withSecret {\n\t\t\tmac = hmac.New(sha1.New, secret)\n\t\t\ttr = io.TeeReader(r.Body, mac)\n\t\t}\n\t\tif err := json.NewDecoder(tr).Decode(&payload); err != nil {\n\t\t\tlog.Print(err)\n\t\t\thttp.Error(w, \"malformed json\",\n\t\t\t\thttp.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif withSecret {\n\t\t\tsig2 := fmt.Sprintf(\"%x\", mac.Sum(nil))\n\t\t\tif sig != sig2 {\n\t\t\t\tlog.Printf(\"signature mismatch, got %q, want %q\", sig, sig2)\n\t\t\t\thttp.Error(w, \"signature mismatch\",\n\t\t\t\t\thttp.StatusPreconditionFailed)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif payload.Repository.Name != ep.RepoName {\n\t\t\tlog.Printf(\"repository names mismatch: got %q, want %q\",\n\t\t\t\tpayload.Repository.Name, ep.RepoName)\n\t\t\thttp.Error(w, \"repository mismatch\",\n\t\t\t\thttp.StatusPreconditionFailed)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase hh.cmds <- execEnv{payload, ep}:\n\t\tdefault: \/\/ spillover\n\t\t\tlog.Print(\"buffer spillover\")\n\t\t\thttp.Error(w, \"spillover\", http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ execEnv used to pass both payload and endpoint info via channel\ntype execEnv struct {\n\tpayload pushPayload\n\tendpoint endpoint\n}\n\ntype pushPayload struct {\n\tRef string `json:\"ref\"`\n\tRepository struct {\n\t\tName string `json:\"name\"`\n\t\tFullName string `json:\"full_name\"`\n\t\tHttpUrl string `json:\"html_url\"`\n\t\tSshUrl string `json:\"ssh_url\"`\n\t\tGitUrl string `json:\"git_url\"`\n\t\tCloneUrl string `json:\"clone_url\"`\n\t} `json:\"repository\"`\n}\n\n\/\/ endpoint represents config for one repository, handled by particular url\ntype endpoint struct {\n\tRepoName string\n\tSecret string\n\tCommand string \/\/ global command used if no per-ref command found\n\tArgs []string\n\tRefs map[string]struct {\n\t\tCommand string \/\/ per-ref commands\n\t\tArgs []string\n\t}\n}\n\n\/\/ readConfig loads configuration from yaml file\n\/\/\n\/\/ Config should be in form map[string]endpoint, where keys are urls used to set\n\/\/ up http handlers.\nfunc readConfig(fileName string) (map[string]endpoint, error) {\n\tb, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make(map[string]endpoint)\n\tif err := yaml.Unmarshal(b, out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\nAdd -verbose and -timeout flagspackage main\n\nimport (\n\t\"context\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/artyom\/autoflags\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nfunc main() {\n\tconfig := struct {\n\t\tAddr string `flag:\"listen,address to listen at\"`\n\t\tQsize int `flag:\"qsize,job queue size\"`\n\t\tConfig string `flag:\"config,path to config (yaml)\"`\n\t\tCertFile string `flag:\"cert,path to ssl certificate\"`\n\t\tKeyFile string `flag:\"key,path to ssl certificate key\"`\n\t\tTimeout time.Duration `flag:\"timeout,timeout for command run\"`\n\t\tVerbose bool `flag:\"verbose,pass stdout\/stderr from commands to stderr\"`\n\t}{\n\t\tAddr: \"127.0.0.1:8080\",\n\t\tQsize: 10,\n\t\tTimeout: 3 * time.Minute,\n\t}\n\tautoflags.Define(&config)\n\tflag.Parse()\n\tcfg, err := readConfig(config.Config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif config.Qsize < 1 {\n\t\tconfig.Qsize = 1\n\t}\n\th := hookHandler{\n\t\tcmds: make(chan execEnv, config.Qsize),\n\t\ttimeout: config.Timeout,\n\t\tverbose: config.Verbose,\n\t}\n\tfor k, v := range cfg {\n\t\thttp.HandleFunc(k, h.endpointHandler(v))\n\t}\n\tgo h.run()\n\tserver := &http.Server{\n\t\tAddr: config.Addr,\n\t\tMaxHeaderBytes: 1 << 20,\n\t\tReadTimeout: 15 * time.Second,\n\t\tWriteTimeout: 15 * time.Second,\n\t}\n\tif len(config.CertFile) > 0 && len(config.KeyFile) > 0 {\n\t\tlog.Fatal(server.ListenAndServeTLS(config.CertFile, config.KeyFile))\n\t}\n\tlog.Fatal(server.ListenAndServe())\n}\n\n\/\/ hookHandler manages receiving\/dispatching hook requests and running\n\/\/ corresponding commands\ntype hookHandler struct {\n\tcmds chan execEnv\n\ttimeout time.Duration\n\tverbose bool\n}\n\n\/\/ run receives commands to run on channel and executes them\nfunc (hh hookHandler) run() {\n\tcmdRun := func(item execEnv) error {\n\t\tctx := context.Background()\n\t\tif hh.timeout > 0 {\n\t\t\tvar cancel func()\n\t\t\tctx, cancel = context.WithTimeout(ctx, hh.timeout)\n\t\t\tdefer cancel()\n\t\t}\n\t\tvar cmd *exec.Cmd\n\t\tc, ok := item.endpoint.Refs[item.payload.Ref]\n\t\tswitch {\n\t\tcase ok:\n\t\t\tlog.Print(\"found per-ref command\")\n\t\t\tcmd = exec.CommandContext(ctx, c.Command, c.Args...)\n\t\tcase !ok && len(item.endpoint.Command) > 0:\n\t\t\tlog.Print(\"found global per-repo command\")\n\t\t\tcmd = exec.CommandContext(ctx,\n\t\t\t\titem.endpoint.Command,\n\t\t\t\titem.endpoint.Args...)\n\t\tdefault:\n\t\t\tlog.Printf(\"no matching command for ref %q found, skipping\",\n\t\t\t\titem.payload.Ref)\n\t\t\treturn nil\n\t\t}\n\t\tlog.Printf(\"repo: %q, ref: %q, command: %v\",\n\t\t\titem.endpoint.RepoName, item.payload.Ref, cmd.Args)\n\t\tif hh.verbose {\n\t\t\tcmd.Stdout = os.Stderr\n\t\t\tcmd.Stderr = os.Stderr\n\t\t}\n\t\treturn cmd.Run()\n\t}\n\tfor item := range hh.cmds {\n\t\tif err := cmdRun(item); err != nil {\n\t\t\tlog.Printf(\"repo: %q, ref: %q, command run: %v\",\n\t\t\t\titem.endpoint.RepoName, item.payload.Ref, err)\n\t\t}\n\t}\n}\n\n\/\/ endpointHandler constructs http.HandlerFunc for particular endpoint\nfunc (hh hookHandler) endpointHandler(ep endpoint) http.HandlerFunc {\n\tsecret := []byte(ep.Secret)\n\twithSecret := len(ep.Secret) > 0\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"POST\" {\n\t\t\thttp.Error(w, \"unsupported method\",\n\t\t\t\thttp.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tswitch r.Header.Get(\"X-Github-Event\") {\n\t\tcase \"push\":\n\t\tcase \"ping\":\n\t\t\treturn \/\/ accept with code 200\n\t\tdefault:\n\t\t\thttp.Error(w, \"unsupported event type\",\n\t\t\t\thttp.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tif r.Header.Get(\"Content-Type\") != \"application\/json\" {\n\t\t\thttp.Error(w, \"unsupported content type\",\n\t\t\t\thttp.StatusUnsupportedMediaType)\n\t\t\treturn\n\t\t}\n\t\tvar sig string\n\t\tif n, err := fmt.Sscanf(\n\t\t\tr.Header.Get(\"X-Hub-Signature\"),\n\t\t\t\"sha1=%s\", &sig); n != 1 || err != nil {\n\t\t\thttp.Error(w, \"malformed signature\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tvar (\n\t\t\ttr io.Reader = r.Body\n\t\t\tmac hash.Hash\n\t\t\tpayload pushPayload\n\t\t)\n\t\tif withSecret {\n\t\t\tmac = hmac.New(sha1.New, secret)\n\t\t\ttr = io.TeeReader(r.Body, mac)\n\t\t}\n\t\tif err := json.NewDecoder(tr).Decode(&payload); err != nil {\n\t\t\tlog.Print(err)\n\t\t\thttp.Error(w, \"malformed json\",\n\t\t\t\thttp.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif withSecret {\n\t\t\tsig2 := fmt.Sprintf(\"%x\", mac.Sum(nil))\n\t\t\tif sig != sig2 {\n\t\t\t\tlog.Printf(\"signature mismatch, got %q, want %q\", sig, sig2)\n\t\t\t\thttp.Error(w, \"signature mismatch\",\n\t\t\t\t\thttp.StatusPreconditionFailed)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif payload.Repository.Name != ep.RepoName {\n\t\t\tlog.Printf(\"repository names mismatch: got %q, want %q\",\n\t\t\t\tpayload.Repository.Name, ep.RepoName)\n\t\t\thttp.Error(w, \"repository mismatch\",\n\t\t\t\thttp.StatusPreconditionFailed)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase hh.cmds <- execEnv{payload, ep}:\n\t\tdefault: \/\/ spillover\n\t\t\tlog.Print(\"buffer spillover\")\n\t\t\thttp.Error(w, \"spillover\", http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ execEnv used to pass both payload and endpoint info via channel\ntype execEnv struct {\n\tpayload pushPayload\n\tendpoint endpoint\n}\n\ntype pushPayload struct {\n\tRef string `json:\"ref\"`\n\tRepository struct {\n\t\tName string `json:\"name\"`\n\t\tFullName string `json:\"full_name\"`\n\t\tHttpUrl string `json:\"html_url\"`\n\t\tSshUrl string `json:\"ssh_url\"`\n\t\tGitUrl string `json:\"git_url\"`\n\t\tCloneUrl string `json:\"clone_url\"`\n\t} `json:\"repository\"`\n}\n\n\/\/ endpoint represents config for one repository, handled by particular url\ntype endpoint struct {\n\tRepoName string\n\tSecret string\n\tCommand string \/\/ global command used if no per-ref command found\n\tArgs []string\n\tRefs map[string]struct {\n\t\tCommand string \/\/ per-ref commands\n\t\tArgs []string\n\t}\n}\n\n\/\/ readConfig loads configuration from yaml file\n\/\/\n\/\/ Config should be in form map[string]endpoint, where keys are urls used to set\n\/\/ up http handlers.\nfunc readConfig(fileName string) (map[string]endpoint, error) {\n\tb, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make(map[string]endpoint)\n\tif err := yaml.Unmarshal(b, out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/gcfg\"\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"fmt\"\n\t\"github.com\/dpapathanasiou\/go-recaptcha\"\n\t\"github.com\/justinas\/nosurf\"\n\t\"github.com\/worr\/chrooter\"\n\t\"github.com\/worr\/secstring\"\n\t\"html\/template\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"time\"\n\ttxttemplate \"text\/template\"\n)\n\ntype Config struct {\n\tMail struct {\n\t\tEmail string\n\t\tUsername string\n\t\tPassword string\n\t\tHostname string\n\t\tpassword *secstring.SecString\n\t}\n\n\tRecaptcha struct {\n\t\tPrivate string\n\t}\n}\n\nvar t = template.Must(template.ParseFiles(\"template\/index.html\"))\nvar emailTemplate = txttemplate.Must(txttemplate.New(\"email\").Parse(\"Here is your exclusive Vim download link: http:\/\/www.vim.org\/download.php?code={{.Code}}\"))\nvar c = make(chan string)\nvar conf Config\n\n\/\/ Default handler\nfunc dispatch(w http.ResponseWriter, r *http.Request) {\n\tcontext := map[string]string{\n\t\t\"token\": nosurf.Token(r),\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tcontext[\"email\"] = r.FormValue(\"email\")\n\t\tif !recaptcha.Confirm(r.RemoteAddr, r.FormValue(\"recaptcha_challenge_field\"), r.FormValue(\"recaptcha_response_field\")) {\n\t\t\thttp.Error(w, \"Failed captcha\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif context[\"email\"] == \"\" {\n\t\t\thttp.Error(w, \"Empty email address\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tc <- context[\"email\"]\n\t}\n\n\tif err := t.Execute(w, context); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n\/\/ Handler for all bad CSRF requests\nfunc failedCSRF(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, nosurf.Reason(r).Error(), http.StatusBadRequest)\n}\n\n\/\/ Pulls email off of the channel and possibly sends download codes\nfunc email() {\n\tauth := smtp.PlainAuth(\"\", conf.Mail.Username, string(conf.Mail.password.String), conf.Mail.Hostname)\n\n\tfor addr := range c {\n\t\t\/\/ Exclusivity\n\t\tif r := rand.Intn(3); r != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar emailAddr *mail.Address\n\t\tvar err error\n\t\tif emailAddr, err = mail.ParseAddress(addr); err != nil {\n\t\t\tlog.Printf(\"Failed to send email to %v: %v\", emailAddr.Address, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfromAddr := mail.Address{Name:\"Vim Download Czar\", Address: conf.Mail.Email}\n\t\theaders := make(map[string]string)\n\t\theaders[\"To\"] = emailAddr.String()\n\t\theaders[\"From\"] = fromAddr.String()\n\t\theaders[\"Date\"] = time.Now().String()\n\t\theaders[\"Subject\"] = \"Your Vim invite is ready\"\n\t\theaders[\"MIME-Version\"] = \"1.0\"\n\t\theaders[\"Content-Type\"] = \"text\/plain; charset=\\\"utf-8\\\"\"\n\n\t\tmsg := \"\"\n\t\tfor key, val := range(headers) {\n\t\t\tmsg += fmt.Sprintf(\"%v: %v\\r\\n\", key, val)\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(make([]byte, 0))\n\t\tif err := emailTemplate.Execute(buf, struct{ Code string }{uuid.NewUUID().String()}); err != nil {\n\t\t\tlog.Printf(\"Can't execute email template: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tmsg += fmt.Sprintf(\"\\r\\n%s\", buf)\n\n\t\tconf.Mail.password.Decrypt()\n\t\tif err = smtp.SendMail(conf.Mail.Hostname, auth, fromAddr.Address, []string{emailAddr.Address}, []byte(msg)); err != nil {\n\t\t\tlog.Printf(\"Failed to send email to %v: %v\", emailAddr.Address, err)\n\t\t\tcontinue\n\t\t}\n\t\tconf.Mail.password.Encrypt()\n\t}\n}\n\nfunc main() {\n\tif err := gcfg.ReadFileInto(&conf, \"vim.sexy.ini\"); err != nil {\n\t\tlog.Fatalf(\"Can't read config file: %v\", err)\n\t}\n\n\tif err := chrooter.Chroot(\"www\", \"\/var\/chroot\/vim.sexy\"); err != nil {\n\t\tlog.Fatalf(\"Can't chroot: %v\", err)\n\t}\n\n\tvar err error\n\tif conf.Mail.password, err = secstring.FromString(&conf.Mail.Password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trecaptcha.Init(conf.Recaptcha.Private)\n\n\tgo email()\n\n\thttp.HandleFunc(\"\/\", dispatch)\n\tcsrf := nosurf.New(http.DefaultServeMux)\n\tcookie := http.Cookie{HttpOnly: true}\n\tcsrf.SetBaseCookie(cookie)\n\tcsrf.SetFailureHandler(http.HandlerFunc(failedCSRF))\n\tif err = http.ListenAndServe(\"127.0.0.1:8000\", csrf); err != nil {\n\t\tlog.Fatalf(\"Cannot listen: %v\", err)\n\t}\n}\nCSRF dickerypackage main\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/gcfg\"\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"fmt\"\n\t\"github.com\/dpapathanasiou\/go-recaptcha\"\n\t\"github.com\/justinas\/nosurf\"\n\t\"github.com\/worr\/chrooter\"\n\t\"github.com\/worr\/secstring\"\n\t\"html\/template\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"time\"\n\ttxttemplate \"text\/template\"\n)\n\ntype Config struct {\n\tMail struct {\n\t\tEmail string\n\t\tUsername string\n\t\tPassword string\n\t\tHostname string\n\t\tpassword *secstring.SecString\n\t}\n\n\tRecaptcha struct {\n\t\tPrivate string\n\t}\n}\n\nvar t = template.Must(template.ParseFiles(\"template\/index.html\"))\nvar emailTemplate = txttemplate.Must(txttemplate.New(\"email\").Parse(\"Here is your exclusive Vim download link: http:\/\/www.vim.org\/download.php?code={{.Code}}\"))\nvar c = make(chan string)\nvar conf Config\n\n\/\/ Default handler\nfunc dispatch(w http.ResponseWriter, r *http.Request) {\n\tcontext := map[string]string{\n\t\t\"token\": nosurf.Token(r),\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tcontext[\"email\"] = r.FormValue(\"email\")\n\t\tif !recaptcha.Confirm(r.RemoteAddr, r.FormValue(\"recaptcha_challenge_field\"), r.FormValue(\"recaptcha_response_field\")) {\n\t\t\thttp.Error(w, \"Failed captcha\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif context[\"email\"] == \"\" {\n\t\t\thttp.Error(w, \"Empty email address\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tc <- context[\"email\"]\n\t}\n\n\tif err := t.Execute(w, context); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n\/\/ Handler for all bad CSRF requests\nfunc failedCSRF(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, nosurf.Reason(r).Error(), http.StatusBadRequest)\n}\n\n\/\/ Pulls email off of the channel and possibly sends download codes\nfunc email() {\n\tauth := smtp.PlainAuth(\"\", conf.Mail.Username, string(conf.Mail.password.String), conf.Mail.Hostname)\n\n\tfor addr := range c {\n\t\t\/\/ Exclusivity\n\t\tif r := rand.Intn(3); r != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar emailAddr *mail.Address\n\t\tvar err error\n\t\tif emailAddr, err = mail.ParseAddress(addr); err != nil {\n\t\t\tlog.Printf(\"Failed to send email to %v: %v\", emailAddr.Address, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfromAddr := mail.Address{Name:\"Vim Download Czar\", Address: conf.Mail.Email}\n\t\theaders := make(map[string]string)\n\t\theaders[\"To\"] = emailAddr.String()\n\t\theaders[\"From\"] = fromAddr.String()\n\t\theaders[\"Date\"] = time.Now().String()\n\t\theaders[\"Subject\"] = \"Your Vim invite is ready\"\n\t\theaders[\"MIME-Version\"] = \"1.0\"\n\t\theaders[\"Content-Type\"] = \"text\/plain; charset=\\\"utf-8\\\"\"\n\n\t\tmsg := \"\"\n\t\tfor key, val := range(headers) {\n\t\t\tmsg += fmt.Sprintf(\"%v: %v\\r\\n\", key, val)\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(make([]byte, 0))\n\t\tif err := emailTemplate.Execute(buf, struct{ Code string }{uuid.NewUUID().String()}); err != nil {\n\t\t\tlog.Printf(\"Can't execute email template: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tmsg += fmt.Sprintf(\"\\r\\n%s\", buf)\n\n\t\tconf.Mail.password.Decrypt()\n\t\tif err = smtp.SendMail(conf.Mail.Hostname, auth, fromAddr.Address, []string{emailAddr.Address}, []byte(msg)); err != nil {\n\t\t\tlog.Printf(\"Failed to send email to %v: %v\", emailAddr.Address, err)\n\t\t\tcontinue\n\t\t}\n\t\tconf.Mail.password.Encrypt()\n\t}\n}\n\nfunc main() {\n\tif err := gcfg.ReadFileInto(&conf, \"vim.sexy.ini\"); err != nil {\n\t\tlog.Fatalf(\"Can't read config file: %v\", err)\n\t}\n\n\tif err := chrooter.Chroot(\"www\", \"\/var\/chroot\/vim.sexy\"); err != nil {\n\t\tlog.Fatalf(\"Can't chroot: %v\", err)\n\t}\n\n\tvar err error\n\tif conf.Mail.password, err = secstring.FromString(&conf.Mail.Password); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trecaptcha.Init(conf.Recaptcha.Private)\n\n\tgo email()\n\n\tcsrf := nosurf.New(http.HandleFunc(\"\/\", dispatch))\n\tcookie := http.Cookie{HttpOnly: true}\n\tcsrf.SetBaseCookie(cookie)\n\tcsrf.SetFailureHandler(http.HandlerFunc(failedCSRF))\n\tif err = http.ListenAndServe(\"127.0.0.1:8000\", csrf); err != nil {\n\t\tlog.Fatalf(\"Cannot listen: %v\", err)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n)\n\nconst (\n\trootDir = \"\/\"\n\twelcomeMessage = \"Welcome to the Go FTP Server\"\n\tUSER = \"USER\"\n\tPASS = \"PASS\"\n)\n\nfunc getMessageFormat(command int) (messageFormat string) {\n\tswitch command {\n\tcase 220:\n\t\tmessageFormat = \"220 %s\"\n\t\tbreak\n\tcase 230:\n\t\tmessageFormat = \"230 %s\"\n\t\tbreak\n\tcase 331:\n\t\tmessageFormat = \"331 %s\"\n\t\tbreak\n\tcase 500:\n\t\tmessageFormat = \"500 %s\"\n\t\tbreak\n\t}\n\treturn messageFormat + \"\\r\\n\"\n}\n\ntype Array struct {\n\tcontainer []interface{}\n}\n\nfunc (a *Array) Append(object interface{}) {\n\tif a.container == nil {\n\t\ta.container = make([]interface{}, 0)\n\t}\n\tnewContainer := make([]interface{}, len(a.container)+1)\n\tcopy(newContainer, a.container)\n\tnewContainer[len(newContainer)-1] = object\n\ta.container = newContainer\n}\n\nfunc (a *Array) Remove(object interface{}) (result bool) {\n\tresult = false\n\tnewContainer := make([]interface{}, len(a.container)-1)\n\ti := 0\n\tfor _, target := range a.container {\n\t\tif target != object {\n\t\t\tnewContainer[i] = target\n\t\t} else {\n\t\t\tresult = true\n\t\t}\n\t\ti++\n\t}\n\treturn\n}\n\ntype FTPServer struct {\n\tname string\n\tlistener *net.TCPListener\n\tconnections *Array\n}\n\nfunc (ftpServer *FTPServer) Listen() (err error) {\n\tfor {\n\t\tftpConn, err := ftpServer.Accept()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tftpServer.connections.Append(ftpConn)\n\t\tterminated := make(chan bool)\n\t\tgo ftpConn.Serve(terminated)\n\t\t<-terminated\n\t\tftpServer.connections.Remove(ftpConn)\n\t\tftpConn.Close()\n\t}\n\treturn\n}\n\nfunc (ftpServer *FTPServer) Accept() (ftpConn *FTPConn, err error) {\n\ttcpConn, err := ftpServer.listener.AcceptTCP()\n\tif err == nil {\n\t\tcontrolReader := bufio.NewReader(tcpConn)\n\t\tcontrolWriter := bufio.NewWriter(tcpConn)\n\t\tftpConn = &FTPConn{\n\t\t\trootDir,\n\t\t\ttcpConn,\n\t\t\tcontrolReader,\n\t\t\tcontrolWriter,\n\t\t\tnil,\n\t\t}\n\t}\n\treturn\n}\n\ntype FTPConn struct {\n\tcwd string\n\tcontrol *net.TCPConn\n\tcontrolReader *bufio.Reader\n\tcontrolWriter *bufio.Writer\n\tdata *net.TCPConn\n}\n\nfunc (ftpConn *FTPConn) WriteMessage(messageFormat string, v ...interface{}) (wrote int, err error) {\n\tmessage := fmt.Sprintf(messageFormat, v...)\n\twrote, err = ftpConn.controlWriter.WriteString(message)\n\tftpConn.controlWriter.Flush()\n\tlog.Print(message)\n\treturn\n}\n\nfunc (ftpConn *FTPConn) Serve(terminated chan bool) {\n\tlog.Print(\"Connection Established\")\n\t\/\/ send welcome\n\tftpConn.WriteMessage(getMessageFormat(220), welcomeMessage)\n\t\/\/ read commands\n\tfor {\n\t\tline, err := ftpConn.controlReader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Print(line)\n\t\tparams := strings.Split(strings.Trim(line, \"\\r\\n\"), \" \")\n\t\tcount := len(params)\n\t\tif count > 0 {\n\t\t\tcommand := params[0]\n\t\t\tswitch command {\n\t\t\tcase USER:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(331), \"User name ok, password required\")\n\t\t\t\tbreak\n\t\t\tcase PASS:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(230), \"Password ok, continue\")\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(500), \"Command not found\")\n\t\t\t}\n\t\t} else {\n\t\t\tftpConn.WriteMessage(getMessageFormat(500), \"Syntax error, zero parameters\")\n\t\t}\n\t}\n\tterminated <- true\n\tlog.Print(\"Connection Terminated\")\n}\n\nfunc (ftpConn *FTPConn) Close() {\n\tftpConn.control.Close()\n\tif ftpConn.data != nil {\n\t\tftpConn.data.Close()\n\t}\n}\n\nfunc main() {\n\tladdr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:3000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlistener, err := net.ListenTCP(\"tcp4\", laddr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tftpServer := &FTPServer{\n\t\t\"Go FTP Server\",\n\t\tlistener,\n\t\tnew(Array),\n\t}\n\tlog.Fatal(ftpServer.Listen())\n}\nremove main function from this packagepackage raval\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n)\n\nconst (\n\trootDir = \"\/\"\n\twelcomeMessage = \"Welcome to the Go FTP Server\"\n\tUSER = \"USER\"\n\tPASS = \"PASS\"\n)\n\nfunc getMessageFormat(command int) (messageFormat string) {\n\tswitch command {\n\tcase 220:\n\t\tmessageFormat = \"220 %s\"\n\t\tbreak\n\tcase 230:\n\t\tmessageFormat = \"230 %s\"\n\t\tbreak\n\tcase 331:\n\t\tmessageFormat = \"331 %s\"\n\t\tbreak\n\tcase 500:\n\t\tmessageFormat = \"500 %s\"\n\t\tbreak\n\t}\n\treturn messageFormat + \"\\r\\n\"\n}\n\ntype Array struct {\n\tcontainer []interface{}\n}\n\nfunc (a *Array) Append(object interface{}) {\n\tif a.container == nil {\n\t\ta.container = make([]interface{}, 0)\n\t}\n\tnewContainer := make([]interface{}, len(a.container)+1)\n\tcopy(newContainer, a.container)\n\tnewContainer[len(newContainer)-1] = object\n\ta.container = newContainer\n}\n\nfunc (a *Array) Remove(object interface{}) (result bool) {\n\tresult = false\n\tnewContainer := make([]interface{}, len(a.container)-1)\n\ti := 0\n\tfor _, target := range a.container {\n\t\tif target != object {\n\t\t\tnewContainer[i] = target\n\t\t} else {\n\t\t\tresult = true\n\t\t}\n\t\ti++\n\t}\n\treturn\n}\n\ntype FTPServer struct {\n\tname string\n\tlistener *net.TCPListener\n\tconnections *Array\n}\n\nfunc (ftpServer *FTPServer) Listen() (err error) {\n\tfor {\n\t\tftpConn, err := ftpServer.Accept()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tftpServer.connections.Append(ftpConn)\n\t\tterminated := make(chan bool)\n\t\tgo ftpConn.Serve(terminated)\n\t\t<-terminated\n\t\tftpServer.connections.Remove(ftpConn)\n\t\tftpConn.Close()\n\t}\n\treturn\n}\n\nfunc (ftpServer *FTPServer) Accept() (ftpConn *FTPConn, err error) {\n\ttcpConn, err := ftpServer.listener.AcceptTCP()\n\tif err == nil {\n\t\tcontrolReader := bufio.NewReader(tcpConn)\n\t\tcontrolWriter := bufio.NewWriter(tcpConn)\n\t\tftpConn = &FTPConn{\n\t\t\trootDir,\n\t\t\ttcpConn,\n\t\t\tcontrolReader,\n\t\t\tcontrolWriter,\n\t\t\tnil,\n\t\t}\n\t}\n\treturn\n}\n\ntype FTPConn struct {\n\tcwd string\n\tcontrol *net.TCPConn\n\tcontrolReader *bufio.Reader\n\tcontrolWriter *bufio.Writer\n\tdata *net.TCPConn\n}\n\nfunc (ftpConn *FTPConn) WriteMessage(messageFormat string, v ...interface{}) (wrote int, err error) {\n\tmessage := fmt.Sprintf(messageFormat, v...)\n\twrote, err = ftpConn.controlWriter.WriteString(message)\n\tftpConn.controlWriter.Flush()\n\tlog.Print(message)\n\treturn\n}\n\nfunc (ftpConn *FTPConn) Serve(terminated chan bool) {\n\tlog.Print(\"Connection Established\")\n\t\/\/ send welcome\n\tftpConn.WriteMessage(getMessageFormat(220), welcomeMessage)\n\t\/\/ read commands\n\tfor {\n\t\tline, err := ftpConn.controlReader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Print(line)\n\t\tparams := strings.Split(strings.Trim(line, \"\\r\\n\"), \" \")\n\t\tcount := len(params)\n\t\tif count > 0 {\n\t\t\tcommand := params[0]\n\t\t\tswitch command {\n\t\t\tcase USER:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(331), \"User name ok, password required\")\n\t\t\t\tbreak\n\t\t\tcase PASS:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(230), \"Password ok, continue\")\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tftpConn.WriteMessage(getMessageFormat(500), \"Command not found\")\n\t\t\t}\n\t\t} else {\n\t\t\tftpConn.WriteMessage(getMessageFormat(500), \"Syntax error, zero parameters\")\n\t\t}\n\t}\n\tterminated <- true\n\tlog.Print(\"Connection Terminated\")\n}\n\nfunc (ftpConn *FTPConn) Close() {\n\tftpConn.control.Close()\n\tif ftpConn.data != nil {\n\t\tftpConn.data.Close()\n\t}\n}\n\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\n\t\"github.com\/eBay\/fabio\/admin\"\n\t\"github.com\/eBay\/fabio\/config\"\n\t\"github.com\/eBay\/fabio\/metrics\"\n\t\"github.com\/eBay\/fabio\/proxy\"\n\t\"github.com\/eBay\/fabio\/registry\"\n\t\"github.com\/eBay\/fabio\/registry\/consul\"\n\t\"github.com\/eBay\/fabio\/registry\/file\"\n\t\"github.com\/eBay\/fabio\/registry\/static\"\n\t\"github.com\/eBay\/fabio\/route\"\n)\n\n\/\/ version contains the version number\n\/\/\n\/\/ It is set by build\/release.sh for tagged releases\n\/\/ so that 'go get' just works.\n\/\/\n\/\/ It is also set by the linker when fabio\n\/\/ is built via the Makefile or the build\/docker.sh\n\/\/ script to ensure the correct version nubmer\nvar version = \"1.1.3rc2\"\n\nfunc main() {\n\tvar filename string\n\tvar v bool\n\tflag.StringVar(&filename, \"cfg\", \"\", \"path to config file\")\n\tflag.BoolVar(&v, \"v\", false, \"show version\")\n\tflag.Parse()\n\n\tif v {\n\t\tfmt.Println(version)\n\t\treturn\n\t}\n\n\tcfg, err := config.Load(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"[FATAL] %s. %s\", version, err)\n\t}\n\n\tlog.Printf(\"[INFO] Runtime config\\n\" + toJSON(cfg))\n\tlog.Printf(\"[INFO] Version %s starting\", version)\n\tlog.Printf(\"[INFO] Go runtime is %s\", runtime.Version())\n\n\tinitRuntime(cfg)\n\tinitMetrics(cfg)\n\tinitBackend(cfg)\n\tgo watchBackend()\n\tstartAdmin(cfg)\n\tstartListeners(cfg.Listen, cfg.Proxy.ShutdownWait, newProxy(cfg))\n\tregistry.Default.Deregister()\n}\n\nfunc newProxy(cfg *config.Config) *proxy.Proxy {\n\tif err := route.SetPickerStrategy(cfg.Proxy.Strategy); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n\tlog.Printf(\"[INFO] Using routing strategy %q\", cfg.Proxy.Strategy)\n\n\tif err := route.SetMatcher(cfg.Proxy.Matcher); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n\tlog.Printf(\"[INFO] Using routing matching %q\", cfg.Proxy.Matcher)\n\n\ttr := &http.Transport{\n\t\tResponseHeaderTimeout: cfg.Proxy.ResponseHeaderTimeout,\n\t\tMaxIdleConnsPerHost: cfg.Proxy.MaxConn,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: cfg.Proxy.DialTimeout,\n\t\t\tKeepAlive: cfg.Proxy.KeepAliveTimeout,\n\t\t}).Dial,\n\t}\n\n\treturn proxy.New(tr, cfg.Proxy)\n}\n\nfunc startAdmin(cfg *config.Config) {\n\tlog.Printf(\"[INFO] Admin server listening on %q\", cfg.UI.Addr)\n\tgo func() {\n\t\tif err := admin.ListenAndServe(cfg, version); err != nil {\n\t\t\tlog.Fatal(\"[FATAL] ui: \", err)\n\t\t}\n\t}()\n}\n\nfunc initMetrics(cfg *config.Config) {\n\tif err := metrics.Init(cfg.Metrics); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n}\n\nfunc initRuntime(cfg *config.Config) {\n\tif os.Getenv(\"GOGC\") == \"\" {\n\t\tlog.Print(\"[INFO] Setting GOGC=\", cfg.Runtime.GOGC)\n\t\tdebug.SetGCPercent(cfg.Runtime.GOGC)\n\t} else {\n\t\tlog.Print(\"[INFO] Using GOGC=\", os.Getenv(\"GOGC\"), \" from env\")\n\t}\n\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\tlog.Print(\"[INFO] Setting GOMAXPROCS=\", cfg.Runtime.GOMAXPROCS)\n\t\truntime.GOMAXPROCS(cfg.Runtime.GOMAXPROCS)\n\t} else {\n\t\tlog.Print(\"[INFO] Using GOMAXPROCS=\", os.Getenv(\"GOMAXPROCS\"), \" from env\")\n\t}\n}\n\nfunc initBackend(cfg *config.Config) {\n\tvar err error\n\n\tswitch cfg.Registry.Backend {\n\tcase \"file\":\n\t\tregistry.Default, err = file.NewBackend(cfg.Registry.File.Path)\n\tcase \"static\":\n\t\tregistry.Default, err = static.NewBackend(cfg.Registry.Static.Routes)\n\tcase \"consul\":\n\t\tregistry.Default, err = consul.NewBackend(&cfg.Registry.Consul)\n\tdefault:\n\t\tlog.Fatal(\"[FATAL] Unknown registry backend \", cfg.Registry.Backend)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(\"[FATAL] Error initializing backend. \", err)\n\t}\n\tif err := registry.Default.Register(); err != nil {\n\t\tlog.Fatal(\"[FATAL] Error registering backend. \", err)\n\t}\n}\n\nfunc watchBackend() {\n\tvar (\n\t\tlast string\n\t\tsvccfg string\n\t\tmancfg string\n\t)\n\n\tsvc := registry.Default.WatchServices()\n\tman := registry.Default.WatchManual()\n\n\tfor {\n\t\tselect {\n\t\tcase svccfg = <-svc:\n\t\tcase mancfg = <-man:\n\t\t}\n\n\t\t\/\/ manual config overrides service config\n\t\t\/\/ order matters\n\t\tnext := svccfg + \"\\n\" + mancfg\n\t\tif next == last {\n\t\t\tcontinue\n\t\t}\n\n\t\tt, err := route.ParseString(next)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[WARN] %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\troute.SetTable(t)\n\n\t\tlast = next\n\t}\n}\n\nfunc toJSON(v interface{}) string {\n\tdata, err := json.MarshalIndent(v, \"\", \" \")\n\tif err != nil {\n\t\tpanic(\"json: \" + err.Error())\n\t}\n\treturn string(data)\n}\nRelease v1.1.3package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\n\t\"github.com\/eBay\/fabio\/admin\"\n\t\"github.com\/eBay\/fabio\/config\"\n\t\"github.com\/eBay\/fabio\/metrics\"\n\t\"github.com\/eBay\/fabio\/proxy\"\n\t\"github.com\/eBay\/fabio\/registry\"\n\t\"github.com\/eBay\/fabio\/registry\/consul\"\n\t\"github.com\/eBay\/fabio\/registry\/file\"\n\t\"github.com\/eBay\/fabio\/registry\/static\"\n\t\"github.com\/eBay\/fabio\/route\"\n)\n\n\/\/ version contains the version number\n\/\/\n\/\/ It is set by build\/release.sh for tagged releases\n\/\/ so that 'go get' just works.\n\/\/\n\/\/ It is also set by the linker when fabio\n\/\/ is built via the Makefile or the build\/docker.sh\n\/\/ script to ensure the correct version nubmer\nvar version = \"1.1.3\"\n\nfunc main() {\n\tvar filename string\n\tvar v bool\n\tflag.StringVar(&filename, \"cfg\", \"\", \"path to config file\")\n\tflag.BoolVar(&v, \"v\", false, \"show version\")\n\tflag.Parse()\n\n\tif v {\n\t\tfmt.Println(version)\n\t\treturn\n\t}\n\n\tcfg, err := config.Load(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"[FATAL] %s. %s\", version, err)\n\t}\n\n\tlog.Printf(\"[INFO] Runtime config\\n\" + toJSON(cfg))\n\tlog.Printf(\"[INFO] Version %s starting\", version)\n\tlog.Printf(\"[INFO] Go runtime is %s\", runtime.Version())\n\n\tinitRuntime(cfg)\n\tinitMetrics(cfg)\n\tinitBackend(cfg)\n\tgo watchBackend()\n\tstartAdmin(cfg)\n\tstartListeners(cfg.Listen, cfg.Proxy.ShutdownWait, newProxy(cfg))\n\tregistry.Default.Deregister()\n}\n\nfunc newProxy(cfg *config.Config) *proxy.Proxy {\n\tif err := route.SetPickerStrategy(cfg.Proxy.Strategy); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n\tlog.Printf(\"[INFO] Using routing strategy %q\", cfg.Proxy.Strategy)\n\n\tif err := route.SetMatcher(cfg.Proxy.Matcher); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n\tlog.Printf(\"[INFO] Using routing matching %q\", cfg.Proxy.Matcher)\n\n\ttr := &http.Transport{\n\t\tResponseHeaderTimeout: cfg.Proxy.ResponseHeaderTimeout,\n\t\tMaxIdleConnsPerHost: cfg.Proxy.MaxConn,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: cfg.Proxy.DialTimeout,\n\t\t\tKeepAlive: cfg.Proxy.KeepAliveTimeout,\n\t\t}).Dial,\n\t}\n\n\treturn proxy.New(tr, cfg.Proxy)\n}\n\nfunc startAdmin(cfg *config.Config) {\n\tlog.Printf(\"[INFO] Admin server listening on %q\", cfg.UI.Addr)\n\tgo func() {\n\t\tif err := admin.ListenAndServe(cfg, version); err != nil {\n\t\t\tlog.Fatal(\"[FATAL] ui: \", err)\n\t\t}\n\t}()\n}\n\nfunc initMetrics(cfg *config.Config) {\n\tif err := metrics.Init(cfg.Metrics); err != nil {\n\t\tlog.Fatal(\"[FATAL] \", err)\n\t}\n}\n\nfunc initRuntime(cfg *config.Config) {\n\tif os.Getenv(\"GOGC\") == \"\" {\n\t\tlog.Print(\"[INFO] Setting GOGC=\", cfg.Runtime.GOGC)\n\t\tdebug.SetGCPercent(cfg.Runtime.GOGC)\n\t} else {\n\t\tlog.Print(\"[INFO] Using GOGC=\", os.Getenv(\"GOGC\"), \" from env\")\n\t}\n\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\tlog.Print(\"[INFO] Setting GOMAXPROCS=\", cfg.Runtime.GOMAXPROCS)\n\t\truntime.GOMAXPROCS(cfg.Runtime.GOMAXPROCS)\n\t} else {\n\t\tlog.Print(\"[INFO] Using GOMAXPROCS=\", os.Getenv(\"GOMAXPROCS\"), \" from env\")\n\t}\n}\n\nfunc initBackend(cfg *config.Config) {\n\tvar err error\n\n\tswitch cfg.Registry.Backend {\n\tcase \"file\":\n\t\tregistry.Default, err = file.NewBackend(cfg.Registry.File.Path)\n\tcase \"static\":\n\t\tregistry.Default, err = static.NewBackend(cfg.Registry.Static.Routes)\n\tcase \"consul\":\n\t\tregistry.Default, err = consul.NewBackend(&cfg.Registry.Consul)\n\tdefault:\n\t\tlog.Fatal(\"[FATAL] Unknown registry backend \", cfg.Registry.Backend)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(\"[FATAL] Error initializing backend. \", err)\n\t}\n\tif err := registry.Default.Register(); err != nil {\n\t\tlog.Fatal(\"[FATAL] Error registering backend. \", err)\n\t}\n}\n\nfunc watchBackend() {\n\tvar (\n\t\tlast string\n\t\tsvccfg string\n\t\tmancfg string\n\t)\n\n\tsvc := registry.Default.WatchServices()\n\tman := registry.Default.WatchManual()\n\n\tfor {\n\t\tselect {\n\t\tcase svccfg = <-svc:\n\t\tcase mancfg = <-man:\n\t\t}\n\n\t\t\/\/ manual config overrides service config\n\t\t\/\/ order matters\n\t\tnext := svccfg + \"\\n\" + mancfg\n\t\tif next == last {\n\t\t\tcontinue\n\t\t}\n\n\t\tt, err := route.ParseString(next)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[WARN] %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\troute.SetTable(t)\n\n\t\tlast = next\n\t}\n}\n\nfunc toJSON(v interface{}) string {\n\tdata, err := json.MarshalIndent(v, \"\", \" \")\n\tif err != nil {\n\t\tpanic(\"json: \" + err.Error())\n\t}\n\treturn string(data)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n \"encoding\/json\"\n \"fmt\"\n \/\/\"html\"\n \"io\/ioutil\"\n \"net\/http\"\n \"os\"\n \"path\/filepath\"\n \"regexp\"\n \/\/\"strconv\"\n \"strings\"\n \"time\"\n)\n\ntype Settings struct {\n RemoteDirectory string\n Address string\n}\n\ntype GameIDs map[string]string\nvar games GameIDs\n\nvar s Settings\nvar re_gamename = regexp.MustCompile(`(.+?)<\/td>`)\n\nfunc main() {\n loadSettings()\n\n if err := init_templates(); err != nil {\n fmt.Printf(\"Error loading templates: %s\\n\", err)\n return\n }\n\n mux := http.NewServeMux()\n mux.HandleFunc(\"\/\", handler_main)\n mux.HandleFunc(\"\/thumb\/\", handler_thumb)\n mux.HandleFunc(\"\/img\/\", handler_image)\n mux.HandleFunc(\"\/banner\/\", handler_banner)\n\n server := &http.Server{\n Addr: s.Address,\n Handler: mux,\n ReadTimeout: 10 * time.Second,\n WriteTimeout: 10 * time.Second,\n MaxHeaderBytes: 1 << 20,\n }\n\n server.ListenAndServe()\n}\n\n\/\/ Returns a list of folders that have screenshot directories\nfunc discover() (map[string][]string, error) {\n loadSettings()\n\n dir, err := filepath.Glob(filepath.Join(s.RemoteDirectory, \"*\"))\n if err != nil {\n return nil, fmt.Errorf(\"Error Globbing: %s\", err)\n }\n\n found := map[string][]string{}\n\n for _, d := range dir {\n if strings.HasPrefix(filepath.Base(d), \".\") {\n continue\n }\n\n dfound := []string{}\n jpg, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.jpg\"))\n if err == nil {\n dfound = append(dfound, jpg...)\n }\n\n png, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.png\"))\n if err == nil {\n dfound = append(dfound, png...)\n }\n\n if len(dfound) > 0 {\n found[filepath.Base(d)] = dfound\n }\n }\n\n return found, nil\n}\n\nfunc SliceContains(s []string, val string) bool {\n for _, v := range s {\n if v == val {\n return true\n }\n }\n return false\n}\n\nfunc GetKeys(m map[string][]string) []string {\n keys := []string{}\n for k, _ := range m {\n keys = append(keys, k)\n }\n\n return keys\n}\n\nfunc loadSettings() error {\n settingsFilename := \"settings.json\"\n if len(os.Args) > 1 {\n settingsFilename = os.Args[1]\n }\n\n settingsFile, err := ioutil.ReadFile(settingsFilename)\n if err != nil {\n return fmt.Errorf(\"Error reading settings file: %s\", err)\n }\n\n err = json.Unmarshal(settingsFile, &s)\n if err != nil {\n return fmt.Errorf(\"Error unmarshaling settings: %s\", err)\n }\n\n return loadGames()\n}\n\nfunc loadGames() error {\n gamesFile, err := ioutil.ReadFile(\"games.json\")\n if err != nil {\n return fmt.Errorf(\"Error reading games file: %s\", err)\n }\n\n err = json.Unmarshal(gamesFile, &games)\n if err != nil {\n return fmt.Errorf(\"Error unmarshaling games: %s\", err)\n }\n\n return nil\n}\n\nfunc getGameName(appid string) (string, error) {\n if appid == \".stfolder\" {\n return appid, nil\n }\n if name, ok := games[appid]; ok {\n return name, nil\n }\n\n fmt.Println(\"[getGameName] Unable to find name for appid: \", appid)\n return appid, nil\n\n \/\/resp, err := http.Get(\"https:\/\/steamdb.info\/app\/\" + appid)\n \/\/if err != nil {\n \/\/ return appid, fmt.Errorf(\"Unable to get appid from steamdb: %s\", err)\n \/\/}\n\n \/\/page, err := ioutil.ReadAll(resp.Body)\n \/\/if err != nil {\n \/\/ return appid, fmt.Errorf(\"Unable to read steamdb response: %s\", err)\n \/\/}\n\n \/\/match := re_gamename.FindSubmatch(page)\n \/\/if len(match) != 2 {\n \/\/ return appid, fmt.Errorf(\"Unable to find game name\")\n \/\/}\n\n \/\/name := html.UnescapeString(string(match[1]))\n \/\/unc, err := strconv.Unquote(name)\n \/\/if err == nil {\n \/\/ name = unc\n \/\/}\n \/\/games[appid] = name\n \/\/fmt.Printf(\"Loaded new appid: [%s] %q\\n\", appid, name)\n\n \/\/marshaled, err := json.MarshalIndent(games, \"\", \" \")\n \/\/if err != nil {\n \/\/ return name, fmt.Errorf(\"Unable to marshal game\")\n \/\/}\n\n \/\/err = ioutil.WriteFile(\"games.json\", marshaled, 0777)\n \/\/if err != nil {\n \/\/ return name, fmt.Errorf(\"Unable to save games.json: %s\", err)\n \/\/}\n\n \/\/return name, nil\n}\n\n\/\/ Returns a filename\nfunc getGameBanner(appid uint64) (string, error) {\n appstr := fmt.Sprintf(\"%d\", appid)\n if exist, _ := exists(\"banners\/\" + appstr + \".jpg\"); exist {\n return \"banners\/\" + appstr + \".jpg\", nil\n }\n\n resp, err := http.Get(\"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/\" + appstr + \"\/header.jpg\")\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to DL header: %s\", err)\n }\n\n if resp.StatusCode >= 400 && resp.StatusCode < 500 {\n \/\/ Game not found. Use unknown.\n\n raw, err := ioutil.ReadFile(\"banners\/unknown.jpg\")\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to read unknown.jpg\")\n }\n\n if err = ioutil.WriteFile(\"banners\/\" + appstr + \".jpg\", raw, 0777); err != nil {\n return \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n }\n\n return \"banners\/\" + appstr + \".jpg\", nil\n }\n\n defer resp.Body.Close()\n\n file, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to read file: %s\", err)\n }\n\n if err = ioutil.WriteFile(\"banners\/\" + appstr + \".jpg\", file, 0777); err != nil {\n return \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n }\n\n return \"banners\/\" + appstr + \".jpg\", nil\n}\n\n\/\/ exists returns whether the given file or directory exists or not.\n\/\/ Taken from https:\/\/stackoverflow.com\/a\/10510783\nfunc exists(path string) (bool, error) {\n _, err := os.Stat(path)\n if err == nil { return true, nil }\n if os.IsNotExist(err) { return false, nil }\n return true, err\n}\nGet game names from steam's serverspackage main\n\nimport (\n \"encoding\/json\"\n \"fmt\"\n \/\/\"html\"\n \"io\/ioutil\"\n \"net\/http\"\n \"os\"\n \"path\/filepath\"\n \"regexp\"\n \/\/\"strconv\"\n \"strings\"\n \"time\"\n)\n\ntype Settings struct {\n RemoteDirectory string\n Address string\n}\n\ntype GameIDs map[string]string\nvar games GameIDs\n\nvar s Settings\nvar re_gamename = regexp.MustCompile(`(.+?)<\/td>`)\n\n\/\/ Structure of json from steam's servers\ntype steamapps struct {\n Applist struct {\n Apps []struct {\n Appid uint64 `json:\"appid\"`\n Name string `json:\"name\"`\n } `json:\"apps\"`\n } `json:\"applist\"`\n}\n\n\nfunc main() {\n loadSettings()\n\n if err := init_templates(); err != nil {\n fmt.Printf(\"Error loading templates: %s\\n\", err)\n return\n }\n\n mux := http.NewServeMux()\n mux.HandleFunc(\"\/\", handler_main)\n mux.HandleFunc(\"\/thumb\/\", handler_thumb)\n mux.HandleFunc(\"\/img\/\", handler_image)\n mux.HandleFunc(\"\/banner\/\", handler_banner)\n\n server := &http.Server{\n Addr: s.Address,\n Handler: mux,\n ReadTimeout: 10 * time.Second,\n WriteTimeout: 10 * time.Second,\n MaxHeaderBytes: 1 << 20,\n }\n\n server.ListenAndServe()\n}\n\n\/\/ Returns a list of folders that have screenshot directories\nfunc discover() (map[string][]string, error) {\n loadSettings()\n\n dir, err := filepath.Glob(filepath.Join(s.RemoteDirectory, \"*\"))\n if err != nil {\n return nil, fmt.Errorf(\"Error Globbing: %s\", err)\n }\n\n found := map[string][]string{}\n\n for _, d := range dir {\n if strings.HasPrefix(filepath.Base(d), \".\") {\n continue\n }\n\n dfound := []string{}\n jpg, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.jpg\"))\n if err == nil {\n dfound = append(dfound, jpg...)\n }\n\n png, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.png\"))\n if err == nil {\n dfound = append(dfound, png...)\n }\n\n if len(dfound) > 0 {\n found[filepath.Base(d)] = dfound\n }\n }\n\n return found, nil\n}\n\nfunc SliceContains(s []string, val string) bool {\n for _, v := range s {\n if v == val {\n return true\n }\n }\n return false\n}\n\nfunc GetKeys(m map[string][]string) []string {\n keys := []string{}\n for k, _ := range m {\n keys = append(keys, k)\n }\n\n return keys\n}\n\nfunc loadSettings() error {\n settingsFilename := \"settings.json\"\n if len(os.Args) > 1 {\n settingsFilename = os.Args[1]\n }\n\n settingsFile, err := ioutil.ReadFile(settingsFilename)\n if err != nil {\n return fmt.Errorf(\"Error reading settings file: %s\", err)\n }\n\n err = json.Unmarshal(settingsFile, &s)\n if err != nil {\n return fmt.Errorf(\"Error unmarshaling settings: %s\", err)\n }\n\n return loadGames()\n}\n\nfunc loadGames() error {\n gamesFile, err := ioutil.ReadFile(\"games.json\")\n if err != nil {\n return fmt.Errorf(\"Error reading games file: %s\", err)\n }\n\n err = json.Unmarshal(gamesFile, &games)\n if err != nil {\n return fmt.Errorf(\"Error unmarshaling games: %s\", err)\n }\n\n return nil\n}\n\nfunc getGameName(appid string) (string, error) {\n if appid == \".stfolder\" {\n return appid, nil\n }\n\n \/\/fmt.Printf(\"Getting name for appid %q\\n\", appid)\n if name, ok := games[appid]; ok {\n return name, nil\n }\n\n \/\/ Large appid, must be a non-steam game. This could have some edge cases\n \/\/ as non-steam games' appids are CRCs.\n if len(appid) > 18 {\n games[appid] = fmt.Sprintf(\"Non-Steam game (%s)\", appid)\n return games[appid], nil\n }\n\n \/\/ TODO: rate limiting\/cache age\n updateGamesJson(appid)\n if name, ok := games[appid]; ok {\n return name, nil\n }\n return appid, nil\n}\n\n\/\/ Update the local cache of appids from steam's servers.\nfunc updateGamesJson(appid string) error {\n fmt.Printf(\"Updating games list; looking for %q\\n\", appid)\n resp, err := http.Get(\"http:\/\/api.steampowered.com\/ISteamApps\/GetAppList\/v2\")\n if err != nil {\n return fmt.Errorf(\"Unable to get appid list from steam: %s\", err)\n }\n defer resp.Body.Close()\n\n js, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n return fmt.Errorf(\"Unable to read appid json: %s\", err)\n }\n\n alist := &steamapps{}\n if err := json.Unmarshal(js, alist); err != nil {\n return fmt.Errorf(\"Unable to unmarshal json: %s\", err)\n }\n\n for _, a := range alist.Applist.Apps {\n id := fmt.Sprintf(\"%d\", a.Appid)\n if _, ok := games[id]; ok {\n if games[id] == id {\n games[id] = a.Name\n }\n } else {\n games[id] = a.Name\n }\n\n if id == appid {\n fmt.Printf(\"Found game for appid %s: %q\\n\", appid, a.Name)\n }\n }\n\n \/\/ save games.json\n marshaled, err := json.MarshalIndent(games, \"\", \" \")\n if err != nil {\n return fmt.Errorf(\"Unable to marshal game json: %s\", err)\n }\n\n err = ioutil.WriteFile(\"games.json\", marshaled, 0777)\n if err != nil {\n return fmt.Errorf(\"Unable to save games.json: %s\", err)\n }\n\n fmt.Printf(\"Finished updating games list. Appids: %d\\n\", len(games))\n return nil\n}\n\n\/\/ Returns a filename\nfunc getGameBanner(appid uint64) (string, error) {\n appstr := fmt.Sprintf(\"%d\", appid)\n if exist, _ := exists(\"banners\/\" + appstr + \".jpg\"); exist {\n return \"banners\/\" + appstr + \".jpg\", nil\n }\n\n resp, err := http.Get(\"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/\" + appstr + \"\/header.jpg\")\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to DL header: %s\", err)\n }\n\n if resp.StatusCode >= 400 && resp.StatusCode < 500 {\n \/\/ Game not found. Use unknown.\n\n raw, err := ioutil.ReadFile(\"banners\/unknown.jpg\")\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to read unknown.jpg\")\n }\n\n if err = ioutil.WriteFile(\"banners\/\" + appstr + \".jpg\", raw, 0777); err != nil {\n return \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n }\n\n return \"banners\/\" + appstr + \".jpg\", nil\n }\n\n defer resp.Body.Close()\n\n file, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n return \"\", fmt.Errorf(\"Unable to read file: %s\", err)\n }\n\n if err = ioutil.WriteFile(\"banners\/\" + appstr + \".jpg\", file, 0777); err != nil {\n return \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n }\n\n return \"banners\/\" + appstr + \".jpg\", nil\n}\n\n\/\/ exists returns whether the given file or directory exists or not.\n\/\/ Taken from https:\/\/stackoverflow.com\/a\/10510783\nfunc exists(path string) (bool, error) {\n _, err := os.Stat(path)\n if err == nil { return true, nil }\n if os.IsNotExist(err) { return false, nil }\n return true, err\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc main() {\n\tif err := newRootCommand().Execute(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc newRootCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"sdb [command]\",\n\t\tShort: \"SDB is collection of utilities for Apache Jackrabbit Oak's Segment Store\",\n\t}\n\tcmd.AddCommand(newTarsCommand())\n\tcmd.AddCommand(newEntriesCommand())\n\tcmd.AddCommand(newSegmentsCommand())\n\tcmd.AddCommand(newSegmentCommand())\n\tcmd.AddCommand(newIndexCommand())\n\tcmd.AddCommand(newGraphCommand())\n\tcmd.AddCommand(newBinariesCommand())\n\treturn cmd\n}\n\nfunc newTarsCommand() *cobra.Command {\n\tvar all bool\n\tcmd := &cobra.Command{\n\t\tUse: \"tars [dir]\",\n\t\tShort: \"Prints the TAR files at the provided path.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tdirectory, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to determine the working directory: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) == 1 {\n\t\t\t\tdirectory = args[0]\n\t\t\t}\n\t\t\tif err := forEachTarFile(directory, all, doPrintTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print TAR files: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&all, \"all\", false, \"List both active and non-active TAR files\")\n\treturn cmd\n}\n\nfunc newEntriesCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"entries file\",\n\t\tShort: \"Prints the entries from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := forEachEntry(args[0], doPrintNameTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print TAR entries: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc newSegmentsCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"segments file\",\n\t\tShort: \"Prints the identifiers of the segments from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := forEachMatchingEntry(args[0], isAnySegment, doPrintSegmentNameTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Unable to print segment IDs: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc newSegmentCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"segment file id\",\n\t\tShort: \"Prints the identifiers of the segments from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) < 2 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) > 2 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isSegment(args[1]), doPrintSegment(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print segment: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newIndexCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"index\",\n\t\tShort: \"Prints the index from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isIndex, doPrintIndex(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print the index: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newGraphCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"graph\",\n\t\tShort: \"Prints the graph from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isGraph, doPrintGraph(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print the graph: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newBinariesCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"binaries\",\n\t\tShort: \"Prints the index of binary references from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isBinary, doPrintBinaries(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Unable to print the index of binary references: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\ntype format string\n\nconst (\n\tformatText format = \"text\"\n\tformatHex format = \"hex\"\n)\n\nfunc (f *format) String() string {\n\treturn string(*f)\n}\n\nfunc (f *format) Set(s string) error {\n\tswitch format(s) {\n\tcase formatHex:\n\t\t*f = formatHex\n\tcase formatText:\n\t\t*f = formatText\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid format '%s'\", s)\n\t}\n\treturn nil\n}\n\nfunc (f *format) Type() string {\n\treturn \"format\"\n}\nFix formatting of output messagespackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc main() {\n\tif err := newRootCommand().Execute(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc newRootCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"sdb [command]\",\n\t\tShort: \"SDB is collection of utilities for Apache Jackrabbit Oak's Segment Store\",\n\t}\n\tcmd.AddCommand(newTarsCommand())\n\tcmd.AddCommand(newEntriesCommand())\n\tcmd.AddCommand(newSegmentsCommand())\n\tcmd.AddCommand(newSegmentCommand())\n\tcmd.AddCommand(newIndexCommand())\n\tcmd.AddCommand(newGraphCommand())\n\tcmd.AddCommand(newBinariesCommand())\n\treturn cmd\n}\n\nfunc newTarsCommand() *cobra.Command {\n\tvar all bool\n\tcmd := &cobra.Command{\n\t\tUse: \"tars [dir]\",\n\t\tShort: \"Prints the TAR files at the provided path.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tdirectory, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to determine the working directory: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) == 1 {\n\t\t\t\tdirectory = args[0]\n\t\t\t}\n\t\t\tif err := forEachTarFile(directory, all, doPrintTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print TAR files: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&all, \"all\", false, \"List both active and non-active TAR files\")\n\treturn cmd\n}\n\nfunc newEntriesCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"entries file\",\n\t\tShort: \"Prints the entries from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := forEachEntry(args[0], doPrintNameTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print TAR entries: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc newSegmentsCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"segments file\",\n\t\tShort: \"Prints the identifiers of the segments from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too many arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := forEachMatchingEntry(args[0], isAnySegment, doPrintSegmentNameTo(os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print segment IDs: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc newSegmentCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"segment file id\",\n\t\tShort: \"Prints the identifiers of the segments from the specified TAR file.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) < 2 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too few arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) > 2 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Too many arguments.\\n\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isSegment(args[1]), doPrintSegment(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print segment: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newIndexCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"index\",\n\t\tShort: \"Prints the index from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too many arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isIndex, doPrintIndex(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print the index: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newGraphCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"graph\",\n\t\tShort: \"Prints the graph from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too many arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isGraph, doPrintGraph(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print the graph: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\nfunc newBinariesCommand() *cobra.Command {\n\tf := formatText\n\tcmd := &cobra.Command{\n\t\tUse: \"binaries\",\n\t\tShort: \"Prints the index of binary references from the specified TAR file\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif len(args) > 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too many arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif len(args) < 1 {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Too few arguments.\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err := onMatchingEntry(args[0], isBinary, doPrintBinaries(f, os.Stdout)); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Unable to print the index of binary references: %v.\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().Var(&f, \"format\", \"Output format (text, hex)\")\n\treturn cmd\n}\n\ntype format string\n\nconst (\n\tformatText format = \"text\"\n\tformatHex format = \"hex\"\n)\n\nfunc (f *format) String() string {\n\treturn string(*f)\n}\n\nfunc (f *format) Set(s string) error {\n\tswitch format(s) {\n\tcase formatHex:\n\t\t*f = formatHex\n\tcase formatText:\n\t\t*f = formatText\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid format '%s'\", s)\n\t}\n\treturn nil\n}\n\nfunc (f *format) Type() string {\n\treturn \"format\"\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/centralmarinsoccer\/teams\/geocode\"\n\t\"github.com\/centralmarinsoccer\/teams\/handler\"\n\t\"github.com\/centralmarinsoccer\/teams\/teamsnap\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/gorilla\/mux\"\n)\n\nconst defaultPort = 8080\nconst urlPath = \"\/teams\/\"\nconst defaultInterval = 60\n\n\/\/ Environment contains all of the required and optional environment variables\ntype Environment struct {\n\tToken string\n\tDivision int\n\tURL string\n\tRefreshInterval time.Duration\n\tGoogleAPIKey\tstring\n}\n\nfunc main() {\n\t\/\/ Make sure we have the appropriate environment variables\n\tvar env Environment\n\tvar ok bool\n\tif env, ok = ValidateEnvs(); !ok {\n\t\tos.Exit(-2)\n\t}\n\n\t\/\/ Create a geocoder\n\tgeocoder := geocode.New(env.GoogleAPIKey)\n\n\tts, err := teamsnap.New(&teamsnap.Configuration{\n\t\tDivision: env.Division,\n\t\tToken: env.Token,\n\t\tGeocoder: geocoder,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create a new TeamSnap. Error: %v\\n\", err)\n\t\tos.Exit(-1)\n\t}\n\n\t\/\/ create a channel to update TeamSnap data\n\tupdate := make(chan bool)\n\n\t\/\/ Setup our HTTP Server\n\th, err := handler.New(ts, update)\n\tif err != nil {\n\t\tlog.Printf(\"Handlers error: %v\\n\", err)\n\t\tos.Exit(-2)\n\t}\n\n\t\/\/mux.Handle(urlPath, h)\n\t\/\/mux.Handle(\"\/metrics\", prometheus.Handler()) \/\/ Add Metrics Handler\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/teams\/\", h)\n\tr.HandleFunc(\"\/teams\/{ID}\", h)\n\tr.Handle(\"\/metrics\", prometheus.Handler()) \/\/ Add Metrics Handler\n\n\tlog.Printf(\"Starting up server at %s%s with data refresh interval of %d for TeamSnap division %d\\n\", env.URL, urlPath, env.RefreshInterval, env.Division)\n\n\tticker := time.NewTicker(env.RefreshInterval * time.Minute)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <- ticker.C:\n\t\t\t\tlog.Println(\"Updating data\")\n\t\t\t\tif ok := ts.Update(); ok {\n\t\t\t\t\tupdate <- true\n\t\t\t\t\tlog.Println(\"Complete\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Failed to update data\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\/\/\thttp.ListenAndServe(env.URL, mux)\n\thttp.ListenAndServe(env.URL, r)\n\n}\n\n\/\/ ValidateEnvs checks to make sure the necessary environment variables are set\nfunc ValidateEnvs() (Environment, bool) {\n\n\tvar env Environment\n\tstate := true\n\n\t\/\/ Required Parameters\n\tvar ok bool\n\tif env.Division, ok = getEnvInt(\"DIVISION\", 0, true); !ok {\n\t\tstate = false\n\t}\n\tif env.Token, ok = getEnvString(\"TOKEN\", \"\", true); !ok {\n\t\tstate = false\n\t}\n\n\tvar port int\n\tvar domain string\n\tif port, ok = getEnvInt(\"PORT\", defaultPort, false); !ok {\n\t\tstate = false\n\t}\n\tif domain, ok = getEnvString(\"DOMAIN\", \"\", false); !ok {\n\t\tstate = false\n\t}\n\n\tif len(domain) != 0 {\n\t\tdomain = \"http:\/\/\" + domain\n\t}\n\tenv.URL = fmt.Sprintf(\"%s:%d\", domain, port)\n\n\tvar interval int\n\tif interval, ok = getEnvInt(\"REFRESHINTERVAL\", defaultInterval, false); ok {\n\t\tenv.RefreshInterval = time.Duration(interval)\n\t} else {\n\t\tstate = false\n\t}\n\n\tif env.GoogleAPIKey, ok = getEnvString(\"GOOGLE_API_KEY\", \"\", true); !ok {\n\t\tstate = false\n\t}\n\n\treturn env, state\n}\n\nfunc getEnvString(name string, defaultVal string, required bool) (string, bool) {\n\tval := os.Getenv(name)\n\tif val == \"\" {\n\t\tif required {\n\t\t\tlog.Printf(\"Missing required environment variable '%s'\\n\", name)\n\t\t\treturn \"\", false\n\t\t}\n\t\treturn defaultVal, true\n\t}\n\n\treturn val, true\n}\n\nfunc getEnvInt(name string, defaultVal int, required bool) (int, bool) {\n\n\tif val, ok := getEnvString(name, \"\", required); ok {\n\t\tif val == \"\" {\n\t\t\treturn defaultVal, true\n\t\t}\n\n\t\ti, err := strconv.Atoi(val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s's value %s is not an integer.\\n\", name, val)\n\t\t\treturn -1, false\n\t\t}\n\t\treturn i, true\n\t}\n\n\treturn -1, false\n}\nNow serves static filespackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/centralmarinsoccer\/teams\/geocode\"\n\t\"github.com\/centralmarinsoccer\/teams\/handler\"\n\t\"github.com\/centralmarinsoccer\/teams\/teamsnap\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/gorilla\/mux\"\n)\n\nconst defaultPort = 8080\nconst urlPath = \"\/teams\/\"\nconst defaultInterval = 60\n\n\/\/ Environment contains all of the required and optional environment variables\ntype Environment struct {\n\tToken string\n\tDivision int\n\tURL string\n\tRefreshInterval time.Duration\n\tGoogleAPIKey\tstring\n}\n\nfunc main() {\n\t\/\/ Make sure we have the appropriate environment variables\n\tvar env Environment\n\tvar ok bool\n\tif env, ok = ValidateEnvs(); !ok {\n\t\tos.Exit(-2)\n\t}\n\n\t\/\/ Create a geocoder\n\tgeocoder := geocode.New(env.GoogleAPIKey)\n\n\tts, err := teamsnap.New(&teamsnap.Configuration{\n\t\tDivision: env.Division,\n\t\tToken: env.Token,\n\t\tGeocoder: geocoder,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create a new TeamSnap. Error: %v\\n\", err)\n\t\tos.Exit(-1)\n\t}\n\n\t\/\/ create a channel to update TeamSnap data\n\tupdate := make(chan bool)\n\n\t\/\/ Setup our HTTP Server\n\th, err := handler.New(ts, update)\n\tif err != nil {\n\t\tlog.Printf(\"Handlers error: %v\\n\", err)\n\t\tos.Exit(-2)\n\t}\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/teams\/\", h)\n\tr.HandleFunc(\"\/teams\/{ID}\", h)\n\tr.Handle(\"\/metrics\", prometheus.Handler()) \/\/ Add Metrics Handler\n\tr.PathPrefix(\"\/teams\/static\/\").Handler(http.StripPrefix(\"\/teams\/static\/\", http.FileServer(http.Dir(\"static\"))))\n\n\t\/\/ Setup timer to refresh TeamSnap data\n\tticker := time.NewTicker(env.RefreshInterval * time.Minute)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <- ticker.C:\n\t\t\t\tlog.Println(\"Updating team data\")\n\t\t\t\tif ok := ts.Update(); ok {\n\t\t\t\t\tupdate <- true\n\t\t\t\t\tlog.Println(\"Complete\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Failed to update data\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tlog.Printf(\"Starting up server at %s%s with data refresh interval of %d for TeamSnap division %d\\n\", env.URL, urlPath, env.RefreshInterval, env.Division)\n\tsrv := &http.Server{\n\t\tHandler: r,\n\t\tAddr: env.URL,\n\t\t\/\/ Good practice: enforce timeouts for servers you create!\n\t\tWriteTimeout: 5 * time.Second,\n\t\tReadTimeout: 5 * time.Second,\n\t}\n\n\tlog.Fatal(srv.ListenAndServe())\n}\n\n\/\/ ValidateEnvs checks to make sure the necessary environment variables are set\nfunc ValidateEnvs() (Environment, bool) {\n\n\tvar env Environment\n\tstate := true\n\n\t\/\/ Required Parameters\n\tvar ok bool\n\tif env.Division, ok = getEnvInt(\"DIVISION\", 0, true); !ok {\n\t\tstate = false\n\t}\n\tif env.Token, ok = getEnvString(\"TOKEN\", \"\", true); !ok {\n\t\tstate = false\n\t}\n\n\tvar port int\n\tvar domain string\n\tif port, ok = getEnvInt(\"PORT\", defaultPort, false); !ok {\n\t\tstate = false\n\t}\n\tif domain, ok = getEnvString(\"DOMAIN\", \"\", false); !ok {\n\t\tstate = false\n\t}\n\n\tif len(domain) != 0 {\n\t\tdomain = \"http:\/\/\" + domain\n\t}\n\tenv.URL = fmt.Sprintf(\"%s:%d\", domain, port)\n\n\tvar interval int\n\tif interval, ok = getEnvInt(\"REFRESHINTERVAL\", defaultInterval, false); ok {\n\t\tenv.RefreshInterval = time.Duration(interval)\n\t} else {\n\t\tstate = false\n\t}\n\n\tif env.GoogleAPIKey, ok = getEnvString(\"GOOGLE_API_KEY\", \"\", true); !ok {\n\t\tstate = false\n\t}\n\n\treturn env, state\n}\n\nfunc getEnvString(name string, defaultVal string, required bool) (string, bool) {\n\tval := os.Getenv(name)\n\tif val == \"\" {\n\t\tif required {\n\t\t\tlog.Printf(\"Missing required environment variable '%s'\\n\", name)\n\t\t\treturn \"\", false\n\t\t}\n\t\treturn defaultVal, true\n\t}\n\n\treturn val, true\n}\n\nfunc getEnvInt(name string, defaultVal int, required bool) (int, bool) {\n\n\tif val, ok := getEnvString(name, \"\", required); ok {\n\t\tif val == \"\" {\n\t\t\treturn defaultVal, true\n\t\t}\n\n\t\ti, err := strconv.Atoi(val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s's value %s is not an integer.\\n\", name, val)\n\t\t\treturn -1, false\n\t\t}\n\t\treturn i, true\n\t}\n\n\treturn -1, false\n}\n<|endoftext|>"} {"text":"package tvdb\n\n\/\/ SeriesRequest is used to request additional series information\ntype SeriesRequest struct {\n\tSeriesID int `json:\"id\"`\n}\n\n\/\/ Series represents a reponse for series information from the TVDB service\ntype Series struct {\n\tAdded string `json:\"added\"`\n\tAirsDayOfWeek string `json:\"airsDayOfWeek\"`\n\tAirsTime string `json:\"airsTime\"`\n\tAliases []string `json:\"aliases\"`\n\tBanner string `json:\"banner\"`\n\tFirstAired string `json:\"firstAired\"`\n\tGenre []string `json:\"genre\"`\n\tID int `json:\"id\"`\n\tImdbID string `json:\"imdbId\"`\n\tLastUpdated int `json:\"lastUpdated\"`\n\tNetwork string `json:\"network\"`\n\tNetworkID string `json:\"networkId\"`\n\tOverview string `json:\"overview\"`\n\tRating string `json:\"rating\"`\n\tRuntime string `json:\"runtime\"`\n\tSeriesID string `json:\"seriesId\"`\n\tSeriesName string `json:\"seriesName\"`\n\tSiteRating float64 `json:\"siteRating\"`\n\tSiteRatingCount int `json:\"siteRatingCount\"`\n\tStatus string `json:\"status\"`\n\tZap2itID string `json:\"zap2itId\"`\n}\n\n\/\/ SeriesData represents the list of responses to get series information\ntype SeriesData struct {\n\tData Series `json:\"data\"`\n\tErrors JSONErrors `json:\"errors,omitempty\"`\n}\n\n\/\/ SeriesEpisodesRequest represents a request to get episode information for a series\ntype SeriesEpisodesRequest struct {\n\tSeriesID int\n\n\t\/* Query parameters *\/\n\tAiredEpisode int `json:\"airedEpisode\"`\n\tAiredSeason int `json:\"airedSeason\"`\n\tDVDEpisode int `json:\"dvdEpisode\"`\n\tDVDSeason int `json:\"dvdSeason\"`\n\tIMDBId int `json:\"imdbId\"`\n}\n\n\/\/ BasicEpisode represents a reponse for episode information from the TVDB service\ntype BasicEpisode struct {\n\tAbsoluteNumber int `json:\"absoluteNumber\"`\n\tAiredEpisodeNumber int `json:\"airedEpisodeNumber\"`\n\tAiredSeason int `json:\"airedSeason\"`\n\tAiredSeasonID int `json:\"airedSeasonID\"`\n\tDVDEpisodeNumber int `json:\"dvdEpisodeNumber\"`\n\tDVDSeason int `json:\"dvdSeason\"`\n\tEpisodeName string `json:\"episodeName\"`\n\tFirstAired string `json:\"firstAired\"`\n\tID int `json:\"id\"`\n\tLastUpdated int `json:\"lastUpdated\"`\n\tOverview string `json:\"overview\"`\n}\n\n\/\/ Links represents the paging information for multiple episode responses\ntype Links struct {\n\tFirstPage int `json:\"first\"`\n\tLastPage int `json:\"last\"`\n\tNextPage int `json:\"next\"`\n\tPreviousPage int `json:\"prev\"`\n}\n\n\/\/ SeriesEpisodes represents the list of responses to get episode information\ntype SeriesEpisodes struct {\n\tLinks Links `json:\"links\"`\n\tData []BasicEpisode `json:\"data\"`\n\tErrors JSONErrors `json:\"errors,omitempty\"`\n}\n\n\/\/ SeriesEpisodesSummary Returns a summary of the episodes and seasons available for the series.\ntype SeriesEpisodesSummary struct {\n\t\/\/ Number of all aired episodes for this series\n\tAiredEpisodes string `json:\"airedEpisodes,omitempty\"`\n\tAiredSeasons []string `json:\"airedSeasons,omitempty\"`\n\t\/\/ Number of all dvd episodes for this series\n\tDvdEpisodes string `json:\"dvdEpisodes,omitempty\"`\n\tDvdSeasons []string `json:\"dvdSeasons,omitempty\"`\n}\n\n\/\/ SeriesActorsData contains information about a single actor\ntype SeriesActorsData struct {\n\tID int `json:\"id\"`\n\tImage string `json:\"image\"`\n\tImageAdded string `json:\"imageAdded\"`\n\tImageAuthor int `json:\"imageAuthor\"`\n\tLastUpdated string `json:\"lastUpdated\"`\n\tName string `json:\"name\"`\n\tRole string `json:\"role\"`\n\tSeriesID int `json:\"seriesId\"`\n\tSortOrder int `json:\"sortOrder\"`\n}\n\n\/\/ SeriesActors is the response of the api when asking for authors\ntype SeriesActors struct {\n\tData []SeriesActorsData `json:\"data\"`\n}\n\n\/\/ SeriesImageQueryRequest used to query images for a given series and type\ntype SeriesImageQueryRequest struct {\n\tSeriesID int `json:\"id\"`\n\tKeyType string `json:\"keyType\"`\n\tResulution string `json:\"resulution\"`\n\tSubKey string `json:\"subKey\"`\n}\n\n\/\/ SeriesImagesCount one single image response\ntype SeriesImagesCount struct {\n\tFileName string `json:\"fileName\"`\n\tID int `json:\"id\"`\n\tKeyType string `json:\"keyType\"`\n\tLanguageID int `json:\"languageId\"`\n\tRatingsInfo map[string]float64 `json:\"ratingsInfo\"`\n\tResolution string `json:\"resulution\"`\n\tSubKey string `json:\"subKey\"`\n\tThumbnail string `json:\"thumbnail\"`\n}\n\n\/\/ SeriesImagesCounts is the response of the api when asking for images\ntype SeriesImagesCounts struct {\n\tData []SeriesImagesCount `json:\"data\"`\n}\nUpdate series.gopackage tvdb\n\n\/\/ SeriesRequest is used to request additional series information\ntype SeriesRequest struct {\n\tSeriesID int `json:\"id\"`\n}\n\n\/\/ Series represents a response for series information from the TVDB service\ntype Series struct {\n\tAdded string `json:\"added\"`\n\tAirsDayOfWeek string `json:\"airsDayOfWeek\"`\n\tAirsTime string `json:\"airsTime\"`\n\tAliases []string `json:\"aliases\"`\n\tBanner string `json:\"banner\"`\n\tFirstAired string `json:\"firstAired\"`\n\tGenre []string `json:\"genre\"`\n\tID int `json:\"id\"`\n\tImdbID string `json:\"imdbId\"`\n\tLastUpdated int `json:\"lastUpdated\"`\n\tNetwork string `json:\"network\"`\n\tNetworkID string `json:\"networkId\"`\n\tOverview string `json:\"overview\"`\n\tRating string `json:\"rating\"`\n\tRuntime string `json:\"runtime\"`\n\tSeriesID string `json:\"seriesId\"`\n\tSeriesName string `json:\"seriesName\"`\n\tSiteRating float64 `json:\"siteRating\"`\n\tSiteRatingCount int `json:\"siteRatingCount\"`\n\tStatus string `json:\"status\"`\n\tZap2itID string `json:\"zap2itId\"`\n}\n\n\/\/ SeriesData represents the list of responses to get series information\ntype SeriesData struct {\n\tData Series `json:\"data\"`\n\tErrors JSONErrors `json:\"errors,omitempty\"`\n}\n\n\/\/ SeriesEpisodesRequest represents a request to get episode information for a series\ntype SeriesEpisodesRequest struct {\n\tSeriesID int\n\n\t\/* Query parameters *\/\n\tAiredEpisode int `json:\"airedEpisode\"`\n\tAiredSeason int `json:\"airedSeason\"`\n\tDVDEpisode int `json:\"dvdEpisode\"`\n\tDVDSeason int `json:\"dvdSeason\"`\n\tIMDBId int `json:\"imdbId\"`\n}\n\n\/\/ BasicEpisode represents a response for episode information from the TVDB service\ntype BasicEpisode struct {\n\tAbsoluteNumber int `json:\"absoluteNumber\"`\n\tAiredEpisodeNumber int `json:\"airedEpisodeNumber\"`\n\tAiredSeason int `json:\"airedSeason\"`\n\tAiredSeasonID int `json:\"airedSeasonID\"`\n\tDVDEpisodeNumber int `json:\"dvdEpisodeNumber\"`\n\tDVDSeason int `json:\"dvdSeason\"`\n\tEpisodeName string `json:\"episodeName\"`\n\tFirstAired string `json:\"firstAired\"`\n\tID int `json:\"id\"`\n\tLastUpdated int `json:\"lastUpdated\"`\n\tOverview string `json:\"overview\"`\n}\n\n\/\/ Links represents the paging information for multiple episode responses\ntype Links struct {\n\tFirstPage int `json:\"first\"`\n\tLastPage int `json:\"last\"`\n\tNextPage int `json:\"next\"`\n\tPreviousPage int `json:\"prev\"`\n}\n\n\/\/ SeriesEpisodes represents the list of responses to get episode information\ntype SeriesEpisodes struct {\n\tLinks Links `json:\"links\"`\n\tData []BasicEpisode `json:\"data\"`\n\tErrors JSONErrors `json:\"errors,omitempty\"`\n}\n\n\/\/ SeriesEpisodesSummary Returns a summary of the episodes and seasons available for the series.\ntype SeriesEpisodesSummary struct {\n\t\/\/ Number of all aired episodes for this series\n\tAiredEpisodes string `json:\"airedEpisodes,omitempty\"`\n\tAiredSeasons []string `json:\"airedSeasons,omitempty\"`\n\t\/\/ Number of all dvd episodes for this series\n\tDvdEpisodes string `json:\"dvdEpisodes,omitempty\"`\n\tDvdSeasons []string `json:\"dvdSeasons,omitempty\"`\n}\n\n\/\/ SeriesActorsData contains information about a single actor\ntype SeriesActorsData struct {\n\tID int `json:\"id\"`\n\tImage string `json:\"image\"`\n\tImageAdded string `json:\"imageAdded\"`\n\tImageAuthor int `json:\"imageAuthor\"`\n\tLastUpdated string `json:\"lastUpdated\"`\n\tName string `json:\"name\"`\n\tRole string `json:\"role\"`\n\tSeriesID int `json:\"seriesId\"`\n\tSortOrder int `json:\"sortOrder\"`\n}\n\n\/\/ SeriesActors is the response of the api when asking for authors\ntype SeriesActors struct {\n\tData []SeriesActorsData `json:\"data\"`\n}\n\n\/\/ SeriesImageQueryRequest used to query images for a given series and type\ntype SeriesImageQueryRequest struct {\n\tSeriesID int `json:\"id\"`\n\tKeyType string `json:\"keyType\"`\n\tResulution string `json:\"resulution\"`\n\tSubKey string `json:\"subKey\"`\n}\n\n\/\/ SeriesImagesCount one single image response\ntype SeriesImagesCount struct {\n\tFileName string `json:\"fileName\"`\n\tID int `json:\"id\"`\n\tKeyType string `json:\"keyType\"`\n\tLanguageID int `json:\"languageId\"`\n\tRatingsInfo map[string]float64 `json:\"ratingsInfo\"`\n\tResolution string `json:\"resulution\"`\n\tSubKey string `json:\"subKey\"`\n\tThumbnail string `json:\"thumbnail\"`\n}\n\n\/\/ SeriesImagesCounts is the response of the api when asking for images\ntype SeriesImagesCounts struct {\n\tData []SeriesImagesCount `json:\"data\"`\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/robvanmieghem\/go-opencl\/cl\"\n\t\"github.com\/robvanmieghem\/gominer\/clients\"\n)\n\n\/\/Version is the released version string of gominer\nvar Version = \"0.5-Dev\"\n\nvar intensity = 28\nvar devicesTypesForMining = cl.DeviceTypeGPU\n\nconst maxUint32 = int64(^uint32(0))\n\nfunc createWork(siaclient clients.SiaClient, miningWorkChannel chan *MiningWork, nrOfMiningDevices int, globalItemSize int) {\n\tsiaclient.Start()\n\tfor {\n\t\ttarget, header, jobStillValid, job, err := siaclient.GetHeaderForWork()\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR fetching work -\", err)\n\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/copy target to header\n\t\tfor i := 0; i < 8; i++ {\n\t\t\theader[i+32] = target[7-i]\n\t\t}\n\t\t\/\/Fill the workchannel with work\n\t\t\/\/ Only generate nonces for a 32 bit space (since gpu's are mostly 32 bit)\n\t\tfor i := int64(0); i*int64(globalItemSize) < (maxUint32 - int64(globalItemSize)); i++ {\n\t\t\t\/\/Do not continue mining the 32 bit nonce space if the current job is deprecated\n\t\t\tselect {\n\t\t\tcase <-jobStillValid:\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tminingWorkChannel <- &MiningWork{header, int(i) * globalItemSize, job}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tprintVersion := flag.Bool(\"v\", false, \"Show version and exit\")\n\tuseCPU := flag.Bool(\"cpu\", false, \"If set, also use the CPU for mining, only GPU's are used by default\")\n\tflag.IntVar(&intensity, \"I\", intensity, \"Intensity\")\n\tsiadHost := flag.String(\"url\", \"localhost:9980\", \"siad host and port, for stratum servers, use `stratum+tcp:\/\/:`\")\n\tpooluser := flag.String(\"user\", \"payoutaddress.rigname\", \"username, most stratum servers take this in the form [payoutaddress].[rigname]\")\n\texcludedGPUs := flag.String(\"E\", \"\", \"Exclude GPU's: comma separated list of devicenumbers\")\n\tflag.Parse()\n\n\tif *printVersion {\n\t\tfmt.Println(\"gominer version\", Version)\n\t\tos.Exit(0)\n\t}\n\n\tsiaclient := clients.NewSiaClient(*siadHost, *pooluser)\n\n\tif *useCPU {\n\t\tdevicesTypesForMining = cl.DeviceTypeAll\n\t}\n\tglobalItemSize := int(math.Exp2(float64(intensity)))\n\n\tplatforms, err := cl.GetPlatforms()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tclDevices := make([]*cl.Device, 0, 4)\n\tfor _, platform := range platforms {\n\t\tlog.Println(\"Platform\", platform.Name())\n\t\tplatormDevices, err := cl.GetDevices(platform, devicesTypesForMining)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tlog.Println(len(platormDevices), \"device(s) found:\")\n\t\tfor i, device := range platormDevices {\n\t\t\tlog.Println(i, \"-\", device.Type(), \"-\", device.Name())\n\t\t\tclDevices = append(clDevices, device)\n\t\t}\n\t}\n\n\tnrOfMiningDevices := len(clDevices)\n\n\tif nrOfMiningDevices == 0 {\n\t\tlog.Println(\"No suitable opencl devices found\")\n\t\tos.Exit(1)\n\t}\n\n\t\/\/Start fetching work\n\tworkChannel := make(chan *MiningWork, nrOfMiningDevices)\n\tgo createWork(siaclient, workChannel, nrOfMiningDevices, globalItemSize)\n\n\t\/\/Start mining routines\n\tvar hashRateReportsChannel = make(chan *HashRateReport, nrOfMiningDevices*10)\n\tfor i, device := range clDevices {\n\t\tif deviceExcludedForMining(i, *excludedGPUs) {\n\t\t\tcontinue\n\t\t}\n\t\tminer := &Miner{\n\t\t\tclDevice: device,\n\t\t\tminerID: i,\n\t\t\thashRateReports: hashRateReportsChannel,\n\t\t\tminingWorkChannel: workChannel,\n\t\t\tGlobalItemSize: globalItemSize,\n\t\t\tsiad: siaclient,\n\t\t}\n\t\tgo miner.mine()\n\t}\n\n\t\/\/Start printing out the hashrates of the different gpu's\n\thashRateReports := make([]float64, nrOfMiningDevices)\n\tfor {\n\t\t\/\/No need to print at every hashreport, we have time\n\t\tfor i := 0; i < nrOfMiningDevices; i++ {\n\t\t\treport := <-hashRateReportsChannel\n\t\t\thashRateReports[report.MinerID] = report.HashRate\n\t\t}\n\t\tfmt.Print(\"\\r\")\n\t\tvar totalHashRate float64\n\t\tfor minerID, hashrate := range hashRateReports {\n\t\t\tfmt.Printf(\"%d-%.1f \", minerID, hashrate)\n\t\t\ttotalHashRate += hashrate\n\t\t}\n\t\tfmt.Printf(\"Total: %.1f MH\/s \", totalHashRate)\n\n\t}\n}\n\n\/\/deviceExcludedForMining checks if the device is in the exclusion list\nfunc deviceExcludedForMining(deviceID int, excludedGPUs string) bool {\n\texcludedGPUList := strings.Split(excludedGPUs, \",\")\n\tfor _, excludedGPU := range excludedGPUList {\n\t\tif strconv.Itoa(deviceID) == excludedGPU {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\nForgot to break outpackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/robvanmieghem\/go-opencl\/cl\"\n\t\"github.com\/robvanmieghem\/gominer\/clients\"\n)\n\n\/\/Version is the released version string of gominer\nvar Version = \"0.5-Dev\"\n\nvar intensity = 28\nvar devicesTypesForMining = cl.DeviceTypeGPU\n\nconst maxUint32 = int64(^uint32(0))\n\nfunc createWork(siaclient clients.SiaClient, miningWorkChannel chan *MiningWork, nrOfMiningDevices int, globalItemSize int) {\n\tsiaclient.Start()\n\tfor {\n\t\ttarget, header, deprecationChannel, job, err := siaclient.GetHeaderForWork()\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR fetching work -\", err)\n\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/copy target to header\n\t\tfor i := 0; i < 8; i++ {\n\t\t\theader[i+32] = target[7-i]\n\t\t}\n\t\t\/\/Fill the workchannel with work\n\t\t\/\/ Only generate nonces for a 32 bit space (since gpu's are mostly 32 bit)\n\t\tfor i := int64(0); i*int64(globalItemSize) < (maxUint32 - int64(globalItemSize)); i++ {\n\t\t\t\/\/Do not continue mining the 32 bit nonce space if the current job is deprecated\n\t\t\tselect {\n\t\t\tcase <-deprecationChannel:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tminingWorkChannel <- &MiningWork{header, int(i) * globalItemSize, job}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tprintVersion := flag.Bool(\"v\", false, \"Show version and exit\")\n\tuseCPU := flag.Bool(\"cpu\", false, \"If set, also use the CPU for mining, only GPU's are used by default\")\n\tflag.IntVar(&intensity, \"I\", intensity, \"Intensity\")\n\tsiadHost := flag.String(\"url\", \"localhost:9980\", \"siad host and port, for stratum servers, use `stratum+tcp:\/\/:`\")\n\tpooluser := flag.String(\"user\", \"payoutaddress.rigname\", \"username, most stratum servers take this in the form [payoutaddress].[rigname]\")\n\texcludedGPUs := flag.String(\"E\", \"\", \"Exclude GPU's: comma separated list of devicenumbers\")\n\tflag.Parse()\n\n\tif *printVersion {\n\t\tfmt.Println(\"gominer version\", Version)\n\t\tos.Exit(0)\n\t}\n\n\tsiaclient := clients.NewSiaClient(*siadHost, *pooluser)\n\n\tif *useCPU {\n\t\tdevicesTypesForMining = cl.DeviceTypeAll\n\t}\n\tglobalItemSize := int(math.Exp2(float64(intensity)))\n\n\tplatforms, err := cl.GetPlatforms()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tclDevices := make([]*cl.Device, 0, 4)\n\tfor _, platform := range platforms {\n\t\tlog.Println(\"Platform\", platform.Name())\n\t\tplatormDevices, err := cl.GetDevices(platform, devicesTypesForMining)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tlog.Println(len(platormDevices), \"device(s) found:\")\n\t\tfor i, device := range platormDevices {\n\t\t\tlog.Println(i, \"-\", device.Type(), \"-\", device.Name())\n\t\t\tclDevices = append(clDevices, device)\n\t\t}\n\t}\n\n\tnrOfMiningDevices := len(clDevices)\n\n\tif nrOfMiningDevices == 0 {\n\t\tlog.Println(\"No suitable opencl devices found\")\n\t\tos.Exit(1)\n\t}\n\n\t\/\/Start fetching work\n\tworkChannel := make(chan *MiningWork, nrOfMiningDevices)\n\tgo createWork(siaclient, workChannel, nrOfMiningDevices, globalItemSize)\n\n\t\/\/Start mining routines\n\tvar hashRateReportsChannel = make(chan *HashRateReport, nrOfMiningDevices*10)\n\tfor i, device := range clDevices {\n\t\tif deviceExcludedForMining(i, *excludedGPUs) {\n\t\t\tcontinue\n\t\t}\n\t\tminer := &Miner{\n\t\t\tclDevice: device,\n\t\t\tminerID: i,\n\t\t\thashRateReports: hashRateReportsChannel,\n\t\t\tminingWorkChannel: workChannel,\n\t\t\tGlobalItemSize: globalItemSize,\n\t\t\tsiad: siaclient,\n\t\t}\n\t\tgo miner.mine()\n\t}\n\n\t\/\/Start printing out the hashrates of the different gpu's\n\thashRateReports := make([]float64, nrOfMiningDevices)\n\tfor {\n\t\t\/\/No need to print at every hashreport, we have time\n\t\tfor i := 0; i < nrOfMiningDevices; i++ {\n\t\t\treport := <-hashRateReportsChannel\n\t\t\thashRateReports[report.MinerID] = report.HashRate\n\t\t}\n\t\tfmt.Print(\"\\r\")\n\t\tvar totalHashRate float64\n\t\tfor minerID, hashrate := range hashRateReports {\n\t\t\tfmt.Printf(\"%d-%.1f \", minerID, hashrate)\n\t\t\ttotalHashRate += hashrate\n\t\t}\n\t\tfmt.Printf(\"Total: %.1f MH\/s \", totalHashRate)\n\n\t}\n}\n\n\/\/deviceExcludedForMining checks if the device is in the exclusion list\nfunc deviceExcludedForMining(deviceID int, excludedGPUs string) bool {\n\texcludedGPUList := strings.Split(excludedGPUs, \",\")\n\tfor _, excludedGPU := range excludedGPUList {\n\t\tif strconv.Itoa(deviceID) == excludedGPU {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Rana Ian. All rights reserved.\n\/\/ Use of this source code is governed by The MIT License\n\/\/ found in the accompanying LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ranaian\/ora\"\n)\n\nfunc main() {\n\t\/\/ example usage of the ora package driver\n\t\/\/ connect to a server and open a session\n\tenv, _ := ora.GetDrv().OpenEnv()\n\tdefer env.Close()\n\tsrv, err := env.OpenSrv(\"orcl\")\n\tdefer srv.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tses, err := srv.OpenSes(\"test\", \"test\")\n\tdefer ses.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ create table\n\ttableName := \"t1\"\n\tstmtTbl, err := ses.Prep(fmt.Sprintf(\"CREATE TABLE %v \"+\n\t\t\"(C1 NUMBER(19,0) GENERATED ALWAYS AS IDENTITY \"+\n\t\t\"(START WITH 1 INCREMENT BY 1), C2 VARCHAR2(48 CHAR))\", tableName))\n\tdefer stmtTbl.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err := stmtTbl.Exe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ begin first transaction\n\ttx1, err := ses.StartTx()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ insert record\n\tvar id uint64\n\tstr := \"Go is expressive, concise, clean, and efficient.\"\n\tstmtIns, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2) RETURNING C1 INTO :C1\", tableName))\n\tdefer stmtIns.Close()\n\trowsAffected, err = stmtIns.Exe(str, &id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ insert nullable String slice\n\ta := make([]ora.String, 4)\n\ta[0] = ora.String{Value: \"Its concurrency mechanisms make it easy to\"}\n\ta[1] = ora.String{IsNull: true}\n\ta[2] = ora.String{Value: \"It's a fast, statically typed, compiled\"}\n\ta[3] = ora.String{Value: \"One of Go's key design goals is code\"}\n\tstmtSliceIns, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2)\", tableName))\n\tdefer stmtSliceIns.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err = stmtSliceIns.Exe(a)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ fetch records\n\tstmtQry, err := ses.Prep(fmt.Sprintf(\n\t\t\"SELECT C1, C2 FROM %v\", tableName))\n\tdefer stmtQry.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trset, err := stmtQry.Qry()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor rset.Next() {\n\t\tfmt.Println(rset.Row[0], rset.Row[1])\n\t}\n\tif rset.Err != nil {\n\t\tpanic(rset.Err)\n\t}\n\n\t\/\/ commit first transaction\n\terr = tx1.Commit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ begin second transaction\n\ttx2, err := ses.StartTx()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ insert null String\n\tnullableStr := ora.String{IsNull: true}\n\tstmtTrans, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2)\", tableName))\n\tdefer stmtTrans.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err = stmtTrans.Exe(nullableStr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\t\/\/ rollback second transaction\n\terr = tx2.Rollback()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ fetch and specify return type\n\tstmtCount, err := ses.Prep(fmt.Sprintf(\n\t\t\"SELECT COUNT(C1) FROM %v WHERE C2 IS NULL\", tableName), ora.U8)\n\tdefer stmtCount.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trset, err = stmtCount.Qry()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trow := rset.NextRow()\n\tif row != nil {\n\t\tfmt.Println(row[0])\n\t}\n\tif rset.Err != nil {\n\t\tpanic(rset.Err)\n\t}\n\n\t\/\/ create stored procedure with sys_refcursor\n\tstmtProcCreate, err := ses.Prep(fmt.Sprintf(\n\t\t\"CREATE OR REPLACE PROCEDURE PROC1(P1 OUT SYS_REFCURSOR) AS BEGIN \"+\n\t\t\t\"OPEN P1 FOR SELECT C1, C2 FROM %v WHERE C1 > 2 ORDER BY C1; \"+\n\t\t\t\"END PROC1;\",\n\t\ttableName))\n\tdefer stmtProcCreate.Close()\n\trowsAffected, err = stmtProcCreate.Exe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ call stored procedure\n\t\/\/ pass *Rset to Exe to receive the results of a sys_refcursor\n\tstmtProcCall, err := ses.Prep(\"CALL PROC1(:1)\")\n\tdefer stmtProcCall.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprocRset := &ora.Rset{}\n\trowsAffected, err = stmtProcCall.Exe(procRset)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif procRset.IsOpen() {\n\t\tfor procRset.Next() {\n\t\t\tfmt.Println(procRset.Row[0], procRset.Row[1])\n\t\t}\n\t\tif procRset.Err != nil {\n\t\t\tpanic(procRset.Err)\n\t\t}\n\t\tfmt.Println(procRset.Len())\n\t}\n\n\t\/\/ Output:\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 4\n\t\/\/ 1 Go is expressive, concise, clean, and efficient.\n\t\/\/ 2 Its concurrency mechanisms make it easy to\n\t\/\/ 3 \n\t\/\/ 4 It's a fast, statically typed, compiled\n\t\/\/ 5 One of Go's key design goals is code\n\t\/\/ 1\n\t\/\/ 1\n\t\/\/ 3 \n\t\/\/ 4 It's a fast, statically typed, compiled\n\t\/\/ 5 One of Go's key design goals is code\n\t\/\/ 3\n}\nrevised sample code\/\/ Copyright 2014 Rana Ian. All rights reserved.\n\/\/ Use of this source code is governed by The MIT License\n\/\/ found in the accompanying LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ranaian\/ora\"\n)\n\nfunc main() {\n\t\/\/ example usage of the ora package driver\n\t\/\/ connect to a server and open a session\n\tenv, err := ora.GetDrv().OpenEnv()\n\tdefer env.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsrv, err := env.OpenSrv(\"orcl\")\n\tdefer srv.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tses, err := srv.OpenSes(\"test\", \"test\")\n\tdefer ses.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ create table\n\ttableName := \"t1\"\n\tstmtTbl, err := ses.Prep(fmt.Sprintf(\"CREATE TABLE %v \"+\n\t\t\"(C1 NUMBER(19,0) GENERATED ALWAYS AS IDENTITY \"+\n\t\t\"(START WITH 1 INCREMENT BY 1), C2 VARCHAR2(48 CHAR))\", tableName))\n\tdefer stmtTbl.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err := stmtTbl.Exe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ begin first transaction\n\ttx1, err := ses.StartTx()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ insert record\n\tvar id uint64\n\tstr := \"Go is expressive, concise, clean, and efficient.\"\n\tstmtIns, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2) RETURNING C1 INTO :C1\", tableName))\n\tdefer stmtIns.Close()\n\trowsAffected, err = stmtIns.Exe(str, &id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ insert nullable String slice\n\ta := make([]ora.String, 4)\n\ta[0] = ora.String{Value: \"Its concurrency mechanisms make it easy to\"}\n\ta[1] = ora.String{IsNull: true}\n\ta[2] = ora.String{Value: \"It's a fast, statically typed, compiled\"}\n\ta[3] = ora.String{Value: \"One of Go's key design goals is code\"}\n\tstmtSliceIns, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2)\", tableName))\n\tdefer stmtSliceIns.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err = stmtSliceIns.Exe(a)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\n\t\/\/ fetch records\n\tstmtQry, err := ses.Prep(fmt.Sprintf(\n\t\t\"SELECT C1, C2 FROM %v\", tableName))\n\tdefer stmtQry.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trset, err := stmtQry.Qry()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor rset.Next() {\n\t\tfmt.Println(rset.Row[0], rset.Row[1])\n\t}\n\tif rset.Err != nil {\n\t\tpanic(rset.Err)\n\t}\n\n\t\/\/ commit first transaction\n\terr = tx1.Commit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ begin second transaction\n\ttx2, err := ses.StartTx()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ insert null String\n\tnullableStr := ora.String{IsNull: true}\n\tstmtTrans, err := ses.Prep(fmt.Sprintf(\n\t\t\"INSERT INTO %v (C2) VALUES (:C2)\", tableName))\n\tdefer stmtTrans.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trowsAffected, err = stmtTrans.Exe(nullableStr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rowsAffected)\n\t\/\/ rollback second transaction\n\terr = tx2.Rollback()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ fetch and specify return type\n\tstmtCount, err := ses.Prep(fmt.Sprintf(\n\t\t\"SELECT COUNT(C1) FROM %v WHERE C2 IS NULL\", tableName), ora.U8)\n\tdefer stmtCount.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trset, err = stmtCount.Qry()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trow := rset.NextRow()\n\tif row != nil {\n\t\tfmt.Println(row[0])\n\t}\n\tif rset.Err != nil {\n\t\tpanic(rset.Err)\n\t}\n\n\t\/\/ create stored procedure with sys_refcursor\n\tstmtProcCreate, err := ses.Prep(fmt.Sprintf(\n\t\t\"CREATE OR REPLACE PROCEDURE PROC1(P1 OUT SYS_REFCURSOR) AS BEGIN \"+\n\t\t\t\"OPEN P1 FOR SELECT C1, C2 FROM %v WHERE C1 > 2 ORDER BY C1; \"+\n\t\t\t\"END PROC1;\",\n\t\ttableName))\n\tdefer stmtProcCreate.Close()\n\trowsAffected, err = stmtProcCreate.Exe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ call stored procedure\n\t\/\/ pass *Rset to Exe to receive the results of a sys_refcursor\n\tstmtProcCall, err := ses.Prep(\"CALL PROC1(:1)\")\n\tdefer stmtProcCall.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tprocRset := &ora.Rset{}\n\trowsAffected, err = stmtProcCall.Exe(procRset)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif procRset.IsOpen() {\n\t\tfor procRset.Next() {\n\t\t\tfmt.Println(procRset.Row[0], procRset.Row[1])\n\t\t}\n\t\tif procRset.Err != nil {\n\t\t\tpanic(procRset.Err)\n\t\t}\n\t\tfmt.Println(procRset.Len())\n\t}\n\n\t\/\/ Output:\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 4\n\t\/\/ 1 Go is expressive, concise, clean, and efficient.\n\t\/\/ 2 Its concurrency mechanisms make it easy to\n\t\/\/ 3 \n\t\/\/ 4 It's a fast, statically typed, compiled\n\t\/\/ 5 One of Go's key design goals is code\n\t\/\/ 1\n\t\/\/ 1\n\t\/\/ 3 \n\t\/\/ 4 It's a fast, statically typed, compiled\n\t\/\/ 5 One of Go's key design goals is code\n\t\/\/ 3\n}\n<|endoftext|>"} {"text":"package steamscreenshots\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/big\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Settings struct {\n\tRemoteDirectory string\n\tAddress string\n\tAppidOverrides []struct {\n\t\tAppid string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t}\n\tRefreshInterval int \/\/ In minutes\n\tApiKey string \/\/ This will be regenerated if it is empty.\n}\n\nvar re_gamename = regexp.MustCompile(`(.+?)<\/td>`)\n\nvar (\n\tgitCommit string\n\tversion string\n)\n\n\/\/ Structure of json from steam's servers\ntype steamapps struct {\n\tApplist struct {\n\t\tApps []struct {\n\t\t\tAppid uint64 `json:\"appid\"`\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"apps\"`\n\t} `json:\"applist\"`\n}\n\ntype Server struct {\n\t\/\/ stats stuff\n\tstartTime time.Time\n\tlastScan time.Time\n\n\tlastUpdate *time.Time\n\n\tsettings Settings\n\n\tGames *GameList\n\tImageCache *GameImages\n\n\tSettingsFile string\n}\n\nfunc (s *Server) Run() {\n\tfmt.Println(\"Starting server\")\n\n\tif len(gitCommit) == 0 {\n\t\tgitCommit = \"Missing commit hash\"\n\t}\n\n\tif len(version) == 0 {\n\t\tversion = \"Missing version info\"\n\t}\n\tfmt.Printf(\"%s@%s\\n\", version, gitCommit)\n\n\ts.startTime = time.Now()\n\ts.Games = NewGameList()\n\n\tif err := s.loadSettings(); err != nil {\n\t\tfmt.Printf(\"Error loading settings: %s\\n\", err)\n\t\treturn\n\t}\n\n\tif err := init_templates(); err != nil {\n\t\tfmt.Printf(\"Error loading templates: %s\\n\", err)\n\t\treturn\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/\", s.handler_main)\n\tmux.HandleFunc(\"\/thumb\/\", s.handler_thumb)\n\tmux.HandleFunc(\"\/img\/\", s.handler_image)\n\tmux.HandleFunc(\"\/banner\/\", s.handler_banner)\n\tmux.HandleFunc(\"\/static\/\", s.handler_static)\n\tmux.HandleFunc(\"\/debug\/\", s.handler_debug)\n\tmux.HandleFunc(\"\/api\/get-cache\", s.handler_api_cache)\n\tmux.HandleFunc(\"\/api\/get-games\", s.handler_api_games)\n\tmux.HandleFunc(\"\/api\/add-image\", s.handler_api_addImage)\n\n\tserver := &http.Server{\n\t\tAddr: s.settings.Address,\n\t\tHandler: mux,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tvar err error\n\ts.ImageCache, err = LoadImageCache(\"image.cache\")\n\tif err != nil {\n\t\tfmt.Println(\"Unable to load image.cache: \", err)\n\n\t\ts.ImageCache = NewGameImages()\n\t\terr = s.scan(true)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Initial scan error: \", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Refreshing RemoteDirectory...\")\n\t\tif err = s.scan(true); err != nil {\n\t\t\tfmt.Println(\"Error refreshing RemoteDirectory: \", err)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Println(\"Initial scan OK\")\n\n\t\/\/ Fire and forget. TODO: graceful shutdown\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Minute * time.Duration(s.settings.RefreshInterval))\n\t\t\tif err := s.scan(false); err != nil {\n\t\t\t\tfmt.Printf(\"Error scanning: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Generate a new API key if it's empty\n\tif s.settings.ApiKey == \"\" {\n\t\tout := \"\"\n\t\tlarge := big.NewInt(int64(1 << 60))\n\t\tlarge = large.Add(large, large)\n\t\tfor len(out) < 50 {\n\t\t\tnum, err := rand.Int(rand.Reader, large)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Error generating session key: \" + err.Error())\n\t\t\t}\n\t\t\tout = fmt.Sprintf(\"%s%X\", out, num)\n\t\t}\n\t\ts.settings.ApiKey = out\n\t\tfmt.Println(\"New API key generated: \" + s.settings.ApiKey)\n\t} else {\n\t\tfmt.Printf(\"using API key in config: %q\\n\", s.settings.ApiKey)\n\t}\n\n\tgo func(s *Server) {\n\t\tfor {\n\t\t\ts.ImageCache.Save(\"image.cache\")\n\t\t\ttime.Sleep(10 * time.Minute)\n\t\t}\n\t}(s)\n\n\tfmt.Println(\"Listening on address: \" + s.settings.Address)\n\tfmt.Println(\"Fisnished startup.\")\n\tserver.ListenAndServe()\n}\n\n\/\/ TODO: use GameImages.FullScan for this?\nfunc (s *Server) scan(printOutput bool) error {\n\ts.lastScan = time.Now()\n\n\tif printOutput {\n\t\tfmt.Printf(\"Scanning %q\\n\", s.settings.RemoteDirectory)\n\t}\n\n\tdir, err := filepath.Glob(filepath.Join(s.settings.RemoteDirectory, \"*\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to glob RemoteDirectory: %s\", err)\n\t}\n\ttmpTree := make(map[string][]string)\n\n\tfor _, d := range dir {\n\t\tbase := filepath.Base(d)\n\n\t\t\/\/ Ignore dotfiles\n\t\tif strings.HasPrefix(base, \".\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif printOutput {\n\t\t\tfmt.Printf(\"[%s] %s\\n\", base, s.Games.Get(base))\n\t\t}\n\n\t\tjpg, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.jpg\"))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"JPG glob error in %q: %s\", d, err)\n\t\t\tcontinue\n\t\t}\n\t\ttmpTree[base] = jpg\n\n\t\t\/\/ TODO: merge ImageCache.ScanPath() and ImagePath.RefreshPath(), possibly removing the jpg glob above as well.\n\t\terr = s.ImageCache.ScanPath(d)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\t\/\/ Write cache to disk after it's updated in-memory so failing this doesn't skip updating.\n\tif err := s.ImageCache.Save(\"image.cache\"); err != nil {\n\t\treturn fmt.Errorf(\"Unable to save image cache: %s\\n\", err)\n\t}\n\n\treturn nil\n}\n\nfunc SliceContains(s []string, val string) bool {\n\tfor _, v := range s {\n\t\tif v == val {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ FIXME: pass the filename in here as an argument\nfunc (s *Server) loadSettings() error {\n\tsettingsFilename := \"settings.json\"\n\n\tif len(s.SettingsFile) > 0 {\n\t\tsettingsFilename = s.SettingsFile\n\t}\n\n\tsettingsFile, err := ioutil.ReadFile(settingsFilename)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading settings file: %s\", err)\n\t}\n\n\terr = json.Unmarshal(settingsFile, &s.settings)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error unmarshaling settings: %s\", err)\n\t}\n\n\tfmt.Println(\"Settings loaded\")\n\n\tif s.settings.RefreshInterval < 1 {\n\t\ts.settings.RefreshInterval = 1\n\t}\n\n\treturn s.loadGames()\n}\n\nfunc (s *Server) loadGames() error {\n\tif ex := exists(\"games.cache\"); !ex {\n\t\tfmt.Println(\"games.cache doesn't exist. Getting a new one.\")\n\t\tif err := s.updateGamesJson(); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable update game list: %s\", err)\n\t\t}\n\t}\n\n\tgamesFile, err := ioutil.ReadFile(\"games.cache\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading games file: %s\", err)\n\t}\n\n\tvar games GameIDs\n\terr = json.Unmarshal(gamesFile, &games)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error unmarshaling games: %s\", err)\n\t}\n\n\ts.Games.Update(games)\n\t\/\/fmt.Println(\"Number of games loaded: \", Games.Length())\n\treturn nil\n}\n\nfunc (s *Server) getGameName(appid string) (string, error) {\n\tif appid == \".stfolder\" {\n\t\treturn appid, nil\n\t}\n\n\t\/\/fmt.Printf(\"Getting name for appid %q\\n\", appid)\n\tif name := s.Games.Get(appid); name != appid {\n\t\treturn name, nil\n\t}\n\n\t\/\/ Large appid, must be a non-steam game. This could have some edge cases\n\t\/\/ as non-steam games' appids are CRCs.\n\tif len(appid) > 18 {\n\t\treturn s.Games.Set(appid, fmt.Sprintf(\"Non-Steam game (%s)\", appid)), nil\n\t}\n\n\t\/\/ TODO: rate limiting\/cache age\n\tif err := s.updateGamesJson(); err == nil {\n\t\tif name := s.Games.Get(appid); name != appid {\n\t\t\treturn name, nil\n\t\t}\n\t}\n\treturn appid, nil\n}\n\n\/\/ Update the local cache of appids from steam's servers.\nfunc (s *Server) updateGamesJson() error {\n\tif s.lastUpdate != nil && time.Since(*s.lastUpdate).Minutes() < 30 {\n\t\t\/\/return fmt.Errorf(\"Cache still good.\")\n\t\tfmt.Println(\"Not updating games list; cache still good.\")\n\t\treturn nil\n\t}\n\n\tnow := time.Now()\n\t\/\/fmt.Printf(\"time.Now(): {}\\n\", now)\n\ts.lastUpdate = &now\n\n\tfmt.Println(\"Updating games list\")\n\tresp, err := http.Get(\"http:\/\/api.steampowered.com\/ISteamApps\/GetAppList\/v2\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get appid list from steam: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tjs, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to read appid json: %s\", err)\n\t}\n\n\talist := &steamapps{}\n\tif err := json.Unmarshal(js, alist); err != nil {\n\t\treturn fmt.Errorf(\"Unable to unmarshal json: %s\", err)\n\t}\n\n\tfor _, a := range alist.Applist.Apps {\n\t\tid := fmt.Sprintf(\"%d\", a.Appid)\n\t\ts.Games.Set(id, a.Name)\n\n\t}\n\n\tfor _, ovr := range s.settings.AppidOverrides {\n\t\ts.Games.Set(ovr.Appid, ovr.Name)\n\t\tfmt.Printf(\"Setting override for [%s]: %q\\n\", ovr.Appid, ovr.Name)\n\t}\n\n\t\/\/ save games.cache\n\tgames := s.Games.GetMap()\n\tmarshaled, err := json.Marshal(games)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to marshal game json: %s\", err)\n\t}\n\n\terr = ioutil.WriteFile(\"games.cache\", marshaled, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to save games.cache: %s\", err)\n\t}\n\n\tfmt.Printf(\"Finished updating games list. Appids: %d\\n\", len(games))\n\treturn nil\n}\n\n\/\/ Returns a filename\nfunc (s *Server) getGameBanner(appid uint64) (string, error) {\n\tappstr := fmt.Sprintf(\"%d\", appid)\n\tif exist := exists(\"banners\/\" + appstr + \".jpg\"); exist {\n\t\treturn \"banners\/\" + appstr + \".jpg\", nil\n\t}\n\n\tresp, err := http.Get(\"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/\" + appstr + \"\/header.jpg\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to DL header: %s\", err)\n\t}\n\n\tif resp.StatusCode >= 400 && resp.StatusCode < 500 {\n\t\t\/\/ Game not found. Use unknown.\n\n\t\traw, err := ioutil.ReadFile(\"banners\/unknown.jpg\")\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to read unknown.jpg\")\n\t\t}\n\n\t\tif err = ioutil.WriteFile(\"banners\/\"+appstr+\".jpg\", raw, 0777); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n\t\t}\n\n\t\treturn \"banners\/\" + appstr + \".jpg\", nil\n\t}\n\n\tdefer resp.Body.Close()\n\n\tfile, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to read file: %s\", err)\n\t}\n\n\tif err = ioutil.WriteFile(\"banners\/\"+appstr+\".jpg\", file, 0777); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n\t}\n\n\treturn \"banners\/\" + appstr + \".jpg\", nil\n}\n\n\/\/ exists returns whether the given file or directory exists or not.\n\/\/ Taken from https:\/\/stackoverflow.com\/a\/10510783\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\nSave API key to settings filepackage steamscreenshots\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/big\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Settings struct {\n\tRemoteDirectory string\n\tAddress string\n\tAppidOverrides []struct {\n\t\tAppid string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t}\n\tRefreshInterval int \/\/ In minutes\n\tApiKey string \/\/ This will be regenerated if it is empty.\n}\n\nvar re_gamename = regexp.MustCompile(`(.+?)<\/td>`)\n\nvar (\n\tgitCommit string\n\tversion string\n)\n\n\/\/ Structure of json from steam's servers\ntype steamapps struct {\n\tApplist struct {\n\t\tApps []struct {\n\t\t\tAppid uint64 `json:\"appid\"`\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"apps\"`\n\t} `json:\"applist\"`\n}\n\ntype Server struct {\n\t\/\/ stats stuff\n\tstartTime time.Time\n\tlastScan time.Time\n\n\tlastUpdate *time.Time\n\n\tsettings Settings\n\n\tGames *GameList\n\tImageCache *GameImages\n\n\tSettingsFile string\n}\n\nfunc (s *Server) Run() {\n\tfmt.Println(\"Starting server\")\n\n\tif len(gitCommit) == 0 {\n\t\tgitCommit = \"Missing commit hash\"\n\t}\n\n\tif len(version) == 0 {\n\t\tversion = \"Missing version info\"\n\t}\n\tfmt.Printf(\"%s@%s\\n\", version, gitCommit)\n\n\ts.startTime = time.Now()\n\ts.Games = NewGameList()\n\n\tif err := s.loadSettings(\"settings.json\"); err != nil {\n\t\tfmt.Printf(\"Error loading settings: %s\\n\", err)\n\t\treturn\n\t}\n\n\tif err := init_templates(); err != nil {\n\t\tfmt.Printf(\"Error loading templates: %s\\n\", err)\n\t\treturn\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/\", s.handler_main)\n\tmux.HandleFunc(\"\/thumb\/\", s.handler_thumb)\n\tmux.HandleFunc(\"\/img\/\", s.handler_image)\n\tmux.HandleFunc(\"\/banner\/\", s.handler_banner)\n\tmux.HandleFunc(\"\/static\/\", s.handler_static)\n\tmux.HandleFunc(\"\/debug\/\", s.handler_debug)\n\tmux.HandleFunc(\"\/api\/get-cache\", s.handler_api_cache)\n\tmux.HandleFunc(\"\/api\/get-games\", s.handler_api_games)\n\tmux.HandleFunc(\"\/api\/add-image\", s.handler_api_addImage)\n\n\tserver := &http.Server{\n\t\tAddr: s.settings.Address,\n\t\tHandler: mux,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tvar err error\n\ts.ImageCache, err = LoadImageCache(\"image.cache\")\n\tif err != nil {\n\t\tfmt.Println(\"Unable to load image.cache: \", err)\n\n\t\ts.ImageCache = NewGameImages()\n\t\terr = s.scan(true)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Initial scan error: \", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Refreshing RemoteDirectory...\")\n\t\tif err = s.scan(true); err != nil {\n\t\t\tfmt.Println(\"Error refreshing RemoteDirectory: \", err)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Println(\"Initial scan OK\")\n\n\t\/\/ Fire and forget. TODO: graceful shutdown\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Minute * time.Duration(s.settings.RefreshInterval))\n\t\t\tif err := s.scan(false); err != nil {\n\t\t\t\tfmt.Printf(\"Error scanning: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Generate a new API key if it's empty\n\tif s.settings.ApiKey == \"\" {\n\t\tout := \"\"\n\t\tlarge := big.NewInt(int64(1 << 60))\n\t\tlarge = large.Add(large, large)\n\t\tfor len(out) < 50 {\n\t\t\tnum, err := rand.Int(rand.Reader, large)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"Error generating session key: \" + err.Error())\n\t\t\t}\n\t\t\tout = fmt.Sprintf(\"%s%X\", out, num)\n\t\t}\n\t\ts.settings.ApiKey = out\n\t\tfmt.Println(\"New API key generated: \" + s.settings.ApiKey)\n\t\tif err = s.saveSettings(\"settings.json\"); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"unable to save settings: %v\", err))\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"using API key in config: %q\\n\", s.settings.ApiKey)\n\t}\n\n\tgo func(s *Server) {\n\t\tfor {\n\t\t\ts.ImageCache.Save(\"image.cache\")\n\t\t\ttime.Sleep(10 * time.Minute)\n\t\t}\n\t}(s)\n\n\tfmt.Println(\"Listening on address: \" + s.settings.Address)\n\tfmt.Println(\"Fisnished startup.\")\n\tserver.ListenAndServe()\n}\n\n\/\/ TODO: use GameImages.FullScan for this?\nfunc (s *Server) scan(printOutput bool) error {\n\ts.lastScan = time.Now()\n\n\tif printOutput {\n\t\tfmt.Printf(\"Scanning %q\\n\", s.settings.RemoteDirectory)\n\t}\n\n\tdir, err := filepath.Glob(filepath.Join(s.settings.RemoteDirectory, \"*\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to glob RemoteDirectory: %s\", err)\n\t}\n\ttmpTree := make(map[string][]string)\n\n\tfor _, d := range dir {\n\t\tbase := filepath.Base(d)\n\n\t\t\/\/ Ignore dotfiles\n\t\tif strings.HasPrefix(base, \".\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif printOutput {\n\t\t\tfmt.Printf(\"[%s] %s\\n\", base, s.Games.Get(base))\n\t\t}\n\n\t\tjpg, err := filepath.Glob(filepath.Join(d, \"screenshots\", \"*.jpg\"))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"JPG glob error in %q: %s\", d, err)\n\t\t\tcontinue\n\t\t}\n\t\ttmpTree[base] = jpg\n\n\t\t\/\/ TODO: merge ImageCache.ScanPath() and ImagePath.RefreshPath(), possibly removing the jpg glob above as well.\n\t\terr = s.ImageCache.ScanPath(d)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\t\/\/ Write cache to disk after it's updated in-memory so failing this doesn't skip updating.\n\tif err := s.ImageCache.Save(\"image.cache\"); err != nil {\n\t\treturn fmt.Errorf(\"Unable to save image cache: %s\\n\", err)\n\t}\n\n\treturn nil\n}\n\nfunc SliceContains(s []string, val string) bool {\n\tfor _, v := range s {\n\t\tif v == val {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Server) saveSettings(filename string) error {\n\traw, err := json.MarshalIndent(s.settings, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(filename, raw, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Chmod(filename, 0600)\n}\n\n\/\/ FIXME: pass the filename in here as an argument\nfunc (s *Server) loadSettings(filename string) error {\n\tsettingsFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading settings file: %s\", err)\n\t}\n\n\terr = json.Unmarshal(settingsFile, &s.settings)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error unmarshaling settings: %s\", err)\n\t}\n\n\tfmt.Println(\"Settings loaded\")\n\n\tif s.settings.RefreshInterval < 1 {\n\t\ts.settings.RefreshInterval = 1\n\t}\n\n\treturn s.loadGames()\n}\n\nfunc (s *Server) loadGames() error {\n\tif ex := exists(\"games.cache\"); !ex {\n\t\tfmt.Println(\"games.cache doesn't exist. Getting a new one.\")\n\t\tif err := s.updateGamesJson(); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable update game list: %s\", err)\n\t\t}\n\t}\n\n\tgamesFile, err := ioutil.ReadFile(\"games.cache\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading games file: %s\", err)\n\t}\n\n\tvar games GameIDs\n\terr = json.Unmarshal(gamesFile, &games)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error unmarshaling games: %s\", err)\n\t}\n\n\ts.Games.Update(games)\n\t\/\/fmt.Println(\"Number of games loaded: \", Games.Length())\n\treturn nil\n}\n\nfunc (s *Server) getGameName(appid string) (string, error) {\n\tif appid == \".stfolder\" {\n\t\treturn appid, nil\n\t}\n\n\t\/\/fmt.Printf(\"Getting name for appid %q\\n\", appid)\n\tif name := s.Games.Get(appid); name != appid {\n\t\treturn name, nil\n\t}\n\n\t\/\/ Large appid, must be a non-steam game. This could have some edge cases\n\t\/\/ as non-steam games' appids are CRCs.\n\tif len(appid) > 18 {\n\t\treturn s.Games.Set(appid, fmt.Sprintf(\"Non-Steam game (%s)\", appid)), nil\n\t}\n\n\t\/\/ TODO: rate limiting\/cache age\n\tif err := s.updateGamesJson(); err == nil {\n\t\tif name := s.Games.Get(appid); name != appid {\n\t\t\treturn name, nil\n\t\t}\n\t}\n\treturn appid, nil\n}\n\n\/\/ Update the local cache of appids from steam's servers.\nfunc (s *Server) updateGamesJson() error {\n\tif s.lastUpdate != nil && time.Since(*s.lastUpdate).Minutes() < 30 {\n\t\t\/\/return fmt.Errorf(\"Cache still good.\")\n\t\tfmt.Println(\"Not updating games list; cache still good.\")\n\t\treturn nil\n\t}\n\n\tnow := time.Now()\n\t\/\/fmt.Printf(\"time.Now(): {}\\n\", now)\n\ts.lastUpdate = &now\n\n\tfmt.Println(\"Updating games list\")\n\tresp, err := http.Get(\"http:\/\/api.steampowered.com\/ISteamApps\/GetAppList\/v2\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get appid list from steam: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tjs, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to read appid json: %s\", err)\n\t}\n\n\talist := &steamapps{}\n\tif err := json.Unmarshal(js, alist); err != nil {\n\t\treturn fmt.Errorf(\"Unable to unmarshal json: %s\", err)\n\t}\n\n\tfor _, a := range alist.Applist.Apps {\n\t\tid := fmt.Sprintf(\"%d\", a.Appid)\n\t\ts.Games.Set(id, a.Name)\n\n\t}\n\n\tfor _, ovr := range s.settings.AppidOverrides {\n\t\ts.Games.Set(ovr.Appid, ovr.Name)\n\t\tfmt.Printf(\"Setting override for [%s]: %q\\n\", ovr.Appid, ovr.Name)\n\t}\n\n\t\/\/ save games.cache\n\tgames := s.Games.GetMap()\n\tmarshaled, err := json.Marshal(games)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to marshal game json: %s\", err)\n\t}\n\n\terr = ioutil.WriteFile(\"games.cache\", marshaled, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to save games.cache: %s\", err)\n\t}\n\n\tfmt.Printf(\"Finished updating games list. Appids: %d\\n\", len(games))\n\treturn nil\n}\n\n\/\/ Returns a filename\nfunc (s *Server) getGameBanner(appid uint64) (string, error) {\n\tappstr := fmt.Sprintf(\"%d\", appid)\n\tif exist := exists(\"banners\/\" + appstr + \".jpg\"); exist {\n\t\treturn \"banners\/\" + appstr + \".jpg\", nil\n\t}\n\n\tresp, err := http.Get(\"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/\" + appstr + \"\/header.jpg\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to DL header: %s\", err)\n\t}\n\n\tif resp.StatusCode >= 400 && resp.StatusCode < 500 {\n\t\t\/\/ Game not found. Use unknown.\n\n\t\traw, err := ioutil.ReadFile(\"banners\/unknown.jpg\")\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to read unknown.jpg\")\n\t\t}\n\n\t\tif err = ioutil.WriteFile(\"banners\/\"+appstr+\".jpg\", raw, 0777); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n\t\t}\n\n\t\treturn \"banners\/\" + appstr + \".jpg\", nil\n\t}\n\n\tdefer resp.Body.Close()\n\n\tfile, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to read file: %s\", err)\n\t}\n\n\tif err = ioutil.WriteFile(\"banners\/\"+appstr+\".jpg\", file, 0777); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to save file: %s\", err)\n\t}\n\n\treturn \"banners\/\" + appstr + \".jpg\", nil\n}\n\n\/\/ exists returns whether the given file or directory exists or not.\n\/\/ Taken from https:\/\/stackoverflow.com\/a\/10510783\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/adamdecaf\/cert-manage\/cmd\"\n)\n\nconst (\n\tversion = \"0.0.1-dev\"\n)\n\nvar (\n\tfs = flag.NewFlagSet(\"flags\", flag.ExitOnError)\n\n\t\/\/ Commands\n\tlist = fs.Bool(\"list\", false, \"List certificates (by default on the system, see -app)\")\n\twhitelist = fs.String(\"whitelist\", \"\", \"Filter certificates according to the provided whitelist\")\n\t\/\/ TODO(adam): future commands\n\t\/\/ - backup\n\t\/\/ - restore\n\n\t\/\/ Filters\n\tapp = fs.String(\"app\", \"\", \"Specify an application (see -list)\")\n\n\t\/\/ Output\n\tformat = fs.String(\"format\", \"table\", \"Specify the output format (options: raw, table)\")\n)\n\nfunc main() {\n\tfs.Parse(os.Args[1:])\n\n\tif list != nil && *list {\n\t\tif app != nil && *app != \"\" {\n\t\t\tcmd.ListCertsForApp(*app, *format)\n\t\t\treturn\n\t\t}\n\t\tcmd.ListCertsForPlatform(*format)\n\t\treturn\n\t}\n\n\twh := strings.TrimSpace(*whitelist)\n\tif whitelist != nil && wh != \"\" {\n\t\tif app != nil && *app != \"\" {\n\t\t\terr := cmd.WhitelistForApp(*app, *whitelist, *format)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terr := cmd.WhitelistForPlatform(*whitelist, *format)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n}\ncmd: let -list be used after -whitelistpackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/adamdecaf\/cert-manage\/cmd\"\n)\n\nconst (\n\tversion = \"0.0.1-dev\"\n)\n\nvar (\n\tfs = flag.NewFlagSet(\"flags\", flag.ExitOnError)\n\n\t\/\/ Commands\n\tlist = fs.Bool(\"list\", false, \"List certificates (by default on the system, see -app)\")\n\twhitelist = fs.String(\"whitelist\", \"\", \"Filter certificates according to the provided whitelist\")\n\t\/\/ TODO(adam): future commands\n\t\/\/ - backup\n\t\/\/ - restore\n\n\t\/\/ Filters\n\tapp = fs.String(\"app\", \"\", \"Specify an application (see -list)\")\n\n\t\/\/ Output\n\tformat = fs.String(\"format\", \"table\", \"Specify the output format (options: raw, table)\")\n)\n\nfunc main() {\n\tfs.Parse(os.Args[1:])\n\n\twh := strings.TrimSpace(*whitelist)\n\tif whitelist != nil && wh != \"\" {\n\t\tif app != nil && *app != \"\" {\n\t\t\terr := cmd.WhitelistForApp(*app, *whitelist, *format)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t\terr := cmd.WhitelistForPlatform(*whitelist, *format)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tif list != nil && *list {\n\t\tif app != nil && *app != \"\" {\n\t\t\tcmd.ListCertsForApp(*app, *format)\n\t\t\treturn\n\t\t}\n\t\tcmd.ListCertsForPlatform(*format)\n\t\treturn\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype engineType int\n\nconst (\n\tengineNone engineType = iota\n\tengineRPGMVX\n\tengineWolf\n)\n\nvar (\n\tengine = engineNone\n\n\tlineLength int\n\tlineTolerance int\n)\n\nfunc main() {\n\tstart := time.Now()\n\n\targs := parseFlags()\n\tif len(args) < 1 {\n\t\tlog.Fatal(\"Program requires patch directory as argument\")\n\t}\n\n\tdir := args[0]\n\terr := checkPatchVersion(dir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfileList := getDirectoryContents(filepath.Join(dir, \"Patch\"))\n\tif len(fileList) < 1 {\n\t\tlog.Fatal(\"Couldn't find anything to translate\")\n\t}\n\n\tif lineLength < 1 {\n\t\tswitch engine {\n\t\tcase engineWolf:\n\t\t\tlineLength = 54\n\t\tdefault:\n\t\t\tlineLength = 42\n\t\t}\n\t}\n\tfmt.Println(\"Current settings:\")\n\tfmt.Println(\"- line length:\", lineLength)\n\tfmt.Println(\"- line length tolerance:\", lineTolerance)\n\n\tcount := len(fileList)\n\tfor i, file := range fileList {\n\t\tfmt.Printf(\"Processing %q (%d\/%d)\\n\", filepath.Base(file), i+1, count)\n\n\t\tpatch, err := parsePatchFile(file)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpatch, err = translatePatch(patch)\n\t\tcheck(err)\n\n\t\terr = writePatchFile(patch)\n\t\tcheck(err)\n\t}\n\n\tfmt.Printf(\"Finished in %s\\n\", time.Since(start))\n}\n\nfunc checkPatchVersion(dir string) error {\n\tfile, err := os.Open(filepath.Join(dir, \"RPGMKTRANSPATCH\"))\n\tif err != nil {\n\t\tfile, err = os.Open(filepath.Join(dir, \"Patch\", \"dump\", \"GameDat.txt\"))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to open RPGMKTRANSPATCH or Patch\/dump\/GameDat.txt\")\n\t\t}\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\n\t\tif text == \"> RPGMAKER TRANS PATCH V3\" {\n\t\t\tfmt.Println(\"Detected RPG Maker VX Ace Patch\")\n\n\t\t\tengine = engineRPGMVX\n\n\t\t\treturn nil\n\t\t} else if text == \"> WOLF TRANS PATCH FILE VERSION 1.0\" {\n\t\t\tfmt.Println(\"Detected WOLF RPG Patch\")\n\n\t\t\tengine = engineWolf\n\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"Unsupported patch version\")\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn err\n}\n\nfunc getDirectoryContents(dir string) []string {\n\tvar fileList []string\n\n\terr := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif f.IsDir() || filepath.Ext(path) != \".txt\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tfileList = append(fileList, path)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn fileList\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc parseFlags() []string {\n\tflag.IntVar(&lineLength, \"length\", 42, \"Max line legth\")\n\tflag.IntVar(&lineTolerance, \"tolerance\", 5, \"Max amount of characters allowed to go over the line limit\")\n\n\tflag.Parse()\n\n\treturn flag.Args()\n}\nChange -length default valuepackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype engineType int\n\nconst (\n\tengineNone engineType = iota\n\tengineRPGMVX\n\tengineWolf\n)\n\nvar (\n\tengine = engineNone\n\n\t\/\/ Flags\n\tlineLength int\n\tlineTolerance int\n)\n\nfunc main() {\n\tstart := time.Now()\n\n\targs := parseFlags()\n\tif len(args) < 1 {\n\t\tlog.Fatal(\"Program requires patch directory as argument\")\n\t}\n\n\tdir := args[0]\n\terr := checkPatchVersion(dir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfileList := getDirectoryContents(filepath.Join(dir, \"Patch\"))\n\tif len(fileList) < 1 {\n\t\tlog.Fatal(\"Couldn't find anything to translate\")\n\t}\n\n\tif lineLength == -1 {\n\t\tif engine == engineWolf {\n\t\t\tlineLength = 54\n\t\t} else {\n\t\t\tlineLength = 42\n\t\t}\n\t}\n\n\tfmt.Println(\"Current settings:\")\n\tfmt.Println(\"- line length:\", lineLength)\n\tfmt.Println(\"- line length tolerance:\", lineTolerance)\n\n\tcount := len(fileList)\n\tfor i, file := range fileList {\n\t\tfmt.Printf(\"Processing %q (%d\/%d)\\n\", filepath.Base(file), i+1, count)\n\n\t\tpatch, err := parsePatchFile(file)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpatch, err = translatePatch(patch)\n\t\tcheck(err)\n\n\t\terr = writePatchFile(patch)\n\t\tcheck(err)\n\t}\n\n\tfmt.Printf(\"Finished in %s\\n\", time.Since(start))\n}\n\nfunc checkPatchVersion(dir string) error {\n\tfile, err := os.Open(filepath.Join(dir, \"RPGMKTRANSPATCH\"))\n\tif err != nil {\n\t\tfile, err = os.Open(filepath.Join(dir, \"Patch\", \"dump\", \"GameDat.txt\"))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to open RPGMKTRANSPATCH or Patch\/dump\/GameDat.txt\")\n\t\t}\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\n\t\tif text == \"> RPGMAKER TRANS PATCH V3\" {\n\t\t\tfmt.Println(\"Detected RPG Maker VX Ace Patch\")\n\n\t\t\tengine = engineRPGMVX\n\n\t\t\treturn nil\n\t\t} else if text == \"> WOLF TRANS PATCH FILE VERSION 1.0\" {\n\t\t\tfmt.Println(\"Detected WOLF RPG Patch\")\n\n\t\t\tengine = engineWolf\n\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"Unsupported patch version\")\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn err\n}\n\nfunc getDirectoryContents(dir string) []string {\n\tvar fileList []string\n\n\terr := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif f.IsDir() || filepath.Ext(path) != \".txt\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tfileList = append(fileList, path)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn fileList\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc parseFlags() []string {\n\tflag.IntVar(&lineLength, \"length\", -1, \"Max line legth\")\n\tflag.IntVar(&lineTolerance, \"tolerance\", 5, \"Max amount of characters allowed to go over the line limit\")\n\n\tflag.Parse()\n\n\treturn flag.Args()\n}\n<|endoftext|>"} {"text":"package telnet\n\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n)\n\n\n\/\/ ListenAndServe listens on the TCP network address `addr` and then spawns a call to the ServeTELNET\n\/\/ method on the `handler` to serve each incoming connection.\n\/\/\n\/\/ For a very simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\t\/\/@TODO: In your code, you would probably want to use a different handler.\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\terr := telnet.ListenAndServe(\":5555\", handler)\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\nfunc ListenAndServe(addr string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServe()\n}\n\n\n\/\/ Serve accepts an incoming TELNET or TELNETS client connection on the net.Listener `listener`.\nfunc Serve(listener net.Listener, handler Handler) error {\n\n\tserver := &Server{Handler: handler}\n\treturn server.Serve(listener)\n}\n\n\n\/\/ A Server defines parameters of a running TELNET server.\n\/\/\n\/\/ For a simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\tserver := &telnet.Server{\n\/\/\t\t\tAddr:\":5555\",\n\/\/\t\t\tHandler:handler,\n\/\/\t\t}\n\/\/\t\n\/\/\t\terr := server.ListenAndServe()\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\ntype Server struct {\n\tAddr string \/\/ TCP address to listen on; \":telnet\" or \":telnets\" if empty (when used with ListenAndServe or ListenAndServeTLS respectively).\n\tHandler Handler \/\/ handler to invoke; telnet.EchoServer if nil\n\n\tTLSConfig *tls.Config \/\/ optional TLS configuration; used by ListenAndServeTLS.\n\n\tLogger Logger\n}\n\n\/\/ ListenAndServe listens on the TCP network address 'server.Addr' and then spawns a call to the ServeTELNET\n\/\/ method on the 'server.Handler' to serve each incoming connection.\n\/\/\n\/\/ For a simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\tserver := &telnet.Server{\n\/\/\t\t\tAddr:\":5555\",\n\/\/\t\t\tHandler:handler,\n\/\/\t\t}\n\/\/\t\n\/\/\t\terr := server.ListenAndServe()\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\nfunc (server *Server) ListenAndServe() error {\n\n\taddr := server.Addr\n\tif \"\" == addr {\n\t\taddr = \":telnet\"\n\t}\n\n\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\n\treturn server.Serve(listener)\n}\n\n\n\/\/ Serve accepts an incoming TELNET client connection on the net.Listener `listener`.\nfunc (server *Server) Serve(listener net.Listener) error {\n\n\tdefer listener.Close()\n\n\n\tlogger := server.logger()\n\n\n\thandler := server.Handler\n\tif nil == handler {\n\/\/@TODO: Should this be a \"ShellHandler\" instead, that gives a shell-like experience by default\n\/\/ If this is changd, then need to change the comment in the \"type Server struct\" definition.\n\t\tlogger.Debug(\"Defaulted handler to EchoHandler.\")\n\t\thandler = EchoHandler\n\t}\n\n\n\tfor {\n\t\t\/\/ Wait for a new TELNET client connection.\n\t\tlogger.Debugf(\"Listening at %q.\", listener.Addr())\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\/\/@TODO: Could try to recover from certain kinds of errors. Maybe waiting a while before trying again.\n\t\t\treturn err\n\t\t}\n\t\tlogger.Debugf(\"Received new connection from %q.\", conn.RemoteAddr())\n\n\t\t\/\/ Handle the new TELNET client connection by spawning\n\t\t\/\/ a new goroutine.\n\t\tgo func(c net.Conn) {\n\/\/@TODO: Add proper context.\n\t\t\tvar ctx Context = NewContext().InjectLogger(logger)\n\n\t\t\tvar w Writer = c\n\t\t\tvar r Reader = c\n\n\t\t\thandler.ServeTELNET(ctx, w, r)\n\t\t\tc.Close()\n\t\t}(conn)\n\t\tlogger.Debugf(\"Spawned handler to handle connection from %q.\", conn.RemoteAddr())\n }\n}\n\n\nfunc (server *Server) logger() Logger {\n\tlogger := server.Logger\n\tif nil == logger {\n\t\tlogger = internalDiscardLogger{}\n\t}\n\n\treturn logger\n}\nsome dev workpackage telnet\n\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n)\n\n\n\/\/ ListenAndServe listens on the TCP network address `addr` and then spawns a call to the ServeTELNET\n\/\/ method on the `handler` to serve each incoming connection.\n\/\/\n\/\/ For a very simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\t\/\/@TODO: In your code, you would probably want to use a different handler.\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\terr := telnet.ListenAndServe(\":5555\", handler)\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\nfunc ListenAndServe(addr string, handler Handler) error {\n\tserver := &Server{Addr: addr, Handler: handler}\n\treturn server.ListenAndServe()\n}\n\n\n\/\/ Serve accepts an incoming TELNET or TELNETS client connection on the net.Listener `listener`.\nfunc Serve(listener net.Listener, handler Handler) error {\n\n\tserver := &Server{Handler: handler}\n\treturn server.Serve(listener)\n}\n\n\n\/\/ A Server defines parameters of a running TELNET server.\n\/\/\n\/\/ For a simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\tserver := &telnet.Server{\n\/\/\t\t\tAddr:\":5555\",\n\/\/\t\t\tHandler:handler,\n\/\/\t\t}\n\/\/\t\n\/\/\t\terr := server.ListenAndServe()\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\ntype Server struct {\n\tAddr string \/\/ TCP address to listen on; \":telnet\" or \":telnets\" if empty (when used with ListenAndServe or ListenAndServeTLS respectively).\n\tHandler Handler \/\/ handler to invoke; telnet.EchoServer if nil\n\n\tTLSConfig *tls.Config \/\/ optional TLS configuration; used by ListenAndServeTLS.\n\n\tLogger Logger\n}\n\n\/\/ ListenAndServe listens on the TCP network address 'server.Addr' and then spawns a call to the ServeTELNET\n\/\/ method on the 'server.Handler' to serve each incoming connection.\n\/\/\n\/\/ For a simple example:\n\/\/\n\/\/\tpackage main\n\/\/\t\n\/\/\timport (\n\/\/\t\t\"github.com\/reiver\/go-telnet\"\n\/\/\t)\n\/\/\t\n\/\/\tfunc main() {\n\/\/\t\n\/\/\t\tvar handler telnet.Handler = telnet.EchoHandler\n\/\/\t\n\/\/\t\tserver := &telnet.Server{\n\/\/\t\t\tAddr:\":5555\",\n\/\/\t\t\tHandler:handler,\n\/\/\t\t}\n\/\/\t\n\/\/\t\terr := server.ListenAndServe()\n\/\/\t\tif nil != err {\n\/\/\t\t\t\/\/@TODO: Handle this error better.\n\/\/\t\t\tpanic(err)\n\/\/\t\t}\n\/\/\t}\nfunc (server *Server) ListenAndServe() error {\n\n\taddr := server.Addr\n\tif \"\" == addr {\n\t\taddr = \":telnet\"\n\t}\n\n\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\n\treturn server.Serve(listener)\n}\n\n\n\/\/ Serve accepts an incoming TELNET client connection on the net.Listener `listener`.\nfunc (server *Server) Serve(listener net.Listener) error {\n\n\tdefer listener.Close()\n\n\n\tlogger := server.logger()\n\n\n\thandler := server.Handler\n\tif nil == handler {\n\/\/@TODO: Should this be a \"ShellHandler\" instead, that gives a shell-like experience by default\n\/\/ If this is changd, then need to change the comment in the \"type Server struct\" definition.\n\t\tlogger.Debug(\"Defaulted handler to EchoHandler.\")\n\t\thandler = EchoHandler\n\t}\n\n\n\tfor {\n\t\t\/\/ Wait for a new TELNET client connection.\n\t\tlogger.Debugf(\"Listening at %q.\", listener.Addr())\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\/\/@TODO: Could try to recover from certain kinds of errors. Maybe waiting a while before trying again.\n\t\t\treturn err\n\t\t}\n\t\tlogger.Debugf(\"Received new connection from %q.\", conn.RemoteAddr())\n\n\t\t\/\/ Handle the new TELNET client connection by spawning\n\t\t\/\/ a new goroutine.\n\t\tgo func(c net.Conn) {\n\t\t\tvar ctx Context = NewContext().InjectLogger(logger)\n\n\t\t\tvar w Writer = NewDataWriter(c)\n\t\t\tvar r Reader = NewDataReader(c)\n\n\t\t\thandler.ServeTELNET(ctx, w, r)\n\t\t\tc.Close()\n\t\t}(conn)\n\t\tlogger.Debugf(\"Spawned handler to handle connection from %q.\", conn.RemoteAddr())\n }\n}\n\n\nfunc (server *Server) logger() Logger {\n\tlogger := server.Logger\n\tif nil == logger {\n\t\tlogger = internalDiscardLogger{}\n\t}\n\n\treturn logger\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\twaitTime = 3 * time.Second\n\texecDigit = 5\n\tbaseURL = \"https:\/\/git.io\/\"\n\tokFmt = \"%s OK!\\n\"\n\tngFmt = \"%s NG!\\n\"\n\tlocFmt = \"Location: %s\\n\"\n)\n\nfunc main() {\n\tc := new(http.Client)\n\tc.CheckRedirect = func(req *http.Request, via []*http.Request) error { return errors.New(\"not redirect\") }\n\n\trunes := []rune{'0'}\n\n\tfor {\n\t\turi := string(runes)\n\n\t\tresp, err := c.Get(baseURL + uri)\n\t\tif err == nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\n\t\tif resp.StatusCode == 404 {\n\t\t\tfmt.Printf(okFmt, uri)\n\t\t} else {\n\t\t\tfmt.Fprintf(os.Stderr, ngFmt, uri)\n\t\t\tfmt.Fprintf(os.Stderr, locFmt, resp.Header.Get(\"Location\"))\n\t\t}\n\n\t\trunes = advanceRunes(runes)\n\n\t\tif len(runes) > execDigit {\n\t\t\t\/\/ exit\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(waitTime)\n\t}\n}\n\nfunc advanceRunes(runes []rune) []rune {\n\tif runes[len(runes)-1] == 'Z' {\n\t\t\/\/ carry over\n\t\taddFlg := true\n\t\tfor i := len(runes) - 1; i > -1; i-- {\n\t\t\tbeforeRune := runes[i]\n\t\t\trunes[i] = getNextRune(runes[i])\n\t\t\tif beforeRune != 'Z' {\n\t\t\t\taddFlg = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif addFlg {\n\t\t\trunes = append(runes, '0')\n\t\t}\n\t} else {\n\t\trunes[len(runes)-1] = getNextRune(runes[len(runes)-1])\n\t}\n\n\treturn runes\n}\n\nfunc getNextRune(r rune) rune {\n\t\/\/ 0 -> 9, a -> z, A -> Z\n\tif r == '9' {\n\t\treturn 'a'\n\t} else if r == 'z' {\n\t\treturn 'A'\n\t} else if r == 'Z' {\n\t\treturn '0'\n\t}\n\n\tr++\n\treturn r\n}\nsplit func \"checkURI\"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\twaitTime = 3 * time.Second\n\texecDigit = 5\n\tbaseURL = \"https:\/\/git.io\/\"\n\tokFmt = \"%s OK!\\n\"\n\tngFmt = \"%s NG!\\n\"\n\tlocFmt = \"Location: %s\\n\"\n)\n\nvar (\n\tc = new(http.Client)\n)\n\nfunc init() {\n\tc.CheckRedirect = func(req *http.Request, via []*http.Request) error { return errors.New(\"not redirect\") }\n}\n\nfunc main() {\n\trunes := []rune{'0'}\n\n\tfor {\n\t\turi := string(runes)\n\n\t\tcheckURI(uri)\n\n\t\trunes = advanceRunes(runes)\n\n\t\tif len(runes) > execDigit {\n\t\t\t\/\/ exit\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(waitTime)\n\t}\n}\n\nfunc checkURI(uri string) {\n\tresp, err := c.Get(baseURL + uri)\n\tif err == nil {\n\t\tresp.Body.Close()\n\t}\n\n\tif resp.StatusCode == 404 {\n\t\tfmt.Printf(okFmt, uri)\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, ngFmt, uri)\n\t\tfmt.Fprintf(os.Stderr, locFmt, resp.Header.Get(\"Location\"))\n\t}\n}\n\nfunc advanceRunes(runes []rune) []rune {\n\tif runes[len(runes)-1] == 'Z' {\n\t\t\/\/ carry over\n\t\taddFlg := true\n\t\tfor i := len(runes) - 1; i > -1; i-- {\n\t\t\tbeforeRune := runes[i]\n\t\t\trunes[i] = getNextRune(runes[i])\n\t\t\tif beforeRune != 'Z' {\n\t\t\t\taddFlg = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif addFlg {\n\t\t\trunes = append(runes, '0')\n\t\t}\n\t} else {\n\t\trunes[len(runes)-1] = getNextRune(runes[len(runes)-1])\n\t}\n\n\treturn runes\n}\n\nfunc getNextRune(r rune) rune {\n\t\/\/ 0 -> 9, a -> z, A -> Z\n\tif r == '9' {\n\t\treturn 'a'\n\t} else if r == 'z' {\n\t\treturn 'A'\n\t} else if r == 'Z' {\n\t\treturn '0'\n\t}\n\n\tr++\n\treturn r\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n)\n\n\/\/ Server - main server object\ntype Server struct {\n\tListen string\n\tCollector *Collector\n\tDebug bool\n\techo *echo.Echo\n}\n\n\/\/ Status - response status struct\ntype Status struct {\n\tStatus string `json:\"status\"`\n\tSendQueue int `json:\"send_queue,omitempty\"`\n\tServers map[string]*ClickhouseServer `json:\"servers,omitempty\"`\n\tTables map[string]*Table `json:\"tables,omitempty\"`\n}\n\n\/\/ NewServer - create server\nfunc NewServer(listen string, collector *Collector, debug bool) *Server {\n\treturn &Server{listen, collector, debug, echo.New()}\n}\n\nfunc (server *Server) writeHandler(c echo.Context) error {\n\tq, _ := ioutil.ReadAll(c.Request().Body)\n\ts := string(q)\n\n\tif server.Debug {\n\t\tlog.Printf(\"DEBUG: query %+v %+v\\n\", c.QueryString(), s)\n\t}\n\n\tqs := c.QueryString()\n\tuser, password, ok := c.Request().BasicAuth()\n\tif ok {\n\t\tif qs == \"\" {\n\t\t\tqs = \"user=\" + user + \"&password=\" + password\n\t\t} else {\n\t\t\tqs = \"user=\" + user + \"&password=\" + password + \"&\" + qs\n\t\t}\n\t}\n\tparams, content, insert := server.Collector.ParseQuery(qs, s)\n\tif insert {\n\t\tgo server.Collector.Push(params, content)\n\t\treturn c.String(http.StatusOK, \"\")\n\t}\n\tresp, status, _ := server.Collector.Sender.SendQuery(&ClickhouseRequest{Params: params, Content: content})\n\treturn c.String(status, resp)\n}\n\nfunc (server *Server) statusHandler(c echo.Context) error {\n\treturn c.JSON(200, Status{Status: \"ok\"})\n}\n\n\/\/ Start - start http server\nfunc (server *Server) Start() error {\n\treturn server.echo.Start(server.Listen)\n}\n\n\/\/ Shutdown - stop http server\nfunc (server *Server) Shutdown(ctx context.Context) error {\n\treturn server.echo.Shutdown(ctx)\n}\n\n\/\/ InitServer - run server\nfunc InitServer(listen string, collector *Collector, debug bool) *Server {\n\tserver := NewServer(listen, collector, debug)\n\tserver.echo.POST(\"\/\", server.writeHandler)\n\tserver.echo.GET(\"\/status\", server.statusHandler)\n\tserver.echo.GET(\"\/metrics\", echo.WrapHandler(promhttp.Handler()))\n\n\treturn server\n}\n\n\/\/ SafeQuit - safe prepare to quit\nfunc SafeQuit(collect *Collector, sender Sender) {\n\tcollect.FlushAll()\n\tif count := sender.Len(); count > 0 {\n\t\tlog.Printf(\"Sending %+v tables\\n\", count)\n\t}\n\tfor !sender.Empty() && !collect.Empty() {\n\t\tcollect.WaitFlush()\n\t}\n\tcollect.WaitFlush()\n}\n\n\/\/ RunServer - run all\nfunc RunServer(cnf Config) {\n\tInitMetrics()\n\tdumper := NewDumper(cnf.DumpDir)\n\tsender := NewClickhouse(cnf.Clickhouse.DownTimeout, cnf.Clickhouse.ConnectTimeout)\n\tsender.Dumper = dumper\n\tfor _, url := range cnf.Clickhouse.Servers {\n\t\tsender.AddServer(url)\n\t}\n\n\tcollect := NewCollector(sender, cnf.FlushCount, cnf.FlushInterval)\n\n\t\/\/ send collected data on SIGTERM and exit\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\n\tsrv := InitServer(cnf.Listen, collect, cnf.Debug)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tgo func() {\n\t\tfor {\n\t\t\t_ = <-signals\n\t\t\tlog.Printf(\"STOP signal\\n\")\n\t\t\tif err := srv.Shutdown(ctx); err != nil {\n\t\t\t\tlog.Printf(\"Shutdown error %+v\\n\", err)\n\t\t\t\tSafeQuit(collect, sender)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif cnf.DumpCheckInterval >= 0 {\n\t\tdumper.Listen(sender, cnf.DumpCheckInterval)\n\t}\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tlog.Printf(\"ListenAndServe: %+v\\n\", err)\n\t\tSafeQuit(collect, sender)\n\t\tos.Exit(1)\n\t}\n}\nremove processing for non insert queriespackage main\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n)\n\n\/\/ Server - main server object\ntype Server struct {\n\tListen string\n\tCollector *Collector\n\tDebug bool\n\techo *echo.Echo\n}\n\n\/\/ Status - response status struct\ntype Status struct {\n\tStatus string `json:\"status\"`\n\tSendQueue int `json:\"send_queue,omitempty\"`\n\tServers map[string]*ClickhouseServer `json:\"servers,omitempty\"`\n\tTables map[string]*Table `json:\"tables,omitempty\"`\n}\n\n\/\/ NewServer - create server\nfunc NewServer(listen string, collector *Collector, debug bool) *Server {\n\treturn &Server{listen, collector, debug, echo.New()}\n}\n\nfunc (server *Server) writeHandler(c echo.Context) error {\n\tq, _ := ioutil.ReadAll(c.Request().Body)\n\ts := string(q)\n\n\tif server.Debug {\n\t\tlog.Printf(\"DEBUG: query %+v %+v\\n\", c.QueryString(), s)\n\t}\n\n\tqs := c.QueryString()\n\tuser, password, ok := c.Request().BasicAuth()\n\tif ok {\n\t\tif qs == \"\" {\n\t\t\tqs = \"user=\" + user + \"&password=\" + password\n\t\t} else {\n\t\t\tqs = \"user=\" + user + \"&password=\" + password + \"&\" + qs\n\t\t}\n\t}\n\tparams, content, insert := server.Collector.ParseQuery(qs, s)\n\tif insert {\n\t\tgo server.Collector.Push(params, content)\n\t\treturn c.String(http.StatusOK, \"\")\n\t}\n\tresp, status, _ := server.Collector.Sender.SendQuery(&ClickhouseRequest{Params: qs, Content: s})\n\treturn c.String(status, resp)\n}\n\nfunc (server *Server) statusHandler(c echo.Context) error {\n\treturn c.JSON(200, Status{Status: \"ok\"})\n}\n\n\/\/ Start - start http server\nfunc (server *Server) Start() error {\n\treturn server.echo.Start(server.Listen)\n}\n\n\/\/ Shutdown - stop http server\nfunc (server *Server) Shutdown(ctx context.Context) error {\n\treturn server.echo.Shutdown(ctx)\n}\n\n\/\/ InitServer - run server\nfunc InitServer(listen string, collector *Collector, debug bool) *Server {\n\tserver := NewServer(listen, collector, debug)\n\tserver.echo.POST(\"\/\", server.writeHandler)\n\tserver.echo.GET(\"\/status\", server.statusHandler)\n\tserver.echo.GET(\"\/metrics\", echo.WrapHandler(promhttp.Handler()))\n\n\treturn server\n}\n\n\/\/ SafeQuit - safe prepare to quit\nfunc SafeQuit(collect *Collector, sender Sender) {\n\tcollect.FlushAll()\n\tif count := sender.Len(); count > 0 {\n\t\tlog.Printf(\"Sending %+v tables\\n\", count)\n\t}\n\tfor !sender.Empty() && !collect.Empty() {\n\t\tcollect.WaitFlush()\n\t}\n\tcollect.WaitFlush()\n}\n\n\/\/ RunServer - run all\nfunc RunServer(cnf Config) {\n\tInitMetrics()\n\tdumper := NewDumper(cnf.DumpDir)\n\tsender := NewClickhouse(cnf.Clickhouse.DownTimeout, cnf.Clickhouse.ConnectTimeout)\n\tsender.Dumper = dumper\n\tfor _, url := range cnf.Clickhouse.Servers {\n\t\tsender.AddServer(url)\n\t}\n\n\tcollect := NewCollector(sender, cnf.FlushCount, cnf.FlushInterval)\n\n\t\/\/ send collected data on SIGTERM and exit\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)\n\n\tsrv := InitServer(cnf.Listen, collect, cnf.Debug)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tgo func() {\n\t\tfor {\n\t\t\t_ = <-signals\n\t\t\tlog.Printf(\"STOP signal\\n\")\n\t\t\tif err := srv.Shutdown(ctx); err != nil {\n\t\t\t\tlog.Printf(\"Shutdown error %+v\\n\", err)\n\t\t\t\tSafeQuit(collect, sender)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif cnf.DumpCheckInterval >= 0 {\n\t\tdumper.Listen(sender, cnf.DumpCheckInterval)\n\t}\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tlog.Printf(\"ListenAndServe: %+v\\n\", err)\n\t\tSafeQuit(collect, sender)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"} {"text":"\/* {{{ Copyright (c) Paul R. Tagliamonte , 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"flag\"\n)\n\nfunc main() {\n\tvar sniffConfig string\n\n\tflag.StringVar(&sniffConfig, \"config\", \"sniff.json\", \"Config\")\n\tflag.Parse()\n\n\tconfig, err := LoadConfig(\"\/home\/paultag\/sniff.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpanic(config.Serve())\n}\n\n\/\/ vim: foldmethod=marker\nupdate\/* {{{ Copyright (c) Paul R. Tagliamonte , 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"flag\"\n)\n\nfunc main() {\n\tvar sniffConfig string\n\n\tflag.StringVar(&sniffConfig, \"config\", \"sniff.json\", \"Config\")\n\tflag.Parse()\n\n\tconfig, err := LoadConfig(sniffConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpanic(config.Serve())\n}\n\n\/\/ vim: foldmethod=marker\n<|endoftext|>"} {"text":"package models\n\nimport (\n\t\"time\"\n\n\t\"github.com\/jackc\/pgx\"\n)\n\n\/\/ ServiceCheck represents a row from 'cyboard.service_check'.\ntype ServiceCheck struct {\n\tCreatedAt time.Time `json:\"created_at\"` \/\/ created_at\n\tTeamID int `json:\"team_id\"` \/\/ team_id\n\tServiceID int `json:\"service_id\"` \/\/ service_id\n\tStatus ExitStatus `json:\"status\"` \/\/ status\n\tExitCode int16 `json:\"exit_code\"` \/\/ exit_code\n}\n\nvar (\n\tserviceCheckTableIdent = pgx.Identifier{\"cyboard\", \"service_check\"}\n\tserviceCheckTableColumns = []string{\n\t\t\"created_at\", \"team_id\", \"service_id\", \"status\", \"exit_code\",\n\t}\n)\n\n\/\/ ServiceCheckSlice is an array of ServiceChecks, suitable to insert many of at once.\ntype ServiceCheckSlice []ServiceCheck\n\n\/\/ serviceCheckCopyFromRows implements the pgx.CopyFromSource interface, allowing\n\/\/ a ServiceCheckSlice to be inserted into the database.\ntype serviceCheckCopyFromRows struct {\n\trows ServiceCheckSlice\n\tidx int\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Next() bool {\n\tctr.idx++\n\treturn ctr.idx < len(ctr.rows)\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Values() ([]interface{}, error) {\n\tsc := ctr.rows[ctr.idx]\n\tval := []interface{}{\n\t\tsc.CreatedAt, sc.TeamID, sc.ServiceID, sc.Status, sc.ExitCode,\n\t}\n\treturn val, nil\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Err() error {\n\treturn nil\n}\n\n\/\/ Insert a batch of service monitor results efficiently into the database.\nfunc (sc ServiceCheckSlice) Insert(db DB) error {\n\t_, err := db.CopyFrom(\n\t\tserviceCheckTableIdent,\n\t\tserviceCheckTableColumns,\n\t\t&serviceCheckCopyFromRows{rows: sc, idx: -1},\n\t)\n\treturn err\n}\n\n\/\/ LatestServiceCheckRun retrieves the timestamp of the last run of the service monitor.\n\/\/ See: `LatestScoreChange` in `scoring.go`. This delta check is specific to services.\nfunc LatestServiceCheckRun(db DB) (time.Time, error) {\n\tconst sqlstr = `SELECT created_at FROM service_check UNION ALL SELECT 'epoch' ORDER BY created_at DESC LIMIT 1`\n\tvar timestamp time.Time\n\terr := db.QueryRow(sqlstr).Scan(×tamp)\n\treturn timestamp, err\n}\n\n\/\/ TeamServiceStatusesView represents the current, calculated\n\/\/ service's status (pass, fail, timeout), for all teams.\ntype TeamServiceStatusesView struct {\n\tServiceID int `json:\"service_id\"`\n\tServiceName string `json:\"service_name\"`\n\tStatuses []ExitStatus `json:\"statuses\"`\n}\n\n\/\/ TeamServiceStatuses gets the current service status (pass, fail, timeout)\n\/\/ for each team, for each non-disabled service.\nfunc TeamServiceStatuses(db DB) ([]TeamServiceStatusesView, error) {\n\tconst sqlstr = `\n\tSELECT ss.service, ss.service_name, jsonb_agg(ss.status) AS statuses\n\tFROM (SELECT * FROM blueteam AS team,\n\tLATERAL (SELECT id AS service, name AS service_name, COALESCE(last(sc.status, sc.created_at), 'timeout') AS status\n\t\tFROM service\n\t\t\tLEFT JOIN service_check AS sc ON id = sc.service_id AND team.id = sc.team_id\n\t\tWHERE service.disabled = false\n\t\tGROUP BY service.id, team.name) AS ss\n\t\tORDER BY ss.service, team.id) AS ss\n\tGROUP BY ss.service, ss.service_name`\n\trows, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\txs := []TeamServiceStatusesView{}\n\tfor rows.Next() {\n\t\tx := TeamServiceStatusesView{}\n\t\tif err = rows.Scan(&x.ServiceID, &x.ServiceName, &x.Statuses); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\txs = append(xs, x)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xs, nil\n}\n\ntype MonitorTeamService struct {\n\tTeam struct { \/\/ `cyboard.team` table\n\t\tID int \/\/ id\n\t\tName string \/\/ name\n\t\tIP int16 \/\/ blueteam_ip\n\t}\n\tService struct { \/\/ `cyboard.service` table\n\t\tID int \/\/ id\n\t\tName string \/\/ name\n\t\tScript string \/\/ script\n\t\tArgs []string \/\/ args\n\t\tStartsAt time.Time \/\/ starts_at\n\t}\n}\n\n\/\/ MonitorTeamsAndServices fetches every active service and blueteam from the\n\/\/ database, at the same time. Returns an empty array for no rows, or an error\n\/\/ if there is a problem fetching data from postgres.\nfunc MonitorTeamsAndServices(db DBClient) ([]MonitorTeamService, error) {\n\tconst sqlstr = `SELECT\n\t\tt.id, t.name, t.blueteam_ip,\n\t\ts.id, s.name, s.script, s.args, s.starts_at\n\tFROM service AS s CROSS JOIN blueteam AS t\n\tWHERE s.disabled = false`\n\trows, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\txs := []MonitorTeamService{}\n\tfor rows.Next() {\n\t\tx := MonitorTeamService{}\n\t\terr = rows.Scan(&x.Team.ID, &x.Team.Name, &x.Team.IP,\n\t\t\t&x.Service.ID, &x.Service.Name, &x.Service.Script, &x.Service.Args, &x.Service.StartsAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\txs = append(xs, x)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xs, nil\n}\nOnly display services that have started on the scoreboardpackage models\n\nimport (\n\t\"time\"\n\n\t\"github.com\/jackc\/pgx\"\n)\n\n\/\/ ServiceCheck represents a row from 'cyboard.service_check'.\ntype ServiceCheck struct {\n\tCreatedAt time.Time `json:\"created_at\"` \/\/ created_at\n\tTeamID int `json:\"team_id\"` \/\/ team_id\n\tServiceID int `json:\"service_id\"` \/\/ service_id\n\tStatus ExitStatus `json:\"status\"` \/\/ status\n\tExitCode int16 `json:\"exit_code\"` \/\/ exit_code\n}\n\nvar (\n\tserviceCheckTableIdent = pgx.Identifier{\"cyboard\", \"service_check\"}\n\tserviceCheckTableColumns = []string{\n\t\t\"created_at\", \"team_id\", \"service_id\", \"status\", \"exit_code\",\n\t}\n)\n\n\/\/ ServiceCheckSlice is an array of ServiceChecks, suitable to insert many of at once.\ntype ServiceCheckSlice []ServiceCheck\n\n\/\/ serviceCheckCopyFromRows implements the pgx.CopyFromSource interface, allowing\n\/\/ a ServiceCheckSlice to be inserted into the database.\ntype serviceCheckCopyFromRows struct {\n\trows ServiceCheckSlice\n\tidx int\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Next() bool {\n\tctr.idx++\n\treturn ctr.idx < len(ctr.rows)\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Values() ([]interface{}, error) {\n\tsc := ctr.rows[ctr.idx]\n\tval := []interface{}{\n\t\tsc.CreatedAt, sc.TeamID, sc.ServiceID, sc.Status, sc.ExitCode,\n\t}\n\treturn val, nil\n}\n\nfunc (ctr *serviceCheckCopyFromRows) Err() error {\n\treturn nil\n}\n\n\/\/ Insert a batch of service monitor results efficiently into the database.\nfunc (sc ServiceCheckSlice) Insert(db DB) error {\n\t_, err := db.CopyFrom(\n\t\tserviceCheckTableIdent,\n\t\tserviceCheckTableColumns,\n\t\t&serviceCheckCopyFromRows{rows: sc, idx: -1},\n\t)\n\treturn err\n}\n\n\/\/ LatestServiceCheckRun retrieves the timestamp of the last run of the service monitor.\n\/\/ See: `LatestScoreChange` in `scoring.go`. This delta check is specific to services.\nfunc LatestServiceCheckRun(db DB) (time.Time, error) {\n\tconst sqlstr = `SELECT created_at FROM service_check UNION ALL SELECT 'epoch' ORDER BY created_at DESC LIMIT 1`\n\tvar timestamp time.Time\n\terr := db.QueryRow(sqlstr).Scan(×tamp)\n\treturn timestamp, err\n}\n\n\/\/ TeamServiceStatusesView represents the current, calculated\n\/\/ service's status (pass, fail, timeout), for all teams.\ntype TeamServiceStatusesView struct {\n\tServiceID int `json:\"service_id\"`\n\tServiceName string `json:\"service_name\"`\n\tStatuses []ExitStatus `json:\"statuses\"`\n}\n\n\/\/ TeamServiceStatuses gets the current service status (pass, fail, timeout)\n\/\/ for each team, for each service that has started and isn't disabled.\nfunc TeamServiceStatuses(db DB) ([]TeamServiceStatusesView, error) {\n\tconst sqlstr = `\n\tSELECT ss.service, ss.service_name, jsonb_agg(ss.status) AS statuses\n\tFROM (SELECT * FROM blueteam AS team,\n\tLATERAL (SELECT id AS service, name AS service_name, COALESCE(last(sc.status, sc.created_at), 'timeout') AS status\n\t\tFROM service\n\t\t\tLEFT JOIN service_check AS sc ON id = sc.service_id AND team.id = sc.team_id\n\t\tWHERE service.disabled = false AND service.starts_at < current_timestamp\n\t\tGROUP BY service.id, team.name) AS ss\n\t\tORDER BY ss.service, team.id) AS ss\n\tGROUP BY ss.service, ss.service_name`\n\trows, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\txs := []TeamServiceStatusesView{}\n\tfor rows.Next() {\n\t\tx := TeamServiceStatusesView{}\n\t\tif err = rows.Scan(&x.ServiceID, &x.ServiceName, &x.Statuses); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\txs = append(xs, x)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xs, nil\n}\n\ntype MonitorTeamService struct {\n\tTeam struct { \/\/ `cyboard.team` table\n\t\tID int \/\/ id\n\t\tName string \/\/ name\n\t\tIP int16 \/\/ blueteam_ip\n\t}\n\tService struct { \/\/ `cyboard.service` table\n\t\tID int \/\/ id\n\t\tName string \/\/ name\n\t\tScript string \/\/ script\n\t\tArgs []string \/\/ args\n\t\tStartsAt time.Time \/\/ starts_at\n\t}\n}\n\n\/\/ MonitorTeamsAndServices fetches every active service and blueteam from the\n\/\/ database, at the same time. Returns an empty array for no rows, or an error\n\/\/ if there is a problem fetching data from postgres.\nfunc MonitorTeamsAndServices(db DBClient) ([]MonitorTeamService, error) {\n\tconst sqlstr = `SELECT\n\t\tt.id, t.name, t.blueteam_ip,\n\t\ts.id, s.name, s.script, s.args, s.starts_at\n\tFROM service AS s CROSS JOIN blueteam AS t\n\tWHERE s.disabled = false`\n\trows, err := db.Query(sqlstr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\txs := []MonitorTeamService{}\n\tfor rows.Next() {\n\t\tx := MonitorTeamService{}\n\t\terr = rows.Scan(&x.Team.ID, &x.Team.Name, &x.Team.IP,\n\t\t\t&x.Service.ID, &x.Service.Name, &x.Service.Script, &x.Service.Args, &x.Service.StartsAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\txs = append(xs, x)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xs, nil\n}\n<|endoftext|>"} {"text":"package veneur\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com\/DataDog\/datadog-go\/statsd\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/getsentry\/raven-go\"\n)\n\ntype Server struct {\n\tWorkers []*Worker\n\n\tstatsd *statsd.Client\n\tlogger *logrus.Logger\n\tsentry *raven.Client\n\n\tHostname string\n\tTags []string\n\n\tDDHostname string\n\tDDAPIKey string\n\n\tUDPAddr *net.UDPAddr\n\tRcvbufBytes int\n\n\tHistogramPercentiles []float64\n\tHistogramCounter bool\n}\n\nfunc NewFromConfig(conf Config) (ret Server, err error) {\n\tret.Hostname = conf.Hostname\n\tret.Tags = conf.Tags\n\tret.DDHostname = conf.APIHostname\n\tret.DDAPIKey = conf.Key\n\tret.HistogramCounter = conf.HistCounters\n\tret.HistogramPercentiles = conf.Percentiles\n\n\tret.statsd, err = statsd.NewBuffered(conf.StatsAddr, 1024)\n\tif err != nil {\n\t\treturn\n\t}\n\tret.statsd.Namespace = \"veneur.\"\n\tret.statsd.Tags = ret.Tags\n\n\t\/\/ nil is a valid sentry client that noops all methods, if there is no DSN\n\t\/\/ we can just leave it as nil\n\tif conf.SentryDSN != \"\" {\n\t\tret.sentry, err = raven.New(conf.SentryDSN)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tret.logger = logrus.New()\n\tif conf.Debug {\n\t\tret.logger.Level = logrus.DebugLevel\n\t}\n\tret.logger.Hooks.Add(sentryHook{\n\t\tc: ret.sentry,\n\t\thostname: ret.Hostname,\n\t\tlv: []logrus.Level{\n\t\t\tlogrus.ErrorLevel,\n\t\t\tlogrus.FatalLevel,\n\t\t\tlogrus.PanicLevel,\n\t\t},\n\t})\n\n\tret.logger.WithField(\"number\", conf.NumWorkers).Info(\"Starting workers\")\n\tret.Workers = make([]*Worker, conf.NumWorkers)\n\tfor i := range ret.Workers {\n\t\tret.Workers[i] = NewWorker(i+1, ret.statsd, ret.logger)\n\t\t\/\/ do not close over loop index\n\t\tgo func(w *Worker) {\n\t\t\tdefer func() {\n\t\t\t\tret.ConsumePanic(recover())\n\t\t\t}()\n\t\t\tw.Work()\n\t\t}(ret.Workers[i])\n\t}\n\n\tret.UDPAddr, err = net.ResolveUDPAddr(\"udp\", conf.UDPAddr)\n\tif err != nil {\n\t\treturn\n\t}\n\tret.RcvbufBytes = conf.ReadBufferSizeBytes\n\n\tconf.Key = \"REDACTED\"\n\tconf.SentryDSN = \"REDACTED\"\n\tret.logger.WithField(\"config\", conf).Debug(\"Initialized server\")\n\n\treturn\n}\n\nfunc (s *Server) HandlePacket(packet []byte, packetPool *sync.Pool) {\n\tmetric, err := ParseMetric(packet)\n\tif err != nil {\n\t\ts.logger.WithFields(logrus.Fields{\n\t\t\tlogrus.ErrorKey: err,\n\t\t\t\"packet\": string(packet),\n\t\t}).Error(\"Could not parse packet\")\n\t\ts.statsd.Count(\"packet.error_total\", 1, nil, 1.0)\n\t}\n\n\tif len(s.Tags) > 0 {\n\t\tmetric.Tags = append(metric.Tags, s.Tags...)\n\t}\n\n\ts.Workers[metric.Digest%uint32(len(s.Workers))].WorkChan <- *metric\n\n\t\/\/ the Metric struct has no byte slices in it, only strings\n\t\/\/ therefore there are no outstanding references to this byte slice, and we\n\t\/\/ can return it to the pool\n\tpacketPool.Put(packet[:cap(packet)])\n}\n\nfunc (s *Server) ReadSocket(packetPool *sync.Pool) {\n\t\/\/ each goroutine gets its own socket\n\t\/\/ if the sockets support SO_REUSEPORT, then this will cause the\n\t\/\/ kernel to distribute datagrams across them, for better read\n\t\/\/ performance\n\ts.logger.WithField(\"address\", s.UDPAddr).Info(\"UDP server listening\")\n\tserverConn, err := NewSocket(s.UDPAddr, s.RcvbufBytes)\n\tif err != nil {\n\t\t\/\/ if any goroutine fails to create the socket, we can't really\n\t\t\/\/ recover, so we just blow up\n\t\t\/\/ this probably indicates a systemic issue, eg lack of\n\t\t\/\/ SO_REUSEPORT support\n\t\ts.logger.WithError(err).Fatal(\"Error listening for UDP\")\n\t}\n\n\tfor {\n\t\tbuf := packetPool.Get().([]byte)\n\t\tn, _, err := serverConn.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\ts.logger.WithError(err).Error(\"Error reading from UDP\")\n\t\t\tcontinue\n\t\t}\n\t\ts.HandlePacket(buf[:n], packetPool)\n\t}\n}\nDo not feed malformed packets to workerspackage veneur\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com\/DataDog\/datadog-go\/statsd\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/getsentry\/raven-go\"\n)\n\ntype Server struct {\n\tWorkers []*Worker\n\n\tstatsd *statsd.Client\n\tlogger *logrus.Logger\n\tsentry *raven.Client\n\n\tHostname string\n\tTags []string\n\n\tDDHostname string\n\tDDAPIKey string\n\n\tUDPAddr *net.UDPAddr\n\tRcvbufBytes int\n\n\tHistogramPercentiles []float64\n\tHistogramCounter bool\n}\n\nfunc NewFromConfig(conf Config) (ret Server, err error) {\n\tret.Hostname = conf.Hostname\n\tret.Tags = conf.Tags\n\tret.DDHostname = conf.APIHostname\n\tret.DDAPIKey = conf.Key\n\tret.HistogramCounter = conf.HistCounters\n\tret.HistogramPercentiles = conf.Percentiles\n\n\tret.statsd, err = statsd.NewBuffered(conf.StatsAddr, 1024)\n\tif err != nil {\n\t\treturn\n\t}\n\tret.statsd.Namespace = \"veneur.\"\n\tret.statsd.Tags = ret.Tags\n\n\t\/\/ nil is a valid sentry client that noops all methods, if there is no DSN\n\t\/\/ we can just leave it as nil\n\tif conf.SentryDSN != \"\" {\n\t\tret.sentry, err = raven.New(conf.SentryDSN)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tret.logger = logrus.New()\n\tif conf.Debug {\n\t\tret.logger.Level = logrus.DebugLevel\n\t}\n\tret.logger.Hooks.Add(sentryHook{\n\t\tc: ret.sentry,\n\t\thostname: ret.Hostname,\n\t\tlv: []logrus.Level{\n\t\t\tlogrus.ErrorLevel,\n\t\t\tlogrus.FatalLevel,\n\t\t\tlogrus.PanicLevel,\n\t\t},\n\t})\n\n\tret.logger.WithField(\"number\", conf.NumWorkers).Info(\"Starting workers\")\n\tret.Workers = make([]*Worker, conf.NumWorkers)\n\tfor i := range ret.Workers {\n\t\tret.Workers[i] = NewWorker(i+1, ret.statsd, ret.logger)\n\t\t\/\/ do not close over loop index\n\t\tgo func(w *Worker) {\n\t\t\tdefer func() {\n\t\t\t\tret.ConsumePanic(recover())\n\t\t\t}()\n\t\t\tw.Work()\n\t\t}(ret.Workers[i])\n\t}\n\n\tret.UDPAddr, err = net.ResolveUDPAddr(\"udp\", conf.UDPAddr)\n\tif err != nil {\n\t\treturn\n\t}\n\tret.RcvbufBytes = conf.ReadBufferSizeBytes\n\n\tconf.Key = \"REDACTED\"\n\tconf.SentryDSN = \"REDACTED\"\n\tret.logger.WithField(\"config\", conf).Debug(\"Initialized server\")\n\n\treturn\n}\n\nfunc (s *Server) HandlePacket(packet []byte) {\n\tmetric, err := ParseMetric(packet)\n\tif err != nil {\n\t\ts.logger.WithFields(logrus.Fields{\n\t\t\tlogrus.ErrorKey: err,\n\t\t\t\"packet\": string(packet),\n\t\t}).Error(\"Could not parse packet\")\n\t\ts.statsd.Count(\"packet.error_total\", 1, nil, 1.0)\n\t\treturn\n\t}\n\n\tif len(s.Tags) > 0 {\n\t\tmetric.Tags = append(metric.Tags, s.Tags...)\n\t}\n\n\ts.Workers[metric.Digest%uint32(len(s.Workers))].WorkChan <- *metric\n}\n\nfunc (s *Server) ReadSocket(packetPool *sync.Pool) {\n\t\/\/ each goroutine gets its own socket\n\t\/\/ if the sockets support SO_REUSEPORT, then this will cause the\n\t\/\/ kernel to distribute datagrams across them, for better read\n\t\/\/ performance\n\ts.logger.WithField(\"address\", s.UDPAddr).Info(\"UDP server listening\")\n\tserverConn, err := NewSocket(s.UDPAddr, s.RcvbufBytes)\n\tif err != nil {\n\t\t\/\/ if any goroutine fails to create the socket, we can't really\n\t\t\/\/ recover, so we just blow up\n\t\t\/\/ this probably indicates a systemic issue, eg lack of\n\t\t\/\/ SO_REUSEPORT support\n\t\ts.logger.WithError(err).Fatal(\"Error listening for UDP\")\n\t}\n\n\tfor {\n\t\tbuf := packetPool.Get().([]byte)\n\t\tn, _, err := serverConn.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\ts.logger.WithError(err).Error(\"Error reading from UDP\")\n\t\t\tcontinue\n\t\t}\n\t\ts.HandlePacket(buf[:n])\n\t\t\/\/ the Metric struct created by HandlePacket has no byte slices in it,\n\t\t\/\/ only strings\n\t\t\/\/ therefore there are no outstanding references to this byte slice, we\n\t\t\/\/ can return it to the pool\n\t\tpacketPool.Put(buf)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/stscreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar verbose = os.Getenv(\"ENV_INJECTOR_VERBOSE\") == \"1\"\n\n\/\/ For lazy initialization\nvar service *ssm.SSM\n\nfunc main() {\n\tinjectEnviron()\n\n\targs := os.Args\n\tif len(args) <= 1 {\n\t\tlog.Fatal(\"missing command\")\n\t}\n\n\tpath, err := exec.LookPath(args[1])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = syscall.Exec(path, args[1:], os.Environ())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc trace(v ...interface{}) {\n\tif verbose {\n\t\tlog.Println(v...)\n\t}\n}\n\nfunc tracef(format string, v ...interface{}) {\n\tif verbose {\n\t\tlog.Printf(format, v...)\n\t}\n}\n\nfunc injectEnviron() {\n\tinjectEnvironByPath()\n\tinjectEnvironByPrefix()\n}\n\nfunc injectEnvironByPath() {\n\tpath := os.Getenv(\"ENV_INJECTOR_PATH\")\n\tif path == \"\" {\n\t\ttrace(\"no parameter path specified, skipping injection by path\")\n\t\treturn\n\t}\n\ttracef(\"parameter path: %s\", path)\n\n\tsvc := getSSMService()\n\tif svc == nil {\n\t\treturn\n\t}\n\n\tvar nextToken *string\n\tfor {\n\t\tresult, err := svc.GetParametersByPath(&ssm.GetParametersByPathInput{\n\t\t\tPath: aws.String(path),\n\t\t\tWithDecryption: aws.Bool(true),\n\t\t\tNextToken: nextToken,\n\t\t})\n\t\tif err != nil {\n\t\t\ttracef(\"failed to get by path: %s\", path)\n\t\t\ttrace(err)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, param := range result.Parameters {\n\t\t\tkey, err := filepath.Rel(path, aws.StringValue(param.Name))\n\t\t\tif err != nil {\n\t\t\t\ttrace(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif os.Getenv(key) == \"\" {\n\t\t\t\tos.Setenv(key, aws.StringValue(param.Value))\n\t\t\t\ttracef(\"env injected: %s\", key)\n\t\t\t}\n\t\t}\n\t\tnextToken = result.NextToken\n\t\tif nextToken == nil || aws.StringValue(nextToken) == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc injectEnvironByPrefix() {\n\tprefix := os.Getenv(\"ENV_INJECTOR_PREFIX\")\n\n\tif prefix == \"\" {\n\t\ttrace(\"no parameter prefix specified, skipping injection by prefix\")\n\t\treturn\n\t}\n\ttracef(\"parameter prefix: %s\", prefix)\n\tif !strings.HasSuffix(prefix, \".\") {\n\t\tprefix += \".\"\n\t}\n\n\tnames := []*string{}\n\tfor _, env := range os.Environ() {\n\t\tparts := strings.SplitN(env, \"=\", 2)\n\t\tif len(parts) == 2 && parts[1] == \"\" {\n\t\t\tnames = append(names, aws.String(prefix+parts[0]))\n\t\t}\n\t}\n\tif len(names) == 0 {\n\t\ttrace(\"nothing to be injected by prefix\")\n\t\treturn\n\t}\n\n\tsvc := getSSMService()\n\tif svc == nil {\n\t\treturn\n\t}\n\n\t\/\/ 'GetParameters' fails entirely when any one of parameters is not permitted to get.\n\t\/\/ So call 'GetParameters' one by one.\n\tfor _, n := range names {\n\t\tresult, err := svc.GetParameters(&ssm.GetParametersInput{\n\t\t\tNames: []*string{n},\n\t\t\tWithDecryption: aws.Bool(true),\n\t\t})\n\t\tif err != nil {\n\t\t\ttracef(\"failed to get: %s\", *n)\n\t\t\ttrace(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, key := range result.InvalidParameters {\n\t\t\ttracef(\"invalid parameter: %s\", aws.StringValue(key))\n\t\t}\n\t\tfor _, param := range result.Parameters {\n\t\t\tkey := strings.TrimPrefix(aws.StringValue(param.Name), prefix)\n\t\t\tos.Setenv(key, aws.StringValue(param.Value))\n\t\t\ttracef(\"env injected: %s\", key)\n\t\t}\n\t}\n}\n\n\/\/ Initialize SSM service lazily, and return it.\nfunc getSSMService() *ssm.SSM {\n\tif service != nil {\n\t\treturn service\n\t}\n\n\tsess, err := session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t})\n\tif err != nil {\n\t\ttrace(err)\n\t\ttrace(\"failed to create session\")\n\t\treturn nil\n\t}\n\tif *sess.Config.Region == \"\" {\n\t\ttrace(\"no explicit region configuration. So now retrieving ec2metadata...\")\n\t\tregion, err := ec2metadata.New(sess).Region()\n\t\tif err != nil {\n\t\t\ttrace(err)\n\t\t\ttrace(\"could not find region configuration\")\n\t\t\treturn nil\n\t\t}\n\t\tsess.Config.Region = aws.String(region)\n\t}\n\n\tif arn := os.Getenv(\"ENV_INJECTOR_ASSUME_ROLE_ARN\"); arn != \"\" {\n\t\tcreds := stscreds.NewCredentials(sess, arn)\n\t\tservice = ssm.New(sess, &aws.Config{Credentials: creds})\n\t} else {\n\t\tservice = ssm.New(sess)\n\t}\n\treturn service\n}\ntreat as a fatal error in some cases (#1)package main\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/stscreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar verbose = os.Getenv(\"ENV_INJECTOR_VERBOSE\") == \"1\"\n\n\/\/ For lazy initialization\nvar service *ssm.SSM\n\nfunc main() {\n\tinjectEnviron()\n\n\targs := os.Args\n\tif len(args) <= 1 {\n\t\tlog.Fatal(\"missing command\")\n\t}\n\n\tpath, err := exec.LookPath(args[1])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = syscall.Exec(path, args[1:], os.Environ())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc trace(v ...interface{}) {\n\tif verbose {\n\t\tlog.Println(v...)\n\t}\n}\n\nfunc tracef(format string, v ...interface{}) {\n\tif verbose {\n\t\tlog.Printf(format, v...)\n\t}\n}\n\nfunc injectEnviron() {\n\tinjectEnvironByPath()\n\tinjectEnvironByPrefix()\n}\n\nfunc injectEnvironByPath() {\n\tpath := os.Getenv(\"ENV_INJECTOR_PATH\")\n\tif path == \"\" {\n\t\ttrace(\"no parameter path specified, skipping injection by path\")\n\t\treturn\n\t}\n\ttracef(\"parameter path: %s\", path)\n\n\tsvc := getSSMService()\n\n\tvar nextToken *string\n\tfor {\n\t\tresult, err := svc.GetParametersByPath(&ssm.GetParametersByPathInput{\n\t\t\tPath: aws.String(path),\n\t\t\tWithDecryption: aws.Bool(true),\n\t\t\tNextToken: nextToken,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ssm:GetParametersByPath failed. (path: %s)\\n %v\", path, err)\n\t\t}\n\n\t\tfor _, param := range result.Parameters {\n\t\t\tkey, err := filepath.Rel(path, aws.StringValue(param.Name))\n\t\t\tif err != nil {\n\t\t\t\ttrace(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif os.Getenv(key) == \"\" {\n\t\t\t\tos.Setenv(key, aws.StringValue(param.Value))\n\t\t\t\ttracef(\"env injected: %s\", key)\n\t\t\t}\n\t\t}\n\t\tnextToken = result.NextToken\n\t\tif nextToken == nil || aws.StringValue(nextToken) == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc injectEnvironByPrefix() {\n\tprefix := os.Getenv(\"ENV_INJECTOR_PREFIX\")\n\n\tif prefix == \"\" {\n\t\ttrace(\"no parameter prefix specified, skipping injection by prefix\")\n\t\treturn\n\t}\n\ttracef(\"parameter prefix: %s\", prefix)\n\tif !strings.HasSuffix(prefix, \".\") {\n\t\tprefix += \".\"\n\t}\n\n\tnames := []*string{}\n\tfor _, env := range os.Environ() {\n\t\tparts := strings.SplitN(env, \"=\", 2)\n\t\tif len(parts) == 2 && parts[1] == \"\" {\n\t\t\tnames = append(names, aws.String(prefix+parts[0]))\n\t\t}\n\t}\n\tif len(names) == 0 {\n\t\ttrace(\"nothing to be injected by prefix\")\n\t\treturn\n\t}\n\n\tsvc := getSSMService()\n\n\t\/\/ 'GetParameters' fails entirely when any one of parameters is not permitted to get.\n\t\/\/ So call 'GetParameters' one by one.\n\tfor _, n := range names {\n\t\tresult, err := svc.GetParameters(&ssm.GetParametersInput{\n\t\t\tNames: []*string{n},\n\t\t\tWithDecryption: aws.Bool(true),\n\t\t})\n\t\tif err != nil {\n\t\t\ttracef(\"failed to get: %s\", *n)\n\t\t\ttrace(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, key := range result.InvalidParameters {\n\t\t\ttracef(\"invalid parameter: %s\", aws.StringValue(key))\n\t\t}\n\t\tfor _, param := range result.Parameters {\n\t\t\tkey := strings.TrimPrefix(aws.StringValue(param.Name), prefix)\n\t\t\tos.Setenv(key, aws.StringValue(param.Value))\n\t\t\ttracef(\"env injected: %s\", key)\n\t\t}\n\t}\n}\n\n\/\/ Initialize SSM service lazily, and return it.\nfunc getSSMService() *ssm.SSM {\n\tif service != nil {\n\t\treturn service\n\t}\n\n\tsess, err := session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create a new session.\\n %v\", err)\n\t}\n\tif *sess.Config.Region == \"\" {\n\t\ttrace(\"no explicit region configuration. So now retrieving ec2metadata...\")\n\t\tregion, err := ec2metadata.New(sess).Region()\n\t\tif err != nil {\n\t\t\ttrace(err)\n\t\t\tlog.Fatalf(\"could not find region configurations\")\n\t\t}\n\t\tsess.Config.Region = aws.String(region)\n\t}\n\n\tif arn := os.Getenv(\"ENV_INJECTOR_ASSUME_ROLE_ARN\"); arn != \"\" {\n\t\tcreds := stscreds.NewCredentials(sess, arn)\n\t\tservice = ssm.New(sess, &aws.Config{Credentials: creds})\n\t} else {\n\t\tservice = ssm.New(sess)\n\t}\n\treturn service\n}\n<|endoftext|>"} {"text":"package restkit\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ JSON creates a application\/json content-type header, sets the given HTTP\n\/\/ status code and encodes the given result object to the response writer.\nfunc JSON(resp http.ResponseWriter, result interface{}, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"application\/json\")\n\tresp.WriteHeader(code)\n\tif result != nil {\n\t\treturn maskAny(json.NewEncoder(resp).Encode(result))\n\t}\n\treturn nil\n}\n\n\/\/ Text creates a text\/plain content-type header, sets the given HTTP\n\/\/ status code and writes the given content to the response writer.\nfunc Text(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text\/plain\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}\n\n\/\/ Html creates a text\/html content-type header, sets the given HTTP\n\/\/ status code and writes the given content to the response writer.\nfunc Html(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text\/html\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}\n\n\/\/ Error sends an error message back to the given response writer.\nfunc Error(resp http.ResponseWriter, err error) error {\n\tcode := http.StatusBadRequest\n\tmessage := err.Error()\n\tif IsForbidden(err) {\n\t\tcode = http.StatusForbidden\n\t} else if IsInternalServer(err) {\n\t\tcode = http.StatusInternalServerError\n\t} else if IsInvalidArgument(err) {\n\t\tcode = http.StatusBadRequest\n\t} else if IsNotFound(err) {\n\t\tcode = http.StatusNotFound\n\t} else if IsUnauthorizedError(err) {\n\t\tcode = http.StatusUnauthorized\n\t}\n\n\tif er, ok := err.(*ErrorResponse); ok {\n\t\treturn maskAny(JSON(resp, er, code))\n\t}\n\n\ter := ErrorResponse{}\n\ter.TheError.Message = message\n\treturn maskAny(JSON(resp, er, code))\n}\nImproved `Error` function with errgo.Causepackage restkit\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/juju\/errgo\"\n)\n\n\/\/ JSON creates a application\/json content-type header, sets the given HTTP\n\/\/ status code and encodes the given result object to the response writer.\nfunc JSON(resp http.ResponseWriter, result interface{}, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"application\/json\")\n\tresp.WriteHeader(code)\n\tif result != nil {\n\t\treturn maskAny(json.NewEncoder(resp).Encode(result))\n\t}\n\treturn nil\n}\n\n\/\/ Text creates a text\/plain content-type header, sets the given HTTP\n\/\/ status code and writes the given content to the response writer.\nfunc Text(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text\/plain\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}\n\n\/\/ Html creates a text\/html content-type header, sets the given HTTP\n\/\/ status code and writes the given content to the response writer.\nfunc Html(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text\/html\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}\n\n\/\/ Error sends an error message back to the given response writer.\nfunc Error(resp http.ResponseWriter, err error) error {\n\tcode := http.StatusBadRequest\n\tmessage := err.Error()\n\tif IsForbidden(err) {\n\t\tcode = http.StatusForbidden\n\t} else if IsInternalServer(err) {\n\t\tcode = http.StatusInternalServerError\n\t} else if IsInvalidArgument(err) {\n\t\tcode = http.StatusBadRequest\n\t} else if IsNotFound(err) {\n\t\tcode = http.StatusNotFound\n\t} else if IsUnauthorizedError(err) {\n\t\tcode = http.StatusUnauthorized\n\t}\n\n\tif er, ok := err.(*ErrorResponse); ok {\n\t\treturn maskAny(JSON(resp, er, code))\n\t}\n\tif er, ok := errgo.Cause(err).(*ErrorResponse); ok {\n\t\treturn maskAny(JSON(resp, er, code))\n\t}\n\n\ter := ErrorResponse{}\n\ter.TheError.Message = message\n\ter.TheError.Code = -1\n\treturn maskAny(JSON(resp, er, code))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nvar commands = []*Command{\n\thelpCmd,\n\tlistCmd,\n\ttagsCmd,\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\thelpFunc(helpCmd)\n\t}\n\tflag.Parse()\n\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tLoad()\n\tdefer Save()\n\n\tsub, args := args[0], args[1:]\n\tfor _, cmd := range commands {\n\t\tif cmd.Name == sub {\n\t\t\tcmd.Exec(args)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfmt.Fprintf(stdout, \"error: unknown command %q\\n\\n\", sub)\n\tflag.Usage()\n}\nallow command prefixespackage main\n\nimport (\n\t\"os\"\n\t\"flag\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar commands = []*Command{\n\thelpCmd,\n\tlistCmd,\n\ttagsCmd,\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\thelpFunc(helpCmd)\n\t}\n\tflag.Parse()\n\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tLoad()\n\tdefer Save()\n\n\tvar found *Command\n\tsub, args := args[0], args[1:]\n\tfor _, cmd := range commands {\n\t\tif strings.HasPrefix(cmd.Name, sub) {\n\t\t\tif found != nil {\n\t\t\t\tfmt.Fprintf(stdout, \"error: non-unique prefix %q\\n\\n\", sub)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tfound = cmd\n\t\t}\n\t}\n\tif found == nil {\n\t\tfmt.Fprintf(stdout, \"error: unknown command %q\\n\\n\", sub)\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tfound.Exec(args)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\tggproto \"github.com\/gogo\/protobuf\/proto\"\n\tp2p_crypto \"github.com\/libp2p\/go-libp2p-crypto\"\n\tp2p_peer \"github.com\/libp2p\/go-libp2p-peer\"\n\tmc \"github.com\/mediachain\/concat\/mc\"\n\tpb \"github.com\/mediachain\/concat\/proto\"\n\tmultihash \"github.com\/multiformats\/go-multihash\"\n\t\"log\"\n\t\"sync\"\n)\n\ntype ManifestStoreImpl struct {\n\tmx sync.Mutex\n\tmf map[string]ManifestRecord\n\tkeys map[string]p2p_crypto.PubKey\n}\n\ntype ManifestRecord struct {\n\tmf *pb.Manifest\n\tsrc p2p_peer.ID\n}\n\nfunc NewManifestStore() ManifestStore {\n\treturn &ManifestStoreImpl{\n\t\tmf: make(map[string]ManifestRecord),\n\t\tkeys: make(map[string]p2p_crypto.PubKey),\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Put(src p2p_peer.ID, lst []*pb.Manifest) {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tfor _, mf := range lst {\n\t\tmfs.putManifest(src, mf)\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) putManifest(src p2p_peer.ID, mf *pb.Manifest) {\n\tmfx, err := hashManifest(mf)\n\tif err != nil {\n\t\tlog.Printf(\"Error hashing manifest; wtf: %s\", err.Error())\n\t\treturn\n\t}\n\n\tmfh := mfx.B58String()\n\n\t_, ok := mfs.mf[mfh]\n\tif ok {\n\t\treturn\n\t}\n\n\tkid := mf.Entity + \":\" + mf.KeyId\n\tpubk, ok := mfs.keys[kid]\n\n\tif !ok {\n\t\t\/\/ XXX This can take arbitrary long and might need to be throttled\n\t\t\/\/ XXX and in the meantime, it holds the manifest store lock...\n\t\t\/\/ XXX The solution to this problem is to fetch keys asynchronously\n\t\t\/\/ XXX with back-off\/retry logic; impl is complicated though, so for now\n\t\t\/\/ XXX damn the torpedoes (but at least release the lock)\n\t\tmfs.mx.Unlock()\n\t\tpubk, err = mc.LookupEntityKey(mf.Entity, mf.KeyId)\n\t\tmfs.mx.Lock()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error looking up entity key %s: %s\", kid, err.Error())\n\t\t\treturn\n\t\t}\n\t\tmfs.keys[kid] = pubk\n\t}\n\n\tok, err = verifyManifest(mf, pubk)\n\tswitch {\n\tcase err != nil:\n\t\tlog.Printf(\"Error verifying manifest %s: %s\", mfh, err.Error())\n\n\tcase !ok:\n\t\tlog.Printf(\"Error verifying manifest %s: signature verification failed\", mfh)\n\n\tdefault:\n\t\t\/\/ yay! a valid manifest.\n\t\tmfs.mf[mfh] = ManifestRecord{mf, src}\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Remove(src p2p_peer.ID) {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tfor mfh, mfr := range mfs.mf {\n\t\tif mfr.src == src {\n\t\t\tdelete(mfs.mf, mfh)\n\t\t}\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Lookup(entity string) []*pb.Manifest {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tres := make([]*pb.Manifest, 0)\n\tfor _, mfr := range mfs.mf {\n\t\tif mfr.mf.Entity == entity {\n\t\t\tres = append(res, mfr.mf)\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc hashManifest(mf *pb.Manifest) (multihash.Multihash, error) {\n\tbytes, err := ggproto.Marshal(mf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn mc.Hash(bytes), nil\n}\n\nfunc verifyManifest(mf *pb.Manifest, pubk p2p_crypto.PubKey) (bool, error) {\n\tsig := mf.Signature\n\tmf.Signature = nil\n\tbytes, err := ggproto.Marshal(mf)\n\tmf.Signature = sig\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn pubk.Verify(bytes, sig)\n}\nmcdir\/mfs: add basic wildcarding for retrieving all manifestspackage main\n\nimport (\n\tggproto \"github.com\/gogo\/protobuf\/proto\"\n\tp2p_crypto \"github.com\/libp2p\/go-libp2p-crypto\"\n\tp2p_peer \"github.com\/libp2p\/go-libp2p-peer\"\n\tmc \"github.com\/mediachain\/concat\/mc\"\n\tpb \"github.com\/mediachain\/concat\/proto\"\n\tmultihash \"github.com\/multiformats\/go-multihash\"\n\t\"log\"\n\t\"sync\"\n)\n\ntype ManifestStoreImpl struct {\n\tmx sync.Mutex\n\tmf map[string]ManifestRecord\n\tkeys map[string]p2p_crypto.PubKey\n}\n\ntype ManifestRecord struct {\n\tmf *pb.Manifest\n\tsrc p2p_peer.ID\n}\n\nfunc NewManifestStore() ManifestStore {\n\treturn &ManifestStoreImpl{\n\t\tmf: make(map[string]ManifestRecord),\n\t\tkeys: make(map[string]p2p_crypto.PubKey),\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Put(src p2p_peer.ID, lst []*pb.Manifest) {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tfor _, mf := range lst {\n\t\tmfs.putManifest(src, mf)\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) putManifest(src p2p_peer.ID, mf *pb.Manifest) {\n\tmfx, err := hashManifest(mf)\n\tif err != nil {\n\t\tlog.Printf(\"Error hashing manifest; wtf: %s\", err.Error())\n\t\treturn\n\t}\n\n\tmfh := mfx.B58String()\n\n\t_, ok := mfs.mf[mfh]\n\tif ok {\n\t\treturn\n\t}\n\n\tkid := mf.Entity + \":\" + mf.KeyId\n\tpubk, ok := mfs.keys[kid]\n\n\tif !ok {\n\t\t\/\/ XXX This can take arbitrary long and might need to be throttled\n\t\t\/\/ XXX and in the meantime, it holds the manifest store lock...\n\t\t\/\/ XXX The solution to this problem is to fetch keys asynchronously\n\t\t\/\/ XXX with back-off\/retry logic; impl is complicated though, so for now\n\t\t\/\/ XXX damn the torpedoes (but at least release the lock)\n\t\tmfs.mx.Unlock()\n\t\tpubk, err = mc.LookupEntityKey(mf.Entity, mf.KeyId)\n\t\tmfs.mx.Lock()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error looking up entity key %s: %s\", kid, err.Error())\n\t\t\treturn\n\t\t}\n\t\tmfs.keys[kid] = pubk\n\t}\n\n\tok, err = verifyManifest(mf, pubk)\n\tswitch {\n\tcase err != nil:\n\t\tlog.Printf(\"Error verifying manifest %s: %s\", mfh, err.Error())\n\n\tcase !ok:\n\t\tlog.Printf(\"Error verifying manifest %s: signature verification failed\", mfh)\n\n\tdefault:\n\t\t\/\/ yay! a valid manifest.\n\t\tmfs.mf[mfh] = ManifestRecord{mf, src}\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Remove(src p2p_peer.ID) {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tfor mfh, mfr := range mfs.mf {\n\t\tif mfr.src == src {\n\t\t\tdelete(mfs.mf, mfh)\n\t\t}\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) Lookup(entity string) []*pb.Manifest {\n\tmfs.mx.Lock()\n\tdefer mfs.mx.Unlock()\n\n\tswitch {\n\tcase entity == \"\":\n\t\tfallthrough\n\tcase entity == \"*\":\n\t\treturn mfs.lookupManifest(func(*pb.Manifest) bool {\n\t\t\treturn true\n\t\t})\n\n\tdefault:\n\t\treturn mfs.lookupManifest(func(mf *pb.Manifest) bool {\n\t\t\treturn mf.Entity == entity\n\t\t})\n\t}\n}\n\nfunc (mfs *ManifestStoreImpl) lookupManifest(filter func(*pb.Manifest) bool) []*pb.Manifest {\n\tres := make([]*pb.Manifest, 0)\n\tfor _, mfr := range mfs.mf {\n\t\tif filter(mfr.mf) {\n\t\t\tres = append(res, mfr.mf)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc hashManifest(mf *pb.Manifest) (multihash.Multihash, error) {\n\tbytes, err := ggproto.Marshal(mf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn mc.Hash(bytes), nil\n}\n\nfunc verifyManifest(mf *pb.Manifest, pubk p2p_crypto.PubKey) (bool, error) {\n\tsig := mf.Signature\n\tmf.Signature = nil\n\tbytes, err := ggproto.Marshal(mf)\n\tmf.Signature = sig\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn pubk.Verify(bytes, sig)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2013 Andrew Medworth\n\nThis file is part of Gopoker, a set of miscellaneous poker-related functions\nwritten in the Go programming language (http:\/\/golang.org).\n\nGopoker is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nGopoker is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with Gopoker. If not, see .\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/amdw\/gopoker\/poker_http\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n)\n\n\/\/ Try some sensible defaults to get the static content path\nfunc defaultStaticBaseDir() string {\n\t\/\/ First try something GOPATH-relative as this is most likely to work\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath != \"\" {\n\t\tgopaths := filepath.SplitList(gopath)\n\t\tfor _, p := range gopaths {\n\t\t\tcandidate := path.Join(p, \"src\", \"github.com\", \"amdw\", \"gopoker\", \"static\")\n\t\t\tlog.Println(\"Trying\", candidate)\n\t\t\tdirInfo, err := os.Stat(candidate)\n\t\t\tif err == nil && dirInfo.IsDir() {\n\t\t\t\treturn candidate\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ If that didn't work, try the current directory\n\tcurrentDir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Println(\"Warning: could not get current working directory:\", err)\n\t\treturn \".\/static\"\n\t}\n\treturn path.Join(currentDir, \"static\")\n}\n\nfunc main() {\n\tvar port int\n\tvar staticBaseDir string\n\tflag.IntVar(&port, \"port\", 8080, \"Listen port for HTTP server\")\n\tflag.StringVar(&staticBaseDir, \"staticbasedir\", defaultStaticBaseDir(), \"Base directory containing static content\")\n\tflag.Parse()\n\n\tdirInfo, err := os.Stat(staticBaseDir)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not stat static content base dir '%v' - provide it on the command line or ensure GOPATH is set correctly.\\n(Error: %v)\", staticBaseDir, err)\n\t}\n\tif !dirInfo.IsDir() {\n\t\tlog.Fatalf(\"staticbasedir '%v' is not a directory\", staticBaseDir)\n\t}\n\n\tlog.Println(\"Using static content base dir\", staticBaseDir)\n\tlog.Printf(\"Listening on port %v...\\n\", port)\n\n\thttp.HandleFunc(\"\/\", poker_http.Menu)\n\thttp.HandleFunc(\"\/holdem\/play\", poker_http.PlayHoldem)\n\thttp.HandleFunc(\"\/holdem\/simulate\", poker_http.SimulateHoldem(staticBaseDir))\n\thttp.HandleFunc(\"\/holdem\/startingcards\", poker_http.StartingCards(staticBaseDir))\n\thttp.HandleFunc(\"\/holdem\/startingcards\/sim\", poker_http.SimulateStartingCards)\n\thttp.HandleFunc(\"\/omaha8\/play\", poker_http.PlayOmaha8)\n\terr = http.ListenAndServe(fmt.Sprintf(\":%v\", port), nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}\nUpdate file header\/*\nCopyright 2013, 2015, 2017 Andrew Medworth\n\nThis file is part of Gopoker, a set of miscellaneous poker-related functions\nwritten in the Go programming language (http:\/\/golang.org).\n\nGopoker is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nGopoker is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with Gopoker. If not, see .\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/amdw\/gopoker\/poker_http\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n)\n\n\/\/ Try some sensible defaults to get the static content path\nfunc defaultStaticBaseDir() string {\n\t\/\/ First try something GOPATH-relative as this is most likely to work\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath != \"\" {\n\t\tgopaths := filepath.SplitList(gopath)\n\t\tfor _, p := range gopaths {\n\t\t\tcandidate := path.Join(p, \"src\", \"github.com\", \"amdw\", \"gopoker\", \"static\")\n\t\t\tlog.Println(\"Trying\", candidate)\n\t\t\tdirInfo, err := os.Stat(candidate)\n\t\t\tif err == nil && dirInfo.IsDir() {\n\t\t\t\treturn candidate\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ If that didn't work, try the current directory\n\tcurrentDir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Println(\"Warning: could not get current working directory:\", err)\n\t\treturn \".\/static\"\n\t}\n\treturn path.Join(currentDir, \"static\")\n}\n\nfunc main() {\n\tvar port int\n\tvar staticBaseDir string\n\tflag.IntVar(&port, \"port\", 8080, \"Listen port for HTTP server\")\n\tflag.StringVar(&staticBaseDir, \"staticbasedir\", defaultStaticBaseDir(), \"Base directory containing static content\")\n\tflag.Parse()\n\n\tdirInfo, err := os.Stat(staticBaseDir)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not stat static content base dir '%v' - provide it on the command line or ensure GOPATH is set correctly.\\n(Error: %v)\", staticBaseDir, err)\n\t}\n\tif !dirInfo.IsDir() {\n\t\tlog.Fatalf(\"staticbasedir '%v' is not a directory\", staticBaseDir)\n\t}\n\n\tlog.Println(\"Using static content base dir\", staticBaseDir)\n\tlog.Printf(\"Listening on port %v...\\n\", port)\n\n\thttp.HandleFunc(\"\/\", poker_http.Menu)\n\thttp.HandleFunc(\"\/holdem\/play\", poker_http.PlayHoldem)\n\thttp.HandleFunc(\"\/holdem\/simulate\", poker_http.SimulateHoldem(staticBaseDir))\n\thttp.HandleFunc(\"\/holdem\/startingcards\", poker_http.StartingCards(staticBaseDir))\n\thttp.HandleFunc(\"\/holdem\/startingcards\/sim\", poker_http.SimulateStartingCards)\n\thttp.HandleFunc(\"\/omaha8\/play\", poker_http.PlayOmaha8)\n\terr = http.ListenAndServe(fmt.Sprintf(\":%v\", port), nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"net\/http\"\n\t\"os\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/gommon\/log\"\n)\n\nfunc main() {\n\te := echo.New()\n\n\te.GET(\"\/:filename\", func(c echo.Context) error {\n\t\tfile, err := os.Open(c.Param(\"filename\"))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdata, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\tlog.Error(data)\n\t\t\treturn err\n\t\t}\n\t\tmimeType := http.DetectContentType(data)\n\t\treturn c.Blob(http.StatusOK, mimeType, data)\n\t})\n\n\te.POST(\"\/\", func(c echo.Context) error {\n\t\tphoto, err := c.FormFile(\"photo\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tsrc, err := photo.Open()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\tdst, err := os.Create(photo.Filename)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tif _, err = io.Copy(dst, src); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.NoContent(http.StatusCreated)\n\t})\n\n\te.PUT(\"\/:filename\", func(c echo.Context) error {\n\t\tphoto, err := c.FormFile(\"photo\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tsrc, err := photo.Open()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\tdst, err := os.Create(c.Param(\"filename\"))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tif _, err = io.Copy(dst, src); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.NoContent(http.StatusOK)\n\t})\n\n\te.DELETE(\"\/:filename\", func(c echo.Context) error {\n\t\tif err := os.Remove(c.Param(\"filename\")); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.NoContent(http.StatusOK)\n\t})\n\n\te.Logger.Debug(e.Start(\":1323\"))\n}\nChange filenamepackage main\n\nimport (\n\t\"net\/http\"\n\t\"os\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/gommon\/log\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Created struct {\n\tId string\n}\n\nfunc main() {\n\te := echo.New()\n\n\te.GET(\"\/:id\", func(c echo.Context) error {\n\t\tfile, err := os.Open(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdata, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\tlog.Error(data)\n\t\t\treturn err\n\t\t}\n\t\tmimeType := http.DetectContentType(data)\n\t\treturn c.Blob(http.StatusOK, mimeType, data)\n\t})\n\n\te.POST(\"\/\", func(c echo.Context) error {\n\t\tphoto, err := c.FormFile(\"photo\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tsrc, err := photo.Open()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\tdata, err := ioutil.ReadAll(src)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\tdataHash := fmt.Sprintf(\"%x\", md5.Sum(data))\n\t\tfilename := fmt.Sprintf(\"%x\", md5.Sum([]byte(dataHash + time.Now().String())))\n\t\tdst, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tif _, err = io.Copy(dst, src); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.JSON(http.StatusCreated, Created{filename})\n\t})\n\n\te.PUT(\"\/:id\", func(c echo.Context) error {\n\t\tphoto, err := c.FormFile(\"photo\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tsrc, err := photo.Open()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\tdst, err := os.Create(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tif _, err = io.Copy(dst, src); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.NoContent(http.StatusOK)\n\t})\n\n\te.DELETE(\"\/:id\", func(c echo.Context) error {\n\t\tif err := os.Remove(c.Param(\"id\")); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn c.NoContent(http.StatusOK)\n\t})\n\n\te.Logger.Debug(e.Start())\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\".\/rakefile\"\n)\n\nfunc main() {\n\trakefile.IsFile(\"rakefile\/rakefile.go\")\n}\nMore.package main\n\nimport (\n\t\".\/rakefile\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n)\n\nfunc main() {\n\trakefile.IsFile(\"rakefile\/rakefile.go\")\n\tcli.NewApp().Run(os.Args)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\nimport (\n\t\"github.com\/satori\/go.uuid\"\n\t\"github.com\/speps\/go-hashids\"\n)\n\nvar rooms = make(map[int]*Room)\nvar roomsMU sync.Mutex\nvar counter int = 0\n\nvar cards []Card\nvar HashID *hashids.HashID\nvar colors = []string{\"Magenta\", \"LightSlateGray\", \"PaleVioletRed\", \"Peru\", \"RebeccaPurple\", \"LightSeaGreen\", \"Tomato\", \"SeaGreen\", \"Maroon\", \"GoldenRod\", \"DarkSlateBlue\"}\n\ntype Card struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n}\n\ntype Room struct {\n\tID int\n\tPlayers []Player `json:\"players\"`\n\tStarted bool `json:\"started\"`\n\tLocation int `json:\"-\"`\n\tCountdown int `json:\"-\"`\n}\n\ntype Player struct {\n\tName string `json:\"name\"`\n\tColor string `json:\"color\"`\n\tAdmin bool `json:\"-\"`\n\tUUID string `json:\"-\"`\n\tSpy bool `json:\"-\"`\n}\n\nfunc (r Room) playerForUUID(uuid string) (p Player, found bool) {\n\tfor _, value := range r.Players {\n\t\tif value.UUID == uuid {\n\t\t\treturn value, true\n\t\t}\n\t}\n\treturn Player{}, false\n}\n\nfunc (r Room) playerForCookies(cookies []*http.Cookie) (p Player, found bool) {\n\tif len(cookies) == 0 {\n\t\treturn Player{}, false\n\t}\n\n\treturn r.playerForUUID(cookies[0].Value) \/\/ TODO: dont take first cookie, search for spyfall cookie\n}\n\nfunc (r *Room) setup() {\n\tr.Location = rand.Intn(len(cards))\n\tspy := rand.Intn(len(r.Players))\n\tr.Players[spy].Spy = true\n\n\tt := int(time.Now().Unix())\n\tt = t + (60 * 10)\n\tr.Countdown = t\n\tr.Started = true\n}\n\nfunc main() {\n\tvar (\n\t\thttpAddr = flag.String(\"http\", \":3000\", \"HTTP service address\")\n\t\tsalt = flag.String(\"salt\", \"super secret salt\", \"Salt is the secret used to make the generated id harder to guess\")\n\t)\n\tflag.Parse()\n\n\tcardsJSON, _ := ioutil.ReadFile(\"static\/cards\/cards.json\")\n\tjson.Unmarshal([]byte(cardsJSON), &cards)\n\n\thd := hashids.NewData()\n\thd.Salt = *salt\n\thd.MinLength = 5\n\thd.Alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\tHashID = hashids.NewWithData(hd)\n\n\thttp.HandleFunc(\"\/room\/new\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\n\t\tc, _ := HashID.Encode([]int{counter})\n\n\t\tuuidS := uuid.NewV4().String()\n\t\tadmin := Player{Name: colors[0], Color: colors[0], Admin: true, UUID: uuidS, Spy: false}\n\t\tplayers := []Player{admin}\n\t\trooms[counter] = &Room{ID: counter, Players: players, Started: false}\n\n\t\texpiration := time.Now().Add(365 * 24 * time.Hour)\n\t\tcookie := http.Cookie{Name: \"spyfall\", Value: uuidS, Path: \"\/\", Expires: expiration}\n\t\thttp.SetCookie(w, &cookie)\n\t\tfmt.Println(\"created new room\", c, counter)\n\n\t\tcounter++\n\t\thttp.Redirect(w, r, \"\/room?code=\"+c, 303)\n\t})\n\n\thttp.HandleFunc(\"\/room\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\n\t\tc := r.URL.Query().Get(\"code\")\n\n\t\td := HashID.Decode(c)\n\t\troomID := d[0]\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tif room.Started {\n\t\t\t\thttp.Redirect(w, r, \"\/\", 303) \/\/ TODO: show error message that room already started\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar player Player\n\n\t\t\tif p, ok := room.playerForCookies(r.Cookies()); ok {\n\t\t\t\tplayer = p\n\t\t\t} else {\n\t\t\t\tuuidS := uuid.NewV4().String()\n\t\t\t\tcolor := colors[len(room.Players)]\n\t\t\t\tplayer = Player{Name: color, Color: color, Admin: false, UUID: uuidS, Spy: false}\n\n\t\t\t\texpiration := time.Now().Add(365 * 24 * time.Hour)\n\t\t\t\tcookie := http.Cookie{Name: \"spyfall\", Value: uuidS, Path: \"\/\", Expires: expiration}\n\t\t\t\thttp.SetCookie(w, &cookie)\n\n\t\t\t\troom.Players = append(room.Players, player)\n\t\t\t}\n\n\t\t\tt, _ := template.ParseFiles(\"static\/room.html\")\n\t\t\tdata := struct {\n\t\t\t\tID int\n\t\t\t\tCode string\n\t\t\t\tPlayer Player\n\t\t\t}{\n\t\t\t\tID: roomID, Code: c, Player: player,\n\t\t\t}\n\t\t\tt.Execute(w, data)\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"\/\", 303)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.HandleFunc(\"\/game\", func(w http.ResponseWriter, r *http.Request) {\n\t\troomIDStr := r.URL.Query().Get(\"id\")\n\t\troomID, err := strconv.Atoi(roomIDStr)\n\t\tif err != nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tif room.Started == false {\n\t\t\t\troom.setup()\n\t\t\t\tfmt.Println(\"Started room\", roomID)\n\t\t\t}\n\t\t\tt, _ := template.ParseFiles(\"static\/game.html\")\n\t\t\tcookie := r.Cookies()[0]\n\t\t\tuuid := cookie.Value\n\t\t\tplayer, ok := room.playerForUUID(uuid)\n\t\t\tif !ok {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdata := struct {\n\t\t\t\tSpy bool\n\t\t\t\tLocation int\n\t\t\t\tCards []Card\n\t\t\t\tCountdown int\n\t\t\t}{\n\t\t\t\tSpy: player.Spy, Location: room.Location, Cards: cards, Countdown: room.Countdown,\n\t\t\t}\n\n\t\t\tt.Execute(w, data)\n\t\t} else {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.HandleFunc(\"\/players.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\troomIDStr := r.URL.Query().Get(\"id\")\n\t\troomID, err := strconv.Atoi(roomIDStr)\n\t\tif err != nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tjs, err := json.Marshal(room)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write(js)\n\t\t} else {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.Handle(\"\/\", http.FileServer(http.Dir(\".\/static\")))\n\tfmt.Println(\"listen on\", *httpAddr)\n\tlog.Fatal(http.ListenAndServe(*httpAddr, nil))\n}\nset round time to 8 minutespackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\nimport (\n\t\"github.com\/satori\/go.uuid\"\n\t\"github.com\/speps\/go-hashids\"\n)\n\nvar rooms = make(map[int]*Room)\nvar roomsMU sync.Mutex\nvar counter int = 0\n\nvar cards []Card\nvar HashID *hashids.HashID\nvar colors = []string{\"Magenta\", \"LightSlateGray\", \"PaleVioletRed\", \"Peru\", \"RebeccaPurple\", \"LightSeaGreen\", \"Tomato\", \"SeaGreen\", \"Maroon\", \"GoldenRod\", \"DarkSlateBlue\"}\n\ntype Card struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n}\n\ntype Room struct {\n\tID int\n\tPlayers []Player `json:\"players\"`\n\tStarted bool `json:\"started\"`\n\tLocation int `json:\"-\"`\n\tCountdown int `json:\"-\"`\n}\n\ntype Player struct {\n\tName string `json:\"name\"`\n\tColor string `json:\"color\"`\n\tAdmin bool `json:\"-\"`\n\tUUID string `json:\"-\"`\n\tSpy bool `json:\"-\"`\n}\n\nfunc (r Room) playerForUUID(uuid string) (p Player, found bool) {\n\tfor _, value := range r.Players {\n\t\tif value.UUID == uuid {\n\t\t\treturn value, true\n\t\t}\n\t}\n\treturn Player{}, false\n}\n\nfunc (r Room) playerForCookies(cookies []*http.Cookie) (p Player, found bool) {\n\tif len(cookies) == 0 {\n\t\treturn Player{}, false\n\t}\n\n\treturn r.playerForUUID(cookies[0].Value) \/\/ TODO: dont take first cookie, search for spyfall cookie\n}\n\nfunc (r *Room) setup() {\n\tr.Location = rand.Intn(len(cards))\n\tspy := rand.Intn(len(r.Players))\n\tr.Players[spy].Spy = true\n\n\tt := int(time.Now().Unix())\n\tt = t + (60 * 8)\n\tr.Countdown = t\n\tr.Started = true\n}\n\nfunc main() {\n\tvar (\n\t\thttpAddr = flag.String(\"http\", \":3000\", \"HTTP service address\")\n\t\tsalt = flag.String(\"salt\", \"super secret salt\", \"Salt is the secret used to make the generated id harder to guess\")\n\t)\n\tflag.Parse()\n\n\tcardsJSON, _ := ioutil.ReadFile(\"static\/cards\/cards.json\")\n\tjson.Unmarshal([]byte(cardsJSON), &cards)\n\n\thd := hashids.NewData()\n\thd.Salt = *salt\n\thd.MinLength = 5\n\thd.Alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\tHashID = hashids.NewWithData(hd)\n\n\thttp.HandleFunc(\"\/room\/new\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\n\t\tc, _ := HashID.Encode([]int{counter})\n\n\t\tuuidS := uuid.NewV4().String()\n\t\tadmin := Player{Name: colors[0], Color: colors[0], Admin: true, UUID: uuidS, Spy: false}\n\t\tplayers := []Player{admin}\n\t\trooms[counter] = &Room{ID: counter, Players: players, Started: false}\n\n\t\texpiration := time.Now().Add(365 * 24 * time.Hour)\n\t\tcookie := http.Cookie{Name: \"spyfall\", Value: uuidS, Path: \"\/\", Expires: expiration}\n\t\thttp.SetCookie(w, &cookie)\n\t\tfmt.Println(\"created new room\", c, counter)\n\n\t\tcounter++\n\t\thttp.Redirect(w, r, \"\/room?code=\"+c, 303)\n\t})\n\n\thttp.HandleFunc(\"\/room\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\n\t\tc := r.URL.Query().Get(\"code\")\n\n\t\td := HashID.Decode(c)\n\t\troomID := d[0]\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tif room.Started {\n\t\t\t\thttp.Redirect(w, r, \"\/\", 303) \/\/ TODO: show error message that room already started\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar player Player\n\n\t\t\tif p, ok := room.playerForCookies(r.Cookies()); ok {\n\t\t\t\tplayer = p\n\t\t\t} else {\n\t\t\t\tuuidS := uuid.NewV4().String()\n\t\t\t\tcolor := colors[len(room.Players)]\n\t\t\t\tplayer = Player{Name: color, Color: color, Admin: false, UUID: uuidS, Spy: false}\n\n\t\t\t\texpiration := time.Now().Add(365 * 24 * time.Hour)\n\t\t\t\tcookie := http.Cookie{Name: \"spyfall\", Value: uuidS, Path: \"\/\", Expires: expiration}\n\t\t\t\thttp.SetCookie(w, &cookie)\n\n\t\t\t\troom.Players = append(room.Players, player)\n\t\t\t}\n\n\t\t\tt, _ := template.ParseFiles(\"static\/room.html\")\n\t\t\tdata := struct {\n\t\t\t\tID int\n\t\t\t\tCode string\n\t\t\t\tPlayer Player\n\t\t\t}{\n\t\t\t\tID: roomID, Code: c, Player: player,\n\t\t\t}\n\t\t\tt.Execute(w, data)\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"\/\", 303)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.HandleFunc(\"\/game\", func(w http.ResponseWriter, r *http.Request) {\n\t\troomIDStr := r.URL.Query().Get(\"id\")\n\t\troomID, err := strconv.Atoi(roomIDStr)\n\t\tif err != nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tif room.Started == false {\n\t\t\t\troom.setup()\n\t\t\t\tfmt.Println(\"Started room\", roomID)\n\t\t\t}\n\t\t\tt, _ := template.ParseFiles(\"static\/game.html\")\n\t\t\tcookie := r.Cookies()[0]\n\t\t\tuuid := cookie.Value\n\t\t\tplayer, ok := room.playerForUUID(uuid)\n\t\t\tif !ok {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdata := struct {\n\t\t\t\tSpy bool\n\t\t\t\tLocation int\n\t\t\t\tCards []Card\n\t\t\t\tCountdown int\n\t\t\t}{\n\t\t\t\tSpy: player.Spy, Location: room.Location, Cards: cards, Countdown: room.Countdown,\n\t\t\t}\n\n\t\t\tt.Execute(w, data)\n\t\t} else {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.HandleFunc(\"\/players.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\troomIDStr := r.URL.Query().Get(\"id\")\n\t\troomID, err := strconv.Atoi(roomIDStr)\n\t\tif err != nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\troomsMU.Lock()\n\t\tdefer roomsMU.Unlock()\n\t\tif room, ok := rooms[roomID]; ok {\n\t\t\tjs, err := json.Marshal(room)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write(js)\n\t\t} else {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t})\n\n\thttp.Handle(\"\/\", http.FileServer(http.Dir(\".\/static\")))\n\tfmt.Println(\"listen on\", *httpAddr)\n\tlog.Fatal(http.ListenAndServe(*httpAddr, nil))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/rollbrettler\/daily-stars\/stars\"\n)\n\nvar port string\n\nfunc init() {\n\tflag.StringVar(&port, \"port\", \":8001\", \"Port to listen on\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\thttp.HandleFunc(\"\/\", showStar)\n\tfs := http.FileServer(http.Dir(\"assets\"))\n\thttp.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", fs))\n\thttp.HandleFunc(\"\/favicon.ico\", handleFavicon)\n\thttp.ListenAndServe(port, nil)\n}\n\nfunc handleFavicon(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"\"))\n}\n\nfunc showStar(w http.ResponseWriter, r *http.Request) {\n\n\tusername := username(r.URL)\n\tlog.Printf(\"%v\\n\", username)\n\ts := stars.Stars{\n\t\tUsername: username,\n\t}\n\n\trepos, err := s.Repos()\n\tif err != nil {\n\t\tw.Write([]byte(\"Wrong username\"))\n\t}\n\n\tt, _ := template.ParseFiles(\"html\/index.html\")\n\n\tt.Execute(w, repos)\n}\n\nfunc username(s *url.URL) string {\n\treturn strings.SplitN(s.Path, \"\/\", 3)[1]\n}\nAdd posibility to use env variable for the portpackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/rollbrettler\/daily-stars\/stars\"\n)\n\nvar port string\n\nfunc init() {\n\tflag.StringVar(&port, \"port\", \":8001\", \"Port to listen on\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tenvPort := os.Getenv(\"PORT\")\n\n\tif envPort != \"\" {\n\t\tport = \":\" + envPort\n\t}\n\n\thttp.HandleFunc(\"\/\", showStar)\n\tfs := http.FileServer(http.Dir(\"assets\"))\n\thttp.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", fs))\n\thttp.HandleFunc(\"\/favicon.ico\", handleFavicon)\n\thttp.ListenAndServe(port, nil)\n}\n\nfunc handleFavicon(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"\"))\n}\n\nfunc showStar(w http.ResponseWriter, r *http.Request) {\n\n\tusername := username(r.URL)\n\tlog.Printf(\"%v\\n\", username)\n\ts := stars.Stars{\n\t\tUsername: username,\n\t}\n\n\trepos, err := s.Repos()\n\tif err != nil {\n\t\tw.Write([]byte(\"Wrong username\"))\n\t}\n\n\tt, _ := template.ParseFiles(\"html\/index.html\")\n\n\tt.Execute(w, repos)\n}\n\nfunc username(s *url.URL) string {\n\treturn strings.SplitN(s.Path, \"\/\", 3)[1]\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/drone\/routes\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\ntype HttpSettings struct {\n\tport int\n}\n\ntype BitTorrentSettings struct {\n\tport int\n\tdownloadRate int\n\tuploadRate int\n\tkeepFiles bool\n}\n\ntype Settings struct {\n\thttp HttpSettings\n\tbitTorrent BitTorrentSettings\n}\n\ntype Server struct {\n\tsettings Settings\n\tmagnets map[string]*Magnet\n}\n\nfunc NewServer() *Server {\n\treturn &Server{magnets: make(map[string]*Magnet)}\n}\n\nvar server = NewServer()\n\nfunc (server *Server) Run() {\n\tlog.Println(\"[HTTP] Starting on port\", server.settings.http.port)\n\n\tmux := routes.New()\n\tmux.Get(\"\/add\", add)\n\tmux.Get(\"\/files\/:infohash\", files)\n\tmux.Get(\"\/files\/:infohash\/:file\", files)\n\tmux.Get(\"\/shutdown\", shutdown)\n\n\thttp.Handle(\"\/\", mux)\n\thttp.ListenAndServe(\":\"+strconv.Itoa(server.settings.http.port), nil)\n}\n\nfunc add(w http.ResponseWriter, r *http.Request) {\n\tmagnetLink := r.URL.Query().Get(\"magnet\")\n\n\tdownloadDir := r.URL.Query().Get(\"download_dir\")\n\tif downloadDir == \"\" {\n\t\tdownloadDir = \".\"\n\t}\n\n\tif magnetLink != \"\" {\n\t\tmagnet := NewMagnet(magnetLink, downloadDir)\n\t\tmagnet.Files = append(magnet.Files, NewMagnetFile(\"Guardians of the Galaxy (2014).mp4\"))\n\t\tserver.magnets[magnetLink] = magnet\n\n\t\tlog.Printf(\"[HTTP] Downloading %s to %s\\n\", magnetLink, downloadDir)\n\t\tfmt.Fprintf(w, \"\")\n\t} else {\n\t\thttp.Error(w, \"Missing Magnet link\", http.StatusBadRequest)\n\t}\n}\n\nfunc files(w http.ResponseWriter, r *http.Request) {\n\tinfoHash := r.URL.Query().Get(\":infohash\")\n\tfile := r.URL.Query().Get(\":file\")\n\n\tif magnet, ok := server.magnets[infoHash]; ok {\n\t\tif file != \"\" {\n\t\t\tr.URL.Path = file\n\t\t\tlog.Printf(\"[HTTP] Serving %s: %s\\n\", magnet.InfoHash, path.Join(magnet.DownloadDir, file))\n\t\t\thttp.FileServer(MagnetFileSystem{magnet}).ServeHTTP(w, r)\n\t\t} else {\n\t\t\tlog.Println(\"[HTTP] Listing\", magnet.InfoHash)\n\t\t\troutes.ServeJson(w, magnet)\n\t\t}\n\t} else {\n\t\thttp.Error(w, \"Invalid Magnet info hash\", http.StatusNotFound)\n\t}\n}\n\nfunc shutdown(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"[HTTP] Shutting down\")\n\tos.Exit(0)\n}\nAdd \/files endpoint to list all active magnet linkspackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/drone\/routes\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n)\n\ntype HttpSettings struct {\n\tport int\n}\n\ntype BitTorrentSettings struct {\n\tport int\n\tdownloadRate int\n\tuploadRate int\n\tkeepFiles bool\n}\n\ntype Settings struct {\n\thttp HttpSettings\n\tbitTorrent BitTorrentSettings\n}\n\ntype Server struct {\n\tsettings Settings\n\tmagnets map[string]*Magnet\n}\n\nfunc NewServer() *Server {\n\treturn &Server{magnets: make(map[string]*Magnet)}\n}\n\nvar server = NewServer()\n\nfunc (server *Server) Run() {\n\tlog.Println(\"[HTTP] Starting on port\", server.settings.http.port)\n\n\tmux := routes.New()\n\tmux.Get(\"\/add\", add)\n\tmux.Get(\"\/files\", files)\n\tmux.Get(\"\/files\/:infohash\", files)\n\tmux.Get(\"\/files\/:infohash\/:file\", files)\n\tmux.Get(\"\/shutdown\", shutdown)\n\n\thttp.Handle(\"\/\", mux)\n\thttp.ListenAndServe(\":\"+strconv.Itoa(server.settings.http.port), nil)\n}\n\nfunc add(w http.ResponseWriter, r *http.Request) {\n\tmagnetLink := r.URL.Query().Get(\"magnet\")\n\n\tdownloadDir := r.URL.Query().Get(\"download_dir\")\n\tif downloadDir == \"\" {\n\t\tdownloadDir = \".\"\n\t}\n\n\tif magnetLink != \"\" {\n\t\tmagnet := NewMagnet(magnetLink, downloadDir)\n\t\tmagnet.Files = append(magnet.Files, NewMagnetFile(\"Guardians of the Galaxy (2014).mp4\"))\n\t\tserver.magnets[magnetLink] = magnet\n\n\t\tlog.Printf(\"[HTTP] Downloading %s to %s\\n\", magnetLink, downloadDir)\n\t\tfmt.Fprintf(w, \"\")\n\t} else {\n\t\thttp.Error(w, \"Missing Magnet link\", http.StatusBadRequest)\n\t}\n}\n\nfunc files(w http.ResponseWriter, r *http.Request) {\n\tinfoHash := r.URL.Query().Get(\":infohash\")\n\tfile := r.URL.Query().Get(\":file\")\n\n\tif infoHash != \"\" {\n\t\tif magnet, ok := server.magnets[infoHash]; ok {\n\t\t\tif file != \"\" {\n\t\t\t\tr.URL.Path = file\n\t\t\t\tlog.Printf(\"[HTTP] Serving %s: %s\\n\", magnet.InfoHash, path.Join(magnet.DownloadDir, file))\n\t\t\t\thttp.FileServer(MagnetFileSystem{magnet}).ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"[HTTP] Listing\", magnet.InfoHash)\n\t\t\t\troutes.ServeJson(w, magnet)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"Invalid Magnet info hash\", http.StatusNotFound)\n\t\t}\n\t} else {\n\t\tlog.Println(\"[HTTP] Listing all Magnets\")\n\t\troutes.ServeJson(w, server.magnets)\n\t}\n}\n\nfunc shutdown(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"[HTTP] Shutting down\")\n\tos.Exit(0)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"html\/template\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v1\"\n\n\t\"github.com\/fsnotify\/fsnotify\"\n)\n\nconst (\n\tcfgPath = \"\/etc\/nginx-static\/config\"\n\ttplPath = \"\/etc\/nginx\/nginx.conf.tpl\"\n\toutPath = \"\/etc\/nginx\/nginx.conf\"\n)\n\nfunc main() {\n\terr := do()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc do() error {\n\ttpl, err := template.ParseFiles(tplPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write initial config\n\terr = writeConfig(tpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start nginx\n\tcmd := exec.Command(\"\/usr\/sbin\/nginx\", \"-g\", \"daemon off;\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Shutdown listener\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, syscall.SIGTERM)\n\n\t\/\/ Config watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tlog.Println(\"event:\", event)\n\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\tlog.Println(\"modified file:\", event.Name)\n\t\t\t\t\terr := process(tpl, cmd)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"Failed to process config: %s\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Printf(\"Config watch error: %s\", err)\n\n\t\t\tcase <-stop:\n\t\t\t\t\/\/ Wait for a while\n\t\t\t\ttime.Sleep(30 * time.Second)\n\t\t\t\terr := cmd.Process.Signal(syscall.SIGINT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = watcher.Add(cfgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Wait()\n}\n\ntype SiteConfig struct {\n\tHost string `yaml:\"host\"`\n\tRoot string `yaml:\"root\"`\n\tRedirect string `yaml:\"redirect\"`\n}\n\nfunc writeConfig(tpl *template.Template) error {\n\tcfg, err := os.Open(cfgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cfg.Close()\n\n\thosts, err := getConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfp, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\treturn tpl.Execute(fp, hosts)\n}\n\nfunc getConfig(in io.Reader) ([]SiteConfig, error) {\n\thosts := make([]SiteConfig, 0)\n\n\tb, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(b, &hosts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hosts, nil\n}\n\nfunc process(tpl *template.Template, cmd *exec.Cmd) error {\n\terr := writeConfig(tpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Trigger reload of config\n\treturn cmd.Process.Signal(syscall.SIGHUP)\n}\nProcess config on any changepackage main\n\nimport (\n\t\"html\/template\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v1\"\n\n\t\"github.com\/fsnotify\/fsnotify\"\n)\n\nconst (\n\tcfgPath = \"\/etc\/nginx-static\/config\"\n\ttplPath = \"\/etc\/nginx\/nginx.conf.tpl\"\n\toutPath = \"\/etc\/nginx\/nginx.conf\"\n)\n\nfunc main() {\n\terr := do()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc do() error {\n\ttpl, err := template.ParseFiles(tplPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write initial config\n\terr = writeConfig(tpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start nginx\n\tcmd := exec.Command(\"\/usr\/sbin\/nginx\", \"-g\", \"daemon off;\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Shutdown listener\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, syscall.SIGTERM)\n\n\t\/\/ Config watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-watcher.Events:\n\t\t\t\terr := process(tpl, cmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Failed to process config: %s\", err)\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Printf(\"Config watch error: %s\", err)\n\t\t\tcase <-stop:\n\t\t\t\t\/\/ Wait for a while\n\t\t\t\ttime.Sleep(30 * time.Second)\n\t\t\t\terr := cmd.Process.Signal(syscall.SIGINT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = watcher.Add(cfgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Wait()\n}\n\ntype SiteConfig struct {\n\tHost string `yaml:\"host\"`\n\tRoot string `yaml:\"root\"`\n\tRedirect string `yaml:\"redirect\"`\n}\n\nfunc writeConfig(tpl *template.Template) error {\n\tcfg, err := os.Open(cfgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cfg.Close()\n\n\thosts, err := getConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfp, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\treturn tpl.Execute(fp, hosts)\n}\n\nfunc getConfig(in io.Reader) ([]SiteConfig, error) {\n\thosts := make([]SiteConfig, 0)\n\n\tb, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(b, &hosts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hosts, nil\n}\n\nfunc process(tpl *template.Template, cmd *exec.Cmd) error {\n\terr := writeConfig(tpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Trigger reload of config\n\treturn cmd.Process.Signal(syscall.SIGHUP)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n\t\"io\/ioutil\"\n\t\"log\/syslog\"\n\n log \"github.com\/Sirupsen\/logrus\"\n logrus_syslog \"github.com\/Sirupsen\/logrus\/hooks\/syslog\"\n\t\"golang.org\/x\/crypto\/ssh\"\n \"github.com\/rifflock\/lfshook\"\n \"github.com\/codegangsta\/cli\"\n\t\/\/ \"github.com\/davecgh\/go-spew\/spew\"\n)\n\nfunc setupLogging(logToSyslog bool, logFile string) {\n logLevel := log.InfoLevel\n if os.Getenv(\"DEBUG\") == \"true\" { logLevel = log.DebugLevel }\n log.SetLevel(logLevel)\n\n\tlog.SetFormatter(&log.TextFormatter{DisableColors: true})\n\n\tif (logToSyslog) { setupSyslogLogging() }\n\tif (len(logFile) > 0) { setupFileLogging(logFile) }\n}\n\nfunc setupSyslogLogging() {\n\tlog.Debugf(\"Logging to syslog\")\n\tlogrusSysLogHook, err := logrus_syslog.NewSyslogHook(\"\", \"localhost:514\", syslog.LOG_INFO, \"sshoney\")\n\tif err != nil { log.Fatalf(\"Failed to add syslog logrus hook - %s\", err) }\n\tlog.AddHook(logrusSysLogHook)\n}\n\nfunc setupFileLogging(logFile string) {\n\tlog.Debugf(\"Logging to %s\", logFile)\n\tlogrusFileHook := lfshook.NewHook(lfshook.PathMap{\n\t log.InfoLevel : logFile, log.WarnLevel : logFile, log.ErrorLevel : logFile, log.FatalLevel : logFile, log.PanicLevel : logFile,\n })\n\tlog.AddHook(logrusFileHook)\n}\n\nfunc setupSSHListener(port string, hostKey string) (ssh.ServerConfig, net.Listener) {\n\tsshConfig := &ssh.ServerConfig{\n\t\tPasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {\n\t\t\tremoteAddr := c.RemoteAddr().String()\n\t\t\tip := remoteAddr[0:strings.Index(remoteAddr, \":\")]\n\t\t\tlog.Printf(\"SSH connection from ip=[%s], username=[%s], password=[%s], version=[%s]\", ip, c.User(), pass, c.ClientVersion())\n\t\t\treturn nil, fmt.Errorf(\"invalid credentials\")\n\t\t},\n\t}\n\n\tprivateBytes, err := ioutil.ReadFile(hostKey)\n\tif err != nil { log.Fatalf(\"Failed to load private key %s. Run make gen_ssh_key %s\", hostKey, hostKey) }\n\n\tprivate, err := ssh.ParsePrivateKey(privateBytes)\n\tif err != nil { log.Fatal(\"Failed to parse private key\") }\n\tsshConfig.AddHostKey(private)\n\n portComplete := fmt.Sprintf(\":%s\", port)\n\tlistener, err := net.Listen(\"tcp4\", portComplete)\n\tif err != nil { log.Fatalf(\"failed to listen on *:%s\", port) }\n\n\tlog.Printf(\"listening on %s\", port)\n\n\treturn *sshConfig, listener;\n}\n\nfunc processConnections(sshConfig *ssh.ServerConfig, listener net.Listener) {\n\tfor {\n\t\ttcpConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"failed to accept incoming connection (%s)\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(sshConfig, tcpConn)\n\t}\n}\n\nfunc handleConnection(sshConfig *ssh.ServerConfig, tcpConn net.Conn) {\n\tdefer tcpConn.Close()\n\tlog.Debugf(\"new TCP connection from %s\", tcpConn.RemoteAddr())\n\n\tsshConn, _, _, err := ssh.NewServerConn(tcpConn, sshConfig)\n\tif err != nil {\n\t\tlog.Debugf(\"failed to handshake (%s)\", err)\n\t} else {\n\t\tsshConn.Close()\n\t}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"sshoney\"\n\tapp.Usage = \"SSH honeypot\"\n\tapp.Version = \"0.1.0\"\n\n\tapp.Flags = []cli.Flag {\n\t\tcli.BoolFlag{ Name: \"log-to-syslog\", Usage: \"log to syslog\" },\n\t\tcli.StringFlag{\n\t Name: \"port\",\n\t Usage: \"port to listen on\",\n\t\t\tValue: \"2222\",\n\t\t\tEnvVar: \"PORT\",\n\t },\n\t\tcli.StringFlag{\n\t Name: \"host-key\",\n\t Usage: \"SSH private host key\",\n\t\t\tValue: \"host.key\",\n\t\t\tEnvVar: \"HOST_KEY\",\n\t },\n\t cli.StringFlag{\n\t Name: \"log-file\",\n\t Usage: \"path to logfile\",\n\t\t\tEnvVar: \"LOG_FILE\",\n\t },\n\t}\n\n\tapp.Action = func(c *cli.Context) {\n\t\tsetupLogging(c.Bool(\"log-to-syslog\"), c.String(\"log-file\"))\n\t\tsshConfig, listener := setupSSHListener(c.String(\"port\"), c.String(\"host-key\"))\n\t\tprocessConnections(&sshConfig, listener)\n\t}\n\n\tapp.Run(os.Args)\n}\nSupport the ability to define the syslog addr and program namepackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n\t\"io\/ioutil\"\n\t\"log\/syslog\"\n\n log \"github.com\/Sirupsen\/logrus\"\n logrus_syslog \"github.com\/Sirupsen\/logrus\/hooks\/syslog\"\n\t\"golang.org\/x\/crypto\/ssh\"\n \"github.com\/rifflock\/lfshook\"\n \"github.com\/codegangsta\/cli\"\n\t\/\/ \"github.com\/davecgh\/go-spew\/spew\"\n)\n\nfunc setupLogging(logToSyslog bool, syslogAddr string, syslogProgramName string, logFile string) {\n logLevel := log.InfoLevel\n if os.Getenv(\"DEBUG\") == \"true\" { logLevel = log.DebugLevel }\n log.SetLevel(logLevel)\n\n\tlog.SetFormatter(&log.TextFormatter{DisableColors: true})\n\n\tif (logToSyslog) { setupSyslogLogging(syslogAddr, syslogProgramName) }\n\tif (len(logFile) > 0) { setupFileLogging(logFile) }\n}\n\nfunc setupSyslogLogging(syslogAddr string, syslogProgramName string) {\n\tlog.Printf(\"Logging to syslog addr=[%s], program_name=[%s]\", syslogAddr, syslogProgramName)\n\tlogrusSysLogHook, err := logrus_syslog.NewSyslogHook(\"udp\", syslogAddr, syslog.LOG_INFO, syslogProgramName)\n\tif err != nil { log.Fatalf(\"Failed to add syslog logrus hook - %s\", err) }\n\tlog.AddHook(logrusSysLogHook)\n}\n\nfunc setupFileLogging(logFile string) {\n\tlog.Printf(\"Logging to file=[%s]\", logFile)\n\tlogrusFileHook := lfshook.NewHook(lfshook.PathMap{\n\t log.InfoLevel : logFile, log.WarnLevel : logFile, log.ErrorLevel : logFile, log.FatalLevel : logFile, log.PanicLevel : logFile,\n })\n\tlog.AddHook(logrusFileHook)\n}\n\nfunc setupSSHListener(port string, hostKey string) (ssh.ServerConfig, net.Listener) {\n\tsshConfig := &ssh.ServerConfig{\n\t\tPasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {\n\t\t\tremoteAddr := c.RemoteAddr().String()\n\t\t\tip := remoteAddr[0:strings.Index(remoteAddr, \":\")]\n\t\t\tlog.Printf(\"SSH connection from ip=[%s], username=[%s], password=[%s], version=[%s]\", ip, c.User(), pass, c.ClientVersion())\n\t\t\treturn nil, fmt.Errorf(\"invalid credentials\")\n\t\t},\n\t}\n\n\tprivateBytes, err := ioutil.ReadFile(hostKey)\n\tif err != nil { log.Fatalf(\"Failed to load private key %s. Run make gen_ssh_key %s\", hostKey, hostKey) }\n\n\tprivate, err := ssh.ParsePrivateKey(privateBytes)\n\tif err != nil { log.Fatal(\"Failed to parse private key\") }\n\tsshConfig.AddHostKey(private)\n\n portComplete := fmt.Sprintf(\":%s\", port)\n\tlistener, err := net.Listen(\"tcp4\", portComplete)\n\tif err != nil { log.Fatalf(\"failed to listen on *:%s\", port) }\n\n\tlog.Printf(\"listening on %s\", port)\n\n\treturn *sshConfig, listener;\n}\n\nfunc processConnections(sshConfig *ssh.ServerConfig, listener net.Listener) {\n\tfor {\n\t\ttcpConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"failed to accept incoming connection (%s)\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(sshConfig, tcpConn)\n\t}\n}\n\nfunc handleConnection(sshConfig *ssh.ServerConfig, tcpConn net.Conn) {\n\tdefer tcpConn.Close()\n\tlog.Debugf(\"new TCP connection from %s\", tcpConn.RemoteAddr())\n\n\tsshConn, _, _, err := ssh.NewServerConn(tcpConn, sshConfig)\n\tif err != nil {\n\t\tlog.Debugf(\"failed to handshake (%s)\", err)\n\t} else {\n\t\tsshConn.Close()\n\t}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"sshoney\"\n\tapp.Usage = \"SSH honeypot\"\n\tapp.Version = \"0.1.0\"\n\n\tapp.Flags = []cli.Flag {\n\t\tcli.BoolFlag{ Name: \"log-to-syslog\", Usage: \"log to syslog\" },\n\t\tcli.StringFlag{\n\t Name: \"port\",\n\t Usage: \"port to listen on\",\n\t\t\tValue: \"2222\",\n\t\t\tEnvVar: \"PORT\",\n\t },\n\t\tcli.StringFlag{\n\t Name: \"syslog-addr\",\n\t Usage: \"host:port of the syslog server\",\n\t\t\tValue: \"localhost:514\",\n\t\t\tEnvVar: \"SYSLOG_ADDR\",\n\t },\n\t\tcli.StringFlag{\n\t Name: \"syslog-program-name\",\n\t Usage: \"syslog program name to use\",\n\t\t\tValue: \"sshoney\",\n\t\t\tEnvVar: \"SYSLOG_PROGRAM_NAME\",\n\t },\n\t\tcli.StringFlag{\n\t Name: \"host-key\",\n\t Usage: \"SSH private host key\",\n\t\t\tValue: \"host.key\",\n\t\t\tEnvVar: \"HOST_KEY\",\n\t },\n\t cli.StringFlag{\n\t Name: \"log-file\",\n\t Usage: \"path to logfile\",\n\t\t\tEnvVar: \"LOG_FILE\",\n\t },\n\t}\n\n\tapp.Action = func(c *cli.Context) {\n\t\tsetupLogging(c.Bool(\"log-to-syslog\"), c.String(\"syslog-addr\"), c.String(\"syslog-program-name\"), c.String(\"log-file\"))\n\t\tsshConfig, listener := setupSSHListener(c.String(\"port\"), c.String(\"host-key\"))\n\t\tprocessConnections(&sshConfig, listener)\n\t}\n\n\tapp.Run(os.Args)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\tpiazza \"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n\tpzlogger \"github.com\/venicegeo\/pz-logger\/logger\"\n\tpzuuidgen \"github.com\/venicegeo\/pz-uuidgen\/uuidgen\"\n\tpzworkflow \"github.com\/venicegeo\/pz-workflow\/workflow\"\n)\n\nfunc main() {\n\tsys, logger, uuidgen := makeSystem()\n\n\tlogger.Info(\"pz-workflow starting...\")\n\n\tindices := makeIndexes(sys)\n\n\tworkflowServer := makeWorkflow(sys, indices, logger, uuidgen)\n\n\tserverLoop(sys, workflowServer)\n}\n\nfunc makeWorkflow(sys *piazza.SystemConfig,\n\tindices []*elasticsearch.Index,\n\tlogger *pzlogger.Client,\n\tuuidgen *pzuuidgen.Client) *pzworkflow.Server {\n\tworkflowService := &pzworkflow.Service{}\n\terr := workflowService.Init(\n\t\tsys,\n\t\tlogger,\n\t\tuuidgen,\n\t\tindices[0],\n\t\tindices[1],\n\t\tindices[2],\n\t\tindices[3],\n\t\tindices[4],\n\t\tindices[5])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = workflowService.InitCron()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tworkflowServer := &pzworkflow.Server{}\n\terr = workflowServer.Init(workflowService)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn workflowServer\n}\n\nfunc makeSystem() (\n\t*piazza.SystemConfig,\n\t*pzlogger.Client,\n\t*pzuuidgen.Client) {\n\n\trequired := []piazza.ServiceName{\n\t\tpiazza.PzElasticSearch,\n\t\tpiazza.PzLogger,\n\t\tpiazza.PzUuidgen,\n\t\tpiazza.PzKafka,\n\t\tpiazza.PzServiceController,\n\t}\n\n\tsys, err := piazza.NewSystemConfig(piazza.PzWorkflow, required)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger, err := pzlogger.NewClient(sys)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tuuidgen, err := pzuuidgen.NewClient(sys)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn sys, logger, uuidgen\n}\n\nfunc serverLoop(sys *piazza.SystemConfig,\n\tworkflowServer *pzworkflow.Server) {\n\tgenericServer := piazza.GenericServer{Sys: sys}\n\n\terr := genericServer.Configure(workflowServer.Routes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdone, err := genericServer.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = <-done\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc makeIndexes(sys *piazza.SystemConfig) []*elasticsearch.Index {\n\teventtypesIndex, err := elasticsearch.NewIndex(sys, \"eventtypes003\", pzworkflow.EventTypeIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\teventsIndex, err := elasticsearch.NewIndex(sys, \"events004\", pzworkflow.EventIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttriggersIndex, err := elasticsearch.NewIndex(sys, \"triggers003\", pzworkflow.TriggerIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\talertsIndex, err := elasticsearch.NewIndex(sys, \"alerts003\", pzworkflow.AlertIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcronIndex, err := elasticsearch.NewIndex(sys, \"crons003\", pzworkflow.CronIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttestElasticsearchIndex, err := elasticsearch.NewIndex(sys, \"testelasticsearch003\", pzworkflow.TestElasticsearchSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tret := []*elasticsearch.Index{\n\t\teventtypesIndex, eventsIndex, triggersIndex,\n\t\talertsIndex, cronIndex, testElasticsearchIndex,\n\t}\n\treturn ret\n}\ncompile fix\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\tpiazza \"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n\tpzlogger \"github.com\/venicegeo\/pz-logger\/logger\"\n\tpzuuidgen \"github.com\/venicegeo\/pz-uuidgen\/uuidgen\"\n\tpzworkflow \"github.com\/venicegeo\/pz-workflow\/workflow\"\n)\n\nfunc main() {\n\tsys, logger, uuidgen := makeSystem()\n\n\tlog.Printf(\"pz-workflow starting...\")\n\n\tindices := makeIndexes(sys)\n\n\tworkflowServer := makeWorkflow(sys, indices, logger, uuidgen)\n\n\tserverLoop(sys, workflowServer)\n}\n\nfunc makeWorkflow(sys *piazza.SystemConfig,\n\tindices []*elasticsearch.Index,\n\tlogger *pzlogger.Client,\n\tuuidgen *pzuuidgen.Client) *pzworkflow.Server {\n\tworkflowService := &pzworkflow.Service{}\n\terr := workflowService.Init(\n\t\tsys,\n\t\tlogger,\n\t\tuuidgen,\n\t\tindices[0],\n\t\tindices[1],\n\t\tindices[2],\n\t\tindices[3],\n\t\tindices[4],\n\t\tindices[5])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = workflowService.InitCron()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tworkflowServer := &pzworkflow.Server{}\n\terr = workflowServer.Init(workflowService)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn workflowServer\n}\n\nfunc makeSystem() (\n\t*piazza.SystemConfig,\n\t*pzlogger.Client,\n\t*pzuuidgen.Client) {\n\n\trequired := []piazza.ServiceName{\n\t\tpiazza.PzElasticSearch,\n\t\tpiazza.PzLogger,\n\t\tpiazza.PzUuidgen,\n\t\tpiazza.PzKafka,\n\t\tpiazza.PzServiceController,\n\t}\n\n\tsys, err := piazza.NewSystemConfig(piazza.PzWorkflow, required)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger, err := pzlogger.NewClient(sys)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tuuidgen, err := pzuuidgen.NewClient(sys)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn sys, logger, uuidgen\n}\n\nfunc serverLoop(sys *piazza.SystemConfig,\n\tworkflowServer *pzworkflow.Server) {\n\tgenericServer := piazza.GenericServer{Sys: sys}\n\n\terr := genericServer.Configure(workflowServer.Routes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdone, err := genericServer.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = <-done\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc makeIndexes(sys *piazza.SystemConfig) []*elasticsearch.Index {\n\teventtypesIndex, err := elasticsearch.NewIndex(sys, \"eventtypes003\", pzworkflow.EventTypeIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\teventsIndex, err := elasticsearch.NewIndex(sys, \"events004\", pzworkflow.EventIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttriggersIndex, err := elasticsearch.NewIndex(sys, \"triggers003\", pzworkflow.TriggerIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\talertsIndex, err := elasticsearch.NewIndex(sys, \"alerts003\", pzworkflow.AlertIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcronIndex, err := elasticsearch.NewIndex(sys, \"crons003\", pzworkflow.CronIndexSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttestElasticsearchIndex, err := elasticsearch.NewIndex(sys, \"testelasticsearch003\", pzworkflow.TestElasticsearchSettings)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tret := []*elasticsearch.Index{\n\t\teventtypesIndex, eventsIndex, triggersIndex,\n\t\talertsIndex, cronIndex, testElasticsearchIndex,\n\t}\n\treturn ret\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 The original author or authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/projectriff\/riff\/pkg\/core\"\n\n\t\"github.com\/projectriff\/riff\/cmd\/commands\"\n)\n\nvar (\n\tbuilder = \"projectriff\/builder\"\n\tdefaultRunImage = \"packs\/run\"\n\n\tmanifests = map[string]*core.Manifest{\n\t\t\"latest\": {\n\t\t\tManifestVersion: \"0.1\",\n\t\t\tIstio: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/latest\/istio.yaml\",\n\t\t\t},\n\t\t\tKnative: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/build\/latest\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/latest\/serving.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181106-a99376f\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181106-a99376f\/release-clusterbus-stub.yaml\",\n\t\t\t},\n\t\t\tNamespace: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/projectriff\/riff-buildtemplate\/riff-cnb-buildtemplate.yaml\",\n\t\t\t},\n\t\t},\n\t\t\"stable\": {\n\t\t\tManifestVersion: \"0.1\",\n\t\t\tIstio: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/previous\/v0.2.2\/istio.yaml\",\n\t\t\t},\n\t\t\tKnative: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/build\/previous\/v0.2.0\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/previous\/v0.2.2\/serving.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181031-a2f9417\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181031-a2f9417\/release-clusterbus-stub.yaml\",\n\t\t\t},\n\t\t\tNamespace: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/projectriff\/riff-buildtemplate\/riff-cnb-buildtemplate-0.0.1-snapshot-ci-a28efbae0dcb.yaml\",\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc main() {\n\n\troot := commands.CreateAndWireRootCommand(manifests, builder, defaultRunImage)\n\n\tsub, err := root.ExecuteC()\n\tif err != nil {\n\t\tif !sub.SilenceUsage { \/\/ May have been switched to true once we're past PreRunE()\n\t\t\tsub.Help()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"\\nError: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\nUse released version v0.1.0 of BuildTemplate\/*\n * Copyright 2018 The original author or authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/projectriff\/riff\/pkg\/core\"\n\n\t\"github.com\/projectriff\/riff\/cmd\/commands\"\n)\n\nvar (\n\tbuilder = \"projectriff\/builder\"\n\tdefaultRunImage = \"packs\/run\"\n\n\tmanifests = map[string]*core.Manifest{\n\t\t\"latest\": {\n\t\t\tManifestVersion: \"0.1\",\n\t\t\tIstio: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/latest\/istio.yaml\",\n\t\t\t},\n\t\t\tKnative: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/build\/latest\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/latest\/serving.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181106-a99376f\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181106-a99376f\/release-clusterbus-stub.yaml\",\n\t\t\t},\n\t\t\tNamespace: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/projectriff\/riff-buildtemplate\/riff-cnb-buildtemplate.yaml\",\n\t\t\t},\n\t\t},\n\t\t\"stable\": {\n\t\t\tManifestVersion: \"0.1\",\n\t\t\tIstio: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/previous\/v0.2.2\/istio.yaml\",\n\t\t\t},\n\t\t\tKnative: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/build\/previous\/v0.2.0\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/serving\/previous\/v0.2.2\/serving.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181031-a2f9417\/release.yaml\",\n\t\t\t\t\"https:\/\/storage.googleapis.com\/knative-releases\/eventing\/previous\/v20181031-a2f9417\/release-clusterbus-stub.yaml\",\n\t\t\t},\n\t\t\tNamespace: []string{\n\t\t\t\t\"https:\/\/storage.googleapis.com\/projectriff\/riff-buildtemplate\/riff-cnb-buildtemplate-0.1.0.yaml\",\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc main() {\n\n\troot := commands.CreateAndWireRootCommand(manifests, builder, defaultRunImage)\n\n\tsub, err := root.ExecuteC()\n\tif err != nil {\n\t\tif !sub.SilenceUsage { \/\/ May have been switched to true once we're past PreRunE()\n\t\t\tsub.Help()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"\\nError: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/VividCortex\/pm\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar statuses = []string{\"starting\",\n\t\"waiting for requests\",\n\t\"accepting request\",\n\t\"receiving data\",\n\t\"querying database\",\n\t\"sending data\",\n\t\"sending response\",\n}\n\nvar pid = 0\nvar mutex sync.Mutex\n\nvar wg sync.WaitGroup\nvar mapPack map[string]interface{}\n\n\/\/attributes *map[string]interface{}\nfunc SomeProcess() {\n\twg.Add(1)\n\tgo func() {\n\t\tmutex.Lock()\n\t\tpid++\n\t\tid := fmt.Sprint(pid)\n\t\tfmt.Println(\"ID: \" + id)\n\t\tmutex.Unlock()\n\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tfmt.Printf(\"pid [%s] cancelled\\n\", id)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\n\t\t\/\/ --- Generate a new, random Map ---\n\t\tattributes:=packValues();\n\n\t\t\/\/ --- Pass the map ---\n\t\tpm.Start(id, nil, &attributes)\n\t\tdefer pm.Done(id)\n\n\t\tfor _, status := range statuses {\n\t\t\ttime.Sleep(time.Duration((rand.Int()) % 7000 * int(time.Millisecond)))\n\t\t\tpm.Status(id, status)\n\t\t}\n\n\t\tSomeProcess()\n\t}()\n\n}\n\n\/\/ --- Not Inclusive of Maximum --- \nfunc randInt(min int , max int) int {\n rand.Seed( time.Now().UTC().UnixNano())\n return min + rand.Intn(max-min)\n}\n\nfunc packValues() map[string]interface{} {\n\n\t\/\/ --- Initialization ---\n\ttheMap:=make(map[string]interface{})\n\n\t\/\/ --- The 'bank' of values to pull from ---\n\ttaste := [] string{\n\t\t\"salty\", \n\t\t\"sweet\", \n\t\t\"sour\",\n\t}\n\tcolor := [] string{\n\t\t\"red\", \n\t\t\"green\", \n\t\t\"blue\",\n\t}\n\ttemperature := [] string{\n\t\t\"hot\", \n\t\t\"medium\", \n\t\t\"cold\",\n\t}\n\n\t\/\/ --- Randomize the Attributes ---\n\tnumAttrs := randInt(1, 4)\n\tfor i:=0; iRemoved superfluous output and commentspackage main\n\nimport (\n\t\"github.com\/VividCortex\/pm\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar statuses = []string{\"starting\",\n\t\"waiting for requests\",\n\t\"accepting request\",\n\t\"receiving data\",\n\t\"querying database\",\n\t\"sending data\",\n\t\"sending response\",\n}\n\nvar pid = 0\nvar mutex sync.Mutex\n\nvar wg sync.WaitGroup\nvar mapPack map[string]interface{}\n\nfunc SomeProcess() {\n\twg.Add(1)\n\tgo func() {\n\t\tmutex.Lock()\n\t\tpid++\n\t\tid := fmt.Sprint(pid)\n\t\tmutex.Unlock()\n\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tfmt.Printf(\"pid [%s] cancelled\\n\", id)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\n\t\t\/\/ --- Generate a new, random Map ---\n\t\tattributes:=packValues();\n\n\t\t\/\/ --- Pass the map ---\n\t\tpm.Start(id, nil, &attributes)\n\t\tdefer pm.Done(id)\n\n\t\tfor _, status := range statuses {\n\t\t\ttime.Sleep(time.Duration((rand.Int()) % 7000 * int(time.Millisecond)))\n\t\t\tpm.Status(id, status)\n\t\t}\n\n\t\tSomeProcess()\n\t}()\n\n}\n\n\/\/ --- Not Inclusive of Maximum --- \nfunc randInt(min int , max int) int {\n rand.Seed( time.Now().UTC().UnixNano())\n return min + rand.Intn(max-min)\n}\n\nfunc packValues() map[string]interface{} {\n\n\t\/\/ --- Initialization ---\n\ttheMap:=make(map[string]interface{})\n\n\t\/\/ --- The 'bank' of values to pull from ---\n\ttaste := [] string{\n\t\t\"salty\", \n\t\t\"sweet\", \n\t\t\"sour\",\n\t}\n\tcolor := [] string{\n\t\t\"red\", \n\t\t\"green\", \n\t\t\"blue\",\n\t}\n\ttemperature := [] string{\n\t\t\"hot\", \n\t\t\"medium\", \n\t\t\"cold\",\n\t}\n\n\t\/\/ --- Randomize the Attributes ---\n\tnumAttrs := randInt(1, 4)\n\tfor i:=0; i"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/pkg\/profile\"\n\t\"github.com\/verath\/archipelago\/lib\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"time\"\n)\n\nconst (\n\thttpReadTimeout = 10 * time.Second\n\thttpWriteTimeout = 10 * time.Second\n)\n\nfunc main() {\n\tvar (\n\t\tdebug bool\n\t\tserveStatic bool\n\t\tserverAddr string\n\t\tprofileMode string\n\t)\n\tflag.BoolVar(&debug, \"debug\", false, \"Set to true to log debug messages.\")\n\tflag.BoolVar(&serveStatic, \"servestatic\", false, \"Enable serving of static assets.\")\n\tflag.StringVar(&serverAddr, \"addr\", \":8080\", \"TCP address for the http server to listen on.\")\n\tflag.StringVar(&profileMode, \"profile\", \"\", \"Enable profiling mode, one of [cpu, mem, mutex, block]\")\n\tflag.Parse()\n\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.TextFormatter{}\n\tif debug {\n\t\tlogger.Level = logrus.DebugLevel\n\t}\n\t\/\/ Setup profiling, if profile flag was set\n\tswitch profileMode {\n\tcase \"cpu\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.CPUProfile).Stop()\n\tcase \"mem\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.MemProfile).Stop()\n\tcase \"mutex\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.MutexProfile).Stop()\n\tcase \"block\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.BlockProfile).Stop()\n\tdefault:\n\t}\n\n\tarchipelagoServer, err := archipelago.New(logger)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Error creating game: %+v\", err)\n\t}\n\n\thttp.Handle(\"\/ws\", archipelagoServer.WebsocketHandler())\n\tif serveStatic {\n\t\tstaticPath := \".\/web\/dist\"\n\t\t\/\/ Explicitly set a max-age of 0 for service worker script.\n\t\thttp.HandleFunc(\"\/sw.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Cache-Control\", \"max-age=0\")\n\t\t\thttp.ServeFile(w, r, path.Join(staticPath, \"sw.js\"))\n\t\t})\n\t\thttp.Handle(\"\/\", http.FileServer(http.Dir(staticPath)))\n\t}\n\thttpServer := &http.Server{\n\t\tAddr: serverAddr,\n\t\tReadTimeout: httpReadTimeout,\n\t\tWriteTimeout: httpWriteTimeout,\n\t}\n\n\tctx, cancel := context.WithCancel(lifetimeContext(logger))\n\terrCh := make(chan error)\n\tgo func() { errCh <- archipelagoServer.Run(ctx) }()\n\tgo func() { errCh <- runHTTPServer(ctx, httpServer) }()\n\terr = <-errCh\n\tcancel()\n\t<-errCh\n\tif errors.Cause(err) == context.Canceled {\n\t\tlogger.Debugf(\"Error caught in main: %+v\", err)\n\t} else {\n\t\tlogger.Fatalf(\"Error caught in main: %+v\", err)\n\t}\n}\n\n\/\/ lifetimeContext returns a context that is cancelled on the first SIGINT or\n\/\/ SIGKILL signal received. The application is force closed if more than\n\/\/ one signal is received.\nfunc lifetimeContext(logger *logrus.Logger) context.Context {\n\tctx, cancel := context.WithCancel(context.Background())\n\tstopSigs := make(chan os.Signal, 2)\n\tsignal.Notify(stopSigs, os.Interrupt, os.Kill)\n\tgo func() {\n\t\t<-stopSigs\n\t\tlogger.Info(\"Caught interrupt, shutting down\")\n\t\tcancel()\n\t\t<-stopSigs\n\t\tlogger.Fatal(\"Caught second interrupt, force closing\")\n\t}()\n\treturn ctx\n}\n\n\/\/ runHTTPServer starts and runs the given HTTP server until either an error\n\/\/ occurs or the context is cancelled.\nfunc runHTTPServer(ctx context.Context, server *http.Server) error {\n\terrCh := make(chan error)\n\tgo func() { errCh <- server.ListenAndServe() }()\n\tselect {\n\tcase err := <-errCh:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tserver.Close()\n\t\treturn ctx.Err()\n\t}\n}\nAdds an http \/healthcheck endpointpackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/pkg\/profile\"\n\t\"github.com\/verath\/archipelago\/lib\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"time\"\n)\n\nconst (\n\thttpReadTimeout = 10 * time.Second\n\thttpWriteTimeout = 10 * time.Second\n)\n\nfunc main() {\n\tvar (\n\t\tdebug bool\n\t\tserveStatic bool\n\t\tserverAddr string\n\t\tprofileMode string\n\t)\n\tflag.BoolVar(&debug, \"debug\", false, \"Set to true to log debug messages.\")\n\tflag.BoolVar(&serveStatic, \"servestatic\", false, \"Enable serving of static assets.\")\n\tflag.StringVar(&serverAddr, \"addr\", \":8080\", \"TCP address for the http server to listen on.\")\n\tflag.StringVar(&profileMode, \"profile\", \"\", \"Enable profiling mode, one of [cpu, mem, mutex, block]\")\n\tflag.Parse()\n\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.TextFormatter{}\n\tif debug {\n\t\tlogger.Level = logrus.DebugLevel\n\t}\n\t\/\/ Setup profiling, if profile flag was set\n\tswitch profileMode {\n\tcase \"cpu\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.CPUProfile).Stop()\n\tcase \"mem\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.MemProfile).Stop()\n\tcase \"mutex\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.MutexProfile).Stop()\n\tcase \"block\":\n\t\tdefer profile.Start(profile.NoShutdownHook, profile.ProfilePath(\".\"), profile.BlockProfile).Stop()\n\tdefault:\n\t}\n\n\tarchipelagoServer, err := archipelago.New(logger)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Error creating game: %+v\", err)\n\t}\n\n\thttp.Handle(\"\/ws\", archipelagoServer.WebsocketHandler())\n\tif serveStatic {\n\t\tstaticPath := \".\/web\/dist\"\n\t\t\/\/ Explicitly set a max-age of 0 for service worker script.\n\t\thttp.HandleFunc(\"\/sw.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Cache-Control\", \"max-age=0\")\n\t\t\thttp.ServeFile(w, r, path.Join(staticPath, \"sw.js\"))\n\t\t})\n\t\thttp.Handle(\"\/\", http.FileServer(http.Dir(staticPath)))\n\t}\n\thttp.HandleFunc(\"\/healthcheck\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t})\n\thttpServer := &http.Server{\n\t\tAddr: serverAddr,\n\t\tReadTimeout: httpReadTimeout,\n\t\tWriteTimeout: httpWriteTimeout,\n\t}\n\n\tctx, cancel := context.WithCancel(lifetimeContext(logger))\n\terrCh := make(chan error)\n\tgo func() { errCh <- archipelagoServer.Run(ctx) }()\n\tgo func() { errCh <- runHTTPServer(ctx, httpServer) }()\n\terr = <-errCh\n\tcancel()\n\t<-errCh\n\tif errors.Cause(err) == context.Canceled {\n\t\tlogger.Debugf(\"Error caught in main: %+v\", err)\n\t} else {\n\t\tlogger.Fatalf(\"Error caught in main: %+v\", err)\n\t}\n}\n\n\/\/ lifetimeContext returns a context that is cancelled on the first SIGINT or\n\/\/ SIGKILL signal received. The application is force closed if more than\n\/\/ one signal is received.\nfunc lifetimeContext(logger *logrus.Logger) context.Context {\n\tctx, cancel := context.WithCancel(context.Background())\n\tstopSigs := make(chan os.Signal, 2)\n\tsignal.Notify(stopSigs, os.Interrupt, os.Kill)\n\tgo func() {\n\t\t<-stopSigs\n\t\tlogger.Info(\"Caught interrupt, shutting down\")\n\t\tcancel()\n\t\t<-stopSigs\n\t\tlogger.Fatal(\"Caught second interrupt, force closing\")\n\t}()\n\treturn ctx\n}\n\n\/\/ runHTTPServer starts and runs the given HTTP server until either an error\n\/\/ occurs or the context is cancelled.\nfunc runHTTPServer(ctx context.Context, server *http.Server) error {\n\terrCh := make(chan error)\n\tgo func() { errCh <- server.ListenAndServe() }()\n\tselect {\n\tcase err := <-errCh:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tserver.Close()\n\t\treturn ctx.Err()\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ TODO: disconnect user if name not set\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n)\n\nfunc error_(err error, r int) {\n\tfmt.Printf(\"Error: %v\\n\", err)\n\tif r >= 0 {\n\t\tos.Exit(r)\n\t}\n}\n\ntype clientMap map[string]net.Conn\n\nfunc (cm clientMap) Write(buf []byte) (n int, err error) {\n\tfor _, c := range cm {\n\t\tgo c.Write(buf)\n\t}\n\tn = len(buf)\n\treturn\n}\n\nfunc (cm clientMap) Add(name string, c net.Conn) bool {\n\t_, present := cm[name]\n\tif present {\n\t\treturn false\n\t}\n\tcm[name] = c\n\treturn true\n}\n\nconst HEADER_BYTE byte = '\\xde'\nconst MAX_NAME_LENGTH int = 65535\n\n\/\/ All packets have the following format:\n\/\/ [header (1)] [packet length (4)] [type (1)] [payload]\n\/\/\n\/\/ The packet length field specifies the number of bytes in the packet\n\/\/ excluding the header\n\/\/\n\/\/ The payload varies for each command or response\n\/\/\nconst (\n\t\/\/ Commands from client\n\tCMD_MSGALL = iota\t\/\/ [data]\n\tCMD_MSGTO\t\t\t\/\/ [target name length (2)] [target name] [data] \n\tCMD_IDENT\t\t\t\/\/ [name]\n\tCMD_WHO\n\n\t\/\/ Responses from server\n\tSVR_NOTICE\t\t\t\/\/ [plaintext message]\n\tSVR_MSG\t\t\t\t\/\/ [sender name length (2)] [sender name] [data]\n)\n\ntype ClientInfo struct {\n\tconn net.Conn\n\tname string\n}\n\nvar clients clientMap\n\nfunc init() {\n\tclients = make(clientMap)\n}\n\n\/\/ Packet:\n\/\/ [header] [packet length excluding header (4)] [type (1)] [packet data]\nfunc client(c net.Conn) {\n\tdefer c.Close()\n\n\tvar info ClientInfo\n\tinfo.conn = c\n\n\tbr := bufio.NewReader(c)\n\n\tpacket, err := readPacket(br)\n\tif packet[0] != CMD_IDENT {\n\t\treturn\n\t}\n\tok := cmd_ident(&info, packet[1:])\n\tif ok {\n\t\tfmt.Printf(\"user %s identified\\n\", info.name)\n\t} else {\n\t\treturn\n\t}\n\t\n\tfor {\n\t\tpacket, err = readPacket(br)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tparse(&info, packet)\n\t}\n\n\t\/\/ On disconnet\n\tsvr_notice_all(info.name + \" disconnected\")\n\tfmt.Printf(\"%v disconnected\\n\", info.name)\n\tdelete(clients, info.name)\n}\n \nfunc readPacket(br *bufio.Reader) ([]byte, error) {\n\t\/\/ Drop bytes preceding HEADER_BYTE\n\t_, err := br.ReadBytes(HEADER_BYTE)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get packet length field\n\tpacket := make([]byte, 4)\n\tread_bytes := 0\n\tfor read_bytes < 4 {\n\t\ttmp := make([]byte, 4)\n\t\tnread, err := br.Read(tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcopy(packet[read_bytes:], tmp[:nread])\n\t\tread_bytes += nread\n\t}\n\tpktlen := int(binary.BigEndian.Uint32(packet))\n\n\t\/\/ Get rest of packet\n\tpacket = make([]byte, pktlen)\n\tread_bytes = 0\n\tfor read_bytes < pktlen {\n\t\ttmp := make([]byte, pktlen)\n\t\tnread, err := br.Read(tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcopy(packet[read_bytes:], tmp[:nread])\n\t\tread_bytes += nread\n\t}\n\treturn packet, nil\n}\n\n\/\/ Parse incoming packet\nfunc parse(info *ClientInfo, packet []byte) {\n\t\/\/ fmt.Printf(\"rx: \")\n\t\/\/ for i := 0; i < len(packet); i++ {\n\t\/\/ \tfmt.Printf(\"%02x \", packet[i])\n\t\/\/ }\n\t\/\/ fmt.Printf(\"\\n\")\n\n\tcmd := packet[0]\n\tswitch {\n\tcase cmd == CMD_MSGALL:\n\t\tcmd_msgall(info, packet[1:])\n\tcase cmd == CMD_MSGTO:\n\t\tcmd_msgto(info, packet[1:])\n\tcase cmd == CMD_WHO:\n\t\tcmd_who(info)\n\tdefault:\n\t}\n}\n\n\/\/ Helper function to set common packet fields\nfunc packetize(packet_type byte, payload []byte) []byte {\n\tvar buf bytes.Buffer\n\tbuf.Write([]byte{ HEADER_BYTE })\n\tbinary.Write(&buf, binary.BigEndian, uint32(len(payload)+1))\n\tbuf.Write([]byte{ packet_type })\n\tbuf.Write(payload)\n\n\/\/\tvar pkt []byte = buf.Bytes()\n\/\/\tfmt.Printf(\"tx: \")\n\/\/\tfor i := 5; i < len(pkt); i++ {\n\/\/\t\tfmt.Printf(\"%02x \", pkt[i])\n\/\/\t}\n\/\/\tfmt.Printf(\"\\n\")\n\treturn buf.Bytes()\n}\n\nfunc svr_notice(c net.Conn, msg string) (int, error) {\n\treturn c.Write(packetize(byte(SVR_NOTICE), []byte(msg)))\n}\n\nfunc svr_notice_all(msg string) (int, error) {\n\treturn clients.Write(packetize(byte(SVR_NOTICE), []byte(msg)))\n}\n\nfunc cmd_msgall(info *ClientInfo, packet []byte) (int, error) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn -1, nil\n\t}\n\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.BigEndian, uint16(len(info.name)))\n\tbuf.Write([]byte(info.name))\n\tbuf.Write(packet)\n\treturn clients.Write(packetize(SVR_MSG, buf.Bytes()))\n}\n\nfunc cmd_msgto(info *ClientInfo, packet []byte) (int, error) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn -1, nil\n\t}\n\n\ttargetlen := int(binary.BigEndian.Uint16(packet[0:2]))\n\ttarget := string(packet[2:2+targetlen])\n\tdata := packet[2+targetlen:]\n\n\tc, present := clients[target]\n\tif !present {\n\t\tsvr_notice(info.conn, fmt.Sprintf(\"unknown recipient %s\", target))\n\t\treturn -1, nil\n\t}\n\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.BigEndian, uint16(len(info.name)))\n\tbuf.Write([]byte(info.name))\n\tbuf.Write(data)\n\treturn c.Write(packetize(byte(SVR_MSG), buf.Bytes()))\n}\n\nfunc cmd_ident(info *ClientInfo, packet []byte) bool {\n\tname := string(packet)\n\n\tif len(name) > MAX_NAME_LENGTH {\n\t\tsvr_notice(info.conn, \"invalid name\")\n\t\treturn false\n\t}\n\n\tif !clients.Add(name, info.conn) {\n\t\tsvr_notice(info.conn, name + \" is already in use\")\n\t\treturn false\n\t}\n\n\tsvr_notice_all(name + \" connected\")\n\tinfo.name = name\n\treturn true\n}\n\nfunc cmd_who(info *ClientInfo) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn\n\t} else {\n\t msg := fmt.Sprintf(\"Who (%v users):\\n\", len(clients))\n\t\tfor key, _ := range clients {\n\t\t msg += fmt.Sprintf(\" %v\\n\", key)\n\t\t}\n\t\tsvr_notice(info.conn, msg)\n }\n}\n\nfunc main() {\n\tvar (\n\t\tport int\n\t\thelp bool\n\t)\n\tflag.IntVar(&port, \"port\", 6150, \"Port to listen on\")\n\tflag.BoolVar(&help, \"help\", false, \"Display this\")\n\tflag.Parse()\n\n\tif help {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Listening for clients on port %v\\n\", port)\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", port))\n\tif err != nil {\n\t\terror_(err, 1)\n\t}\n\n\tfor {\n\t\tc, err := lis.Accept()\n\t\tif err != nil {\n\t\t\terror_(err, -1)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo client(c)\n\t}\n}\nadd check for read error on initial connect\/\/ TODO: disconnect user if name not set\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n)\n\nfunc error_(err error, r int) {\n\tfmt.Printf(\"Error: %v\\n\", err)\n\tif r >= 0 {\n\t\tos.Exit(r)\n\t}\n}\n\ntype clientMap map[string]net.Conn\n\nfunc (cm clientMap) Write(buf []byte) (n int, err error) {\n\tfor _, c := range cm {\n\t\tgo c.Write(buf)\n\t}\n\tn = len(buf)\n\treturn\n}\n\nfunc (cm clientMap) Add(name string, c net.Conn) bool {\n\t_, present := cm[name]\n\tif present {\n\t\treturn false\n\t}\n\tcm[name] = c\n\treturn true\n}\n\nconst HEADER_BYTE byte = '\\xde'\nconst MAX_NAME_LENGTH int = 65535\n\n\/\/ All packets have the following format:\n\/\/ [header (1)] [packet length (4)] [type (1)] [payload]\n\/\/\n\/\/ The packet length field specifies the number of bytes in the packet\n\/\/ excluding the header\n\/\/\n\/\/ The payload varies for each command or response\n\/\/\nconst (\n\t\/\/ Commands from client\n\tCMD_MSGALL = iota\t\/\/ [data]\n\tCMD_MSGTO\t\t\t\/\/ [target name length (2)] [target name] [data] \n\tCMD_IDENT\t\t\t\/\/ [name]\n\tCMD_WHO\n\n\t\/\/ Responses from server\n\tSVR_NOTICE\t\t\t\/\/ [plaintext message]\n\tSVR_MSG\t\t\t\t\/\/ [sender name length (2)] [sender name] [data]\n)\n\ntype ClientInfo struct {\n\tconn net.Conn\n\tname string\n}\n\nvar clients clientMap\n\nfunc init() {\n\tclients = make(clientMap)\n}\n\n\/\/ Packet:\n\/\/ [header] [packet length excluding header (4)] [type (1)] [packet data]\nfunc client(c net.Conn) {\n\tdefer c.Close()\n\n\tvar info ClientInfo\n\tinfo.conn = c\n\n\tbr := bufio.NewReader(c)\n\n\tpacket, err := readPacket(br)\n\tif (err != nil) || (packet[0] != CMD_IDENT) {\n\t\treturn\n\t}\n\tok := cmd_ident(&info, packet[1:])\n\tif ok {\n\t\tfmt.Printf(\"user %s identified\\n\", info.name)\n\t} else {\n\t\treturn\n\t}\n\t\n\tfor {\n\t\tpacket, err = readPacket(br)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tparse(&info, packet)\n\t}\n\n\t\/\/ On disconnet\n\tsvr_notice_all(info.name + \" disconnected\")\n\tfmt.Printf(\"%v disconnected\\n\", info.name)\n\tdelete(clients, info.name)\n}\n \nfunc readPacket(br *bufio.Reader) ([]byte, error) {\n\t\/\/ Drop bytes preceding HEADER_BYTE\n\t_, err := br.ReadBytes(HEADER_BYTE)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get packet length field\n\tpacket := make([]byte, 4)\n\tread_bytes := 0\n\tfor read_bytes < 4 {\n\t\ttmp := make([]byte, 4)\n\t\tnread, err := br.Read(tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcopy(packet[read_bytes:], tmp[:nread])\n\t\tread_bytes += nread\n\t}\n\tpktlen := int(binary.BigEndian.Uint32(packet))\n\n\t\/\/ Get rest of packet\n\tpacket = make([]byte, pktlen)\n\tread_bytes = 0\n\tfor read_bytes < pktlen {\n\t\ttmp := make([]byte, pktlen)\n\t\tnread, err := br.Read(tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcopy(packet[read_bytes:], tmp[:nread])\n\t\tread_bytes += nread\n\t}\n\treturn packet, nil\n}\n\n\/\/ Parse incoming packet\nfunc parse(info *ClientInfo, packet []byte) {\n\t\/\/ fmt.Printf(\"rx: \")\n\t\/\/ for i := 0; i < len(packet); i++ {\n\t\/\/ \tfmt.Printf(\"%02x \", packet[i])\n\t\/\/ }\n\t\/\/ fmt.Printf(\"\\n\")\n\n\tcmd := packet[0]\n\tswitch {\n\tcase cmd == CMD_MSGALL:\n\t\tcmd_msgall(info, packet[1:])\n\tcase cmd == CMD_MSGTO:\n\t\tcmd_msgto(info, packet[1:])\n\tcase cmd == CMD_WHO:\n\t\tcmd_who(info)\n\tdefault:\n\t}\n}\n\n\/\/ Helper function to set common packet fields\nfunc packetize(packet_type byte, payload []byte) []byte {\n\tvar buf bytes.Buffer\n\tbuf.Write([]byte{ HEADER_BYTE })\n\tbinary.Write(&buf, binary.BigEndian, uint32(len(payload)+1))\n\tbuf.Write([]byte{ packet_type })\n\tbuf.Write(payload)\n\n\/\/\tvar pkt []byte = buf.Bytes()\n\/\/\tfmt.Printf(\"tx: \")\n\/\/\tfor i := 5; i < len(pkt); i++ {\n\/\/\t\tfmt.Printf(\"%02x \", pkt[i])\n\/\/\t}\n\/\/\tfmt.Printf(\"\\n\")\n\treturn buf.Bytes()\n}\n\nfunc svr_notice(c net.Conn, msg string) (int, error) {\n\treturn c.Write(packetize(byte(SVR_NOTICE), []byte(msg)))\n}\n\nfunc svr_notice_all(msg string) (int, error) {\n\treturn clients.Write(packetize(byte(SVR_NOTICE), []byte(msg)))\n}\n\nfunc cmd_msgall(info *ClientInfo, packet []byte) (int, error) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn -1, nil\n\t}\n\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.BigEndian, uint16(len(info.name)))\n\tbuf.Write([]byte(info.name))\n\tbuf.Write(packet)\n\treturn clients.Write(packetize(SVR_MSG, buf.Bytes()))\n}\n\nfunc cmd_msgto(info *ClientInfo, packet []byte) (int, error) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn -1, nil\n\t}\n\n\ttargetlen := int(binary.BigEndian.Uint16(packet[0:2]))\n\ttarget := string(packet[2:2+targetlen])\n\tdata := packet[2+targetlen:]\n\n\tc, present := clients[target]\n\tif !present {\n\t\tsvr_notice(info.conn, fmt.Sprintf(\"unknown recipient %s\", target))\n\t\treturn -1, nil\n\t}\n\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.BigEndian, uint16(len(info.name)))\n\tbuf.Write([]byte(info.name))\n\tbuf.Write(data)\n\treturn c.Write(packetize(byte(SVR_MSG), buf.Bytes()))\n}\n\nfunc cmd_ident(info *ClientInfo, packet []byte) bool {\n\tname := string(packet)\n\n\tif len(name) > MAX_NAME_LENGTH {\n\t\tsvr_notice(info.conn, \"invalid name\")\n\t\treturn false\n\t}\n\n\tif !clients.Add(name, info.conn) {\n\t\tsvr_notice(info.conn, name + \" is already in use\")\n\t\treturn false\n\t}\n\n\tsvr_notice_all(name + \" connected\")\n\tinfo.name = name\n\treturn true\n}\n\nfunc cmd_who(info *ClientInfo) {\n\tif info.name == \"\" {\n\t\tsvr_notice(info.conn, \"please identify yourself\")\n\t\treturn\n\t} else {\n\t msg := fmt.Sprintf(\"Who (%v users):\\n\", len(clients))\n\t\tfor key, _ := range clients {\n\t\t msg += fmt.Sprintf(\" %v\\n\", key)\n\t\t}\n\t\tsvr_notice(info.conn, msg)\n }\n}\n\nfunc main() {\n\tvar (\n\t\tport int\n\t\thelp bool\n\t)\n\tflag.IntVar(&port, \"port\", 6150, \"Port to listen on\")\n\tflag.BoolVar(&help, \"help\", false, \"Display this\")\n\tflag.Parse()\n\n\tif help {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Listening for clients on port %v\\n\", port)\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", port))\n\tif err != nil {\n\t\terror_(err, 1)\n\t}\n\n\tfor {\n\t\tc, err := lis.Accept()\n\t\tif err != nil {\n\t\t\terror_(err, -1)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo client(c)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\n\tgoyaml \"gopkg.in\/yaml.v2\"\n)\n\nfunc main() {\n\terr := _main()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\tos.Exit(0)\n}\nfunc _main() error {\n\tvar data interface{}\n\tinput, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = goyaml.Unmarshal(input, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err = transformData(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutput, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = os.Stdout.Write([]byte(output))\n\treturn err\n}\nfunc transformData(in interface{}) (out interface{}, err error) {\n\tswitch in.(type) {\n\tcase map[interface{}]interface{}:\n\t\to := make(map[string]interface{})\n\t\tfor k, v := range in.(map[interface{}]interface{}) {\n\t\t\tsk := \"\"\n\t\t\tswitch k.(type) {\n\t\t\tcase string:\n\t\t\t\tsk = k.(string)\n\t\t\tcase int:\n\t\t\t\tsk = strconv.Itoa(k.(int))\n\t\t\tdefault:\n\t\t\t\treturn nil, errors.New(\n\t\t\t\t\tfmt.Sprintf(\"type not match: expect map key string or int get: %T\", k))\n\t\t\t}\n\t\t\tv, err = transformData(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\to[sk] = v\n\t\t}\n\t\treturn o, nil\n\tcase []interface{}:\n\t\tin1 := in.([]interface{})\n\t\tlen1 := len(in1)\n\t\to := make([]interface{}, len1)\n\t\tfor i := 0; i < len1; i++ {\n\t\t\to[i], err = transformData(in1[i])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn o, nil\n\tdefault:\n\t\treturn in, nil\n\t}\n\treturn in, nil\n}\nFaster! Convert in placepackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\n\tgoyaml \"gopkg.in\/yaml.v2\"\n)\n\nfunc main() {\n\terr := _main()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\tos.Exit(0)\n}\n\nfunc _main() error {\n\tvar data interface{}\n\tinput, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = goyaml.Unmarshal(input, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = transformData(&data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutput, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = os.Stdout.Write([]byte(output))\n\treturn err\n}\n\nfunc transformData(pIn *interface{}) (err error) {\n\tswitch in := (*pIn).(type) {\n\tcase map[interface{}]interface{}:\n\t\tm := make(map[string]interface{}, len(in))\n\t\tfor k, v := range in {\n\t\t\tif err = transformData(&v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar sk string\n\t\t\tswitch k.(type) {\n\t\t\tcase string:\n\t\t\t\tsk = k.(string)\n\t\t\tcase int:\n\t\t\t\tsk = strconv.Itoa(k.(int))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"type mismatch: expect map key string or int; got: %T\", k)\n\t\t\t}\n\t\t\tm[sk] = v\n\t\t}\n\t\t*pIn = m\n\tcase []interface{}:\n\t\tfor i := len(in) - 1; i >= 0; i-- {\n\t\t\tif err = transformData(&in[i]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport \"os\"\n\nfunc main() {\n\tparser := NewParser()\n\tvar err error\n\tif len(os.Args) < 2 {\n\t\terr = parser.ParseInput()\n\t} else {\n\t\terr = parser.ParseFile(os.Args[1])\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\nPrint to stderr instead of panickingpackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tparser := NewParser()\n\tvar err error\n\tif len(os.Args) < 2 {\n\t\terr = parser.ParseInput()\n\t} else {\n\t\terr = parser.ParseFile(os.Args[1])\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Parse error:\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/deferpanic\/deferclient\/deferstats\"\n\t\"github.com\/fzzy\/radix\/extra\/pool\"\n\t\"github.com\/fzzy\/radix\/redis\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"github.com\/namsral\/flag\"\n\t\"github.com\/unrolled\/render\"\n\t\/\/ \"github.com\/deferpanic\/deferclient\/errors\"\n\t\"golang.org\/x\/oauth2\"\n\tgithuboauth \"golang.org\/x\/oauth2\/github\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ func QueryScore(terms []string, title) float32 {\n\/\/ \treturn 1.0\n\/\/ }\n\nfunc errHndlr(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\tpanic(err)\n\t}\n}\n\nfunc isOnHTTPS(req *http.Request) bool {\n\tif req.Header.Get(\"is-secure\") == \"true\" {\n\t\treturn true\n\t}\n\t\/\/ default is to use the flag\n\t\/\/ which is only really useful for local development\n\treturn usingHTTPS\n}\n\ntype domainRow struct {\n\tKey string\n\tDomain string\n}\n\nfunc indexHandler(w http.ResponseWriter, req *http.Request) {\n\tcontext := map[string]interface{}{\n\t\t\"staticPrefix\": staticPrefix,\n\t\t\"isNotDebug\": !debug,\n\t\t\"Username\": \"\",\n\t\t\"domains\": make([]string, 0),\n\t}\n\n\tcookie, err := req.Cookie(\"username\")\n\tif err == nil {\n\t\tvar username string\n\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\/\/ Yay! You're signed in!\n\n\t\t\tcontext[\"Username\"] = username\n\t\t\tc, err := redisPool.Get()\n\t\t\terrHndlr(err)\n\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\treplies, err := c.Cmd(\"SMEMBERS\", userdomainsKey).List()\n\t\t\terrHndlr(err)\n\n\t\t\tvar domains []domainRow\n\n\t\t\tvar domain string\n\t\t\tfor _, key := range replies {\n\t\t\t\treply := c.Cmd(\"HGET\", \"$domainkeys\", key)\n\t\t\t\tif reply.Type != redis.NilReply {\n\t\t\t\t\tdomain, err = reply.Str()\n\t\t\t\t\terrHndlr(err)\n\t\t\t\t\tdomains = append(domains, domainRow{\n\t\t\t\t\t\tKey: key,\n\t\t\t\t\t\tDomain: domain,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontext[\"domains\"] = domains\n\t\t}\n\t}\n\t\/\/ this assumes there's a `templates\/index.tmpl` file\n\trenderer.HTML(w, http.StatusOK, \"index\", context)\n}\n\nfunc logoutHandler(w http.ResponseWriter, req *http.Request) {\n\texpire := time.Now().AddDate(0, 0, -1)\n\tsecureCookie := isOnHTTPS(req)\n\tcookie := &http.Cookie{\n\t\tName: \"username\",\n\t\tValue: \"*deleted*\",\n\t\tPath: \"\/\",\n\t\tExpires: expire,\n\t\tMaxAge: -1,\n\t\tSecure: secureCookie,\n\t\tHttpOnly: true,\n\t}\n\thttp.SetCookie(w, cookie)\n\thttp.Redirect(w, req, \"\/#loggedout\", http.StatusTemporaryRedirect)\n}\n\nfunc handleGitHubLogin(w http.ResponseWriter, req *http.Request) {\n\turl := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)\n\thttp.Redirect(w, req, url, http.StatusTemporaryRedirect)\n}\n\nfunc handleGitHubCallback(w http.ResponseWriter, req *http.Request) {\n\tstate := req.FormValue(\"state\")\n\tif state != oauthStateString {\n\t\tfmt.Printf(\"invalid oauth state, expected '%s', got '%s'\\n\", oauthStateString, state)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tcode := req.FormValue(\"code\")\n\ttoken, err := oauthConf.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tfmt.Printf(\"oauthConf.Exchange() failed with '%s'\\n\", err)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\toauthClient := oauthConf.Client(oauth2.NoContext, token)\n\tclient := github.NewClient(oauthClient)\n\t\/\/ the second item here is the github.Rate config\n\tuser, _, err := client.Users.Get(\"\")\n\n\tif err != nil {\n\t\tfmt.Printf(\"client.Users.Get() faled with '%s'\\n\", err)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Logged in as GitHub user: %s\\n\", *user.Login)\n\t\/\/ fmt.Printf(\"Logged in as GitHub user: %s\\n\", *user)\n\tencoded, err := sCookie.Encode(\"username\", *user.Login)\n\terrHndlr(err)\n\texpire := time.Now().AddDate(0, 0, 1) \/\/ how long is this?\n\tsecureCookie := isOnHTTPS(req)\n\n\tcookie := &http.Cookie{\n\t\tName: \"username\",\n\t\tValue: encoded,\n\t\tPath: \"\/\",\n\t\tExpires: expire,\n\t\tMaxAge: 60 * 60 * 24 * 30, \/\/ 30 days\n\t\tSecure: secureCookie,\n\t\tHttpOnly: true,\n\t}\n\thttp.SetCookie(w, cookie)\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusTemporaryRedirect)\n}\n\nvar letters = []rune(\n\t\"abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ123456789\",\n)\n\nfunc randString(n int) string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}\n\nfunc domainkeyNewHandler(w http.ResponseWriter, req *http.Request) {\n\tdomain := strings.Trim(req.FormValue(\"domain\"), \" \")\n\tif domain != \"\" {\n\t\tcookie, err := req.Cookie(\"username\")\n\t\tif err == nil {\n\t\t\tvar username string\n\t\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\tc, err := redisPool.Get()\n\t\t\t\terrHndlr(err)\n\t\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\t\tkey := randString(24)\n\t\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\t\terr = c.Cmd(\"SADD\", userdomainsKey, key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t\terr = c.Cmd(\"HSET\", \"$domainkeys\", key, domain).Err\n\t\t\t\terrHndlr(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ http.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusFound)\n}\n\nfunc domainkeyDeleteHandler(w http.ResponseWriter, req *http.Request) {\n\tkey := strings.Trim(req.FormValue(\"key\"), \" \")\n\tif key != \"\" {\n\t\tcookie, err := req.Cookie(\"username\")\n\t\tif err == nil {\n\t\t\tvar username string\n\t\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\t\/\/ Yay! You're signed in!\n\t\t\t\tc, err := redisPool.Get()\n\t\t\t\terrHndlr(err)\n\t\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\t\terr = c.Cmd(\"SREM\", userdomainsKey, key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t\terr = c.Cmd(\"HDEL\", \"$domainkeys\", key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t} \/\/ else, we should yield some sort of 403 message maybe\n\n\t\t}\n\t}\n\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusFound)\n}\n\nvar (\n\tredisPool *pool.Pool\n\tprocs int\n\tdebug = true\n\trenderer = render.New()\n\tredisURL = \"127.0.0.1:6379\"\n\tstaticPrefix = \"\"\n\tusingHTTPS = false\n\tsCookie *securecookie.SecureCookie\n)\n\nvar (\n\t\/\/ You must register the app at https:\/\/github.com\/settings\/applications\n\t\/\/ Set callback to http:\/\/127.0.0.1:7000\/github_oauth_cb\n\t\/\/ Set ClientId and ClientSecret to\n\toauthConf = &oauth2.Config{\n\t\tClientID: \"\",\n\t\tClientSecret: \"\",\n\t\tScopes: []string{\"user:email\"},\n\t\tEndpoint: githuboauth.Endpoint,\n\t}\n\t\/\/ random string for oauth2 API calls to protect against CSRF\n\toauthStateString = randString(24)\n)\n\nfunc main() {\n\tvar (\n\t\tport = 3001\n\t\tredisDatabase = 0\n\t\tredisPoolSize = 10\n\t\tclientID = \"\"\n\t\tclientSecret = \"\"\n\t\thashKey = \"randomishstringthatsi32charslong\"\n\t\tblockKey = \"randomishstringthatsi32charslong\"\n\t\tdeferPanicKey = \"\"\n\t)\n\tflag.IntVar(&port, \"port\", port, \"Port to start the server on\")\n\tflag.IntVar(&procs, \"procs\", 1, \"Number of CPU processors (0 to use max)\")\n\tflag.BoolVar(&debug, \"debug\", false, \"Debug mode\")\n\tflag.StringVar(\n\t\t&redisURL, \"redisURL\", redisURL,\n\t\t\"Redis URL to tcp connect to\")\n\tflag.StringVar(\n\t\t&staticPrefix, \"staticPrefix\", staticPrefix,\n\t\t\"Prefix in front of static assets in HTML\")\n\tflag.IntVar(&redisDatabase, \"redisDatabase\", redisDatabase,\n\t\t\"Redis database number to connect to\")\n\tflag.StringVar(\n\t\t&clientID, \"clientID\", clientID,\n\t\t\"OAuth Client ID\")\n\tflag.StringVar(\n\t\t&clientSecret, \"clientSecret\", clientSecret,\n\t\t\"OAuth Client Secret\")\n\tflag.BoolVar(&usingHTTPS, \"usingHTTPS\", usingHTTPS,\n\t\t\"Whether requests are made under HTTPS\")\n\tflag.StringVar(\n\t\t&hashKey, \"hashKey\", hashKey,\n\t\t\"HMAC hash key to use for encoding cookies\")\n\tflag.StringVar(\n\t\t&blockKey, \"blockKey\", blockKey,\n\t\t\"Block key to encrypt cookie values\")\n\tflag.StringVar(\n\t\t&deferPanicKey, \"deferPanicKey\", deferPanicKey,\n\t\t\"Auth key for deferpanic.com\")\n\tflag.Parse()\n\n\tif deferPanicKey != \"\" {\n\t\tdeferstats.Token = deferPanicKey\n\t\tgo deferstats.CaptureStats()\n\t}\n\n\toauthConf.ClientID = clientID\n\toauthConf.ClientSecret = clientSecret\n\n\tsCookie = securecookie.New([]byte(hashKey), []byte(blockKey))\n\n\tfmt.Println(\"REDIS DATABASE:\", redisDatabase)\n\tfmt.Println(\"DEBUG MODE:\", debug)\n\tfmt.Println(\"STATIC PREFIX:\", staticPrefix)\n\n\tif !debug {\n\t\tredisPoolSize = 100\n\t}\n\n\t\/\/ Figuring out how many processors to use.\n\tmaxProcs := runtime.NumCPU()\n\tif procs == 0 {\n\t\tprocs = maxProcs\n\t} else if procs < 0 {\n\t\tpanic(\"PROCS < 0\")\n\t} else if procs > maxProcs {\n\t\tpanic(fmt.Sprintf(\"PROCS > max (%v)\", maxProcs))\n\t}\n\tfmt.Println(\"PROCS:\", procs)\n\truntime.GOMAXPROCS(procs)\n\n\trenderer = render.New(render.Options{\n\t\tIndentJSON: debug,\n\t\tIsDevelopment: debug,\n\t})\n\n\tdf := func(network, addr string) (*redis.Client, error) {\n\t\tclient, err := redis.Dial(network, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = client.Cmd(\"SELECT\", redisDatabase).Err\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ if err = client.Cmd(\"AUTH\", \"SUPERSECRET\").Err; err != nil {\n\t\t\/\/ \tclient.Close()\n\t\t\/\/ \treturn nil, err\n\t\t\/\/ }\n\t\treturn client, nil\n\t}\n\n\tvar err error\n\tredisPool, err = pool.NewCustomPool(\"tcp\", redisURL, redisPoolSize, df)\n\terrHndlr(err)\n\n\tmux := mux.NewRouter()\n\tmux.HandleFunc(\"\/\", deferstats.HTTPHandler(indexHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\/ping\", deferstats.HTTPHandler(pingHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\", deferstats.HTTPHandler(fetchHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\", deferstats.HTTPHandler(updateHandler)).Methods(\"POST\", \"PUT\")\n\tmux.HandleFunc(\"\/v1\", deferstats.HTTPHandler(deleteHandler)).Methods(\"DELETE\")\n\tmux.HandleFunc(\"\/v1\/stats\", deferstats.HTTPHandler(privateStatsHandler)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/v1\/flush\", deferstats.HTTPHandler(flushHandler)).Methods(\"DELETE\")\n\tmux.HandleFunc(\"\/v1\/bulk\", deferstats.HTTPHandler(bulkHandler)).Methods(\"POST\", \"PUT\")\n\tmux.HandleFunc(\"\/login\", deferstats.HTTPHandler(handleGitHubLogin)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/logout\", deferstats.HTTPHandler(logoutHandler)).Methods(\"GET\", \"POST\")\n\tmux.HandleFunc(\"\/github_oauth_cb\", deferstats.HTTPHandler(handleGitHubCallback)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/domainkeys\/new\", deferstats.HTTPHandler(domainkeyNewHandler)).Methods(\"POST\")\n\tmux.HandleFunc(\"\/domainkeys\/delete\", deferstats.HTTPHandler(domainkeyDeleteHandler)).Methods(\"POST\")\n\n\tn := negroni.Classic()\n\n\tn.UseHandler(mux)\n\tn.Run(fmt.Sprintf(\":%d\", port))\n}\nuse the new way to set deferpanic tokenpackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/deferpanic\/deferclient\/deferstats\"\n\t\"github.com\/fzzy\/radix\/extra\/pool\"\n\t\"github.com\/fzzy\/radix\/redis\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"github.com\/namsral\/flag\"\n\t\"github.com\/unrolled\/render\"\n\t\/\/ \"github.com\/deferpanic\/deferclient\/errors\"\n\t\"golang.org\/x\/oauth2\"\n\tgithuboauth \"golang.org\/x\/oauth2\/github\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ func QueryScore(terms []string, title) float32 {\n\/\/ \treturn 1.0\n\/\/ }\n\nfunc errHndlr(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\tpanic(err)\n\t}\n}\n\nfunc isOnHTTPS(req *http.Request) bool {\n\tif req.Header.Get(\"is-secure\") == \"true\" {\n\t\treturn true\n\t}\n\t\/\/ default is to use the flag\n\t\/\/ which is only really useful for local development\n\treturn usingHTTPS\n}\n\ntype domainRow struct {\n\tKey string\n\tDomain string\n}\n\nfunc indexHandler(w http.ResponseWriter, req *http.Request) {\n\tcontext := map[string]interface{}{\n\t\t\"staticPrefix\": staticPrefix,\n\t\t\"isNotDebug\": !debug,\n\t\t\"Username\": \"\",\n\t\t\"domains\": make([]string, 0),\n\t}\n\n\tcookie, err := req.Cookie(\"username\")\n\tif err == nil {\n\t\tvar username string\n\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\/\/ Yay! You're signed in!\n\n\t\t\tcontext[\"Username\"] = username\n\t\t\tc, err := redisPool.Get()\n\t\t\terrHndlr(err)\n\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\treplies, err := c.Cmd(\"SMEMBERS\", userdomainsKey).List()\n\t\t\terrHndlr(err)\n\n\t\t\tvar domains []domainRow\n\n\t\t\tvar domain string\n\t\t\tfor _, key := range replies {\n\t\t\t\treply := c.Cmd(\"HGET\", \"$domainkeys\", key)\n\t\t\t\tif reply.Type != redis.NilReply {\n\t\t\t\t\tdomain, err = reply.Str()\n\t\t\t\t\terrHndlr(err)\n\t\t\t\t\tdomains = append(domains, domainRow{\n\t\t\t\t\t\tKey: key,\n\t\t\t\t\t\tDomain: domain,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontext[\"domains\"] = domains\n\t\t}\n\t}\n\t\/\/ this assumes there's a `templates\/index.tmpl` file\n\trenderer.HTML(w, http.StatusOK, \"index\", context)\n}\n\nfunc logoutHandler(w http.ResponseWriter, req *http.Request) {\n\texpire := time.Now().AddDate(0, 0, -1)\n\tsecureCookie := isOnHTTPS(req)\n\tcookie := &http.Cookie{\n\t\tName: \"username\",\n\t\tValue: \"*deleted*\",\n\t\tPath: \"\/\",\n\t\tExpires: expire,\n\t\tMaxAge: -1,\n\t\tSecure: secureCookie,\n\t\tHttpOnly: true,\n\t}\n\thttp.SetCookie(w, cookie)\n\thttp.Redirect(w, req, \"\/#loggedout\", http.StatusTemporaryRedirect)\n}\n\nfunc handleGitHubLogin(w http.ResponseWriter, req *http.Request) {\n\turl := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)\n\thttp.Redirect(w, req, url, http.StatusTemporaryRedirect)\n}\n\nfunc handleGitHubCallback(w http.ResponseWriter, req *http.Request) {\n\tstate := req.FormValue(\"state\")\n\tif state != oauthStateString {\n\t\tfmt.Printf(\"invalid oauth state, expected '%s', got '%s'\\n\", oauthStateString, state)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tcode := req.FormValue(\"code\")\n\ttoken, err := oauthConf.Exchange(oauth2.NoContext, code)\n\tif err != nil {\n\t\tfmt.Printf(\"oauthConf.Exchange() failed with '%s'\\n\", err)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\toauthClient := oauthConf.Client(oauth2.NoContext, token)\n\tclient := github.NewClient(oauthClient)\n\t\/\/ the second item here is the github.Rate config\n\tuser, _, err := client.Users.Get(\"\")\n\n\tif err != nil {\n\t\tfmt.Printf(\"client.Users.Get() faled with '%s'\\n\", err)\n\t\thttp.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Logged in as GitHub user: %s\\n\", *user.Login)\n\t\/\/ fmt.Printf(\"Logged in as GitHub user: %s\\n\", *user)\n\tencoded, err := sCookie.Encode(\"username\", *user.Login)\n\terrHndlr(err)\n\texpire := time.Now().AddDate(0, 0, 1) \/\/ how long is this?\n\tsecureCookie := isOnHTTPS(req)\n\n\tcookie := &http.Cookie{\n\t\tName: \"username\",\n\t\tValue: encoded,\n\t\tPath: \"\/\",\n\t\tExpires: expire,\n\t\tMaxAge: 60 * 60 * 24 * 30, \/\/ 30 days\n\t\tSecure: secureCookie,\n\t\tHttpOnly: true,\n\t}\n\thttp.SetCookie(w, cookie)\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusTemporaryRedirect)\n}\n\nvar letters = []rune(\n\t\"abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ123456789\",\n)\n\nfunc randString(n int) string {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letters[rand.Intn(len(letters))]\n\t}\n\treturn string(b)\n}\n\nfunc domainkeyNewHandler(w http.ResponseWriter, req *http.Request) {\n\tdomain := strings.Trim(req.FormValue(\"domain\"), \" \")\n\tif domain != \"\" {\n\t\tcookie, err := req.Cookie(\"username\")\n\t\tif err == nil {\n\t\t\tvar username string\n\t\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\tc, err := redisPool.Get()\n\t\t\t\terrHndlr(err)\n\t\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\t\tkey := randString(24)\n\t\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\t\terr = c.Cmd(\"SADD\", userdomainsKey, key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t\terr = c.Cmd(\"HSET\", \"$domainkeys\", key, domain).Err\n\t\t\t\terrHndlr(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ http.Redirect(w, req, \"\/\", http.StatusTemporaryRedirect)\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusFound)\n}\n\nfunc domainkeyDeleteHandler(w http.ResponseWriter, req *http.Request) {\n\tkey := strings.Trim(req.FormValue(\"key\"), \" \")\n\tif key != \"\" {\n\t\tcookie, err := req.Cookie(\"username\")\n\t\tif err == nil {\n\t\t\tvar username string\n\t\t\tif err = sCookie.Decode(\"username\", cookie.Value, &username); err == nil {\n\t\t\t\t\/\/ Yay! You're signed in!\n\t\t\t\tc, err := redisPool.Get()\n\t\t\t\terrHndlr(err)\n\t\t\t\tdefer redisPool.CarefullyPut(c, &err)\n\n\t\t\t\tuserdomainsKey := fmt.Sprintf(\"$userdomains$%v\", username)\n\t\t\t\terr = c.Cmd(\"SREM\", userdomainsKey, key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t\terr = c.Cmd(\"HDEL\", \"$domainkeys\", key).Err\n\t\t\t\terrHndlr(err)\n\t\t\t} \/\/ else, we should yield some sort of 403 message maybe\n\n\t\t}\n\t}\n\n\thttp.Redirect(w, req, \"\/#auth\", http.StatusFound)\n}\n\nvar (\n\tredisPool *pool.Pool\n\tprocs int\n\tdebug = true\n\trenderer = render.New()\n\tredisURL = \"127.0.0.1:6379\"\n\tstaticPrefix = \"\"\n\tusingHTTPS = false\n\tsCookie *securecookie.SecureCookie\n)\n\nvar (\n\t\/\/ You must register the app at https:\/\/github.com\/settings\/applications\n\t\/\/ Set callback to http:\/\/127.0.0.1:7000\/github_oauth_cb\n\t\/\/ Set ClientId and ClientSecret to\n\toauthConf = &oauth2.Config{\n\t\tClientID: \"\",\n\t\tClientSecret: \"\",\n\t\tScopes: []string{\"user:email\"},\n\t\tEndpoint: githuboauth.Endpoint,\n\t}\n\t\/\/ random string for oauth2 API calls to protect against CSRF\n\toauthStateString = randString(24)\n)\n\nfunc main() {\n\tvar (\n\t\tport = 3001\n\t\tredisDatabase = 0\n\t\tredisPoolSize = 10\n\t\tclientID = \"\"\n\t\tclientSecret = \"\"\n\t\thashKey = \"randomishstringthatsi32charslong\"\n\t\tblockKey = \"randomishstringthatsi32charslong\"\n\t\tdeferPanicKey = \"\"\n\t)\n\tflag.IntVar(&port, \"port\", port, \"Port to start the server on\")\n\tflag.IntVar(&procs, \"procs\", 1, \"Number of CPU processors (0 to use max)\")\n\tflag.BoolVar(&debug, \"debug\", false, \"Debug mode\")\n\tflag.StringVar(\n\t\t&redisURL, \"redisURL\", redisURL,\n\t\t\"Redis URL to tcp connect to\")\n\tflag.StringVar(\n\t\t&staticPrefix, \"staticPrefix\", staticPrefix,\n\t\t\"Prefix in front of static assets in HTML\")\n\tflag.IntVar(&redisDatabase, \"redisDatabase\", redisDatabase,\n\t\t\"Redis database number to connect to\")\n\tflag.StringVar(\n\t\t&clientID, \"clientID\", clientID,\n\t\t\"OAuth Client ID\")\n\tflag.StringVar(\n\t\t&clientSecret, \"clientSecret\", clientSecret,\n\t\t\"OAuth Client Secret\")\n\tflag.BoolVar(&usingHTTPS, \"usingHTTPS\", usingHTTPS,\n\t\t\"Whether requests are made under HTTPS\")\n\tflag.StringVar(\n\t\t&hashKey, \"hashKey\", hashKey,\n\t\t\"HMAC hash key to use for encoding cookies\")\n\tflag.StringVar(\n\t\t&blockKey, \"blockKey\", blockKey,\n\t\t\"Block key to encrypt cookie values\")\n\tflag.StringVar(\n\t\t&deferPanicKey, \"deferPanicKey\", deferPanicKey,\n\t\t\"Auth key for deferpanic.com\")\n\tflag.Parse()\n\n\tdfs := deferstats.NewClient(deferPanicKey)\n\tgo dfs.CaptureStats()\n\t\/\/ if deferPanicKey != \"\" {\n\t\/\/ \tdfs := deferstats.NewClient(deferPanicKey)\n\t\/\/ \tgo dfs.CaptureStats()\n\t\/\/ }\n\n\toauthConf.ClientID = clientID\n\toauthConf.ClientSecret = clientSecret\n\n\tsCookie = securecookie.New([]byte(hashKey), []byte(blockKey))\n\n\tfmt.Println(\"REDIS DATABASE:\", redisDatabase)\n\tfmt.Println(\"DEBUG MODE:\", debug)\n\tfmt.Println(\"STATIC PREFIX:\", staticPrefix)\n\n\tif !debug {\n\t\tredisPoolSize = 100\n\t}\n\n\t\/\/ Figuring out how many processors to use.\n\tmaxProcs := runtime.NumCPU()\n\tif procs == 0 {\n\t\tprocs = maxProcs\n\t} else if procs < 0 {\n\t\tpanic(\"PROCS < 0\")\n\t} else if procs > maxProcs {\n\t\tpanic(fmt.Sprintf(\"PROCS > max (%v)\", maxProcs))\n\t}\n\tfmt.Println(\"PROCS:\", procs)\n\truntime.GOMAXPROCS(procs)\n\n\trenderer = render.New(render.Options{\n\t\tIndentJSON: debug,\n\t\tIsDevelopment: debug,\n\t})\n\n\tdf := func(network, addr string) (*redis.Client, error) {\n\t\tclient, err := redis.Dial(network, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = client.Cmd(\"SELECT\", redisDatabase).Err\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ if err = client.Cmd(\"AUTH\", \"SUPERSECRET\").Err; err != nil {\n\t\t\/\/ \tclient.Close()\n\t\t\/\/ \treturn nil, err\n\t\t\/\/ }\n\t\treturn client, nil\n\t}\n\n\tvar err error\n\tredisPool, err = pool.NewCustomPool(\"tcp\", redisURL, redisPoolSize, df)\n\terrHndlr(err)\n\n\tmux := mux.NewRouter()\n\tmux.HandleFunc(\"\/\", dfs.HTTPHandler(indexHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\/ping\", dfs.HTTPHandler(pingHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\", dfs.HTTPHandler(fetchHandler)).Methods(\"GET\", \"HEAD\")\n\tmux.HandleFunc(\"\/v1\", dfs.HTTPHandler(updateHandler)).Methods(\"POST\", \"PUT\")\n\tmux.HandleFunc(\"\/v1\", dfs.HTTPHandler(deleteHandler)).Methods(\"DELETE\")\n\tmux.HandleFunc(\"\/v1\/stats\", dfs.HTTPHandler(privateStatsHandler)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/v1\/flush\", dfs.HTTPHandler(flushHandler)).Methods(\"DELETE\")\n\tmux.HandleFunc(\"\/v1\/bulk\", dfs.HTTPHandler(bulkHandler)).Methods(\"POST\", \"PUT\")\n\tmux.HandleFunc(\"\/login\", dfs.HTTPHandler(handleGitHubLogin)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/logout\", dfs.HTTPHandler(logoutHandler)).Methods(\"GET\", \"POST\")\n\tmux.HandleFunc(\"\/github_oauth_cb\", dfs.HTTPHandler(handleGitHubCallback)).Methods(\"GET\")\n\tmux.HandleFunc(\"\/domainkeys\/new\", dfs.HTTPHandler(domainkeyNewHandler)).Methods(\"POST\")\n\tmux.HandleFunc(\"\/domainkeys\/delete\", dfs.HTTPHandler(domainkeyDeleteHandler)).Methods(\"POST\")\n\n\tn := negroni.Classic()\n\n\tn.UseHandler(mux)\n\tn.Run(fmt.Sprintf(\":%d\", port))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"archive\/zip\"\n\t\"bufio\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"rsc.io\/letsencrypt\"\n\n\t\"github.com\/beevik\/etree\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/urfave\/negroni\"\n)\n\n\/\/ Metadata metadata struct\ntype Metadata struct {\n\tTitle string `json:\"title\"`\n\tAuthor string `json:\"author\"`\n\tIdentifier string `json:\"identifier\"`\n\tLanguage string `json:\"language\"`\n\tModified time.Time `json:\"modified\"`\n}\n\n\/\/ Link link struct\ntype Link struct {\n\tRel string `json:\"rel,omitempty\"`\n\tHref string `json:\"href\"`\n\tTypeLink string `json:\"type\"`\n\tHeight int `json:\"height,omitempty\"`\n\tWidth int `json:\"width,omitempty\"`\n}\n\n\/\/ Manifest manifest struct\ntype Manifest struct {\n\tMetadata Metadata `json:\"metadata\"`\n\tLinks []Link `json:\"links\"`\n\tSpine []Link `json:\"spine,omitempty\"`\n\tResources []Link `json:\"resources\"`\n}\n\n\/\/ Icon icon struct for AppInstall\ntype Icon struct {\n\tSrc string `json:\"src\"`\n\tSize string `json:\"size\"`\n\tMediaType string `json:\"type\"`\n}\n\n\/\/ AppInstall struct for app install banner\ntype AppInstall struct {\n\tShortName string `json:\"short_name\"`\n\tName string `json:\"name\"`\n\tStartURL string `json:\"start_url\"`\n\tDisplay string `json:\"display\"`\n\tIcons Icon `json:\"icons\"`\n}\n\nfunc main() {\n\n\tn := negroni.Classic()\n\tn.Use(negroni.NewStatic(http.Dir(\"public\")))\n\tn.UseHandler(loanHandler(false))\n\n\tvar m letsencrypt.Manager\n\tif err := m.CacheFile(\"letsencrypt.cache\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif len(os.Args) > 1 && os.Args[1] == \"dev\" {\n\t\ts := &http.Server{\n\t\t\tHandler: n,\n\t\t\tReadTimeout: 10 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t\tMaxHeaderBytes: 1 << 20,\n\t\t\tAddr: \":8080\",\n\t\t}\n\n\t\t\/\/\t\tlog.Fatal(s.ListenAndServeTLS(\"test.cert\", \"test.key\"))\n\t\tlog.Fatal(s.ListenAndServe())\n\t} else {\n\n\t\ts := &http.Server{\n\t\t\tHandler: n,\n\t\t\tReadTimeout: 10 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t\tMaxHeaderBytes: 1 << 20,\n\t\t\tAddr: \":443\",\n\t\t\tTLSConfig: &tls.Config{\n\t\t\t\tGetCertificate: m.GetCertificate,\n\t\t\t},\n\t\t}\n\n\t\tlog.Fatal(s.ListenAndServeTLS(\"\", \"\"))\n\t}\n}\n\nfunc loanHandler(test bool) http.Handler {\n\tserv := mux.NewRouter()\n\n\tserv.HandleFunc(\"\/index.html\", getBooks)\n\tserv.HandleFunc(\"\/\", getBooks)\n\tserv.HandleFunc(\"\/viewer.js\", viewer)\n\tserv.HandleFunc(\"\/sw.js\", sw)\n\tserv.HandleFunc(\"\/{filename}\/\", bookIndex)\n\tserv.HandleFunc(\"\/{filename}\/manifest.json\", getManifest)\n\tserv.HandleFunc(\"\/{filename}\/webapp.webmanifest\", getWebAppManifest)\n\tserv.HandleFunc(\"\/{filename}\/index.html\", bookIndex)\n\tserv.HandleFunc(\"\/{filename}\/{asset:.*}\", getAsset)\n\treturn serv\n}\n\nfunc getManifest(w http.ResponseWriter, req *http.Request) {\n\tvar opfFileName string\n\tvar manifestStruct Manifest\n\tvar metaStruct Metadata\n\n\tmetaStruct.Modified = time.Now()\n\n\tvars := mux.Vars(req)\n\tfilename := vars[\"filename\"]\n\tfilename_path := \"books\/\" + filename\n\n\tself := Link{\n\t\tRel: \"self\",\n\t\tHref: \"http:\/\/\" + req.Host + \"\/\" + filename + \"\/manifest.json\",\n\t\tTypeLink: \"application\/json\",\n\t}\n\tmanifestStruct.Links = make([]Link, 1)\n\tmanifestStruct.Resources = make([]Link, 0)\n\tmanifestStruct.Resources = make([]Link, 0)\n\tmanifestStruct.Links[0] = self\n\n\tzipReader, err := zip.OpenReader(filename_path)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, f := range zipReader.File {\n\t\tif f.Name == \"META-INF\/container.xml\" {\n\t\t\trc, errOpen := f.Open()\n\t\t\tif errOpen != nil {\n\t\t\t\tfmt.Println(\"error openging \" + f.Name)\n\t\t\t}\n\t\t\tdoc := etree.NewDocument()\n\t\t\t_, err = doc.ReadFrom(rc)\n\t\t\tif err == nil {\n\t\t\t\troot := doc.SelectElement(\"container\")\n\t\t\t\trootFiles := root.SelectElements(\"rootfiles\")\n\t\t\t\tfor _, rootFileTag := range rootFiles {\n\t\t\t\t\trootFile := rootFileTag.SelectElement(\"rootfile\")\n\t\t\t\t\tif rootFile != nil {\n\t\t\t\t\t\topfFileName = rootFile.SelectAttrValue(\"full-path\", \"\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\trc.Close()\n\t\t}\n\t}\n\n\tif opfFileName != \"\" {\n\t\tfor _, f := range zipReader.File {\n\t\t\tif f.Name == opfFileName {\n\t\t\t\trc, errOpen := f.Open()\n\t\t\t\tif errOpen != nil {\n\t\t\t\t\tfmt.Println(\"error openging \" + f.Name)\n\t\t\t\t}\n\t\t\t\tdoc := etree.NewDocument()\n\t\t\t\t_, err = doc.ReadFrom(rc)\n\t\t\t\tif err == nil {\n\t\t\t\t\troot := doc.SelectElement(\"package\")\n\t\t\t\t\tmeta := root.SelectElement(\"metadata\")\n\n\t\t\t\t\ttitleTag := meta.SelectElement(\"title\")\n\t\t\t\t\tmetaStruct.Title = titleTag.Text()\n\n\t\t\t\t\tlangTag := meta.SelectElement(\"language\")\n\t\t\t\t\tmetaStruct.Language = langTag.Text()\n\n\t\t\t\t\tidentifierTag := meta.SelectElement(\"identifier\")\n\t\t\t\t\tmetaStruct.Identifier = identifierTag.Text()\n\n\t\t\t\t\tcreatorTag := meta.SelectElement(\"creator\")\n\t\t\t\t\tmetaStruct.Author = creatorTag.Text()\n\n\t\t\t\t\tbookManifest := root.SelectElement(\"manifest\")\n\t\t\t\t\titemsManifest := bookManifest.SelectElements(\"item\")\n\t\t\t\t\tfor _, item := range itemsManifest {\n\t\t\t\t\t\tlinkItem := Link{}\n\t\t\t\t\t\tlinkItem.TypeLink = item.SelectAttrValue(\"media-type\", \"\")\n\t\t\t\t\t\tlinkItem.Href = item.SelectAttrValue(\"href\", \"\")\n\t\t\t\t\t\tif linkItem.TypeLink == \"application\/xhtml+xml\" {\n\t\t\t\t\t\t\tmanifestStruct.Spine = append(manifestStruct.Spine, linkItem)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmanifestStruct.Resources = append(manifestStruct.Resources, linkItem)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmanifestStruct.Metadata = metaStruct\n\t\t\t\t\tj, _ := json.Marshal(manifestStruct)\n\t\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\t\t\tw.Write(j)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc getAsset(w http.ResponseWriter, req *http.Request) {\n\tvar opfFileName string\n\tvar buff string\n\n\tvars := mux.Vars(req)\n\tfilename := \"books\/\" + vars[\"filename\"]\n\tassetname := vars[\"asset\"]\n\tjsInject := req.URL.Query().Get(\"js\")\n\n\tzipReader, err := zip.OpenReader(filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tfor _, f := range zipReader.File {\n\t\tif f.Name == \"META-INF\/container.xml\" {\n\t\t\trc, errOpen := f.Open()\n\t\t\tif errOpen != nil {\n\t\t\t\tfmt.Println(\"error openging \" + f.Name)\n\t\t\t}\n\t\t\tdoc := etree.NewDocument()\n\t\t\t_, err = doc.ReadFrom(rc)\n\t\t\tif err == nil {\n\t\t\t\troot := doc.SelectElement(\"container\")\n\t\t\t\trootFiles := root.SelectElements(\"rootfiles\")\n\t\t\t\tfor _, rootFileTag := range rootFiles {\n\t\t\t\t\trootFile := rootFileTag.SelectElement(\"rootfile\")\n\t\t\t\t\tif rootFile != nil {\n\t\t\t\t\t\topfFileName = rootFile.SelectAttrValue(\"full-path\", \"\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\trc.Close()\n\t\t}\n\t}\n\n\tresourcePath := strings.Split(opfFileName, \"\/\")[0]\n\n\tfor _, f := range zipReader.File {\n\t\t\/\/fmt.Println(f.Name)\n\t\tif f.Name == resourcePath+\"\/\"+assetname {\n\t\t\trc, errOpen := f.Open()\n\t\t\tif errOpen != nil {\n\t\t\t\tfmt.Println(\"error openging \" + f.Name)\n\t\t\t}\n\t\t\tdefer rc.Close()\n\n\t\t\textension := filepath.Ext(f.Name)\n\t\t\tif extension == \".css\" {\n\t\t\t\tw.Header().Set(\"Content-Type\", \"text\/css\")\n\t\t\t}\n\t\t\tif extension == \".xml\" {\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/xhtml+xml\")\n\t\t\t}\n\t\t\tif extension == \".js\" {\n\t\t\t\tw.Header().Set(\"Content-Type\", \"text\/javascript\")\n\t\t\t}\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t\t\tif jsInject != \"\" {\n\t\t\t\tscanner := bufio.NewScanner(rc)\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tif strings.Contains(scanner.Text(), \"<\/head>\") {\n\t\t\t\t\t\tbuff += strings.Replace(scanner.Text(), \"<\/head>\", \"