{"text":"package websocket\n\nimport (\n\t\"github.com\/smancke\/guble\/protocol\"\n\t\"github.com\/smancke\/guble\/server\/auth\"\n\t\"github.com\/smancke\/guble\/server\/router\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/rs\/xid\"\n\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar webSocketUpgrader = websocket.Upgrader{\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\n\/\/ WSHandler is a struct used for handling websocket connections on a certain prefix.\ntype WSHandler struct {\n\trouter router.Router\n\tprefix string\n\taccessManager auth.AccessManager\n}\n\n\/\/ NewWSHandler returns a new WSHandler.\nfunc NewWSHandler(router router.Router, prefix string) (*WSHandler, error) {\n\taccessManager, err := router.AccessManager()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WSHandler{\n\t\trouter: router,\n\t\tprefix: prefix,\n\t\taccessManager: accessManager,\n\t}, nil\n}\n\n\/\/ GetPrefix returns the prefix.\n\/\/ It is a part of the service.endpoint implementation.\nfunc (handler *WSHandler) GetPrefix() string {\n\treturn handler.prefix\n}\n\n\/\/ ServeHTTP is an http.Handler.\n\/\/ It is a part of the service.endpoint implementation.\nfunc (handler *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tc, err := webSocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Error on upgrading to websocket\")\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\tNewWebSocket(handler, &wsconn{c}, extractUserID(r.RequestURI)).Start()\n}\n\n\/\/ WSConnection is a wrapper interface for the needed functions of the websocket.Conn\n\/\/ It is introduced for testability of the WSHandler\ntype WSConnection interface {\n\tClose()\n\tSend(bytes []byte) (err error)\n\tReceive(bytes *[]byte) (err error)\n}\n\n\/\/ wsconnImpl is a Wrapper of the websocket.Conn\n\/\/ implementing the interface WSConn for better testability\ntype wsconn struct {\n\t*websocket.Conn\n}\n\n\/\/ Close the connection.\nfunc (conn *wsconn) Close() {\n\tconn.Conn.Close()\n}\n\n\/\/ Send bytes through the connection and possibly return an error.\nfunc (conn *wsconn) Send(bytes []byte) error {\n\treturn conn.WriteMessage(websocket.BinaryMessage, bytes)\n}\n\n\/\/ Receive bytes through the connection and possibly return an error.\nfunc (conn *wsconn) Receive(bytes *[]byte) (err error) {\n\t_, *bytes, err = conn.ReadMessage()\n\treturn err\n}\n\n\/\/ WebSocket struct represents a websocket.\ntype WebSocket struct {\n\t*WSHandler\n\tWSConnection\n\tapplicationID string\n\tuserID string\n\tsendChannel chan []byte\n\treceivers map[protocol.Path]*Receiver\n}\n\n\/\/ NewWebSocket returns a new WebSocket.\nfunc NewWebSocket(handler *WSHandler, wsConn WSConnection, userID string) *WebSocket {\n\treturn &WebSocket{\n\t\tWSHandler: handler,\n\t\tWSConnection: wsConn,\n\t\tapplicationID: xid.New().String(),\n\t\tuserID: userID,\n\t\tsendChannel: make(chan []byte, 10),\n\t\treceivers: make(map[protocol.Path]*Receiver),\n\t}\n}\n\n\/\/ Start the WebSocket (the send and receive loops).\n\/\/ It is implementing the service.startable interface.\nfunc (ws *WebSocket) Start() error {\n\tws.sendConnectionMessage()\n\tgo ws.sendLoop()\n\tws.receiveLoop()\n\treturn nil\n}\n\nfunc (ws *WebSocket) sendLoop() {\n\tfor raw := range ws.sendChannel {\n\t\tif !ws.checkAccess(raw) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := ws.Send(raw); err != nil {\n\t\t\tlogger.WithFields(log.Fields{\n\t\t\t\t\"userId\": ws.userID,\n\t\t\t\t\"applicationID\": ws.applicationID,\n\t\t\t\t\"totalSize\": len(raw),\n\t\t\t\t\"actualContent\": string(raw),\n\t\t\t}).Error(\"Could not send\")\n\t\t\tws.cleanAndClose()\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ws *WebSocket) checkAccess(raw []byte) bool {\n\tif raw[0] == byte('\/') {\n\t\tpath := getPathFromRawMessage(raw)\n\n\t\tlogger.WithFields(log.Fields{\n\t\t\t\"userID\": ws.userID,\n\t\t\t\"path\": path,\n\t\t}).Debug(\"Received msg\")\n\n\t\treturn len(path) == 0 || ws.accessManager.IsAllowed(auth.READ, ws.userID, path)\n\n\t}\n\treturn true\n}\n\nfunc getPathFromRawMessage(raw []byte) protocol.Path {\n\ti := strings.Index(string(raw), \",\")\n\treturn protocol.Path(raw[:i])\n}\n\nfunc (ws *WebSocket) receiveLoop() {\n\tvar message []byte\n\tfor {\n\t\terr := ws.Receive(&message)\n\t\tif err != nil {\n\n\t\t\tlogger.WithFields(log.Fields{\n\t\t\t\t\"applicationID\": ws.applicationID,\n\t\t\t}).Debug(\"Closed connnection by application\")\n\n\t\t\tws.cleanAndClose()\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/protocol.Debug(\"websocket_connector, raw message received: %v\", string(message))\n\t\tcmd, err := protocol.ParseCmd(message)\n\t\tif err != nil {\n\t\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"error parsing command. %v\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tswitch cmd.Name {\n\t\tcase protocol.CmdSend:\n\t\t\tws.handleSendCmd(cmd)\n\t\tcase protocol.CmdReceive:\n\t\t\tws.handleReceiveCmd(cmd)\n\t\tcase protocol.CmdCancel:\n\t\t\tws.handleCancelCmd(cmd)\n\t\tdefault:\n\t\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"unknown command %v\", cmd.Name)\n\t\t}\n\t}\n}\n\nfunc (ws *WebSocket) sendConnectionMessage() {\n\tn := &protocol.NotificationMessage{\n\t\tName: protocol.SUCCESS_CONNECTED,\n\t\tArg: \"You are connected to the server.\",\n\t\tJson: fmt.Sprintf(`{\"ApplicationId\": \"%s\", \"UserId\": \"%s\", \"Time\": \"%s\"}`, ws.applicationID, ws.userID, time.Now().Format(time.RFC3339)),\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\nfunc (ws *WebSocket) handleReceiveCmd(cmd *protocol.Cmd) {\n\trec, err := NewReceiverFromCmd(\n\t\tws.applicationID,\n\t\tcmd,\n\t\tws.sendChannel,\n\t\tws.router,\n\t\tws.userID,\n\t)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Client error in handleReceiveCmd\")\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, err.Error())\n\t\treturn\n\t}\n\tws.receivers[rec.path] = rec\n\trec.Start()\n}\n\nfunc (ws *WebSocket) handleCancelCmd(cmd *protocol.Cmd) {\n\tif len(cmd.Arg) == 0 {\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"- command requires a path argument, but none given\")\n\t\treturn\n\t}\n\tpath := protocol.Path(cmd.Arg)\n\trec, exist := ws.receivers[path]\n\tif exist {\n\t\trec.Stop()\n\t\tdelete(ws.receivers, path)\n\t}\n}\n\nfunc (ws *WebSocket) handleSendCmd(cmd *protocol.Cmd) {\n\tlogger.WithFields(log.Fields{\n\t\t\"cmd\": string(cmd.Bytes()),\n\t}).Debug(\"Sending \")\n\n\tif len(cmd.Arg) == 0 {\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"send command requires a path argument, but none given\")\n\t\treturn\n\t}\n\n\targs := strings.SplitN(cmd.Arg, \" \", 2)\n\tmsg := &protocol.Message{\n\t\tPath: protocol.Path(args[0]),\n\t\tApplicationID: ws.applicationID,\n\t\tUserID: ws.userID,\n\t\tHeaderJSON: cmd.HeaderJSON,\n\t\tBody: cmd.Body,\n\t}\n\n\tws.router.HandleMessage(msg)\n\n\tws.sendOK(protocol.SUCCESS_SEND, \"\")\n}\n\nfunc (ws *WebSocket) cleanAndClose() {\n\n\tlogger.WithFields(log.Fields{\n\t\t\"applicationID\": ws.applicationID,\n\t}).Debug(\"Closing applicationId\")\n\n\tfor path, rec := range ws.receivers {\n\t\trec.Stop()\n\t\tdelete(ws.receivers, path)\n\t}\n\n\tws.Close()\n}\n\nfunc (ws *WebSocket) sendError(name string, argPattern string, params ...interface{}) {\n\tn := &protocol.NotificationMessage{\n\t\tName: name,\n\t\tArg: fmt.Sprintf(argPattern, params...),\n\t\tIsError: true,\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\nfunc (ws *WebSocket) sendOK(name string, argPattern string, params ...interface{}) {\n\tn := &protocol.NotificationMessage{\n\t\tName: name,\n\t\tArg: fmt.Sprintf(argPattern, params...),\n\t\tIsError: false,\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\n\/\/ Extracts the userID out of an URI or empty string if format not met\n\/\/ Example:\n\/\/ \t\thttp:\/\/example.com\/user\/user01\/ -> user01\n\/\/ \t\thttp:\/\/example.com\/user\/ -> \"\"\nfunc extractUserID(uri string) string {\n\turiParts := strings.SplitN(uri, \"\/user\/\", 2)\n\tif len(uriParts) != 2 {\n\t\treturn \"\"\n\t}\n\treturn uriParts[1]\n}\ncheck slice index before accesspackage websocket\n\nimport (\n\t\"github.com\/smancke\/guble\/protocol\"\n\t\"github.com\/smancke\/guble\/server\/auth\"\n\t\"github.com\/smancke\/guble\/server\/router\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/rs\/xid\"\n\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar webSocketUpgrader = websocket.Upgrader{\n\tCheckOrigin: func(r *http.Request) bool { return true },\n}\n\n\/\/ WSHandler is a struct used for handling websocket connections on a certain prefix.\ntype WSHandler struct {\n\trouter router.Router\n\tprefix string\n\taccessManager auth.AccessManager\n}\n\n\/\/ NewWSHandler returns a new WSHandler.\nfunc NewWSHandler(router router.Router, prefix string) (*WSHandler, error) {\n\taccessManager, err := router.AccessManager()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WSHandler{\n\t\trouter: router,\n\t\tprefix: prefix,\n\t\taccessManager: accessManager,\n\t}, nil\n}\n\n\/\/ GetPrefix returns the prefix.\n\/\/ It is a part of the service.endpoint implementation.\nfunc (handler *WSHandler) GetPrefix() string {\n\treturn handler.prefix\n}\n\n\/\/ ServeHTTP is an http.Handler.\n\/\/ It is a part of the service.endpoint implementation.\nfunc (handler *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tc, err := webSocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Error on upgrading to websocket\")\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\tNewWebSocket(handler, &wsconn{c}, extractUserID(r.RequestURI)).Start()\n}\n\n\/\/ WSConnection is a wrapper interface for the needed functions of the websocket.Conn\n\/\/ It is introduced for testability of the WSHandler\ntype WSConnection interface {\n\tClose()\n\tSend(bytes []byte) (err error)\n\tReceive(bytes *[]byte) (err error)\n}\n\n\/\/ wsconnImpl is a Wrapper of the websocket.Conn\n\/\/ implementing the interface WSConn for better testability\ntype wsconn struct {\n\t*websocket.Conn\n}\n\n\/\/ Close the connection.\nfunc (conn *wsconn) Close() {\n\tconn.Conn.Close()\n}\n\n\/\/ Send bytes through the connection and possibly return an error.\nfunc (conn *wsconn) Send(bytes []byte) error {\n\treturn conn.WriteMessage(websocket.BinaryMessage, bytes)\n}\n\n\/\/ Receive bytes through the connection and possibly return an error.\nfunc (conn *wsconn) Receive(bytes *[]byte) (err error) {\n\t_, *bytes, err = conn.ReadMessage()\n\treturn err\n}\n\n\/\/ WebSocket struct represents a websocket.\ntype WebSocket struct {\n\t*WSHandler\n\tWSConnection\n\tapplicationID string\n\tuserID string\n\tsendChannel chan []byte\n\treceivers map[protocol.Path]*Receiver\n}\n\n\/\/ NewWebSocket returns a new WebSocket.\nfunc NewWebSocket(handler *WSHandler, wsConn WSConnection, userID string) *WebSocket {\n\treturn &WebSocket{\n\t\tWSHandler: handler,\n\t\tWSConnection: wsConn,\n\t\tapplicationID: xid.New().String(),\n\t\tuserID: userID,\n\t\tsendChannel: make(chan []byte, 10),\n\t\treceivers: make(map[protocol.Path]*Receiver),\n\t}\n}\n\n\/\/ Start the WebSocket (the send and receive loops).\n\/\/ It is implementing the service.startable interface.\nfunc (ws *WebSocket) Start() error {\n\tws.sendConnectionMessage()\n\tgo ws.sendLoop()\n\tws.receiveLoop()\n\treturn nil\n}\n\nfunc (ws *WebSocket) sendLoop() {\n\tfor raw := range ws.sendChannel {\n\t\tif !ws.checkAccess(raw) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := ws.Send(raw); err != nil {\n\t\t\tlogger.WithFields(log.Fields{\n\t\t\t\t\"userId\": ws.userID,\n\t\t\t\t\"applicationID\": ws.applicationID,\n\t\t\t\t\"totalSize\": len(raw),\n\t\t\t\t\"actualContent\": string(raw),\n\t\t\t}).Error(\"Could not send\")\n\t\t\tws.cleanAndClose()\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (ws *WebSocket) checkAccess(raw []byte) bool {\n\tif len(raw) > 0 && raw[0] == byte('\/') {\n\t\tpath := getPathFromRawMessage(raw)\n\n\t\tlogger.WithFields(log.Fields{\n\t\t\t\"userID\": ws.userID,\n\t\t\t\"path\": path,\n\t\t}).Debug(\"Received msg\")\n\n\t\treturn len(path) == 0 || ws.accessManager.IsAllowed(auth.READ, ws.userID, path)\n\n\t}\n\treturn true\n}\n\nfunc getPathFromRawMessage(raw []byte) protocol.Path {\n\ti := strings.Index(string(raw), \",\")\n\treturn protocol.Path(raw[:i])\n}\n\nfunc (ws *WebSocket) receiveLoop() {\n\tvar message []byte\n\tfor {\n\t\terr := ws.Receive(&message)\n\t\tif err != nil {\n\n\t\t\tlogger.WithFields(log.Fields{\n\t\t\t\t\"applicationID\": ws.applicationID,\n\t\t\t}).Debug(\"Closed connnection by application\")\n\n\t\t\tws.cleanAndClose()\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/protocol.Debug(\"websocket_connector, raw message received: %v\", string(message))\n\t\tcmd, err := protocol.ParseCmd(message)\n\t\tif err != nil {\n\t\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"error parsing command. %v\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tswitch cmd.Name {\n\t\tcase protocol.CmdSend:\n\t\t\tws.handleSendCmd(cmd)\n\t\tcase protocol.CmdReceive:\n\t\t\tws.handleReceiveCmd(cmd)\n\t\tcase protocol.CmdCancel:\n\t\t\tws.handleCancelCmd(cmd)\n\t\tdefault:\n\t\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"unknown command %v\", cmd.Name)\n\t\t}\n\t}\n}\n\nfunc (ws *WebSocket) sendConnectionMessage() {\n\tn := &protocol.NotificationMessage{\n\t\tName: protocol.SUCCESS_CONNECTED,\n\t\tArg: \"You are connected to the server.\",\n\t\tJson: fmt.Sprintf(`{\"ApplicationId\": \"%s\", \"UserId\": \"%s\", \"Time\": \"%s\"}`, ws.applicationID, ws.userID, time.Now().Format(time.RFC3339)),\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\nfunc (ws *WebSocket) handleReceiveCmd(cmd *protocol.Cmd) {\n\trec, err := NewReceiverFromCmd(\n\t\tws.applicationID,\n\t\tcmd,\n\t\tws.sendChannel,\n\t\tws.router,\n\t\tws.userID,\n\t)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Client error in handleReceiveCmd\")\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, err.Error())\n\t\treturn\n\t}\n\tws.receivers[rec.path] = rec\n\trec.Start()\n}\n\nfunc (ws *WebSocket) handleCancelCmd(cmd *protocol.Cmd) {\n\tif len(cmd.Arg) == 0 {\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"- command requires a path argument, but none given\")\n\t\treturn\n\t}\n\tpath := protocol.Path(cmd.Arg)\n\trec, exist := ws.receivers[path]\n\tif exist {\n\t\trec.Stop()\n\t\tdelete(ws.receivers, path)\n\t}\n}\n\nfunc (ws *WebSocket) handleSendCmd(cmd *protocol.Cmd) {\n\tlogger.WithFields(log.Fields{\n\t\t\"cmd\": string(cmd.Bytes()),\n\t}).Debug(\"Sending \")\n\n\tif len(cmd.Arg) == 0 {\n\t\tws.sendError(protocol.ERROR_BAD_REQUEST, \"send command requires a path argument, but none given\")\n\t\treturn\n\t}\n\n\targs := strings.SplitN(cmd.Arg, \" \", 2)\n\tmsg := &protocol.Message{\n\t\tPath: protocol.Path(args[0]),\n\t\tApplicationID: ws.applicationID,\n\t\tUserID: ws.userID,\n\t\tHeaderJSON: cmd.HeaderJSON,\n\t\tBody: cmd.Body,\n\t}\n\n\tws.router.HandleMessage(msg)\n\n\tws.sendOK(protocol.SUCCESS_SEND, \"\")\n}\n\nfunc (ws *WebSocket) cleanAndClose() {\n\n\tlogger.WithFields(log.Fields{\n\t\t\"applicationID\": ws.applicationID,\n\t}).Debug(\"Closing applicationId\")\n\n\tfor path, rec := range ws.receivers {\n\t\trec.Stop()\n\t\tdelete(ws.receivers, path)\n\t}\n\n\tws.Close()\n}\n\nfunc (ws *WebSocket) sendError(name string, argPattern string, params ...interface{}) {\n\tn := &protocol.NotificationMessage{\n\t\tName: name,\n\t\tArg: fmt.Sprintf(argPattern, params...),\n\t\tIsError: true,\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\nfunc (ws *WebSocket) sendOK(name string, argPattern string, params ...interface{}) {\n\tn := &protocol.NotificationMessage{\n\t\tName: name,\n\t\tArg: fmt.Sprintf(argPattern, params...),\n\t\tIsError: false,\n\t}\n\tws.sendChannel <- n.Bytes()\n}\n\n\/\/ Extracts the userID out of an URI or empty string if format not met\n\/\/ Example:\n\/\/ \t\thttp:\/\/example.com\/user\/user01\/ -> user01\n\/\/ \t\thttp:\/\/example.com\/user\/ -> \"\"\nfunc extractUserID(uri string) string {\n\turiParts := strings.SplitN(uri, \"\/user\/\", 2)\n\tif len(uriParts) != 2 {\n\t\treturn \"\"\n\t}\n\treturn uriParts[1]\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2013 Miquel Sabaté Solà\n\/\/ This file is licensed under the MIT license.\n\/\/ See the LICENSE file.\n\n\/\/ This package encapsulates all the methods regarding the File Cache.\npackage fcache\n\nimport (\n \"os\"\n \"fmt\"\n \"path\"\n \"time\"\n \"errors\"\n \"io\/ioutil\"\n)\n\n\/\/ This type contains some needed info that will be used when caching.\ntype Cache struct {\n \/\/ The directory \n Dir string\n\n \/\/ The expiration time to be set for each file.\n Expiration time.Duration\n\n \/\/ The permissions to be set when this cache creates new files.\n Permissions os.FileMode\n}\n\n\/\/ Internal: get whether the cache file is still hot (valid) or not.\n\/\/\n\/\/ mod - The last modification time of the cache file.\n\/\/\n\/\/ Returns true if the cache file is still valid, false otherwise.\nfunc (c *Cache) isHot(mod time.Time) bool {\n elapsed := time.Now().Sub(mod)\n return c.Expiration > elapsed\n}\n\n\/\/ Get a pointer to an initialized Cache structure.\n\/\/\n\/\/ dir - The path to the cache directory. If the directory does not\n\/\/ exist, it will create a new directory with permissions 0644.\n\/\/ expiration - The expiration time. That is, how many nanoseconds has to pass\n\/\/ by when a cache file is no longer considered valid.\n\/\/ perm - The permissions that the cache should operate in when creating\n\/\/ new files.\n\/\/\n\/\/ Returns a Cache pointer that points to an initialized Cache structure. It\n\/\/ will return nil if something goes wrong.\nfunc NewCache(dir string, expiration time.Duration, perm os.FileMode) *Cache {\n \/\/ First of all, get the directory path straight.\n if _, err := os.Stat(dir); err != nil {\n if os.IsNotExist(err) {\n if err = os.MkdirAll(dir, perm); err != nil {\n fmt.Printf(\"Error: %v\\n\", err)\n return nil\n }\n } else {\n fmt.Printf(\"Error: %v\\n\", err)\n return nil\n }\n }\n\n \/\/ Now it's safe to create the cache.\n cache := new(Cache)\n cache.Dir = dir\n cache.Expiration = expiration\n cache.Permissions = perm\n return cache\n}\n\n\/\/ Set the contents for a cache file. If this file doesn't exist already, it\n\/\/ will be created with permissions 0644.\n\/\/\n\/\/ name - The name of the file.\n\/\/ contents - The contents that the cache file has to contain after calling\n\/\/ this function.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) Set(name string, contents []byte) error {\n url := path.Join(c.Dir, name)\n return ioutil.WriteFile(url, contents, c.Permissions)\n}\n\n\/\/ Get the contents of a valid cache file.\n\/\/\n\/\/ name - The name of the file.\n\/\/\n\/\/ Returns a slice of bytes and an error. The slice of bytes contain the\n\/\/ contents of the cache file. The error is set to nil if everything was fine.\nfunc (c *Cache) Get(name string) ([]byte, error) {\n url := path.Join(c.Dir, name)\n if fi, err := os.Stat(url); err == nil {\n if c.isHot(fi.ModTime()) {\n return ioutil.ReadFile(url)\n }\n \/\/ Remove this file, its time has expired.\n os.Remove(url)\n }\n return []byte{}, errors.New(\"miss.\")\n}\n\n\/\/ Remove a cache file.\n\/\/\n\/\/ name - The name of the file.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) Flush(name string) error {\n url := path.Join(c.Dir, name)\n return os.Remove(url)\n}\n\n\/\/ Remove all the files from the cache.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) FlushAll() error {\n url := path.Join(c.Dir)\n err := os.RemoveAll(url)\n if err == nil {\n err = os.MkdirAll(url, c.Permissions)\n }\n return err\n}\nRemoved and extra space\/\/ Copyright (C) 2013 Miquel Sabaté Solà\n\/\/ This file is licensed under the MIT license.\n\/\/ See the LICENSE file.\n\n\/\/ This package encapsulates all the methods regarding the File Cache.\npackage fcache\n\nimport (\n \"os\"\n \"fmt\"\n \"path\"\n \"time\"\n \"errors\"\n \"io\/ioutil\"\n)\n\n\/\/ This type contains some needed info that will be used when caching.\ntype Cache struct {\n \/\/ The directory\n Dir string\n\n \/\/ The expiration time to be set for each file.\n Expiration time.Duration\n\n \/\/ The permissions to be set when this cache creates new files.\n Permissions os.FileMode\n}\n\n\/\/ Internal: get whether the cache file is still hot (valid) or not.\n\/\/\n\/\/ mod - The last modification time of the cache file.\n\/\/\n\/\/ Returns true if the cache file is still valid, false otherwise.\nfunc (c *Cache) isHot(mod time.Time) bool {\n elapsed := time.Now().Sub(mod)\n return c.Expiration > elapsed\n}\n\n\/\/ Get a pointer to an initialized Cache structure.\n\/\/\n\/\/ dir - The path to the cache directory. If the directory does not\n\/\/ exist, it will create a new directory with permissions 0644.\n\/\/ expiration - The expiration time. That is, how many nanoseconds has to pass\n\/\/ by when a cache file is no longer considered valid.\n\/\/ perm - The permissions that the cache should operate in when creating\n\/\/ new files.\n\/\/\n\/\/ Returns a Cache pointer that points to an initialized Cache structure. It\n\/\/ will return nil if something goes wrong.\nfunc NewCache(dir string, expiration time.Duration, perm os.FileMode) *Cache {\n \/\/ First of all, get the directory path straight.\n if _, err := os.Stat(dir); err != nil {\n if os.IsNotExist(err) {\n if err = os.MkdirAll(dir, perm); err != nil {\n fmt.Printf(\"Error: %v\\n\", err)\n return nil\n }\n } else {\n fmt.Printf(\"Error: %v\\n\", err)\n return nil\n }\n }\n\n \/\/ Now it's safe to create the cache.\n cache := new(Cache)\n cache.Dir = dir\n cache.Expiration = expiration\n cache.Permissions = perm\n return cache\n}\n\n\/\/ Set the contents for a cache file. If this file doesn't exist already, it\n\/\/ will be created with permissions 0644.\n\/\/\n\/\/ name - The name of the file.\n\/\/ contents - The contents that the cache file has to contain after calling\n\/\/ this function.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) Set(name string, contents []byte) error {\n url := path.Join(c.Dir, name)\n return ioutil.WriteFile(url, contents, c.Permissions)\n}\n\n\/\/ Get the contents of a valid cache file.\n\/\/\n\/\/ name - The name of the file.\n\/\/\n\/\/ Returns a slice of bytes and an error. The slice of bytes contain the\n\/\/ contents of the cache file. The error is set to nil if everything was fine.\nfunc (c *Cache) Get(name string) ([]byte, error) {\n url := path.Join(c.Dir, name)\n if fi, err := os.Stat(url); err == nil {\n if c.isHot(fi.ModTime()) {\n return ioutil.ReadFile(url)\n }\n \/\/ Remove this file, its time has expired.\n os.Remove(url)\n }\n return []byte{}, errors.New(\"miss.\")\n}\n\n\/\/ Remove a cache file.\n\/\/\n\/\/ name - The name of the file.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) Flush(name string) error {\n url := path.Join(c.Dir, name)\n return os.Remove(url)\n}\n\n\/\/ Remove all the files from the cache.\n\/\/\n\/\/ Returns nil if everything was ok. Otherwise it will return an error.\nfunc (c *Cache) FlushAll() error {\n url := path.Join(c.Dir)\n err := os.RemoveAll(url)\n if err == nil {\n err = os.MkdirAll(url, c.Permissions)\n }\n return err\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 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\/\/ Package socktest provides utilities for socket testing.\npackage socktest\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\/\/ A Switch represents a callpath point switch for socket system\n\/\/ calls.\ntype Switch struct {\n\tonce sync.Once\n\n\tfmu sync.RWMutex\n\tfltab map[FilterType]Filter\n\n\tsmu sync.RWMutex\n\tsotab Sockets\n\tstats stats\n}\n\nfunc (sw *Switch) init() {\n\tsw.fltab = make(map[FilterType]Filter)\n\tsw.sotab = make(Sockets)\n\tsw.stats = make(stats)\n}\n\n\/\/ Stats returns a list of per-cookie socket statistics.\nfunc (sw *Switch) Stats() []Stat {\n\tvar st []Stat\n\tsw.smu.RLock()\n\tfor _, s := range sw.stats {\n\t\tns := *s\n\t\tst = append(st, ns)\n\t}\n\tsw.smu.RUnlock()\n\treturn st\n}\n\n\/\/ Sockets returns mappings of socket descriptor to socket status.\nfunc (sw *Switch) Sockets() Sockets {\n\tsw.smu.RLock()\n\ttab := make(Sockets, len(sw.sotab))\n\tfor i, s := range sw.sotab {\n\t\ttab[i] = s\n\t}\n\tsw.smu.RUnlock()\n\treturn tab\n}\n\n\/\/ A Cookie represents a 3-tuple of a socket; address family, socket\n\/\/ type and protocol number.\ntype Cookie uint64\n\n\/\/ Family returns an address family.\nfunc (c Cookie) Family() int { return int(c >> 48) }\n\n\/\/ Type returns a socket type.\nfunc (c Cookie) Type() int { return int(c << 16 >> 32) }\n\n\/\/ Protocol returns a protocol number.\nfunc (c Cookie) Protocol() int { return int(c & 0xff) }\n\nfunc cookie(family, sotype, proto int) Cookie {\n\treturn Cookie(family)<<48 | Cookie(sotype)&0xffffffff<<16 | Cookie(proto)&0xff\n}\n\n\/\/ A Status represents the status of a socket.\ntype Status struct {\n\tCookie Cookie\n\tErr error \/\/ error status of socket system call\n\tSocketErr error \/\/ error status of socket by SO_ERROR\n}\n\nfunc (so Status) String() string {\n\treturn fmt.Sprintf(\"(%s, %s, %s): syscallerr=%v, socketerr=%v\", familyString(so.Cookie.Family()), typeString(so.Cookie.Type()), protocolString(so.Cookie.Protocol()), so.Err, so.SocketErr)\n}\n\n\/\/ A Stat represents a per-cookie socket statistics.\ntype Stat struct {\n\tFamily int \/\/ address family\n\tType int \/\/ socket type\n\tProtocol int \/\/ protocol number\n\n\tOpened uint64 \/\/ number of sockets opened\n\tConnected uint64 \/\/ number of sockets connected\n\tListened uint64 \/\/ number of sockets listened\n\tAccepted uint64 \/\/ number of sockets accepted\n\tClosed uint64 \/\/ number of sockets closed\n\n\tOpenFailed uint64 \/\/ number of sockets open failed\n\tConnectFailed uint64 \/\/ number of sockets connect failed\n\tListenFailed uint64 \/\/ number of sockets listen failed\n\tAcceptFailed uint64 \/\/ number of sockets accept failed\n\tCloseFailed uint64 \/\/ number of sockets close failed\n}\n\nfunc (st Stat) String() string {\n\treturn fmt.Sprintf(\"(%s, %s, %s): opened=%d, connected=%d, listened=%d, accepted=%d, closed=%d, openfailed=%d, connectfailed=%d, listenfailed=%d, acceptfailed=%d, closefailed=%d\", familyString(st.Family), typeString(st.Type), protocolString(st.Protocol), st.Opened, st.Connected, st.Listened, st.Accepted, st.Closed, st.OpenFailed, st.ConnectFailed, st.ListenFailed, st.AcceptFailed, st.CloseFailed)\n}\n\ntype stats map[Cookie]*Stat\n\nfunc (st stats) getLocked(c Cookie) *Stat {\n\ts, ok := st[c]\n\tif !ok {\n\t\ts = &Stat{Family: c.Family(), Type: c.Type(), Protocol: c.Protocol()}\n\t\tst[c] = s\n\t}\n\treturn s\n}\n\n\/\/ A FilterType represents a filter type.\ntype FilterType int\n\nconst (\n\tFilterSocket FilterType = iota \/\/ for Socket\n\tFilterConnect \/\/ for Connect or ConnectEx\n\tFilterListen \/\/ for Listen\n\tFilterAccept \/\/ for Accept or Accept4\n\tFilterGetsockoptInt \/\/ for GetsockoptInt\n\tFilterClose \/\/ for Close or Closesocket\n)\n\n\/\/ A Filter represents a socket system call filter.\n\/\/\n\/\/ It will only be executed before a system call for a socket that has\n\/\/ an entry in internal table.\n\/\/ If the filter returns a non-nil error, the execution of system call\n\/\/ will be canceled and the system call function returns the non-nil\n\/\/ error.\n\/\/ It can return a non-nil AfterFilter for filtering after the\n\/\/ execution of the system call.\ntype Filter func(*Status) (AfterFilter, error)\n\nfunc (f Filter) apply(st *Status) (AfterFilter, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\treturn f(st)\n}\n\n\/\/ An AfterFilter represents a socket system call filter after an\n\/\/ execution of a system call.\n\/\/\n\/\/ It will only be executed after a system call for a socket that has\n\/\/ an entry in internal table.\n\/\/ If the filter returns a non-nil error, the system call function\n\/\/ returns the non-nil error.\ntype AfterFilter func(*Status) error\n\nfunc (f AfterFilter) apply(st *Status) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\treturn f(st)\n}\n\n\/\/ Set deploys the socket system call filter f for the filter type t.\nfunc (sw *Switch) Set(t FilterType, f Filter) {\n\tsw.once.Do(sw.init)\n\tsw.fmu.Lock()\n\tsw.fltab[t] = f\n\tsw.fmu.Unlock()\n}\nnet\/internal\/socktest: simplify log message format\/\/ Copyright 2015 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\/\/ Package socktest provides utilities for socket testing.\npackage socktest\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\n\/\/ A Switch represents a callpath point switch for socket system\n\/\/ calls.\ntype Switch struct {\n\tonce sync.Once\n\n\tfmu sync.RWMutex\n\tfltab map[FilterType]Filter\n\n\tsmu sync.RWMutex\n\tsotab Sockets\n\tstats stats\n}\n\nfunc (sw *Switch) init() {\n\tsw.fltab = make(map[FilterType]Filter)\n\tsw.sotab = make(Sockets)\n\tsw.stats = make(stats)\n}\n\n\/\/ Stats returns a list of per-cookie socket statistics.\nfunc (sw *Switch) Stats() []Stat {\n\tvar st []Stat\n\tsw.smu.RLock()\n\tfor _, s := range sw.stats {\n\t\tns := *s\n\t\tst = append(st, ns)\n\t}\n\tsw.smu.RUnlock()\n\treturn st\n}\n\n\/\/ Sockets returns mappings of socket descriptor to socket status.\nfunc (sw *Switch) Sockets() Sockets {\n\tsw.smu.RLock()\n\ttab := make(Sockets, len(sw.sotab))\n\tfor i, s := range sw.sotab {\n\t\ttab[i] = s\n\t}\n\tsw.smu.RUnlock()\n\treturn tab\n}\n\n\/\/ A Cookie represents a 3-tuple of a socket; address family, socket\n\/\/ type and protocol number.\ntype Cookie uint64\n\n\/\/ Family returns an address family.\nfunc (c Cookie) Family() int { return int(c >> 48) }\n\n\/\/ Type returns a socket type.\nfunc (c Cookie) Type() int { return int(c << 16 >> 32) }\n\n\/\/ Protocol returns a protocol number.\nfunc (c Cookie) Protocol() int { return int(c & 0xff) }\n\nfunc cookie(family, sotype, proto int) Cookie {\n\treturn Cookie(family)<<48 | Cookie(sotype)&0xffffffff<<16 | Cookie(proto)&0xff\n}\n\n\/\/ A Status represents the status of a socket.\ntype Status struct {\n\tCookie Cookie\n\tErr error \/\/ error status of socket system call\n\tSocketErr error \/\/ error status of socket by SO_ERROR\n}\n\nfunc (so Status) String() string {\n\treturn fmt.Sprintf(\"(%s, %s, %s): syscallerr=%v socketerr=%v\", familyString(so.Cookie.Family()), typeString(so.Cookie.Type()), protocolString(so.Cookie.Protocol()), so.Err, so.SocketErr)\n}\n\n\/\/ A Stat represents a per-cookie socket statistics.\ntype Stat struct {\n\tFamily int \/\/ address family\n\tType int \/\/ socket type\n\tProtocol int \/\/ protocol number\n\n\tOpened uint64 \/\/ number of sockets opened\n\tConnected uint64 \/\/ number of sockets connected\n\tListened uint64 \/\/ number of sockets listened\n\tAccepted uint64 \/\/ number of sockets accepted\n\tClosed uint64 \/\/ number of sockets closed\n\n\tOpenFailed uint64 \/\/ number of sockets open failed\n\tConnectFailed uint64 \/\/ number of sockets connect failed\n\tListenFailed uint64 \/\/ number of sockets listen failed\n\tAcceptFailed uint64 \/\/ number of sockets accept failed\n\tCloseFailed uint64 \/\/ number of sockets close failed\n}\n\nfunc (st Stat) String() string {\n\treturn fmt.Sprintf(\"(%s, %s, %s): opened=%d connected=%d listened=%d accepted=%d closed=%d openfailed=%d connectfailed=%d listenfailed=%d acceptfailed=%d closefailed=%d\", familyString(st.Family), typeString(st.Type), protocolString(st.Protocol), st.Opened, st.Connected, st.Listened, st.Accepted, st.Closed, st.OpenFailed, st.ConnectFailed, st.ListenFailed, st.AcceptFailed, st.CloseFailed)\n}\n\ntype stats map[Cookie]*Stat\n\nfunc (st stats) getLocked(c Cookie) *Stat {\n\ts, ok := st[c]\n\tif !ok {\n\t\ts = &Stat{Family: c.Family(), Type: c.Type(), Protocol: c.Protocol()}\n\t\tst[c] = s\n\t}\n\treturn s\n}\n\n\/\/ A FilterType represents a filter type.\ntype FilterType int\n\nconst (\n\tFilterSocket FilterType = iota \/\/ for Socket\n\tFilterConnect \/\/ for Connect or ConnectEx\n\tFilterListen \/\/ for Listen\n\tFilterAccept \/\/ for Accept or Accept4\n\tFilterGetsockoptInt \/\/ for GetsockoptInt\n\tFilterClose \/\/ for Close or Closesocket\n)\n\n\/\/ A Filter represents a socket system call filter.\n\/\/\n\/\/ It will only be executed before a system call for a socket that has\n\/\/ an entry in internal table.\n\/\/ If the filter returns a non-nil error, the execution of system call\n\/\/ will be canceled and the system call function returns the non-nil\n\/\/ error.\n\/\/ It can return a non-nil AfterFilter for filtering after the\n\/\/ execution of the system call.\ntype Filter func(*Status) (AfterFilter, error)\n\nfunc (f Filter) apply(st *Status) (AfterFilter, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\treturn f(st)\n}\n\n\/\/ An AfterFilter represents a socket system call filter after an\n\/\/ execution of a system call.\n\/\/\n\/\/ It will only be executed after a system call for a socket that has\n\/\/ an entry in internal table.\n\/\/ If the filter returns a non-nil error, the system call function\n\/\/ returns the non-nil error.\ntype AfterFilter func(*Status) error\n\nfunc (f AfterFilter) apply(st *Status) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\treturn f(st)\n}\n\n\/\/ Set deploys the socket system call filter f for the filter type t.\nfunc (sw *Switch) Set(t FilterType, f Filter) {\n\tsw.once.Do(sw.init)\n\tsw.fmu.Lock()\n\tsw.fltab[t] = f\n\tsw.fmu.Unlock()\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2019 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 service\n\nimport (\n\t\"time\"\n)\n\nconst (\n\t\/\/ RespondingTimeout is how long to wait for a service to be responding.\n\tRespondingTimeout = 2 * time.Minute\n\n\t\/\/ MaxNodesForEndpointsTests is the max number for testing endpoints.\n\t\/\/ Don't test with more than 3 nodes.\n\t\/\/ Many tests create an endpoint per node, in large clusters, this is\n\t\/\/ resource and time intensive.\n\tMaxNodesForEndpointsTests = 3\n\n\t\/\/ KubeProxyLagTimeout is the maximum time a kube-proxy daemon on a node is allowed\n\t\/\/ to not notice a Service update, such as type=NodePort.\n\t\/\/ TODO: This timeout should be O(10s), observed values are O(1m), 5m is very\n\t\/\/ liberal. Fix tracked in #20567.\n\tKubeProxyLagTimeout = 5 * time.Minute\n\n\t\/\/ KubeProxyEndpointLagTimeout is the maximum time a kube-proxy daemon on a node is allowed\n\t\/\/ to not notice an Endpoint update.\n\tKubeProxyEndpointLagTimeout = 30 * time.Second\n\n\t\/\/ LoadBalancerLagTimeoutDefault is the maximum time a load balancer is allowed to\n\t\/\/ not respond after creation.\n\tLoadBalancerLagTimeoutDefault = 2 * time.Minute\n\n\t\/\/ LoadBalancerLagTimeoutAWS is the delay between ELB creation and serving traffic\n\t\/\/ on AWS. A few minutes is typical, so use 10m.\n\tLoadBalancerLagTimeoutAWS = 10 * time.Minute\n\n\t\/\/ LoadBalancerCreateTimeoutDefault is the default time to wait for a load balancer to be created\/modified.\n\t\/\/ TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable\n\t\/\/ Hideen - use GetServiceLoadBalancerCreateTimeout function instead.\n\tloadBalancerCreateTimeoutDefault = 10 * time.Minute\n\t\/\/ LoadBalancerCreateTimeoutLarge is the maximum time to wait for a load balancer to be created\/modified.\n\t\/\/ Hideen - use GetServiceLoadBalancerCreateTimeout function instead.\n\tloadBalancerCreateTimeoutLarge = 45 * time.Minute\n\n\t\/\/ LoadBalancerPropagationTimeoutDefault is the default time to wait for pods to\n\t\/\/ be targeted by load balancers.\n\t\/\/ Hideen - use GetServiceLoadBalancerPropagationTimeout function instead.\n\tloadBalancerPropagationTimeoutDefault = 10 * time.Minute\n\t\/\/ LoadBalancerPropagationTimeoutLarge is the maximum time to wait for pods to\n\t\/\/ be targeted by load balancers.\n\t\/\/ Hideen - use GetServiceLoadBalancerPropagationTimeout function instead.\n\tloadBalancerPropagationTimeoutLarge = time.Hour\n\n\t\/\/ LoadBalancerCleanupTimeout is the time required by the loadbalancer to cleanup, proportional to numApps\/Ing.\n\t\/\/ Bring the cleanup timeout back down to 5m once b\/33588344 is resolved.\n\tLoadBalancerCleanupTimeout = 15 * time.Minute\n\n\t\/\/ LoadBalancerPollInterval is the interval value in which the loadbalancer polls.\n\tLoadBalancerPollInterval = 30 * time.Second\n\n\t\/\/ LargeClusterMinNodesNumber is the number of nodes which a large cluster consists of.\n\tLargeClusterMinNodesNumber = 100\n\n\t\/\/ TestTimeout is used for most polling\/waiting activities\n\tTestTimeout = 60 * time.Second\n\n\t\/\/ ServiceEndpointsTimeout is the maximum time in which endpoints for the service should be created.\n\tServiceEndpointsTimeout = 2 * time.Minute\n\n\t\/\/ ServiceReachabilityShortPollTimeout is the maximum time in which service must be reachable during polling.\n\tServiceReachabilityShortPollTimeout = 2 * time.Minute\n)\nbump e2e loadbalancer timeouts to 15m\/*\nCopyright 2019 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 service\n\nimport (\n\t\"time\"\n)\n\nconst (\n\t\/\/ RespondingTimeout is how long to wait for a service to be responding.\n\tRespondingTimeout = 2 * time.Minute\n\n\t\/\/ MaxNodesForEndpointsTests is the max number for testing endpoints.\n\t\/\/ Don't test with more than 3 nodes.\n\t\/\/ Many tests create an endpoint per node, in large clusters, this is\n\t\/\/ resource and time intensive.\n\tMaxNodesForEndpointsTests = 3\n\n\t\/\/ KubeProxyLagTimeout is the maximum time a kube-proxy daemon on a node is allowed\n\t\/\/ to not notice a Service update, such as type=NodePort.\n\t\/\/ TODO: This timeout should be O(10s), observed values are O(1m), 5m is very\n\t\/\/ liberal. Fix tracked in #20567.\n\tKubeProxyLagTimeout = 5 * time.Minute\n\n\t\/\/ KubeProxyEndpointLagTimeout is the maximum time a kube-proxy daemon on a node is allowed\n\t\/\/ to not notice an Endpoint update.\n\tKubeProxyEndpointLagTimeout = 30 * time.Second\n\n\t\/\/ LoadBalancerLagTimeoutDefault is the maximum time a load balancer is allowed to\n\t\/\/ not respond after creation.\n\tLoadBalancerLagTimeoutDefault = 2 * time.Minute\n\n\t\/\/ LoadBalancerLagTimeoutAWS is the delay between ELB creation and serving traffic\n\t\/\/ on AWS. A few minutes is typical, so use 10m.\n\tLoadBalancerLagTimeoutAWS = 10 * time.Minute\n\n\t\/\/ LoadBalancerCreateTimeoutDefault is the default time to wait for a load balancer to be created\/modified.\n\t\/\/ TODO: once support ticket 21807001 is resolved, reduce this timeout back to something reasonable\n\t\/\/ Hideen - use GetServiceLoadBalancerCreateTimeout function instead.\n\tloadBalancerCreateTimeoutDefault = 15 * time.Minute\n\t\/\/ LoadBalancerCreateTimeoutLarge is the maximum time to wait for a load balancer to be created\/modified.\n\t\/\/ Hideen - use GetServiceLoadBalancerCreateTimeout function instead.\n\tloadBalancerCreateTimeoutLarge = 45 * time.Minute\n\n\t\/\/ LoadBalancerPropagationTimeoutDefault is the default time to wait for pods to\n\t\/\/ be targeted by load balancers.\n\t\/\/ Hideen - use GetServiceLoadBalancerPropagationTimeout function instead.\n\tloadBalancerPropagationTimeoutDefault = 10 * time.Minute\n\t\/\/ LoadBalancerPropagationTimeoutLarge is the maximum time to wait for pods to\n\t\/\/ be targeted by load balancers.\n\t\/\/ Hideen - use GetServiceLoadBalancerPropagationTimeout function instead.\n\tloadBalancerPropagationTimeoutLarge = time.Hour\n\n\t\/\/ LoadBalancerCleanupTimeout is the time required by the loadbalancer to cleanup, proportional to numApps\/Ing.\n\t\/\/ Bring the cleanup timeout back down to 5m once b\/33588344 is resolved.\n\tLoadBalancerCleanupTimeout = 15 * time.Minute\n\n\t\/\/ LoadBalancerPollInterval is the interval value in which the loadbalancer polls.\n\tLoadBalancerPollInterval = 30 * time.Second\n\n\t\/\/ LargeClusterMinNodesNumber is the number of nodes which a large cluster consists of.\n\tLargeClusterMinNodesNumber = 100\n\n\t\/\/ TestTimeout is used for most polling\/waiting activities\n\tTestTimeout = 60 * time.Second\n\n\t\/\/ ServiceEndpointsTimeout is the maximum time in which endpoints for the service should be created.\n\tServiceEndpointsTimeout = 2 * time.Minute\n\n\t\/\/ ServiceReachabilityShortPollTimeout is the maximum time in which service must be reachable during polling.\n\tServiceReachabilityShortPollTimeout = 2 * time.Minute\n)\n<|endoftext|>"} {"text":"package sniff\n\nimport (\n\t\"cred-alert\/scanners\"\n\t\"cred-alert\/sniff\/matchers\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nconst bashStringInterpolationPattern = `[\"]\\$`\nconst fakePattern = `(?i)fake`\nconst examplePattern = `(?i)example`\n\nconst awsAccessKeyIDPattern = `AKIA[A-Z0-9]{16}`\nconst awsSecretAccessKeyPattern = `(?i)(\"|')?(aws)?_?(secret)?_?(access)?_?(key)(\"|')?\\s*(:|=>|=)\\s*(\"|')?[A-Za-z0-9\/\\+=]{40}(\"|')?`\nconst awsAccountIDPattern = `(?i)(\"|')?(aws)?_?(account)_?(id)?(\"|')?\\s*(:|=>|=)\\s*(\"|')?[0-9]{4}\\-?[0-9]{4}\\-?[0-9]{4}(\"|')?`\nconst cryptMD5Pattern = `\\$1\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{22}`\nconst cryptSHA256Pattern = `\\$5\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{43}`\nconst cryptSHA512Pattern = `\\$6\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{86}`\nconst rsaPrivateKeyHeaderPattern = `-----BEGIN RSA PRIVATE KEY-----`\n\n\/\/go:generate counterfeiter . Scanner\n\ntype Scanner interface {\n\tScan(lager.Logger) bool\n\tLine(lager.Logger) *scanners.Line\n}\n\n\/\/go:generate counterfeiter . Sniffer\n\ntype Sniffer interface {\n\tSniff(lager.Logger, Scanner, func(scanners.Line) error) error\n}\n\ntype sniffer struct {\n\tmatcher matchers.Matcher\n\texclusionMatcher matchers.Matcher\n}\n\nfunc NewSniffer(matcher, exclusionMatcher matchers.Matcher) Sniffer {\n\treturn &sniffer{\n\t\tmatcher: matcher,\n\t\texclusionMatcher: exclusionMatcher,\n\t}\n}\n\nfunc NewDefaultSniffer() Sniffer {\n\treturn &sniffer{\n\t\tmatcher: matchers.Multi(\n\t\t\tmatchers.KnownFormat(awsAccessKeyIDPattern),\n\t\t\tmatchers.KnownFormat(awsSecretAccessKeyPattern),\n\t\t\tmatchers.KnownFormat(awsAccountIDPattern),\n\t\t\tmatchers.KnownFormat(cryptMD5Pattern),\n\t\t\tmatchers.KnownFormat(cryptSHA256Pattern),\n\t\t\tmatchers.KnownFormat(cryptSHA512Pattern),\n\t\t\tmatchers.KnownFormat(rsaPrivateKeyHeaderPattern),\n\t\t\tmatchers.Assignment(),\n\t\t),\n\t\texclusionMatcher: matchers.Multi(\n\t\t\tmatchers.KnownFormat(bashStringInterpolationPattern),\n\t\t\tmatchers.KnownFormat(fakePattern),\n\t\t\tmatchers.KnownFormat(examplePattern),\n\t\t),\n\t}\n}\n\nfunc (s *sniffer) Sniff(\n\tlogger lager.Logger,\n\tscanner Scanner,\n\thandleViolation func(scanners.Line) error,\n) error {\n\tlogger = logger.Session(\"sniff\")\n\n\tvar result error\n\n\tfor scanner.Scan(logger) {\n\t\tline := *scanner.Line(logger)\n\n\t\tif s.exclusionMatcher.Match(line.Content) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif s.matcher.Match(line.Content) {\n\t\t\terr := handleViolation(line)\n\t\t\tif err != nil {\n\t\t\t\tresult = multierror.Append(result, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\nregularize loggin in sniff packagepackage sniff\n\nimport (\n\t\"cred-alert\/scanners\"\n\t\"cred-alert\/sniff\/matchers\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nconst bashStringInterpolationPattern = `[\"]\\$`\nconst fakePattern = `(?i)fake`\nconst examplePattern = `(?i)example`\n\nconst awsAccessKeyIDPattern = `AKIA[A-Z0-9]{16}`\nconst awsSecretAccessKeyPattern = `(?i)(\"|')?(aws)?_?(secret)?_?(access)?_?(key)(\"|')?\\s*(:|=>|=)\\s*(\"|')?[A-Za-z0-9\/\\+=]{40}(\"|')?`\nconst awsAccountIDPattern = `(?i)(\"|')?(aws)?_?(account)_?(id)?(\"|')?\\s*(:|=>|=)\\s*(\"|')?[0-9]{4}\\-?[0-9]{4}\\-?[0-9]{4}(\"|')?`\nconst cryptMD5Pattern = `\\$1\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{22}`\nconst cryptSHA256Pattern = `\\$5\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{43}`\nconst cryptSHA512Pattern = `\\$6\\$[a-zA-Z0-9.\/]{16}\\$[a-zA-Z0-9.\/]{86}`\nconst rsaPrivateKeyHeaderPattern = `-----BEGIN RSA PRIVATE KEY-----`\n\n\/\/go:generate counterfeiter . Scanner\n\ntype Scanner interface {\n\tScan(lager.Logger) bool\n\tLine(lager.Logger) *scanners.Line\n}\n\n\/\/go:generate counterfeiter . Sniffer\n\ntype Sniffer interface {\n\tSniff(lager.Logger, Scanner, func(scanners.Line) error) error\n}\n\ntype sniffer struct {\n\tmatcher matchers.Matcher\n\texclusionMatcher matchers.Matcher\n}\n\nfunc NewSniffer(matcher, exclusionMatcher matchers.Matcher) Sniffer {\n\treturn &sniffer{\n\t\tmatcher: matcher,\n\t\texclusionMatcher: exclusionMatcher,\n\t}\n}\n\nfunc NewDefaultSniffer() Sniffer {\n\treturn &sniffer{\n\t\tmatcher: matchers.Multi(\n\t\t\tmatchers.KnownFormat(awsAccessKeyIDPattern),\n\t\t\tmatchers.KnownFormat(awsSecretAccessKeyPattern),\n\t\t\tmatchers.KnownFormat(awsAccountIDPattern),\n\t\t\tmatchers.KnownFormat(cryptMD5Pattern),\n\t\t\tmatchers.KnownFormat(cryptSHA256Pattern),\n\t\t\tmatchers.KnownFormat(cryptSHA512Pattern),\n\t\t\tmatchers.KnownFormat(rsaPrivateKeyHeaderPattern),\n\t\t\tmatchers.Assignment(),\n\t\t),\n\t\texclusionMatcher: matchers.Multi(\n\t\t\tmatchers.KnownFormat(bashStringInterpolationPattern),\n\t\t\tmatchers.KnownFormat(fakePattern),\n\t\t\tmatchers.KnownFormat(examplePattern),\n\t\t),\n\t}\n}\n\nfunc (s *sniffer) Sniff(\n\tlogger lager.Logger,\n\tscanner Scanner,\n\thandleViolation func(scanners.Line) error,\n) error {\n\tlogger = logger.Session(\"sniff\")\n\tlogger.Info(\"starting\")\n\n\tvar result error\n\n\tfor scanner.Scan(logger) {\n\t\tline := *scanner.Line(logger)\n\n\t\tif s.exclusionMatcher.Match(line.Content) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif s.matcher.Match(line.Content) {\n\t\t\terr := handleViolation(line)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Session(\"handle-violation\").Error(\"failed\", err)\n\t\t\t\tresult = multierror.Append(result, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger.Info(\"done\")\n\treturn result\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Gorilla WebSocket 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\"strings\"\n\n\t\"fmt\"\n\n\t\"github.com\/gorilla\/websocket\"\n)\n\ntype OnMessage func(fromAddr string, msg []byte)\n\n\/\/ Client is a middleman between the websocket connection and the hub.\ntype RequestMsg struct {\n\t\/\/ The websocket connection.\n\tconn *websocket.Conn\n\tmsg []byte\n}\n\n\/\/ hub maintains the set of active clients and broadcasts messages to the\n\/\/ clients.\ntype Hub struct {\n\t\/\/ Registered clients.\n\tclients map[*Client]bool\n\n\t\/\/ Inbound messages from the clients.\n\trequest chan *RequestMsg\n\n\t\/\/ Register requests from the clients.\n\tregister chan *Client\n\n\t\/\/ Unregister requests from clients.\n\tunregister chan *Client\n}\n\nfunc newHub() *Hub {\n\treturn &Hub{\n\t\trequest: make(chan *RequestMsg),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n}\n\nfunc (h *Hub) sendMessageToAddr(sendToIP string, message []byte) {\n\t\/\/ TODO: make this a hashtable to avoid iterating over all clients\n\tfor client := range h.clients {\n\t\tfmt.Println(\"Finding client to forward to...\")\n\t\tclientIP := strings.Split(client.conn.RemoteAddr().String(), \":\")[0]\n\t\tif clientIP == sendToIP {\n\t\t\tclient.send <- message\n\t\t\tfmt.Println(\"...done\")\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (h *Hub) run(cb OnMessage) {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase req := <-h.request:\n\t\t\tcb(req.conn.RemoteAddr().String(), req.msg)\n\t\t}\n\t}\n}\ncheck ports when comparing clients\/\/ Copyright 2013 The Gorilla WebSocket 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\"fmt\"\n\n\t\"github.com\/gorilla\/websocket\"\n)\n\ntype OnMessage func(fromAddr string, msg []byte)\n\n\/\/ Client is a middleman between the websocket connection and the hub.\ntype RequestMsg struct {\n\t\/\/ The websocket connection.\n\tconn *websocket.Conn\n\tmsg []byte\n}\n\n\/\/ hub maintains the set of active clients and broadcasts messages to the\n\/\/ clients.\ntype Hub struct {\n\t\/\/ Registered clients.\n\tclients map[*Client]bool\n\n\t\/\/ Inbound messages from the clients.\n\trequest chan *RequestMsg\n\n\t\/\/ Register requests from the clients.\n\tregister chan *Client\n\n\t\/\/ Unregister requests from clients.\n\tunregister chan *Client\n}\n\nfunc newHub() *Hub {\n\treturn &Hub{\n\t\trequest: make(chan *RequestMsg),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n}\n\nfunc (h *Hub) sendMessageToAddr(sendToIP string, message []byte) {\n\t\/\/ TODO: make this a hashtable to avoid iterating over all clients\n\tfor client := range h.clients {\n\t\tfmt.Println(\"Finding client to forward to...\")\n\t\tif client.conn.RemoteAddr().String() == sendToIP {\n\t\t\tclient.send <- message\n\t\t\tfmt.Println(\"...done\")\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (h *Hub) run(cb OnMessage) {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase req := <-h.request:\n\t\t\tcb(req.conn.RemoteAddr().String(), req.msg)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package aws\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/hashicorp\/terraform\/helper\/hashcode\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\n\/\/ How long to sleep if a limit-exceeded event happens\nvar routeTargetValidationError = errors.New(\"Error: more than 1 target specified. Only 1 of gateway_id\" +\n\t\"nat_gateway_id, instance_id, network_interface_id, route_table_id or\" +\n\t\"vpc_peering_connection_id is allowed.\")\n\n\/\/ AWS Route resource Schema declaration\nfunc resourceAwsRoute() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsRouteCreate,\n\t\tRead: resourceAwsRouteRead,\n\t\tUpdate: resourceAwsRouteUpdate,\n\t\tDelete: resourceAwsRouteDelete,\n\t\tExists: resourceAwsRouteExists,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"destination_cidr_block\": &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\n\t\t\t\"destination_prefix_list_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"gateway_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"nat_gateway_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"instance_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"instance_owner_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"network_interface_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"origin\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"state\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"route_table_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\n\t\t\t\"vpc_peering_connection_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\tvar numTargets int\n\tvar setTarget string\n\tallowedTargets := []string{\n\t\t\"gateway_id\",\n\t\t\"nat_gateway_id\",\n\t\t\"instance_id\",\n\t\t\"network_interface_id\",\n\t\t\"vpc_peering_connection_id\",\n\t}\n\n\t\/\/ Check if more than 1 target is specified\n\tfor _, target := range allowedTargets {\n\t\tif len(d.Get(target).(string)) > 0 {\n\t\t\tnumTargets++\n\t\t\tsetTarget = target\n\t\t}\n\t}\n\n\tif numTargets > 1 {\n\t\treturn routeTargetValidationError\n\t}\n\n\tcreateOpts := &ec2.CreateRouteInput{}\n\t\/\/ Formulate CreateRouteInput based on the target type\n\tswitch setTarget {\n\tcase \"gateway_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tGatewayId: aws.String(d.Get(\"gateway_id\").(string)),\n\t\t}\n\tcase \"nat_gateway_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNatGatewayId: aws.String(d.Get(\"nat_gateway_id\").(string)),\n\t\t}\n\tcase \"instance_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tInstanceId: aws.String(d.Get(\"instance_id\").(string)),\n\t\t}\n\tcase \"network_interface_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"vpc_peering_connection_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tVpcPeeringConnectionId: aws.String(d.Get(\"vpc_peering_connection_id\").(string)),\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error: invalid target type specified.\")\n\t}\n\tlog.Printf(\"[DEBUG] Route create config: %s\", createOpts)\n\n\t\/\/ Create the route\n\t_, err := conn.CreateRoute(createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating route: %s\", err)\n\t}\n\n\troute, err := findResourceRoute(conn, d.Get(\"route_table_id\").(string), d.Get(\"destination_cidr_block\").(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(routeIDHash(d, route))\n\n\treturn resourceAwsRouteRead(d, meta)\n}\n\nfunc resourceAwsRouteRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\troute, err := findResourceRoute(conn, d.Get(\"route_table_id\").(string), d.Get(\"destination_cidr_block\").(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Set(\"destination_prefix_list_id\", route.DestinationPrefixListId)\n\td.Set(\"gateway_id\", route.GatewayId)\n\td.Set(\"nat_gateway_id\", route.NatGatewayId)\n\td.Set(\"instance_id\", route.InstanceId)\n\td.Set(\"instance_owner_id\", route.InstanceOwnerId)\n\td.Set(\"network_interface_id\", route.NetworkInterfaceId)\n\td.Set(\"origin\", route.Origin)\n\td.Set(\"state\", route.State)\n\td.Set(\"vpc_peering_connection_id\", route.VpcPeeringConnectionId)\n\n\treturn nil\n}\n\nfunc resourceAwsRouteUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\tvar numTargets int\n\tvar setTarget string\n\tallowedTargets := []string{\n\t\t\"gateway_id\",\n\t\t\"nat_gateway_id\",\n\t\t\"instance_id\",\n\t\t\"network_interface_id\",\n\t\t\"vpc_peering_connection_id\",\n\t}\n\treplaceOpts := &ec2.ReplaceRouteInput{}\n\n\t\/\/ Check if more than 1 target is specified\n\tfor _, target := range allowedTargets {\n\t\tif len(d.Get(target).(string)) > 0 {\n\t\t\tnumTargets++\n\t\t\tsetTarget = target\n\t\t}\n\t}\n\n\tif numTargets > 1 {\n\t\treturn routeTargetValidationError\n\t}\n\n\t\/\/ Formulate ReplaceRouteInput based on the target type\n\tswitch setTarget {\n\tcase \"gateway_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tGatewayId: aws.String(d.Get(\"gateway_id\").(string)),\n\t\t}\n\tcase \"nat_gateway_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNatGatewayId: aws.String(d.Get(\"nat_gateway_id\").(string)),\n\t\t}\n\tcase \"instance_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tInstanceId: aws.String(d.Get(\"instance_id\").(string)),\n\t\t\t\/\/NOOP: Ensure we don't blow away network interface id that is set after instance is launched\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"network_interface_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"vpc_peering_connection_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tVpcPeeringConnectionId: aws.String(d.Get(\"vpc_peering_connection_id\").(string)),\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error: invalid target type specified.\")\n\t}\n\tlog.Printf(\"[DEBUG] Route replace config: %s\", replaceOpts)\n\n\t\/\/ Replace the route\n\t_, err := conn.ReplaceRoute(replaceOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsRouteDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tdeleteOpts := &ec2.DeleteRouteInput{\n\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t}\n\tlog.Printf(\"[DEBUG] Route delete opts: %s\", deleteOpts)\n\n\tresp, err := conn.DeleteRoute(deleteOpts)\n\tlog.Printf(\"[DEBUG] Route delete result: %s\", resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceAwsRouteExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tconn := meta.(*AWSClient).ec2conn\n\trouteTableId := d.Get(\"route_table_id\").(string)\n\n\tfindOpts := &ec2.DescribeRouteTablesInput{\n\t\tRouteTableIds: []*string{&routeTableId},\n\t}\n\n\tres, err := conn.DescribeRouteTables(findOpts)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Error while checking if route exists: %s\", err)\n\t}\n\n\tif len(res.RouteTables) < 1 || res.RouteTables[0] == nil {\n\t\tlog.Printf(\"[WARN] Route table %s is gone, so route does not exist.\",\n\t\t\trouteTableId)\n\t\treturn false, nil\n\t}\n\n\tcidr := d.Get(\"destination_cidr_block\").(string)\n\tfor _, route := range (*res.RouteTables[0]).Routes {\n\t\tif route.DestinationCidrBlock != nil && *route.DestinationCidrBlock == cidr {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\n\/\/ Create an ID for a route\nfunc routeIDHash(d *schema.ResourceData, r *ec2.Route) string {\n\treturn fmt.Sprintf(\"r-%s%d\", d.Get(\"route_table_id\").(string), hashcode.String(*r.DestinationCidrBlock))\n}\n\n\/\/ Helper: retrieve a route\nfunc findResourceRoute(conn *ec2.EC2, rtbid string, cidr string) (*ec2.Route, error) {\n\trouteTableID := rtbid\n\n\tfindOpts := &ec2.DescribeRouteTablesInput{\n\t\tRouteTableIds: []*string{&routeTableID},\n\t}\n\n\tresp, err := conn.DescribeRouteTables(findOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.RouteTables) < 1 || resp.RouteTables[0] == nil {\n\t\treturn nil, fmt.Errorf(\"Route table %s is gone, so route does not exist.\",\n\t\t\trouteTableID)\n\t}\n\n\tfor _, route := range (*resp.RouteTables[0]).Routes {\n\t\tif *route.DestinationCidrBlock == cidr {\n\t\t\treturn route, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(`\nerror finding matching route for Route table (%s) and destination CIDR block (%s)`,\n\t\trtbid, cidr)\n}\nUse resource.Retry for route creation and deletion (#6225)package aws\n\nimport (\n\t\"errors\"\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\/hashcode\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\n\/\/ How long to sleep if a limit-exceeded event happens\nvar routeTargetValidationError = errors.New(\"Error: more than 1 target specified. Only 1 of gateway_id\" +\n\t\"nat_gateway_id, instance_id, network_interface_id, route_table_id or\" +\n\t\"vpc_peering_connection_id is allowed.\")\n\n\/\/ AWS Route resource Schema declaration\nfunc resourceAwsRoute() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsRouteCreate,\n\t\tRead: resourceAwsRouteRead,\n\t\tUpdate: resourceAwsRouteUpdate,\n\t\tDelete: resourceAwsRouteDelete,\n\t\tExists: resourceAwsRouteExists,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"destination_cidr_block\": &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\n\t\t\t\"destination_prefix_list_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"gateway_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"nat_gateway_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"instance_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"instance_owner_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"network_interface_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"origin\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"state\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"route_table_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\n\t\t\t\"vpc_peering_connection_id\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\tvar numTargets int\n\tvar setTarget string\n\tallowedTargets := []string{\n\t\t\"gateway_id\",\n\t\t\"nat_gateway_id\",\n\t\t\"instance_id\",\n\t\t\"network_interface_id\",\n\t\t\"vpc_peering_connection_id\",\n\t}\n\n\t\/\/ Check if more than 1 target is specified\n\tfor _, target := range allowedTargets {\n\t\tif len(d.Get(target).(string)) > 0 {\n\t\t\tnumTargets++\n\t\t\tsetTarget = target\n\t\t}\n\t}\n\n\tif numTargets > 1 {\n\t\treturn routeTargetValidationError\n\t}\n\n\tcreateOpts := &ec2.CreateRouteInput{}\n\t\/\/ Formulate CreateRouteInput based on the target type\n\tswitch setTarget {\n\tcase \"gateway_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tGatewayId: aws.String(d.Get(\"gateway_id\").(string)),\n\t\t}\n\tcase \"nat_gateway_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNatGatewayId: aws.String(d.Get(\"nat_gateway_id\").(string)),\n\t\t}\n\tcase \"instance_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tInstanceId: aws.String(d.Get(\"instance_id\").(string)),\n\t\t}\n\tcase \"network_interface_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"vpc_peering_connection_id\":\n\t\tcreateOpts = &ec2.CreateRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tVpcPeeringConnectionId: aws.String(d.Get(\"vpc_peering_connection_id\").(string)),\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error: invalid target type specified.\")\n\t}\n\tlog.Printf(\"[DEBUG] Route create config: %s\", createOpts)\n\n\t\/\/ Create the route\n\tvar err error\n\n\terr = resource.Retry(2*time.Minute, func() *resource.RetryError {\n\t\t_, err = conn.CreateRoute(createOpts)\n\n\t\tif err != nil {\n\t\t\tec2err, ok := err.(awserr.Error)\n\t\t\tif !ok {\n\t\t\t\treturn resource.NonRetryableError(err)\n\t\t\t}\n\t\t\tif ec2err.Code() == \"InvalidParameterException\" {\n\t\t\t\tlog.Printf(\"[DEBUG] Trying to create route again: %q\", ec2err.Message())\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating route: %s\", err)\n\t}\n\n\troute, err := findResourceRoute(conn, d.Get(\"route_table_id\").(string), d.Get(\"destination_cidr_block\").(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(routeIDHash(d, route))\n\n\treturn resourceAwsRouteRead(d, meta)\n}\n\nfunc resourceAwsRouteRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\troute, err := findResourceRoute(conn, d.Get(\"route_table_id\").(string), d.Get(\"destination_cidr_block\").(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Set(\"destination_prefix_list_id\", route.DestinationPrefixListId)\n\td.Set(\"gateway_id\", route.GatewayId)\n\td.Set(\"nat_gateway_id\", route.NatGatewayId)\n\td.Set(\"instance_id\", route.InstanceId)\n\td.Set(\"instance_owner_id\", route.InstanceOwnerId)\n\td.Set(\"network_interface_id\", route.NetworkInterfaceId)\n\td.Set(\"origin\", route.Origin)\n\td.Set(\"state\", route.State)\n\td.Set(\"vpc_peering_connection_id\", route.VpcPeeringConnectionId)\n\n\treturn nil\n}\n\nfunc resourceAwsRouteUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\tvar numTargets int\n\tvar setTarget string\n\tallowedTargets := []string{\n\t\t\"gateway_id\",\n\t\t\"nat_gateway_id\",\n\t\t\"instance_id\",\n\t\t\"network_interface_id\",\n\t\t\"vpc_peering_connection_id\",\n\t}\n\treplaceOpts := &ec2.ReplaceRouteInput{}\n\n\t\/\/ Check if more than 1 target is specified\n\tfor _, target := range allowedTargets {\n\t\tif len(d.Get(target).(string)) > 0 {\n\t\t\tnumTargets++\n\t\t\tsetTarget = target\n\t\t}\n\t}\n\n\tif numTargets > 1 {\n\t\treturn routeTargetValidationError\n\t}\n\n\t\/\/ Formulate ReplaceRouteInput based on the target type\n\tswitch setTarget {\n\tcase \"gateway_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tGatewayId: aws.String(d.Get(\"gateway_id\").(string)),\n\t\t}\n\tcase \"nat_gateway_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNatGatewayId: aws.String(d.Get(\"nat_gateway_id\").(string)),\n\t\t}\n\tcase \"instance_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tInstanceId: aws.String(d.Get(\"instance_id\").(string)),\n\t\t\t\/\/NOOP: Ensure we don't blow away network interface id that is set after instance is launched\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"network_interface_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tNetworkInterfaceId: aws.String(d.Get(\"network_interface_id\").(string)),\n\t\t}\n\tcase \"vpc_peering_connection_id\":\n\t\treplaceOpts = &ec2.ReplaceRouteInput{\n\t\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t\t\tVpcPeeringConnectionId: aws.String(d.Get(\"vpc_peering_connection_id\").(string)),\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error: invalid target type specified.\")\n\t}\n\tlog.Printf(\"[DEBUG] Route replace config: %s\", replaceOpts)\n\n\t\/\/ Replace the route\n\t_, err := conn.ReplaceRoute(replaceOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsRouteDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).ec2conn\n\n\tdeleteOpts := &ec2.DeleteRouteInput{\n\t\tRouteTableId: aws.String(d.Get(\"route_table_id\").(string)),\n\t\tDestinationCidrBlock: aws.String(d.Get(\"destination_cidr_block\").(string)),\n\t}\n\tlog.Printf(\"[DEBUG] Route delete opts: %s\", deleteOpts)\n\n\tvar err error\n\terr = resource.Retry(5*time.Minute, func() *resource.RetryError {\n\t\tlog.Printf(\"[DEBUG] Trying to delete route with opts %s\", deleteOpts)\n\t\tresp, err := conn.DeleteRoute(deleteOpts)\n\t\tlog.Printf(\"[DEBUG] Route delete result: %s\", resp)\n\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tec2err, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\tif ec2err.Code() == \"InvalidParameterException\" {\n\t\t\tlog.Printf(\"[DEBUG] Trying to delete route again: %q\",\n\t\t\t\tec2err.Message())\n\t\t\treturn resource.RetryableError(err)\n\t\t}\n\n\t\treturn resource.NonRetryableError(err)\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceAwsRouteExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tconn := meta.(*AWSClient).ec2conn\n\trouteTableId := d.Get(\"route_table_id\").(string)\n\n\tfindOpts := &ec2.DescribeRouteTablesInput{\n\t\tRouteTableIds: []*string{&routeTableId},\n\t}\n\n\tres, err := conn.DescribeRouteTables(findOpts)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Error while checking if route exists: %s\", err)\n\t}\n\n\tif len(res.RouteTables) < 1 || res.RouteTables[0] == nil {\n\t\tlog.Printf(\"[WARN] Route table %s is gone, so route does not exist.\",\n\t\t\trouteTableId)\n\t\treturn false, nil\n\t}\n\n\tcidr := d.Get(\"destination_cidr_block\").(string)\n\tfor _, route := range (*res.RouteTables[0]).Routes {\n\t\tif route.DestinationCidrBlock != nil && *route.DestinationCidrBlock == cidr {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\n\/\/ Create an ID for a route\nfunc routeIDHash(d *schema.ResourceData, r *ec2.Route) string {\n\treturn fmt.Sprintf(\"r-%s%d\", d.Get(\"route_table_id\").(string), hashcode.String(*r.DestinationCidrBlock))\n}\n\n\/\/ Helper: retrieve a route\nfunc findResourceRoute(conn *ec2.EC2, rtbid string, cidr string) (*ec2.Route, error) {\n\trouteTableID := rtbid\n\n\tfindOpts := &ec2.DescribeRouteTablesInput{\n\t\tRouteTableIds: []*string{&routeTableID},\n\t}\n\n\tresp, err := conn.DescribeRouteTables(findOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.RouteTables) < 1 || resp.RouteTables[0] == nil {\n\t\treturn nil, fmt.Errorf(\"Route table %s is gone, so route does not exist.\",\n\t\t\trouteTableID)\n\t}\n\n\tfor _, route := range (*resp.RouteTables[0]).Routes {\n\t\tif *route.DestinationCidrBlock == cidr {\n\t\t\treturn route, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(`\nerror finding matching route for Route table (%s) and destination CIDR block (%s)`,\n\t\trtbid, cidr)\n}\n<|endoftext|>"} {"text":"package sakuracloud\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/yamamoto-febc\/libsacloud\/api\"\n\t\"testing\"\n)\n\nfunc TestAccSakuraCloudDNSDataSource_Basic(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tPreventPostDestroyRefresh: true,\n\t\tCheckDestroy: testAccCheckSakuraCloudDNSDataSourceDestroy,\n\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSBase,\n\t\t\t\tCheck: testAccCheckSakuraCloudDNSDataSourceID(\"sakuracloud_dns.foobar\"),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceID(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"zone\", \"test-terraform-sakuracloud.com\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"description\", \"description_test\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.#\", \"3\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.0\", \"tag1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.1\", \"tag2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.2\", \"tag3\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_With_Tag,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceID(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_NotExists,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceNotExists(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_With_NotExists_Tag,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceNotExists(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceID(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Can't find DNS data source: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"DNS data source ID not set\")\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceNotExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\t_, ok := s.RootModule().Resources[n]\n\t\tif ok {\n\t\t\treturn fmt.Errorf(\"Found DNS data source: %s\", n)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceDestroy(s *terraform.State) error {\n\tclient := testAccProvider.Meta().(*api.Client)\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"sakuracloud_dns\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := client.DNS.Read(rs.Primary.ID)\n\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"DNS still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nvar testAccCheckSakuraCloudDataSourceDNSBase = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Zone\"\n\tvalues = [\"name_test\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_With_Tag = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Tags\"\n\tvalues = [\"tag1\",\"tag3\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_With_NotExists_Tag = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Tags\"\n\tvalues = [\"tag1-xxxxxxx\",\"tag3-xxxxxxxx\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_NotExists = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Zone\"\n\tvalues = [\"xxxxxxxxxxxxxxxxxx\"]\n }\n}`\nFix DNS testpackage sakuracloud\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/yamamoto-febc\/libsacloud\/api\"\n\t\"testing\"\n)\n\nfunc TestAccSakuraCloudDNSDataSource_Basic(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tPreventPostDestroyRefresh: true,\n\t\tCheckDestroy: testAccCheckSakuraCloudDNSDataSourceDestroy,\n\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSBase,\n\t\t\t\tCheck: testAccCheckSakuraCloudDNSDataSourceID(\"sakuracloud_dns.foobar\"),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceID(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"zone\", \"test-terraform-sakuracloud.com\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"description\", \"description_test\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.#\", \"3\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.0\", \"tag1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.1\", \"tag2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\"data.sakuracloud_dns.foobar\", \"tags.2\", \"tag3\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_With_Tag,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceID(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_NotExists,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceNotExists(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tDestroy: true,\n\t\t\t\tConfig: testAccCheckSakuraCloudDataSourceDNSConfig_With_NotExists_Tag,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckSakuraCloudDNSDataSourceNotExists(\"data.sakuracloud_dns.foobar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceID(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Can't find DNS data source: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"DNS data source ID not set\")\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceNotExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\t_, ok := s.RootModule().Resources[n]\n\t\tif ok {\n\t\t\treturn fmt.Errorf(\"Found DNS data source: %s\", n)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSakuraCloudDNSDataSourceDestroy(s *terraform.State) error {\n\tclient := testAccProvider.Meta().(*api.Client)\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"sakuracloud_dns\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := client.DNS.Read(rs.Primary.ID)\n\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"DNS still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nvar testAccCheckSakuraCloudDataSourceDNSBase = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Zone\"\n\tvalues = [\"test-terraform-sakuracloud.com\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_With_Tag = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Tags\"\n\tvalues = [\"tag1\",\"tag3\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_With_NotExists_Tag = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Tags\"\n\tvalues = [\"tag1-xxxxxxx\",\"tag3-xxxxxxxx\"]\n }\n}`\n\nvar testAccCheckSakuraCloudDataSourceDNSConfig_NotExists = `\nresource \"sakuracloud_dns\" \"foobar\" {\n zone = \"test-terraform-sakuracloud.com\"\n description = \"description_test\"\n tags = [\"tag1\",\"tag2\",\"tag3\"]\n}\ndata \"sakuracloud_dns\" \"foobar\" {\n filter = {\n\tname = \"Zone\"\n\tvalues = [\"xxxxxxxxxxxxxxxxxx\"]\n }\n}`\n<|endoftext|>"} {"text":"package builds\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n\n\tg \"github.com\/onsi\/ginkgo\"\n\to \"github.com\/onsi\/gomega\"\n\n\tbuildapi \"github.com\/openshift\/origin\/pkg\/build\/api\"\n\texutil \"github.com\/openshift\/origin\/test\/extended\/util\"\n)\n\nvar _ = g.Describe(\"builds: parallel: oc start-build\", func() {\n\tdefer g.GinkgoRecover()\n\tvar (\n\t\tbuildFixture = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build.json\")\n\t\texampleDockerfile = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build-app\", \"Dockerfile\")\n\t\texampleBuild = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build-app\")\n\t\toc = exutil.NewCLI(\"cli-start-build\", exutil.KubeConfigPath())\n\t)\n\n\tg.JustBeforeEach(func() {\n\t\tg.By(\"waiting for builder service account\")\n\t\terr := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace()))\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\toc.Run(\"create\").Args(\"-f\", buildFixture).Execute()\n\t})\n\n\tg.Describe(\"oc start-build --wait\", func() {\n\t\tg.It(\"should start a build and wait for the build to complete\", func() {\n\t\t\tg.By(\"starting the build with --wait flag\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--wait\").Output()\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(out)\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should start a build and wait for the build to fail\", func() {\n\t\t\tg.By(\"starting the build with --wait flag but wrong --commit\")\n\t\t\tout, err := oc.Run(\"start-build\").\n\t\t\t\tArgs(\"sample-build\", \"--wait\", \"--commit\", \"fffffff\").\n\t\t\t\tOutput()\n\t\t\to.Expect(err).To(o.HaveOccurred())\n\t\t\to.Expect(out).Should(o.ContainSubstring(`status is \"Failed\"`))\n\t\t})\n\t})\n\n\tg.Describe(\"binary builds\", func() {\n\t\tg.It(\"should accept --from-file as input\", func() {\n\t\t\tg.By(\"starting the build with a Dockerfile\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-file=%s\", exampleDockerfile)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading file\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Successfully built\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should accept --from-dir as input\", func() {\n\t\t\tg.By(\"starting the build with a directory\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-dir=%s\", exampleBuild)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading directory\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Successfully built\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should accept --from-repo as input\", func() {\n\t\t\tg.By(\"starting the build with a Git repository\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-repo=%s\", exampleBuild)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading Git repository\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Successfully built\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\t})\n\n\tg.Describe(\"cancelling build started by oc start-build --wait\", func() {\n\t\tg.It(\"should start a build and wait for the build to cancel\", func() {\n\t\t\tg.By(\"starting the build with --wait flag\")\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer g.GinkgoRecover()\n\t\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--wait\").Output()\n\t\t\t\tdefer wg.Done()\n\t\t\t\to.Expect(err).To(o.HaveOccurred())\n\t\t\t\to.Expect(out).Should(o.ContainSubstring(`status is \"Cancelled\"`))\n\t\t\t}()\n\n\t\t\tg.By(\"getting the build name\")\n\t\t\tvar buildName string\n\t\t\twait.Poll(time.Duration(100*time.Millisecond), time.Duration(60*time.Second), func() (bool, error) {\n\t\t\t\tout, err := oc.Run(\"get\").\n\t\t\t\t\tArgs(\"build\", \"--template\", \"{{ (index .items 0).metadata.name }}\").Output()\n\t\t\t\t\/\/ Give it second chance in case the build resource was not created yet\n\t\t\t\tif err != nil || len(out) == 0 {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tbuildName = out\n\t\t\t\treturn true, nil\n\t\t\t})\n\n\t\t\to.Expect(buildName).ToNot(o.BeEmpty())\n\n\t\t\tg.By(fmt.Sprintf(\"cancelling the build %q\", buildName))\n\t\t\terr := oc.Run(\"cancel-build\").Args(buildName).Execute()\n\t\t\to.Expect(err).ToNot(o.HaveOccurred())\n\t\t\twg.Wait()\n\t\t})\n\n\t})\n\n})\nFix extended tests for --from-* binarypackage builds\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n\n\tg \"github.com\/onsi\/ginkgo\"\n\to \"github.com\/onsi\/gomega\"\n\n\tbuildapi \"github.com\/openshift\/origin\/pkg\/build\/api\"\n\texutil \"github.com\/openshift\/origin\/test\/extended\/util\"\n)\n\nvar _ = g.Describe(\"builds: parallel: oc start-build\", func() {\n\tdefer g.GinkgoRecover()\n\tvar (\n\t\tbuildFixture = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build.json\")\n\t\texampleGemfile = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build-app\", \"Gemfile\")\n\t\texampleBuild = exutil.FixturePath(\"..\", \"extended\", \"fixtures\", \"test-build-app\")\n\t\toc = exutil.NewCLI(\"cli-start-build\", exutil.KubeConfigPath())\n\t)\n\n\tg.JustBeforeEach(func() {\n\t\tg.By(\"waiting for builder service account\")\n\t\terr := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace()))\n\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\toc.Run(\"create\").Args(\"-f\", buildFixture).Execute()\n\t})\n\n\tg.Describe(\"oc start-build --wait\", func() {\n\t\tg.It(\"should start a build and wait for the build to complete\", func() {\n\t\t\tg.By(\"starting the build with --wait flag\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--wait\").Output()\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(out)\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should start a build and wait for the build to fail\", func() {\n\t\t\tg.By(\"starting the build with --wait flag but wrong --commit\")\n\t\t\tout, err := oc.Run(\"start-build\").\n\t\t\t\tArgs(\"sample-build\", \"--wait\", \"--commit\", \"fffffff\").\n\t\t\t\tOutput()\n\t\t\to.Expect(err).To(o.HaveOccurred())\n\t\t\to.Expect(out).Should(o.ContainSubstring(`status is \"Failed\"`))\n\t\t})\n\t})\n\n\tg.Describe(\"binary builds\", func() {\n\t\tg.It(\"should accept --from-file as input\", func() {\n\t\t\tg.By(\"starting the build with a Dockerfile\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-file=%s\", exampleGemfile)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading file\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Your bundle is complete\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should accept --from-dir as input\", func() {\n\t\t\tg.By(\"starting the build with a directory\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-dir=%s\", exampleBuild)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading directory\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Your bundle is complete\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\n\t\tg.It(\"should accept --from-repo as input\", func() {\n\t\t\tg.By(\"starting the build with a Git repository\")\n\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--follow\", \"--wait\", fmt.Sprintf(\"--from-repo=%s\", exampleBuild)).Output()\n\t\t\tg.By(fmt.Sprintf(\"verifying the build %q status\", out))\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Uploading Git repository\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"as binary input for the build ...\"))\n\t\t\to.Expect(out).To(o.ContainSubstring(\"Your bundle is complete\"))\n\n\t\t\tbuild, err := oc.REST().Builds(oc.Namespace()).Get(\"sample-build-1\")\n\t\t\to.Expect(err).NotTo(o.HaveOccurred())\n\t\t\to.Expect(build.Status.Phase).Should(o.BeEquivalentTo(buildapi.BuildPhaseComplete))\n\t\t})\n\t})\n\n\tg.Describe(\"cancelling build started by oc start-build --wait\", func() {\n\t\tg.It(\"should start a build and wait for the build to cancel\", func() {\n\t\t\tg.By(\"starting the build with --wait flag\")\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer g.GinkgoRecover()\n\t\t\t\tout, err := oc.Run(\"start-build\").Args(\"sample-build\", \"--wait\").Output()\n\t\t\t\tdefer wg.Done()\n\t\t\t\to.Expect(err).To(o.HaveOccurred())\n\t\t\t\to.Expect(out).Should(o.ContainSubstring(`status is \"Cancelled\"`))\n\t\t\t}()\n\n\t\t\tg.By(\"getting the build name\")\n\t\t\tvar buildName string\n\t\t\twait.Poll(time.Duration(100*time.Millisecond), time.Duration(60*time.Second), func() (bool, error) {\n\t\t\t\tout, err := oc.Run(\"get\").\n\t\t\t\t\tArgs(\"build\", \"--template\", \"{{ (index .items 0).metadata.name }}\").Output()\n\t\t\t\t\/\/ Give it second chance in case the build resource was not created yet\n\t\t\t\tif err != nil || len(out) == 0 {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tbuildName = out\n\t\t\t\treturn true, nil\n\t\t\t})\n\n\t\t\to.Expect(buildName).ToNot(o.BeEmpty())\n\n\t\t\tg.By(fmt.Sprintf(\"cancelling the build %q\", buildName))\n\t\t\terr := oc.Run(\"cancel-build\").Args(buildName).Execute()\n\t\t\to.Expect(err).ToNot(o.HaveOccurred())\n\t\t\twg.Wait()\n\t\t})\n\n\t})\n\n})\n<|endoftext|>"} {"text":"package gotoc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n)\n\nfunc (gtc *GTC) FuncDecl(d *ast.FuncDecl, il int) (cdds []*CDD) {\n\tf := gtc.object(d.Name).(*types.Func)\n\n\tcdd := gtc.newCDD(f, FuncDecl, il)\n\tw := new(bytes.Buffer)\n\tfname := cdd.NameStr(f, true)\n\n\tsig := f.Type().(*types.Signature)\n\tres, params := cdd.signature(sig, true)\n\n\tw.WriteString(res.typ)\n\tw.WriteByte(' ')\n\tw.WriteString(dimFuncPtr(fname+params, res.dim))\n\n\tcdds = append(cdds, res.acds...)\n\tcdds = append(cdds, cdd)\n\n\tcdd.init = (f.Name() == \"init\" && sig.Recv() == nil && !cdd.gtc.isLocal(f))\n\n\tif !cdd.init {\n\t\tcdd.copyDecl(w, \";\\n\")\n\t}\n\n\tif d.Body == nil {\n\t\treturn\n\t}\n\n\tcdd.body = true\n\n\tw.WriteByte(' ')\n\n\tall := true\n\tif res.hasNames {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"{\\n\")\n\t\tcdd.il++\n\t\tfor i, v := range res.fields {\n\t\t\tname := res.names[i]\n\t\t\tif name == \"_\" && len(res.fields) > 1 {\n\t\t\t\tall = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcdd.indent(w)\n\t\t\tdim, acds := cdd.Type(w, v.Type())\n\t\t\tcdds = append(cdds, acds...)\n\t\t\tw.WriteByte(' ')\n\t\t\tw.WriteString(dimFuncPtr(name, dim))\n\t\t\tw.WriteString(\" = {0};\\n\")\n\t\t}\n\t\tcdd.indent(w)\n\t}\n\n\tend, acds := cdd.BlockStmt(w, d.Body, res.typ, sig.Results())\n\tcdds = append(cdds, acds...)\n\tw.WriteByte('\\n')\n\n\tif res.hasNames {\n\t\tif end {\n\t\t\tcdd.il--\n\t\t\tcdd.indent(w)\n\t\t\tw.WriteString(\"end:\\n\")\n\t\t\tcdd.il++\n\n\t\t\tcdd.indent(w)\n\t\t\tw.WriteString(\"return \")\n\t\t\tif len(res.fields) == 1 {\n\t\t\t\tw.WriteString(res.names[0])\n\t\t\t} else {\n\t\t\t\tw.WriteString(\"(\" + res.typ + \"){\")\n\t\t\t\tcomma := false\n\t\t\t\tfor i, name := range res.names {\n\t\t\t\t\tif name == \"_\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif comma {\n\t\t\t\t\t\tw.WriteString(\", \")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcomma = true\n\t\t\t\t\t}\n\t\t\t\t\tif !all {\n\t\t\t\t\t\tw.WriteString(\"._\" + strconv.Itoa(i) + \"=\")\n\t\t\t\t\t}\n\t\t\t\t\tw.WriteString(name)\n\t\t\t\t}\n\t\t\t\tw.WriteByte('}')\n\t\t\t}\n\t\t\tw.WriteString(\";\\n\")\n\t\t}\n\t\tcdd.il--\n\t\tw.WriteString(\"}\\n\")\n\t}\n\tcdd.copyDef(w)\n\n\tif cdd.init {\n\t\tcdd.Init = []byte(\"\\t\" + fname + \"();\\n\")\n\t}\n\treturn\n}\n\nfunc (gtc *GTC) GenDecl(d *ast.GenDecl, il int) (cdds []*CDD) {\n\tw := new(bytes.Buffer)\n\n\tswitch d.Tok {\n\tcase token.IMPORT:\n\t\t\/\/ Only for unrefferenced imports\n\t\tfor _, s := range d.Specs {\n\t\t\tis := s.(*ast.ImportSpec)\n\t\t\tif is.Name != nil && is.Name.Name == \"_\" {\n\t\t\t\tcdd := gtc.newCDD(gtc.object(is.Name), ImportDecl, il)\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t}\n\t\t}\n\n\tcase token.CONST:\n\t\tfor _, s := range d.Specs {\n\t\t\tvs := s.(*ast.ValueSpec)\n\n\t\t\tfor _, n := range vs.Names {\n\t\t\t\tc := gtc.object(n).(*types.Const)\n\n\t\t\t\t\/\/ All constants in expressions are evaluated so\n\t\t\t\t\/\/ only exported constants need be translated to C\n\t\t\t\tif !c.Exported() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcdd := gtc.newCDD(c, ConstDecl, il)\n\n\t\t\t\tw.WriteString(\"#define \")\n\t\t\t\tcdd.Name(w, c, true)\n\t\t\t\tw.WriteByte(' ')\n\t\t\t\tcdd.Value(w, c.Val(), c.Type())\n\t\t\t\tcdd.copyDecl(w, \"\\n\")\n\t\t\t\tw.Reset()\n\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t}\n\t\t}\n\n\tcase token.VAR:\n\t\tfor _, s := range d.Specs {\n\t\t\tvs := s.(*ast.ValueSpec)\n\t\t\tvals := vs.Values\n\n\t\t\tfor i, n := range vs.Names {\n\t\t\t\tv := gtc.object(n).(*types.Var)\n\t\t\t\tcdd := gtc.newCDD(v, VarDecl, il)\n\t\t\t\tname := cdd.NameStr(v, true)\n\n\t\t\t\tvar val ast.Expr\n\t\t\t\tif i < len(vals) {\n\t\t\t\t\tval = vals[i]\n\t\t\t\t}\n\t\t\t\tif i > 0 {\n\t\t\t\t\tcdd.indent(w)\n\t\t\t\t}\n\t\t\t\tacds := cdd.varDecl(w, v.Type(), cdd.gtc.isGlobal(v), name, val)\n\n\t\t\t\tw.Reset()\n\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t\tcdds = append(cdds, acds...)\n\t\t\t}\n\t\t}\n\n\tcase token.TYPE:\n\t\tfor i, s := range d.Specs {\n\t\t\tts := s.(*ast.TypeSpec)\n\t\t\tto := gtc.object(ts.Name)\n\t\t\ttt := gtc.exprType(ts.Type)\n\t\t\tcdd := gtc.newCDD(to, TypeDecl, il)\n\t\t\tname := cdd.NameStr(to, true)\n\n\t\t\tif i > 0 {\n\t\t\t\tcdd.indent(w)\n\t\t\t}\n\n\t\t\tswitch typ := tt.(type) {\n\t\t\tcase *types.Struct:\n\t\t\t\tcdd.structDecl(w, name, typ)\n\n\t\t\tdefault:\n\t\t\t\tw.WriteString(\"typedef \")\n\t\t\t\tdim, acds := cdd.Type(w, typ)\n\t\t\t\tcdds = append(cdds, acds...)\n\t\t\t\tw.WriteByte(' ')\n\t\t\t\tw.WriteString(dimFuncPtr(name, dim))\n\t\t\t\tcdd.copyDecl(w, \";\\n\")\n\t\t\t}\n\t\t\tw.Reset()\n\n\t\t\tcdds = append(cdds, cdd)\n\t\t}\n\n\tdefault:\n\t\t\/\/ Return fake CDD for unknown declaration\n\t\tcdds = []*CDD{{\n\t\t\tDecl: []byte(fmt.Sprintf(\"@%v (%T)@\\n\", d.Tok, d)),\n\t\t}}\n\t}\n\treturn\n}\n\nfunc (cdd *CDD) varDecl(w *bytes.Buffer, typ types.Type, global bool, name string, val ast.Expr) (acds []*CDD) {\n\n\tdim, acds := cdd.Type(w, typ)\n\tw.WriteByte(' ')\n\tw.WriteString(dimFuncPtr(name, dim))\n\n\tconstInit := true \/\/ true if C declaration can init value\n\n\tif global {\n\t\tcdd.copyDecl(w, \";\\n\") \/\/ Global variables may need declaration\n\t\tif val != nil {\n\t\t\tconstInit = cdd.exprValue(val) != nil\n\t\t}\n\t}\n\tif constInit {\n\t\tw.WriteString(\" = \")\n\t\tif val != nil {\n\t\t\tcdd.Expr(w, val, typ)\n\t\t} else {\n\t\t\tw.WriteString(\"{0}\")\n\t\t}\n\t}\n\tw.WriteString(\";\\n\")\n\tcdd.copyDef(w)\n\n\tif !constInit {\n\t\t\/\/ Runtime initialisation\n\t\tw.Reset()\n\n\t\tassign := false\n\n\t\tswitch t := typ.(type) {\n\t\tcase *types.Slice:\n\t\t\tswitch vt := val.(type) {\n\t\t\tcase *ast.CompositeLit:\n\t\t\t\taname := \"array\" + cdd.gtc.uniqueId()\n\t\t\t\tat := types.NewArray(t.Elem(), int64(len(vt.Elts)))\n\t\t\t\to := types.NewVar(vt.Lbrace, cdd.gtc.pkg, aname, at)\n\t\t\t\tcdd.gtc.pkg.Scope().Insert(o)\n\t\t\t\tacd := cdd.gtc.newCDD(o, VarDecl, cdd.il)\n\t\t\t\tav := *vt\n\t\t\t\tcdd.gtc.ti.Types[&av] = types.TypeAndValue{Type: at} \/\/ BUG: thread-unsafe\n\t\t\t\tn := w.Len()\n\t\t\t\tacd.varDecl(w, o.Type(), cdd.gtc.isGlobal(o), aname, &av)\n\t\t\t\tw.Truncate(n)\n\t\t\t\tacds = append(acds, acd)\n\n\t\t\t\tw.WriteByte('\\t')\n\t\t\t\tw.WriteString(name)\n\t\t\t\tw.WriteString(\" = ASLICE(\")\n\t\t\t\tw.WriteString(aname)\n\t\t\t\tw.WriteString(\");\\n\")\n\n\t\t\tdefault:\n\t\t\t\tassign = true\n\t\t\t}\n\n\t\tcase *types.Array:\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(\"ACPY(\")\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\", \")\n\n\t\t\tswitch val.(type) {\n\t\t\tcase *ast.CompositeLit:\n\t\t\t\tw.WriteString(\"((\")\n\t\t\t\tdim, _ := cdd.Type(w, t.Elem())\n\t\t\t\tdim = append([]string{\"[]\"}, dim...)\n\t\t\t\tw.WriteString(\"(\" + dimFuncPtr(\"\", dim) + \"))\")\n\t\t\t\tcdd.Expr(w, val, typ)\n\n\t\t\tdefault:\n\t\t\t\tcdd.Expr(w, val, typ)\n\t\t\t}\n\n\t\t\tw.WriteString(\"));\\n\")\n\n\t\tcase *types.Pointer:\n\t\t\tu, ok := val.(*ast.UnaryExpr)\n\t\t\tif !ok {\n\t\t\t\tassign = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc, ok := u.X.(*ast.CompositeLit)\n\t\t\tif !ok {\n\t\t\t\tassign = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcname := \"cl\" + cdd.gtc.uniqueId()\n\t\t\tct := cdd.exprType(c)\n\t\t\to := types.NewVar(c.Lbrace, cdd.gtc.pkg, cname, ct)\n\t\t\tcdd.gtc.pkg.Scope().Insert(o)\n\t\t\tacd := cdd.gtc.newCDD(o, VarDecl, cdd.il)\n\t\t\tn := w.Len()\n\t\t\tacd.varDecl(w, o.Type(), cdd.gtc.isGlobal(o), cname, c)\n\t\t\tw.Truncate(n)\n\t\t\tacds = append(acds, acd)\n\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\" = &\")\n\t\t\tw.WriteString(cname)\n\t\t\tw.WriteString(\";\\n\")\n\n\t\tdefault:\n\t\t\tassign = true\n\t\t}\n\n\t\tif assign {\n\t\t\t\/\/ Ordinary assignment gos to the init() function\n\t\t\tcdd.init = true\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\" = \")\n\t\t\tcdd.Expr(w, val, typ)\n\t\t\tw.WriteString(\";\\n\")\n\t\t}\n\t\tcdd.copyInit(w)\n\t}\n\treturn\n}\n\nfunc (cdd *CDD) structDecl(w *bytes.Buffer, name string, typ *types.Struct) {\n\tn := w.Len()\n\n\tw.WriteString(\"struct \")\n\tw.WriteString(name)\n\tw.WriteString(\"_struct;\\n\")\n\tcdd.indent(w)\n\tw.WriteString(\"typedef struct \")\n\tw.WriteString(name)\n\tw.WriteString(\"_struct \")\n\tw.WriteString(name)\n\n\tcdd.copyDecl(w, \";\\n\")\n\tw.Truncate(n)\n\n\ttuple := strings.Contains(name, \"$$\")\n\n\tif tuple {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#ifndef \" + name + \"$\\n\")\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#define \" + name + \"$\\n\")\n\t}\n\tcdd.indent(w)\n\tw.WriteString(\"struct \")\n\tw.WriteString(name)\n\tw.WriteByte('_')\n\tcdd.Type(w, typ)\n\tw.WriteString(\";\\n\")\n\tif tuple {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#endif\\n\")\n\t}\n\n\tcdd.copyDef(w)\n\tw.Truncate(n)\n}\n\nfunc (cc *GTC) Decl(decl ast.Decl, il int) []*CDD {\n\tswitch d := decl.(type) {\n\tcase *ast.FuncDecl:\n\t\treturn cc.FuncDecl(d, il)\n\n\tcase *ast.GenDecl:\n\t\treturn cc.GenDecl(d, il)\n\t}\n\n\tpanic(fmt.Sprint(\"Unknown declaration: \", decl))\n}\nSupprot for empty structs and arrayspackage gotoc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n)\n\nfunc (gtc *GTC) FuncDecl(d *ast.FuncDecl, il int) (cdds []*CDD) {\n\tf := gtc.object(d.Name).(*types.Func)\n\n\tcdd := gtc.newCDD(f, FuncDecl, il)\n\tw := new(bytes.Buffer)\n\tfname := cdd.NameStr(f, true)\n\n\tsig := f.Type().(*types.Signature)\n\tres, params := cdd.signature(sig, true)\n\n\tw.WriteString(res.typ)\n\tw.WriteByte(' ')\n\tw.WriteString(dimFuncPtr(fname+params, res.dim))\n\n\tcdds = append(cdds, res.acds...)\n\tcdds = append(cdds, cdd)\n\n\tcdd.init = (f.Name() == \"init\" && sig.Recv() == nil && !cdd.gtc.isLocal(f))\n\n\tif !cdd.init {\n\t\tcdd.copyDecl(w, \";\\n\")\n\t}\n\n\tif d.Body == nil {\n\t\treturn\n\t}\n\n\tcdd.body = true\n\n\tw.WriteByte(' ')\n\n\tall := true\n\tif res.hasNames {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"{\\n\")\n\t\tcdd.il++\n\t\tfor i, v := range res.fields {\n\t\t\tname := res.names[i]\n\t\t\tif name == \"_\" && len(res.fields) > 1 {\n\t\t\t\tall = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcdd.indent(w)\n\t\t\tdim, acds := cdd.Type(w, v.Type())\n\t\t\tcdds = append(cdds, acds...)\n\t\t\tw.WriteByte(' ')\n\t\t\tw.WriteString(dimFuncPtr(name, dim))\n\t\t\tw.WriteString(\" = {0};\\n\")\n\t\t}\n\t\tcdd.indent(w)\n\t}\n\n\tend, acds := cdd.BlockStmt(w, d.Body, res.typ, sig.Results())\n\tcdds = append(cdds, acds...)\n\tw.WriteByte('\\n')\n\n\tif res.hasNames {\n\t\tif end {\n\t\t\tcdd.il--\n\t\t\tcdd.indent(w)\n\t\t\tw.WriteString(\"end:\\n\")\n\t\t\tcdd.il++\n\n\t\t\tcdd.indent(w)\n\t\t\tw.WriteString(\"return \")\n\t\t\tif len(res.fields) == 1 {\n\t\t\t\tw.WriteString(res.names[0])\n\t\t\t} else {\n\t\t\t\tw.WriteString(\"(\" + res.typ + \"){\")\n\t\t\t\tcomma := false\n\t\t\t\tfor i, name := range res.names {\n\t\t\t\t\tif name == \"_\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif comma {\n\t\t\t\t\t\tw.WriteString(\", \")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcomma = true\n\t\t\t\t\t}\n\t\t\t\t\tif !all {\n\t\t\t\t\t\tw.WriteString(\"._\" + strconv.Itoa(i) + \"=\")\n\t\t\t\t\t}\n\t\t\t\t\tw.WriteString(name)\n\t\t\t\t}\n\t\t\t\tw.WriteByte('}')\n\t\t\t}\n\t\t\tw.WriteString(\";\\n\")\n\t\t}\n\t\tcdd.il--\n\t\tw.WriteString(\"}\\n\")\n\t}\n\tcdd.copyDef(w)\n\n\tif cdd.init {\n\t\tcdd.Init = []byte(\"\\t\" + fname + \"();\\n\")\n\t}\n\treturn\n}\n\nfunc (gtc *GTC) GenDecl(d *ast.GenDecl, il int) (cdds []*CDD) {\n\tw := new(bytes.Buffer)\n\n\tswitch d.Tok {\n\tcase token.IMPORT:\n\t\t\/\/ Only for unrefferenced imports\n\t\tfor _, s := range d.Specs {\n\t\t\tis := s.(*ast.ImportSpec)\n\t\t\tif is.Name != nil && is.Name.Name == \"_\" {\n\t\t\t\tcdd := gtc.newCDD(gtc.object(is.Name), ImportDecl, il)\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t}\n\t\t}\n\n\tcase token.CONST:\n\t\tfor _, s := range d.Specs {\n\t\t\tvs := s.(*ast.ValueSpec)\n\n\t\t\tfor _, n := range vs.Names {\n\t\t\t\tc := gtc.object(n).(*types.Const)\n\n\t\t\t\t\/\/ All constants in expressions are evaluated so\n\t\t\t\t\/\/ only exported constants need be translated to C\n\t\t\t\tif !c.Exported() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcdd := gtc.newCDD(c, ConstDecl, il)\n\n\t\t\t\tw.WriteString(\"#define \")\n\t\t\t\tcdd.Name(w, c, true)\n\t\t\t\tw.WriteByte(' ')\n\t\t\t\tcdd.Value(w, c.Val(), c.Type())\n\t\t\t\tcdd.copyDecl(w, \"\\n\")\n\t\t\t\tw.Reset()\n\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t}\n\t\t}\n\n\tcase token.VAR:\n\t\tfor _, s := range d.Specs {\n\t\t\tvs := s.(*ast.ValueSpec)\n\t\t\tvals := vs.Values\n\n\t\t\tfor i, n := range vs.Names {\n\t\t\t\tv := gtc.object(n).(*types.Var)\n\t\t\t\tcdd := gtc.newCDD(v, VarDecl, il)\n\t\t\t\tname := cdd.NameStr(v, true)\n\n\t\t\t\tvar val ast.Expr\n\t\t\t\tif i < len(vals) {\n\t\t\t\t\tval = vals[i]\n\t\t\t\t}\n\t\t\t\tif i > 0 {\n\t\t\t\t\tcdd.indent(w)\n\t\t\t\t}\n\t\t\t\tacds := cdd.varDecl(w, v.Type(), cdd.gtc.isGlobal(v), name, val)\n\n\t\t\t\tw.Reset()\n\n\t\t\t\tcdds = append(cdds, cdd)\n\t\t\t\tcdds = append(cdds, acds...)\n\t\t\t}\n\t\t}\n\n\tcase token.TYPE:\n\t\tfor i, s := range d.Specs {\n\t\t\tts := s.(*ast.TypeSpec)\n\t\t\tto := gtc.object(ts.Name)\n\t\t\ttt := gtc.exprType(ts.Type)\n\t\t\tcdd := gtc.newCDD(to, TypeDecl, il)\n\t\t\tname := cdd.NameStr(to, true)\n\n\t\t\tif i > 0 {\n\t\t\t\tcdd.indent(w)\n\t\t\t}\n\n\t\t\tswitch typ := tt.(type) {\n\t\t\tcase *types.Struct:\n\t\t\t\tcdd.structDecl(w, name, typ)\n\n\t\t\tdefault:\n\t\t\t\tw.WriteString(\"typedef \")\n\t\t\t\tdim, acds := cdd.Type(w, typ)\n\t\t\t\tcdds = append(cdds, acds...)\n\t\t\t\tw.WriteByte(' ')\n\t\t\t\tw.WriteString(dimFuncPtr(name, dim))\n\t\t\t\tcdd.copyDecl(w, \";\\n\")\n\t\t\t}\n\t\t\tw.Reset()\n\n\t\t\tcdds = append(cdds, cdd)\n\t\t}\n\n\tdefault:\n\t\t\/\/ Return fake CDD for unknown declaration\n\t\tcdds = []*CDD{{\n\t\t\tDecl: []byte(fmt.Sprintf(\"@%v (%T)@\\n\", d.Tok, d)),\n\t\t}}\n\t}\n\treturn\n}\n\nfunc (cdd *CDD) varDecl(w *bytes.Buffer, typ types.Type, global bool, name string, val ast.Expr) (acds []*CDD) {\n\n\tdim, acds := cdd.Type(w, typ)\n\tw.WriteByte(' ')\n\tw.WriteString(dimFuncPtr(name, dim))\n\n\tif t, ok := typ.(*types.Named); ok {\n\t\ttyp = t.Underlying()\n\t}\n\n\tconstInit := true \/\/ true if C declaration can init value\n\n\tif global {\n\t\tcdd.copyDecl(w, \";\\n\") \/\/ Global variables may need declaration\n\t\tif val != nil {\n\t\t\tconstInit = cdd.exprValue(val) != nil\n\t\t}\n\t}\n\n\tif constInit {\n\t\tif val != nil {\n\t\t\tw.WriteString(\" = \")\n\t\t\tcdd.Expr(w, val, typ)\n\t\t} else {\n\t\t\tif t, ok := typ.(*types.Struct); ok && t.NumFields() == 0 {\n\t\t\t} else if t, ok := typ.(*types.Array); ok && t.Len() == 0 {\n\t\t\t} else {\n\t\t\t\tw.WriteString(\" = {0}\")\n\t\t\t}\n\t\t}\n\t}\n\tw.WriteString(\";\\n\")\n\tcdd.copyDef(w)\n\n\tif !constInit {\n\t\t\/\/ Runtime initialisation\n\t\tw.Reset()\n\n\t\tassign := false\n\n\t\tswitch t := typ.(type) {\n\t\tcase *types.Slice:\n\t\t\tswitch vt := val.(type) {\n\t\t\tcase *ast.CompositeLit:\n\t\t\t\taname := \"array\" + cdd.gtc.uniqueId()\n\t\t\t\tat := types.NewArray(t.Elem(), int64(len(vt.Elts)))\n\t\t\t\to := types.NewVar(vt.Lbrace, cdd.gtc.pkg, aname, at)\n\t\t\t\tcdd.gtc.pkg.Scope().Insert(o)\n\t\t\t\tacd := cdd.gtc.newCDD(o, VarDecl, cdd.il)\n\t\t\t\tav := *vt\n\t\t\t\tcdd.gtc.ti.Types[&av] = types.TypeAndValue{Type: at} \/\/ BUG: thread-unsafe\n\t\t\t\tn := w.Len()\n\t\t\t\tacd.varDecl(w, o.Type(), cdd.gtc.isGlobal(o), aname, &av)\n\t\t\t\tw.Truncate(n)\n\t\t\t\tacds = append(acds, acd)\n\n\t\t\t\tw.WriteByte('\\t')\n\t\t\t\tw.WriteString(name)\n\t\t\t\tw.WriteString(\" = ASLICE(\")\n\t\t\t\tw.WriteString(aname)\n\t\t\t\tw.WriteString(\");\\n\")\n\n\t\t\tdefault:\n\t\t\t\tassign = true\n\t\t\t}\n\n\t\tcase *types.Array:\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(\"ACPY(\")\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\", \")\n\n\t\t\tswitch val.(type) {\n\t\t\tcase *ast.CompositeLit:\n\t\t\t\tw.WriteString(\"((\")\n\t\t\t\tdim, _ := cdd.Type(w, t.Elem())\n\t\t\t\tdim = append([]string{\"[]\"}, dim...)\n\t\t\t\tw.WriteString(\"(\" + dimFuncPtr(\"\", dim) + \"))\")\n\t\t\t\tcdd.Expr(w, val, typ)\n\n\t\t\tdefault:\n\t\t\t\tcdd.Expr(w, val, typ)\n\t\t\t}\n\n\t\t\tw.WriteString(\"));\\n\")\n\n\t\tcase *types.Pointer:\n\t\t\tu, ok := val.(*ast.UnaryExpr)\n\t\t\tif !ok {\n\t\t\t\tassign = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc, ok := u.X.(*ast.CompositeLit)\n\t\t\tif !ok {\n\t\t\t\tassign = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcname := \"cl\" + cdd.gtc.uniqueId()\n\t\t\tct := cdd.exprType(c)\n\t\t\to := types.NewVar(c.Lbrace, cdd.gtc.pkg, cname, ct)\n\t\t\tcdd.gtc.pkg.Scope().Insert(o)\n\t\t\tacd := cdd.gtc.newCDD(o, VarDecl, cdd.il)\n\t\t\tn := w.Len()\n\t\t\tacd.varDecl(w, o.Type(), cdd.gtc.isGlobal(o), cname, c)\n\t\t\tw.Truncate(n)\n\t\t\tacds = append(acds, acd)\n\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\" = &\")\n\t\t\tw.WriteString(cname)\n\t\t\tw.WriteString(\";\\n\")\n\n\t\tdefault:\n\t\t\tassign = true\n\t\t}\n\n\t\tif assign {\n\t\t\t\/\/ Ordinary assignment gos to the init() function\n\t\t\tcdd.init = true\n\t\t\tw.WriteByte('\\t')\n\t\t\tw.WriteString(name)\n\t\t\tw.WriteString(\" = \")\n\t\t\tcdd.Expr(w, val, typ)\n\t\t\tw.WriteString(\";\\n\")\n\t\t}\n\t\tcdd.copyInit(w)\n\t}\n\treturn\n}\n\nfunc (cdd *CDD) structDecl(w *bytes.Buffer, name string, typ *types.Struct) {\n\tn := w.Len()\n\n\tw.WriteString(\"struct \")\n\tw.WriteString(name)\n\tw.WriteString(\"_struct;\\n\")\n\tcdd.indent(w)\n\tw.WriteString(\"typedef struct \")\n\tw.WriteString(name)\n\tw.WriteString(\"_struct \")\n\tw.WriteString(name)\n\n\tcdd.copyDecl(w, \";\\n\")\n\tw.Truncate(n)\n\n\ttuple := strings.Contains(name, \"$$\")\n\n\tif tuple {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#ifndef \" + name + \"$\\n\")\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#define \" + name + \"$\\n\")\n\t}\n\tcdd.indent(w)\n\tw.WriteString(\"struct \")\n\tw.WriteString(name)\n\tw.WriteByte('_')\n\tcdd.Type(w, typ)\n\tw.WriteString(\";\\n\")\n\tif tuple {\n\t\tcdd.indent(w)\n\t\tw.WriteString(\"#endif\\n\")\n\t}\n\n\tcdd.copyDef(w)\n\tw.Truncate(n)\n}\n\nfunc (cc *GTC) Decl(decl ast.Decl, il int) []*CDD {\n\tswitch d := decl.(type) {\n\tcase *ast.FuncDecl:\n\t\treturn cc.FuncDecl(d, il)\n\n\tcase *ast.GenDecl:\n\t\treturn cc.GenDecl(d, il)\n\t}\n\n\tpanic(fmt.Sprint(\"Unknown declaration: \", decl))\n}\n<|endoftext|>"} {"text":"package bitband\n\nimport (\n\t\"mmio\"\n\t\"unsafe\"\n)\n\n\/\/c:volatile\ntype Bit struct {\n\ta *mmio.U32\n}\n\nfunc (b Bit) Load() int {\n\treturn int(b.a.Load())\n}\n\nfunc (b Bit) Store(v int) {\n\tb.a.Store(uint32(v))\n}\n\nfunc (b Bit) Set() {\n\tb.Store(1)\n}\n\nfunc (b Bit) Clear() {\n\tb.Store(0)\n}\n\n\/\/ 0x20000000 - 0x200FFFFF: SRAM bit-band region.\n\/\/ 0x22000000 - 0x23FFFFFF: SRAM bit-band alias.\n\/\/\n\/\/ 0x40000000 - 0x400FFFFF: peripheral bit-band region.\n\/\/ 0x42000000 - 0x43FFFFFF: peripheral bit-band alias.\nfunc bitAlias(addr unsafe.Pointer) unsafe.Pointer {\n\ta := uintptr(addr)\n\tbase := a &^ 0xfffff\n\tif base != 0x40000000 && base != 0x20000000 {\n\t\tpanic(\"bitband: not in region\")\n\t}\n\tbase += 0x2000000\n\toffset := a & 0xfffff\n\treturn unsafe.Pointer(base + offset*32)\n}\n\ntype Bits8 struct {\n\ta *[8]mmio.U32\n}\n\nfunc (b Bits8) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias8(r *mmio.U8) Bits8 {\n\treturn Bits8{(*[8]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\n\ntype Bits16 struct {\n\ta *[16]mmio.U32\n}\n\nfunc (b Bits16) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias16(r *mmio.U16) Bits16 {\n\treturn Bits16{(*[16]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\n\ntype Bits32 struct {\n\ta *[32]mmio.U32\n}\n\nfunc (b Bits32) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias32(r *mmio.U32) Bits32 {\n\treturn Bits32{(*[32]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\narch\/cortexm\/bitband: Remove unnecessary volatile pragma.package bitband\n\nimport (\n\t\"mmio\"\n\t\"unsafe\"\n)\n\ntype Bit struct {\n\ta *mmio.U32\n}\n\nfunc (b Bit) Load() int {\n\treturn int(b.a.Load())\n}\n\nfunc (b Bit) Store(v int) {\n\tb.a.Store(uint32(v))\n}\n\nfunc (b Bit) Set() {\n\tb.Store(1)\n}\n\nfunc (b Bit) Clear() {\n\tb.Store(0)\n}\n\n\/\/ 0x20000000 - 0x200FFFFF: SRAM bit-band region.\n\/\/ 0x22000000 - 0x23FFFFFF: SRAM bit-band alias.\n\/\/\n\/\/ 0x40000000 - 0x400FFFFF: peripheral bit-band region.\n\/\/ 0x42000000 - 0x43FFFFFF: peripheral bit-band alias.\nfunc bitAlias(addr unsafe.Pointer) unsafe.Pointer {\n\ta := uintptr(addr)\n\tbase := a &^ 0xfffff\n\tif base != 0x40000000 && base != 0x20000000 {\n\t\tpanic(\"bitband: not in region\")\n\t}\n\tbase += 0x2000000\n\toffset := a & 0xfffff\n\treturn unsafe.Pointer(base + offset*32)\n}\n\ntype Bits8 struct {\n\ta *[8]mmio.U32\n}\n\nfunc (b Bits8) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias8(r *mmio.U8) Bits8 {\n\treturn Bits8{(*[8]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\n\ntype Bits16 struct {\n\ta *[16]mmio.U32\n}\n\nfunc (b Bits16) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias16(r *mmio.U16) Bits16 {\n\treturn Bits16{(*[16]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\n\ntype Bits32 struct {\n\ta *[32]mmio.U32\n}\n\nfunc (b Bits32) Bit(n int) Bit {\n\treturn Bit{&b.a[n]}\n}\n\nfunc Alias32(r *mmio.U32) Bits32 {\n\treturn Bits32{(*[32]mmio.U32)(bitAlias(unsafe.Pointer(r)))}\n}\n<|endoftext|>"} {"text":"package gridt\n\nimport (\n\t\"testing\"\n)\n\nconst (\n\tcheckMark = \"\\u2713\"\n\tballotX = \"\\u2717\"\n\n\tlogMsg = \"\\n%s: %s\"\n\tfatalMsg = logMsg + \"\\nwidths = %v\\nfit = %v\"\n)\n\nfunc end(passed bool, msg string, ws []uint, f bool, t *testing.T) {\n\tif !passed {\n\t\tt.Fatalf(fatalMsg, msg, ballotX, ws, f)\n\t}\n\tt.Logf(logMsg, msg, checkMark)\n}\n\nfunc TestFromBidimensional(t *testing.T) {\n\tvar msg string\n\tvar passed, f bool\n\tvar l uint\n\tvar ws []uint\n\n\tt.Run(\"EmptyList\", func(t *testing.T) {\n\t\tmsg = \"Should return an empty list of widths that fits\"\n\t\tws, l, f = FromBidimensional([]string{}, 10, TopToBottom, \" \")\n\t\tpassed = len(ws) == 0 && l == 0 && f\n\t\tend(passed, msg, ws, f, t)\n\t})\n\n\tt.Run(\"OneItem\", func(t *testing.T) {\n\t\tt.Run(\"SufficientSize\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with one width that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\"}, 20, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 1 && l == 1 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"UnsufficientSize\", func(t *testing.T) {\n\t\t\tmsg = \"Should return an empty list that does not fit\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\"}, 5, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 0 && l == 0 && !f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t})\n\n\tt.Run(\"TwoItems\", func(t *testing.T) {\n\t\tt.Run(\"SufficientSizeForTwoColumns\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with two widths that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 50, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 2 && l == 1 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"SufficientSizeForOneColumn\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with one width that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 15, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 1 && l == 2 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"UnsufficientSizeFor\", func(t *testing.T) {\n\t\t\tmsg = \"Should return an empty list that does not fit\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 5, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 0 && l == 0 && !f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t})\n}\nDetails.package gridt\n\nimport (\n\t\"testing\"\n)\n\nconst (\n\tcheckMark = \"\\u2713\"\n\tballotX = \"\\u2717\"\n\n\tlogMsgf = \"\\n%s: %s\"\n\tfatalMsgf = logMsgf + \"\\nwidths = %v\\nfit = %v\"\n)\n\nfunc end(passed bool, msg string, ws []uint, f bool, t *testing.T) {\n\tif !passed {\n\t\tt.Fatalf(fatalMsgf, msg, ballotX, ws, f)\n\t}\n\tt.Logf(logMsgf, msg, checkMark)\n}\n\nfunc TestFromBidimensional(t *testing.T) {\n\tvar msg string\n\tvar passed, f bool\n\tvar l uint\n\tvar ws []uint\n\n\tt.Run(\"EmptyList\", func(t *testing.T) {\n\t\tmsg = \"Should return an empty list of widths that fits\"\n\t\tws, l, f = FromBidimensional([]string{}, 10, TopToBottom, \" \")\n\t\tpassed = len(ws) == 0 && l == 0 && f\n\t\tend(passed, msg, ws, f, t)\n\t})\n\n\tt.Run(\"OneItem\", func(t *testing.T) {\n\t\tt.Run(\"SufficientSize\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with one width that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\"}, 20, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 1 && l == 1 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"UnsufficientSize\", func(t *testing.T) {\n\t\t\tmsg = \"Should return an empty list that does not fit\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\"}, 5, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 0 && l == 0 && !f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t})\n\n\tt.Run(\"TwoItems\", func(t *testing.T) {\n\t\tt.Run(\"SufficientSizeForTwoColumns\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with two widths that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 50, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 2 && l == 1 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"SufficientSizeForOneColumn\", func(t *testing.T) {\n\t\t\tmsg = \"Should return a list with one width that fits\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 15, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 1 && l == 2 && f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t\tt.Run(\"UnsufficientSizeFor\", func(t *testing.T) {\n\t\t\tmsg = \"Should return an empty list that does not fit\"\n\t\t\tws, l, f = FromBidimensional([]string{\"1234567890\", \"1234567890\"}, 5, TopToBottom, \" \")\n\t\t\tpassed = len(ws) == 0 && l == 0 && !f\n\t\t\tend(passed, msg, ws, f, t)\n\t\t})\n\t})\n}\n<|endoftext|>"} {"text":"package scanner\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com\/brettlangdon\/gython\/errorcode\"\n\t\"github.com\/brettlangdon\/gython\/token\"\n)\n\nvar EOF rune = 0\nvar MAXINDENT int = 100\n\ntype Scanner struct {\n\tstate errorcode.ErrorCode\n\treader *bufio.Reader\n\tcurrentPosition *Position\n\tpositionBuffer []*Position\n\n\tcurrentLine int\n\tcurrentColumn int\n}\n\nfunc NewScanner(r io.Reader) *Scanner {\n\treturn &Scanner{\n\t\tstate: errorcode.E_OK,\n\t\treader: bufio.NewReader(r),\n\t\tpositionBuffer: make([]*Position, 0),\n\t\tcurrentLine: 1,\n\t\tcurrentColumn: 0,\n\t}\n}\n\nfunc (scanner *Scanner) nextPosition() *Position {\n\tif len(scanner.positionBuffer) > 0 {\n\t\tlast := len(scanner.positionBuffer) - 1\n\t\tscanner.currentPosition = scanner.positionBuffer[last]\n\t\tscanner.positionBuffer = scanner.positionBuffer[0:last]\n\t\treturn scanner.currentPosition\n\t}\n\n\tnext, _, err := scanner.reader.ReadRune()\n\tif err != nil {\n\t\tscanner.state = errorcode.E_EOF\n\t\tnext = EOF\n\t\tscanner.currentLine++\n\t\tscanner.currentColumn = 0\n\t}\n\n\tpos := &Position{\n\t\tChar: next,\n\t\tLine: scanner.currentLine,\n\t\tColumn: scanner.currentColumn,\n\t}\n\n\tscanner.currentColumn++\n\tif next == '\\n' || next == EOF {\n\t\tscanner.currentLine++\n\t\tscanner.currentColumn = 0\n\t}\n\n\treturn pos\n}\n\nfunc (scanner *Scanner) unreadPosition(pos *Position) {\n\tscanner.positionBuffer = append(scanner.positionBuffer, pos)\n}\n\nfunc (scanner *Scanner) parseQuoted(positions *Positions, quote rune) *token.Token {\n\t\/\/ Determine quote size, 1 or 3 (e.g. 'string', '''string''')\n\tquoteSize := 1\n\tendQuoteSize := 0\n\tpos := scanner.nextPosition()\n\tif pos.Char == quote {\n\t\tpos2 := scanner.nextPosition()\n\t\tif pos2.Char == quote {\n\t\t\tpositions.Append(pos)\n\t\t\tpositions.Append(pos2)\n\t\t\tquoteSize = 3\n\t\t} else {\n\t\t\tscanner.unreadPosition(pos2)\n\t\t\tendQuoteSize = 1\n\t\t}\n\t} else {\n\t\tscanner.unreadPosition(pos)\n\t}\n\n\tfor {\n\t\tif endQuoteSize == quoteSize {\n\t\t\tbreak\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t\tpositions.Append(pos)\n\t\tif pos.Char == EOF {\n\t\t\treturn positions.AsToken(token.ERRORTOKEN)\n\t\t}\n\t\tif quoteSize == 1 && pos.Char == '\\n' {\n\t\t\treturn positions.AsToken(token.ERRORTOKEN)\n\t\t}\n\t\tif pos.Char == quote {\n\t\t\tendQuoteSize += 1\n\t\t} else {\n\t\t\tendQuoteSize = 0\n\t\t\tif pos.Char == '\\\\' {\n\t\t\t\tpos = scanner.nextPosition()\n\t\t\t}\n\t\t}\n\t}\n\treturn positions.AsToken(token.STRING)\n}\n\nfunc (scanner *Scanner) NextToken() *token.Token {\n\tpositions := NewPositions()\n\n\tpos := scanner.nextPosition()\n\t\/\/ skip spaces\n\tfor {\n\t\tif pos.Char != ' ' && pos.Char != '\\t' {\n\t\t\tbreak\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t}\n\n\t\/\/ skip comments\n\tif pos.Char == '#' {\n\t\tfor {\n\t\t\tpos = scanner.nextPosition()\n\t\t\tif pos.Char == EOF || pos.Char == '\\n' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tpositions.Append(pos)\n\tswitch ch := pos.Char; {\n\tcase ch == EOF:\n\t\tid := token.ENDMARKER\n\t\tif scanner.state != errorcode.E_EOF {\n\t\t\tid = token.ERRORTOKEN\n\t\t}\n\t\treturn positions.AsToken(id)\n\tcase IsIdentifierStart(ch):\n\t\t\/\/ Parse Identifier\n\t\tsaw_b, saw_r, saw_u := false, false, false\n\t\tfor {\n\t\t\tif !(saw_b || saw_u) && (ch == 'b' || ch == 'B') {\n\t\t\t\tsaw_b = true\n\t\t\t} else if !(saw_b || saw_u || saw_r) && (ch == 'u' || ch == 'U') {\n\t\t\t\tsaw_u = true\n\t\t\t} else if !(saw_r || saw_u) && (ch == 'r' || ch == 'R') {\n\t\t\t\tsaw_r = true\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpos = scanner.nextPosition()\n\t\t\tif IsQuote(pos.Char) {\n\t\t\t\tpositions.Append(pos)\n\t\t\t\treturn scanner.parseQuoted(positions, pos.Char)\n\t\t\t}\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t\tfor IsIdentifierChar(pos.Char) {\n\t\t\tpositions.Append(pos)\n\t\t\tpos = scanner.nextPosition()\n\t\t}\n\t\tscanner.unreadPosition(pos)\n\t\treturn positions.AsToken(token.NAME)\n\tcase ch == '\\n':\n\t\treturn positions.AsToken(token.NEWLINE)\n\tcase ch == '.':\n\t\tpos2 := scanner.nextPosition()\n\t\tif IsDigit(pos2.Char) {\n\t\t\t\/\/ Parse Number\n\t\t} else if pos2.Char == '.' {\n\t\t\tpositions.Append(pos2)\n\t\t\tpos3 := scanner.nextPosition()\n\t\t\tif pos3.Char == '.' {\n\t\t\t\tpositions.Append(pos3)\n\t\t\t\treturn positions.AsToken(token.ELLIPSIS)\n\t\t\t}\n\t\t\tscanner.unreadPosition(pos3)\n\t\t}\n\t\tscanner.unreadPosition(pos2)\n\n\t\treturn positions.AsToken(token.DOT)\n\tcase IsDigit(ch):\n\t\t\/\/ Parse Number\n\tcase IsQuote(ch):\n\t\t\/\/ Parse String\n\t\treturn scanner.parseQuoted(positions, ch)\n\tcase ch == '\\\\':\n\t\t\/\/ Parse Continuation\n\tdefault:\n\t\t\/\/ Two and Three character operators\n\t\tpos2 := scanner.nextPosition()\n\t\top2Id := GetTwoCharTokenID(pos.Char, pos2.Char)\n\t\tif op2Id != token.OP {\n\t\t\tpositions.Append(pos2)\n\t\t\tpos3 := scanner.nextPosition()\n\t\t\top3Id := GetThreeCharTokenID(pos.Char, pos2.Char, pos3.Char)\n\t\t\tif op3Id != token.OP {\n\t\t\t\tpositions.Append(pos3)\n\t\t\t\treturn positions.AsToken(op3Id)\n\t\t\t}\n\t\t\tscanner.unreadPosition(pos3)\n\t\t\treturn positions.AsToken(op2Id)\n\t\t}\n\t\tscanner.unreadPosition(pos2)\n\t}\n\tswitch pos.Char {\n\tcase '(', '[', '{':\n\t\t\/\/ Increment indentation level\n\t\t\/\/ scanner.indentationLevel++\n\t\tbreak\n\tcase ')', ']', '}':\n\t\t\/\/ Decrement indentation level\n\t\t\/\/ scanner.indentationLevel--\n\t\tbreak\n\t}\n\n\topId := GetOneCharTokenID(pos.Char)\n\treturn positions.AsToken(opId)\n}\nshuffle line\/column incrementing aroundpackage scanner\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\n\t\"github.com\/brettlangdon\/gython\/errorcode\"\n\t\"github.com\/brettlangdon\/gython\/token\"\n)\n\nvar EOF rune = 0\nvar MAXINDENT int = 100\n\ntype Scanner struct {\n\tstate errorcode.ErrorCode\n\treader *bufio.Reader\n\tcurrentPosition *Position\n\tpositionBuffer []*Position\n\n\tcurrentLine int\n\tcurrentColumn int\n}\n\nfunc NewScanner(r io.Reader) *Scanner {\n\treturn &Scanner{\n\t\tstate: errorcode.E_OK,\n\t\treader: bufio.NewReader(r),\n\t\tpositionBuffer: make([]*Position, 0),\n\t\tcurrentLine: 1,\n\t\tcurrentColumn: 0,\n\t}\n}\n\nfunc (scanner *Scanner) nextPosition() *Position {\n\tif len(scanner.positionBuffer) > 0 {\n\t\tlast := len(scanner.positionBuffer) - 1\n\t\tscanner.currentPosition = scanner.positionBuffer[last]\n\t\tscanner.positionBuffer = scanner.positionBuffer[0:last]\n\t\treturn scanner.currentPosition\n\t}\n\n\tnext, _, err := scanner.reader.ReadRune()\n\tif err != nil {\n\t\tscanner.state = errorcode.E_EOF\n\t\tnext = EOF\n\t\tscanner.currentLine++\n\t\tscanner.currentColumn = 0\n\t}\n\n\tif next == '\\n' || next == EOF {\n\t\tscanner.currentLine++\n\t\tscanner.currentColumn = 0\n\t}\n\n\tpos := &Position{\n\t\tChar: next,\n\t\tLine: scanner.currentLine,\n\t\tColumn: scanner.currentColumn,\n\t}\n\tscanner.currentColumn++\n\treturn pos\n}\n\nfunc (scanner *Scanner) unreadPosition(pos *Position) {\n\tscanner.positionBuffer = append(scanner.positionBuffer, pos)\n}\n\nfunc (scanner *Scanner) parseQuoted(positions *Positions, quote rune) *token.Token {\n\t\/\/ Determine quote size, 1 or 3 (e.g. 'string', '''string''')\n\tquoteSize := 1\n\tendQuoteSize := 0\n\tpos := scanner.nextPosition()\n\tif pos.Char == quote {\n\t\tpos2 := scanner.nextPosition()\n\t\tif pos2.Char == quote {\n\t\t\tpositions.Append(pos)\n\t\t\tpositions.Append(pos2)\n\t\t\tquoteSize = 3\n\t\t} else {\n\t\t\tscanner.unreadPosition(pos2)\n\t\t\tendQuoteSize = 1\n\t\t}\n\t} else {\n\t\tscanner.unreadPosition(pos)\n\t}\n\n\tfor {\n\t\tif endQuoteSize == quoteSize {\n\t\t\tbreak\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t\tpositions.Append(pos)\n\t\tif pos.Char == EOF {\n\t\t\treturn positions.AsToken(token.ERRORTOKEN)\n\t\t}\n\t\tif quoteSize == 1 && pos.Char == '\\n' {\n\t\t\treturn positions.AsToken(token.ERRORTOKEN)\n\t\t}\n\t\tif pos.Char == quote {\n\t\t\tendQuoteSize += 1\n\t\t} else {\n\t\t\tendQuoteSize = 0\n\t\t\tif pos.Char == '\\\\' {\n\t\t\t\tpos = scanner.nextPosition()\n\t\t\t}\n\t\t}\n\t}\n\treturn positions.AsToken(token.STRING)\n}\n\nfunc (scanner *Scanner) NextToken() *token.Token {\n\tpositions := NewPositions()\n\n\tpos := scanner.nextPosition()\n\t\/\/ skip spaces\n\tfor {\n\t\tif pos.Char != ' ' && pos.Char != '\\t' {\n\t\t\tbreak\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t}\n\n\t\/\/ skip comments\n\tif pos.Char == '#' {\n\t\tfor {\n\t\t\tpos = scanner.nextPosition()\n\t\t\tif pos.Char == EOF || pos.Char == '\\n' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tpositions.Append(pos)\n\tswitch ch := pos.Char; {\n\tcase ch == EOF:\n\t\tid := token.ENDMARKER\n\t\tif scanner.state != errorcode.E_EOF {\n\t\t\tid = token.ERRORTOKEN\n\t\t}\n\t\treturn positions.AsToken(id)\n\tcase IsIdentifierStart(ch):\n\t\t\/\/ Parse Identifier\n\t\tsaw_b, saw_r, saw_u := false, false, false\n\t\tfor {\n\t\t\tif !(saw_b || saw_u) && (ch == 'b' || ch == 'B') {\n\t\t\t\tsaw_b = true\n\t\t\t} else if !(saw_b || saw_u || saw_r) && (ch == 'u' || ch == 'U') {\n\t\t\t\tsaw_u = true\n\t\t\t} else if !(saw_r || saw_u) && (ch == 'r' || ch == 'R') {\n\t\t\t\tsaw_r = true\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpos = scanner.nextPosition()\n\t\t\tif IsQuote(pos.Char) {\n\t\t\t\tpositions.Append(pos)\n\t\t\t\treturn scanner.parseQuoted(positions, pos.Char)\n\t\t\t}\n\t\t}\n\t\tpos = scanner.nextPosition()\n\t\tfor IsIdentifierChar(pos.Char) {\n\t\t\tpositions.Append(pos)\n\t\t\tpos = scanner.nextPosition()\n\t\t}\n\t\tscanner.unreadPosition(pos)\n\t\treturn positions.AsToken(token.NAME)\n\tcase ch == '\\n':\n\t\treturn positions.AsToken(token.NEWLINE)\n\tcase ch == '.':\n\t\tpos2 := scanner.nextPosition()\n\t\tif IsDigit(pos2.Char) {\n\t\t\t\/\/ Parse Number\n\t\t} else if pos2.Char == '.' {\n\t\t\tpositions.Append(pos2)\n\t\t\tpos3 := scanner.nextPosition()\n\t\t\tif pos3.Char == '.' {\n\t\t\t\tpositions.Append(pos3)\n\t\t\t\treturn positions.AsToken(token.ELLIPSIS)\n\t\t\t}\n\t\t\tscanner.unreadPosition(pos3)\n\t\t}\n\t\tscanner.unreadPosition(pos2)\n\n\t\treturn positions.AsToken(token.DOT)\n\tcase IsDigit(ch):\n\t\t\/\/ Parse Number\n\tcase IsQuote(ch):\n\t\t\/\/ Parse String\n\t\treturn scanner.parseQuoted(positions, ch)\n\tcase ch == '\\\\':\n\t\t\/\/ Parse Continuation\n\tdefault:\n\t\t\/\/ Two and Three character operators\n\t\tpos2 := scanner.nextPosition()\n\t\top2Id := GetTwoCharTokenID(pos.Char, pos2.Char)\n\t\tif op2Id != token.OP {\n\t\t\tpositions.Append(pos2)\n\t\t\tpos3 := scanner.nextPosition()\n\t\t\top3Id := GetThreeCharTokenID(pos.Char, pos2.Char, pos3.Char)\n\t\t\tif op3Id != token.OP {\n\t\t\t\tpositions.Append(pos3)\n\t\t\t\treturn positions.AsToken(op3Id)\n\t\t\t}\n\t\t\tscanner.unreadPosition(pos3)\n\t\t\treturn positions.AsToken(op2Id)\n\t\t}\n\t\tscanner.unreadPosition(pos2)\n\t}\n\tswitch pos.Char {\n\tcase '(', '[', '{':\n\t\t\/\/ Increment indentation level\n\t\t\/\/ scanner.indentationLevel++\n\t\tbreak\n\tcase ')', ']', '}':\n\t\t\/\/ Decrement indentation level\n\t\t\/\/ scanner.indentationLevel--\n\t\tbreak\n\t}\n\n\topId := GetOneCharTokenID(pos.Char)\n\treturn positions.AsToken(opId)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/xml\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nvar dbFile = flag.String(\"db\", \"xrguide.db\", \"Database file.\")\nvar textDir = flag.String(\"t\", \".\", \"Directory with text files.\")\nvar verbose = flag.Bool(\"v\", true, \"Verbose output.\")\n\nvar insert string = `\nINSERT INTO text_entries\n(language_id, page_id, text_id, text)\nVALUES\n(?, ?, ?, ?)\n`\n\nfunc main() {\n\tflag.Parse()\n\terr := backupDb(*dbFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb, err := sql.Open(\"sqlite3\", *dbFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening db: %v\", err)\n\t}\n\terr = prepareDb(db)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\terr = read(db, *textDir, *verbose)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype Text struct {\n\tId int64 `xml:\"id,attr\"`\n\tEntry string `xml:\",innerxml\"`\n}\n\ntype Page struct {\n\tId int64 `xml:\"id,attr\"`\n\tEntries []Text `xml:\"t\"`\n}\n\ntype LangFile struct {\n\tXMLName xml.Name `xml:\"language\"`\n\tLangId int64 `xml:\"id,attr\"`\n\tPages []Page `xml:\"page\"`\n}\n\nfunc read(db *sql.DB, directory string, verbose bool) error {\n\tinfo, err := os.Stat(directory)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Could not stat text directory: %v\", err)\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Text directory not found: %s\", directory)\n\t}\n\tif !info.IsDir() {\n\t\treturn fmt.Errorf(\"%s is not a directory.\", directory)\n\t}\n\tdir, err := os.Open(directory)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error opening text directory: %v\", err)\n\t}\n\tdefer dir.Close()\n\tpattern := regexp.MustCompile(\"0001-L(\\\\d{3})\\\\.xml\")\n\tstmt, err := db.Prepare(insert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error preparing statement: %v\", err)\n\t}\n\tvar langId int64\n\tvar fileName string\n\tvar lang LangFile\n\tfor {\n\t\tf, err := dir.Readdir(1)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error on reading text directory: %v\")\n\t\t}\n\t\tfileName = filepath.Join(dir.Name(), f[0].Name())\n\t\tif !pattern.MatchString(f[0].Name()) {\n\t\t\tlog.Printf(\"Skipping %s\", fileName)\n\t\t\tcontinue\n\t\t}\n\t\tmatches := pattern.FindStringSubmatch(f[0].Name())\n\t\tlangId, err = strconv.ParseInt(matches[1], 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error on parsing filename: %s (%v)\", fileName, err)\n\t\t\tcontinue\n\t\t}\n\t\tif langId == 0 {\n\t\t\tlog.Printf(\"Error on filename %s. Invalid lang id.\", fileName)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"Text file %s. Language Id %d\", fileName, langId)\n\n\t\tfile, err := os.Open(fileName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error opening file %s.\", fileName)\n\t\t}\n\t\tdecoder := xml.NewDecoder(file)\n\t\terr = decoder.Decode(&lang)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn fmt.Errorf(\"Error decoding file %s: %v\", fileName, err)\n\t\t}\n\t\tfor _, page := range lang.Pages {\n\t\t\tif lang.LangId != langId {\n\t\t\t\tfmt.Printf(\"Language Id does not match in %s. Id %d.\", fileName, lang.LangId)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif verbose {\n\t\t\t\tlog.Printf(\"Lang %d Page %d.\", lang.LangId, page.Id)\n\t\t\t}\n\t\t\tfor _, t := range page.Entries {\n\t\t\t\tif verbose {\n\t\t\t\t\tlog.Printf(\"Lang %d Page %d Text %d.\", lang.LangId, page.Id, t.Id)\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(lang.LangId, page.Id, t.Id, t.Entry)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error on insert. Aborting: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfile.Close()\n\t}\n\treturn nil\n}\n\nfunc backupDb(fileName string) error {\n\tinfo, err := os.Stat(fileName)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Error backing up db stat: %v\", err)\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\tif info.IsDir() {\n\t\treturn fmt.Errorf(\"DB file is a directory. Cannot continue.\")\n\t}\n\torig, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not open db: %v\", err)\n\t}\n\tdefer orig.Close()\n\tbak, err := os.Create(fileName + \".bak\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating backup file: %v\", err)\n\t}\n\tdefer bak.Close()\n\t_, err = io.Copy(bak, orig)\n\treturn nil\n}\n\nfunc prepareDb(db *sql.DB) error {\n\tvar err error\n\tstmts := []string{\n\t\t`\nDROP TABLE IF EXISTS languages;\n\t\t`,\n\t\t`\nCREATE TABLE languages (\n\tid INTEGER PRIMARY KEY ASC,\n\tname TEXT UNIQUE\n)\n\t\t`,\n\t\t`\nDROP TABLE IF EXISTS text_entries;\n\t\t`,\n\t\t`\nCREATE TABLE text_entries (\n\tlanguage_id INTEGER,\n\tpage_id INTEGER,\n\ttext_id INTEGER,\n\ttext TEXT,\n\tPRIMARY KEY (language_id, page_id, text_id ASC),\n\tFOREIGN KEY (language_id) REFERENCES languages(id) ON DELETE RESTRICT ON UPDATE CASCADE\n)\n\t\t`,\n\t\t`\nINSERT INTO languages\n(id, name)\nVALUES\n(7, 'Russian'),\n(33, 'French'),\n(34, 'Spanish'),\n(39, 'Italian'),\n(44, 'English'),\n(49, 'German'),\n(86, 'Chinese (traditional)'),\n(88, 'Chinese (simplified)')\n\t\t`,\n\t}\n\tfor _, sql := range stmts {\n\t\t_, err = db.Exec(sql)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error preparing db: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}\nsupport selective reset of db, selective languages and pages. minor internal fixespackage main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/xml\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\nvar dbFile = flag.String(\"db\", \"xrguide.db\", \"Database file.\")\nvar rebuild = flag.Bool(\"r\", false, \"Whether to reinitialize db.\")\nvar textDir = flag.String(\"t\", \".\", \"Directory with text files.\")\nvar verbose = flag.Bool(\"v\", true, \"Verbose output.\")\nvar lang = flag.Int64(\"l\", 0, \"Language Id. If not specified all.\")\nvar page = flag.Int64(\"p\", 0, \"Page Id. If not specified all.\")\n\nvar reset string = `\nDELETE FROM text_entries\nWHERE\nlanguage_id = ?\nAND\npage_id = ?\n`\nvar insert string = `\nINSERT INTO text_entries\n(language_id, page_id, text_id, text)\nVALUES\n(?, ?, ?, ?)\n`\n\nfunc main() {\n\tflag.Parse()\n\terr := backupDb(*dbFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb, err := sql.Open(\"sqlite3\", *dbFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening db: %v\", err)\n\t}\n\tdefer db.Close()\n\tif *rebuild {\n\t\terr = prepareDb(db)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\terr = read(db, *textDir, *verbose, *lang, *page)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype Text struct {\n\tId int64 `xml:\"id,attr\"`\n\tEntry string `xml:\",innerxml\"`\n}\n\ntype Page struct {\n\tId int64 `xml:\"id,attr\"`\n\tEntries []Text `xml:\"t\"`\n}\n\ntype LangFile struct {\n\tXMLName xml.Name `xml:\"language\"`\n\tLangId int64 `xml:\"id,attr\"`\n\tPages []Page `xml:\"page\"`\n}\n\nfunc read(db *sql.DB, directory string, verbose bool, useLang, usePage int64) error {\n\tinfo, err := os.Stat(directory)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Could not stat text directory: %v\", err)\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Text directory not found: %s\", directory)\n\t}\n\tif !info.IsDir() {\n\t\treturn fmt.Errorf(\"%s is not a directory.\", directory)\n\t}\n\tdir, err := os.Open(directory)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error opening text directory: %v\", err)\n\t}\n\tdefer dir.Close()\n\tpattern := regexp.MustCompile(\"0001-L(\\\\d{3})\\\\.xml\")\n\tstmt, err := db.Prepare(insert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error preparing statement: %v\", err)\n\t}\n\treset, err := db.Prepare(reset)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error preparing statement: %v\", err)\n\t}\n\tvar langId int64\n\tvar fileName string\n\tvar lang LangFile\n\tfor {\n\t\tf, err := dir.Readdir(1)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error on reading text directory: %v\")\n\t\t}\n\t\tfileName = filepath.Join(dir.Name(), f[0].Name())\n\t\tif !pattern.MatchString(f[0].Name()) {\n\t\t\tlog.Printf(\"Skipping %s\", fileName)\n\t\t\tcontinue\n\t\t}\n\t\tmatches := pattern.FindStringSubmatch(f[0].Name())\n\t\tlangId, err = strconv.ParseInt(matches[1], 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error on parsing filename: %s (%v)\", fileName, err)\n\t\t\tcontinue\n\t\t}\n\t\tif langId == 0 {\n\t\t\tlog.Printf(\"Error on filename %s. Invalid lang id.\", fileName)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"Text file %s. Language Id %d\", fileName, langId)\n\n\t\tif useLang != 0 && useLang != langId {\n\t\t\tlog.Printf(\"Skipping %s.\", fileName)\n\t\t\tcontinue\n\t\t}\n\n\t\tfile, err := os.Open(fileName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error opening file %s.\", fileName)\n\t\t}\n\t\tdecoder := xml.NewDecoder(file)\n\t\terr = decoder.Decode(&lang)\n\t\tif err != nil {\n\t\t\tfile.Close()\n\t\t\treturn fmt.Errorf(\"Error decoding file %s: %v\", fileName, err)\n\t\t}\n\t\tfor _, page := range lang.Pages {\n\t\t\tif lang.LangId != langId {\n\t\t\t\tlog.Printf(\"Language Id does not match in %s. Id %d.\", fileName, lang.LangId)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif usePage != 0 && usePage != page.Id {\n\t\t\t\tif verbose {\n\t\t\t\t\tlog.Printf(\"Skipping page %d.\", page.Id)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif verbose {\n\t\t\t\tlog.Printf(\"Lang %d Page %d.\", lang.LangId, page.Id)\n\t\t\t}\n\t\t\t_, err = reset.Exec(lang.LangId, page.Id)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error on reset. Aborting: %v\", err)\n\t\t\t}\n\t\t\tfor _, t := range page.Entries {\n\t\t\t\tif verbose {\n\t\t\t\t\tlog.Printf(\"Lang %d Page %d Text %d.\", lang.LangId, page.Id, t.Id)\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(lang.LangId, page.Id, t.Id, t.Entry)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error on insert. Aborting: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfile.Close()\n\t}\n\treturn nil\n}\n\nfunc backupDb(fileName string) error {\n\tinfo, err := os.Stat(fileName)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Error backing up db stat: %v\", err)\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\tif info.IsDir() {\n\t\treturn fmt.Errorf(\"DB file is a directory. Cannot continue.\")\n\t}\n\torig, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not open db: %v\", err)\n\t}\n\tdefer orig.Close()\n\tbak, err := os.Create(fileName + \".bak\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating backup file: %v\", err)\n\t}\n\tdefer bak.Close()\n\t_, err = io.Copy(bak, orig)\n\treturn nil\n}\n\nfunc prepareDb(db *sql.DB) error {\n\tvar err error\n\tstmts := []string{\n\t\t`\nDROP TABLE IF EXISTS languages;\n\t\t`,\n\t\t`\nCREATE TABLE languages (\n\tid INTEGER PRIMARY KEY ASC,\n\tname TEXT UNIQUE\n)\n\t\t`,\n\t\t`\nDROP TABLE IF EXISTS text_entries;\n\t\t`,\n\t\t`\nCREATE TABLE text_entries (\n\tlanguage_id INTEGER,\n\tpage_id INTEGER,\n\ttext_id INTEGER,\n\ttext TEXT,\n\tPRIMARY KEY (language_id, page_id, text_id ASC),\n\tFOREIGN KEY (language_id) REFERENCES languages(id) ON DELETE RESTRICT ON UPDATE CASCADE\n)\n\t\t`,\n\t\t`\nINSERT INTO languages\n(id, name)\nVALUES\n(7, 'Russian'),\n(33, 'French'),\n(34, 'Spanish'),\n(39, 'Italian'),\n(44, 'English'),\n(49, 'German'),\n(86, 'Chinese (traditional)'),\n(88, 'Chinese (simplified)')\n\t\t`,\n\t}\n\tfor _, sql := range stmts {\n\t\t_, err = db.Exec(sql)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error preparing db: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 tsuru 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\"errors\"\n\t\"github.com\/fsouza\/gogit\/git\"\n\t\"io\"\n\t. \"launchpad.net\/gocheck\"\n\t\"os\"\n\t\"path\"\n\t\"syscall\"\n)\n\nfunc writeConfig(sourceFile string, c *C) string {\n\tsrcConfig, err := os.Open(sourceFile)\n\tc.Assert(err, IsNil)\n\tdefer srcConfig.Close()\n\tp := path.Join(os.TempDir(), \"guesser-tests\")\n\terr = os.MkdirAll(p, 0700)\n\tc.Assert(err, IsNil)\n\trepo, err := git.InitRepository(p, false)\n\tc.Assert(err, IsNil)\n\tdefer repo.Free()\n\tdstConfig, err := os.OpenFile(path.Join(p, \".git\", \"config\"), syscall.O_WRONLY|syscall.O_TRUNC|syscall.O_CREAT|syscall.O_CLOEXEC, 0644)\n\tc.Assert(err, IsNil)\n\tdefer dstConfig.Close()\n\t_, err = io.Copy(dstConfig, srcConfig)\n\tc.Assert(err, IsNil)\n\treturn p\n}\n\nfunc (s *S) TestGitGuesser(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-ok\", c)\n\tdefer os.RemoveAll(p)\n\tdirPath := path.Join(p, \"somepath\")\n\terr := os.MkdirAll(dirPath, 0700) \/\/ Will be removed when p is removed.\n\tc.Assert(err, IsNil)\n\tg := GitGuesser{}\n\tname, err := g.GuessName(p) \/\/ repository root\n\tc.Assert(err, IsNil)\n\tc.Assert(name, Equals, \"gopher\")\n\tname, err = g.GuessName(dirPath) \/\/ subdirectory\n\tc.Assert(err, IsNil)\n\tc.Assert(name, Equals, \"gopher\")\n}\n\n\/\/ This test may fail if you have a git repository in \/tmp. By the way, if you\n\/\/ do have a repository in the temporary file hierarchy, please kill yourself.\nfunc (s *S) TestGitGuesserWhenTheDirectoryIsNotAGitRepository(c *C) {\n\tp := path.Join(os.TempDir(), \"guesser-tests\")\n\terr := os.MkdirAll(p, 0700)\n\tc.Assert(err, IsNil)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err, ErrorMatches, \"^Git repository not found:.*\")\n}\n\nfunc (s *S) TestGitGuesserWithoutTsuruRemote(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-without-tsuru-remote\", c)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err.Error(), Equals, \"tsuru remote not declared.\")\n}\n\nfunc (s *S) TestGitGuesserWithTsuruRemoteNotMatchingTsuruPattern(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-not-matching\", c)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err.Error(), Equals, `\"tsuru\" remote did not match the pattern. Want something like git@:.git, got me@myhost.com:gopher.git`)\n}\n\nfunc (s *S) TestGuessingCommandGuesserNil(c *C) {\n\tg := GuessingCommand{g: nil}\n\tc.Assert(g.guesser(), FitsTypeOf, GitGuesser{})\n}\n\nfunc (s *S) TestGuessingCommandGuesserNonNil(c *C) {\n\tfake := &FakeGuesser{}\n\tg := GuessingCommand{g: fake}\n\tc.Assert(g.guesser(), DeepEquals, fake)\n}\n\ntype FakeGuesser struct {\n\tname string\n}\n\nfunc (f *FakeGuesser) GuessName(path string) (string, error) {\n\treturn f.name, nil\n}\n\ntype FailingFakeGuesser struct {\n\tmessage string\n}\n\nfunc (f *FailingFakeGuesser) GuessName(path string) (string, error) {\n\treturn \"\", errors.New(f.message)\n}\ncmd\/tsuru: logging guesses in fake guessers\/\/ Copyright 2012 tsuru 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\"errors\"\n\t\"github.com\/fsouza\/gogit\/git\"\n\t\"io\"\n\t. \"launchpad.net\/gocheck\"\n\t\"os\"\n\t\"path\"\n\t\"syscall\"\n)\n\nfunc writeConfig(sourceFile string, c *C) string {\n\tsrcConfig, err := os.Open(sourceFile)\n\tc.Assert(err, IsNil)\n\tdefer srcConfig.Close()\n\tp := path.Join(os.TempDir(), \"guesser-tests\")\n\terr = os.MkdirAll(p, 0700)\n\tc.Assert(err, IsNil)\n\trepo, err := git.InitRepository(p, false)\n\tc.Assert(err, IsNil)\n\tdefer repo.Free()\n\tdstConfig, err := os.OpenFile(path.Join(p, \".git\", \"config\"), syscall.O_WRONLY|syscall.O_TRUNC|syscall.O_CREAT|syscall.O_CLOEXEC, 0644)\n\tc.Assert(err, IsNil)\n\tdefer dstConfig.Close()\n\t_, err = io.Copy(dstConfig, srcConfig)\n\tc.Assert(err, IsNil)\n\treturn p\n}\n\nfunc (s *S) TestGitGuesser(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-ok\", c)\n\tdefer os.RemoveAll(p)\n\tdirPath := path.Join(p, \"somepath\")\n\terr := os.MkdirAll(dirPath, 0700) \/\/ Will be removed when p is removed.\n\tc.Assert(err, IsNil)\n\tg := GitGuesser{}\n\tname, err := g.GuessName(p) \/\/ repository root\n\tc.Assert(err, IsNil)\n\tc.Assert(name, Equals, \"gopher\")\n\tname, err = g.GuessName(dirPath) \/\/ subdirectory\n\tc.Assert(err, IsNil)\n\tc.Assert(name, Equals, \"gopher\")\n}\n\n\/\/ This test may fail if you have a git repository in \/tmp. By the way, if you\n\/\/ do have a repository in the temporary file hierarchy, please kill yourself.\nfunc (s *S) TestGitGuesserWhenTheDirectoryIsNotAGitRepository(c *C) {\n\tp := path.Join(os.TempDir(), \"guesser-tests\")\n\terr := os.MkdirAll(p, 0700)\n\tc.Assert(err, IsNil)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err, ErrorMatches, \"^Git repository not found:.*\")\n}\n\nfunc (s *S) TestGitGuesserWithoutTsuruRemote(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-without-tsuru-remote\", c)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err.Error(), Equals, \"tsuru remote not declared.\")\n}\n\nfunc (s *S) TestGitGuesserWithTsuruRemoteNotMatchingTsuruPattern(c *C) {\n\tp := writeConfig(\"testdata\/gitconfig-not-matching\", c)\n\tdefer os.RemoveAll(p)\n\tname, err := GitGuesser{}.GuessName(p)\n\tc.Assert(name, Equals, \"\")\n\tc.Assert(err, NotNil)\n\tc.Assert(err.Error(), Equals, `\"tsuru\" remote did not match the pattern. Want something like git@:.git, got me@myhost.com:gopher.git`)\n}\n\nfunc (s *S) TestGuessingCommandGuesserNil(c *C) {\n\tg := GuessingCommand{g: nil}\n\tc.Assert(g.guesser(), FitsTypeOf, GitGuesser{})\n}\n\nfunc (s *S) TestGuessingCommandGuesserNonNil(c *C) {\n\tfake := &FakeGuesser{}\n\tg := GuessingCommand{g: fake}\n\tc.Assert(g.guesser(), DeepEquals, fake)\n}\n\ntype FakeGuesser struct {\n\tlog []string\n\tname string\n}\n\nfunc (f *FakeGuesser) GuessName(path string) (string, error) {\n\tf.log = append(f.log, \"Guessing \"+path)\n\treturn f.name, nil\n}\n\ntype FailingFakeGuesser struct {\n\tlog []string\n\tmessage string\n}\n\nfunc (f *FailingFakeGuesser) GuessName(path string) (string, error) {\n\tf.log = append(f.log, \"Guessing \"+path)\n\treturn \"\", errors.New(f.message)\n}\n<|endoftext|>"} {"text":"package torrent\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cenkalti\/backoff\"\n)\n\nfunc (s *Session) startBlocklistReloader() error {\n\tif s.config.BlocklistURL == \"\" {\n\t\treturn nil\n\t}\n\tblocklistTimestamp, err := s.getBlocklistTimestamp()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mBlocklist.Lock()\n\ts.blocklistTimestamp = blocklistTimestamp\n\ts.mBlocklist.Unlock()\n\n\tdeadline := blocklistTimestamp.Add(s.config.BlocklistUpdateInterval)\n\tnow := time.Now().UTC()\n\tdelta := now.Sub(deadline)\n\tif blocklistTimestamp.IsZero() {\n\t\ts.log.Infof(\"Blocklist is empty. Loading blacklist...\")\n\t\ts.retryReloadBlocklist()\n\t} else if delta > 0 {\n\t\ts.log.Infof(\"Last blocklist reload was %s ago. Reloading blacklist...\", delta.String())\n\t\ts.retryReloadBlocklist()\n\t}\n\tgo s.blocklistReloader(delta)\n\treturn nil\n}\n\nfunc (s *Session) getBlocklistTimestamp() (time.Time, error) {\n\tvar t time.Time\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(sessionBucket)\n\t\tval := b.Get(blocklistTimestampKey)\n\t\tif val == nil {\n\t\t\treturn nil\n\t\t}\n\t\tvar err2 error\n\t\tt, err2 = time.ParseInLocation(time.RFC3339, string(val), time.UTC)\n\t\treturn err2\n\t})\n\treturn t, err\n}\n\nfunc (s *Session) retryReloadBlocklist() {\n\tbo := backoff.NewExponentialBackOff()\n\tbo.MaxElapsedTime = 0\n\n\tticker := backoff.NewTicker(bo)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\terr := s.reloadBlocklist()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Errorln(\"cannot load blocklist:\", err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn\n\t\tcase <-s.closeC:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Session) reloadBlocklist() error {\n\tresp, err := http.Get(s.config.BlocklistURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"invalid blocklist status code\")\n\t}\n\n\tvar r io.Reader = resp.Body\n\tif resp.Header.Get(\"content-type\") == \"application\/x-gzip\" {\n\t\tgr, gerr := gzip.NewReader(r)\n\t\tif gerr != nil {\n\t\t\treturn gerr\n\t\t}\n\t\tdefer gr.Close()\n\t\tr = gr\n\t}\n\n\tbuf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength))\n\tr = io.TeeReader(r, buf)\n\n\tn, err := s.blocklist.Reload(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.log.Infof(\"Loaded %d rules from blocklist.\", n)\n\n\tnow := time.Now()\n\n\ts.mBlocklist.Lock()\n\ts.blocklistTimestamp = now\n\ts.mBlocklist.Unlock()\n\n\treturn s.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(sessionBucket)\n\t\terr2 := b.Put(blocklistKey, buf.Bytes())\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\t\treturn b.Put(blocklistTimestampKey, []byte(now.UTC().Format(time.RFC3339)))\n\t})\n}\n\nfunc (s *Session) blocklistReloader(d time.Duration) {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(d):\n\t\tcase <-s.closeC:\n\t\t\treturn\n\t\t}\n\n\t\ts.retryReloadBlocklist()\n\t\td = s.config.BlocklistUpdateInterval\n\t}\n}\nmore log in blocklist reloadpackage torrent\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cenkalti\/backoff\"\n)\n\nfunc (s *Session) startBlocklistReloader() error {\n\tif s.config.BlocklistURL == \"\" {\n\t\treturn nil\n\t}\n\tblocklistTimestamp, err := s.getBlocklistTimestamp()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mBlocklist.Lock()\n\ts.blocklistTimestamp = blocklistTimestamp\n\ts.mBlocklist.Unlock()\n\n\tdeadline := blocklistTimestamp.Add(s.config.BlocklistUpdateInterval)\n\tnow := time.Now().UTC()\n\tdelta := now.Sub(deadline)\n\tif blocklistTimestamp.IsZero() {\n\t\ts.log.Infof(\"Blocklist is empty. Loading blocklist...\")\n\t\ts.retryReloadBlocklist()\n\t} else if delta > 0 {\n\t\ts.log.Infof(\"Last blocklist reload was %s ago. Reloading blocklist...\", delta.String())\n\t\ts.retryReloadBlocklist()\n\t}\n\tgo s.blocklistReloader(delta)\n\treturn nil\n}\n\nfunc (s *Session) getBlocklistTimestamp() (time.Time, error) {\n\tvar t time.Time\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(sessionBucket)\n\t\tval := b.Get(blocklistTimestampKey)\n\t\tif val == nil {\n\t\t\treturn nil\n\t\t}\n\t\tvar err2 error\n\t\tt, err2 = time.ParseInLocation(time.RFC3339, string(val), time.UTC)\n\t\treturn err2\n\t})\n\treturn t, err\n}\n\nfunc (s *Session) retryReloadBlocklist() {\n\tbo := backoff.NewExponentialBackOff()\n\tbo.MaxElapsedTime = 0\n\n\tticker := backoff.NewTicker(bo)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\terr := s.reloadBlocklist()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Errorln(\"cannot load blocklist:\", err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn\n\t\tcase <-s.closeC:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Session) reloadBlocklist() error {\n\tresp, err := http.Get(s.config.BlocklistURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"invalid blocklist status code\")\n\t}\n\n\tvar r io.Reader = resp.Body\n\tif resp.Header.Get(\"content-type\") == \"application\/x-gzip\" {\n\t\tgr, gerr := gzip.NewReader(r)\n\t\tif gerr != nil {\n\t\t\treturn gerr\n\t\t}\n\t\tdefer gr.Close()\n\t\tr = gr\n\t}\n\n\tbuf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength))\n\tr = io.TeeReader(r, buf)\n\n\tn, err := s.blocklist.Reload(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.log.Infof(\"Loaded %d rules from blocklist.\", n)\n\n\tnow := time.Now()\n\n\ts.mBlocklist.Lock()\n\ts.blocklistTimestamp = now\n\ts.mBlocklist.Unlock()\n\n\treturn s.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(sessionBucket)\n\t\terr2 := b.Put(blocklistKey, buf.Bytes())\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\t\treturn b.Put(blocklistTimestampKey, []byte(now.UTC().Format(time.RFC3339)))\n\t})\n}\n\nfunc (s *Session) blocklistReloader(d time.Duration) {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(d):\n\t\tcase <-s.closeC:\n\t\t\treturn\n\t\t}\n\n\t\ts.log.Info(\"Reloading blocklist...\")\n\t\ts.retryReloadBlocklist()\n\t\td = s.config.BlocklistUpdateInterval\n\t}\n}\n<|endoftext|>"} {"text":"package tq\n\nimport (\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/git-lfs\/git-lfs\/errors\"\n\t\"github.com\/git-lfs\/git-lfs\/tools\"\n\t\"github.com\/rubyist\/tracerx\"\n)\n\n\/\/ Adapter for basic HTTP downloads, includes resuming via HTTP Range\ntype basicDownloadAdapter struct {\n\t*adapterBase\n}\n\nfunc (a *basicDownloadAdapter) ClearTempStorage() error {\n\treturn os.RemoveAll(a.tempDir())\n}\n\nfunc (a *basicDownloadAdapter) tempDir() string {\n\t\/\/ Must be dedicated to this adapter as deleted by ClearTempStorage\n\t\/\/ Also make local to this repo not global, and separate to localstorage temp,\n\t\/\/ which gets cleared at the end of every invocation\n\td := filepath.Join(a.fs.LFSStorageDir, \"incomplete\")\n\tif err := tools.MkdirAll(d, a.fs); err != nil {\n\t\treturn os.TempDir()\n\t}\n\treturn d\n}\n\nfunc (a *basicDownloadAdapter) WorkerStarting(workerNum int) (interface{}, error) {\n\treturn nil, nil\n}\nfunc (a *basicDownloadAdapter) WorkerEnding(workerNum int, ctx interface{}) {\n}\n\nfunc (a *basicDownloadAdapter) DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error {\n\tf, fromByte, hashSoFar, err := a.checkResumeDownload(t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.download(t, cb, authOkFunc, f, fromByte, hashSoFar)\n}\n\n\/\/ Checks to see if a download can be resumed, and if so returns a non-nil locked file, byte start and hash\nfunc (a *basicDownloadAdapter) checkResumeDownload(t *Transfer) (outFile *os.File, fromByte int64, hashSoFar hash.Hash, e error) {\n\t\/\/ lock the file by opening it for read\/write, rather than checking Stat() etc\n\t\/\/ which could be subject to race conditions by other processes\n\tf, err := os.OpenFile(a.downloadFilename(t), os.O_RDWR, 0644)\n\n\tif err != nil {\n\t\t\/\/ Create a new file instead, must not already exist or error (permissions \/ race condition)\n\t\tnewfile, err := os.OpenFile(a.downloadFilename(t), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0644)\n\t\treturn newfile, 0, nil, err\n\t}\n\n\t\/\/ Successfully opened an existing file at this point\n\t\/\/ Read any existing data into hash then return file handle at end\n\thash := tools.NewLfsContentHash()\n\tn, err := io.Copy(hash, f)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, 0, nil, err\n\t}\n\ttracerx.Printf(\"xfer: Attempting to resume download of %q from byte %d\", t.Oid, n)\n\treturn f, n, hash, nil\n\n}\n\n\/\/ Create or open a download file for resuming\nfunc (a *basicDownloadAdapter) downloadFilename(t *Transfer) string {\n\t\/\/ Not a temp file since we will be resuming it\n\treturn filepath.Join(a.tempDir(), t.Oid+\".tmp\")\n}\n\n\/\/ download starts or resumes and download. Always closes dlFile if non-nil\nfunc (a *basicDownloadAdapter) download(t *Transfer, cb ProgressCallback, authOkFunc func(), dlFile *os.File, fromByte int64, hash hash.Hash) error {\n\tif dlFile != nil {\n\t\t\/\/ ensure we always close dlFile. Note that this does not conflict with the\n\t\t\/\/ early close below, as close is idempotent.\n\t\tdefer dlFile.Close()\n\t}\n\n\trel, err := t.Rel(\"download\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif rel == nil {\n\t\treturn errors.Errorf(\"Object %s not found on the server.\", t.Oid)\n\t}\n\n\treq, err := a.newHTTPRequest(\"GET\", rel)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fromByte > 0 {\n\t\tif dlFile == nil || hash == nil {\n\t\t\treturn fmt.Errorf(\"Cannot restart %v from %d without a file & hash\", t.Oid, fromByte)\n\t\t}\n\n\t\tif fromByte < t.Size-1 {\n\t\t\t\/\/ We could just use a start byte, but since we know the length be specific\n\t\t\treq.Header.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", fromByte, t.Size-1))\n\t\t} else {\n\t\t\t\/\/ Somehow we have more data than expected. Let's retry\n\t\t\t\/\/ from the top.\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\n\t\t\tdlFile = nil\n\t\t\tfromByte = 0\n\t\t\thash = nil\n\t\t}\n\t}\n\n\treq = a.apiClient.LogRequest(req, \"lfs.data.download\")\n\tres, err := a.makeRequest(t, req)\n\tif err != nil {\n\t\tif res == nil {\n\t\t\t\/\/ We encountered a network or similar error which caused us\n\t\t\t\/\/ to not receive a response at all.\n\t\t\treturn errors.NewRetriableError(err)\n\t\t}\n\n\t\t\/\/ Special-case status code 416 () - fall back\n\t\tif fromByte > 0 && dlFile != nil && res.StatusCode == 416 {\n\t\t\ttracerx.Printf(\"xfer: server rejected resume download request for %q from byte %d; re-downloading from start\", t.Oid, fromByte)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t}\n\n\t\t\/\/ Special-cae status code 429 - retry after certain time\n\t\tif res.StatusCode == 429 {\n\t\t\tretLaterErr := errors.NewRetriableLaterError(err, res.Header[\"Retry-After\"][0])\n\t\t\tif retLaterErr != nil {\n\t\t\t\treturn retLaterErr\n\t\t\t}\n\t\t}\n\n\t\treturn errors.NewRetriableError(err)\n\t}\n\n\tdefer res.Body.Close()\n\n\t\/\/ Range request must return 206 & content range to confirm\n\tif fromByte > 0 {\n\t\trangeRequestOk := false\n\t\tvar failReason string\n\t\t\/\/ check 206 and Content-Range, fall back if either not as expected\n\t\tif res.StatusCode == 206 {\n\t\t\t\/\/ Probably a successful range request, check Content-Range\n\t\t\tif rangeHdr := res.Header.Get(\"Content-Range\"); rangeHdr != \"\" {\n\t\t\t\tregex := regexp.MustCompile(`bytes (\\d+)\\-.*`)\n\t\t\t\tmatch := regex.FindStringSubmatch(rangeHdr)\n\t\t\t\tif match != nil && len(match) > 1 {\n\t\t\t\t\tcontentStart, _ := strconv.ParseInt(match[1], 10, 64)\n\t\t\t\t\tif contentStart == fromByte {\n\t\t\t\t\t\trangeRequestOk = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailReason = fmt.Sprintf(\"Content-Range start byte incorrect: %s expected %d\", match[1], fromByte)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfailReason = fmt.Sprintf(\"badly formatted Content-Range header: %q\", rangeHdr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfailReason = \"missing Content-Range header in response\"\n\t\t\t}\n\t\t} else {\n\t\t\tfailReason = fmt.Sprintf(\"expected status code 206, received %d\", res.StatusCode)\n\t\t}\n\t\tif rangeRequestOk {\n\t\t\ttracerx.Printf(\"xfer: server accepted resume download request: %q from byte %d\", t.Oid, fromByte)\n\t\t\tadvanceCallbackProgress(cb, t, fromByte)\n\t\t} else {\n\t\t\t\/\/ Abort resume, perform regular download\n\t\t\ttracerx.Printf(\"xfer: failed to resume download for %q from byte %d: %s. Re-downloading from start\", t.Oid, fromByte, failReason)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\tif res.StatusCode == 200 {\n\t\t\t\t\/\/ If status code was 200 then server just ignored Range header and\n\t\t\t\t\/\/ sent everything. Don't re-request, use this one from byte 0\n\t\t\t\tdlFile = nil\n\t\t\t\tfromByte = 0\n\t\t\t\thash = nil\n\t\t\t} else {\n\t\t\t\t\/\/ re-request needed\n\t\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Signal auth OK on success response, before starting download to free up\n\t\/\/ other workers immediately\n\tif authOkFunc != nil {\n\t\tauthOkFunc()\n\t}\n\n\tvar hasher *tools.HashingReader\n\thttpReader := tools.NewRetriableReader(res.Body)\n\n\tif fromByte > 0 && hash != nil {\n\t\t\/\/ pre-load hashing reader with previous content\n\t\thasher = tools.NewHashingReaderPreloadHash(httpReader, hash)\n\t} else {\n\t\thasher = tools.NewHashingReader(httpReader)\n\t}\n\n\tif dlFile == nil {\n\t\t\/\/ New file start\n\t\tdlFile, err = os.OpenFile(a.downloadFilename(t), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer dlFile.Close()\n\t}\n\tdlfilename := dlFile.Name()\n\t\/\/ Wrap callback to give name context\n\tccb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tif cb != nil {\n\t\t\treturn cb(t.Name, totalSize, readSoFar+fromByte, readSinceLast)\n\t\t}\n\t\treturn nil\n\t}\n\twritten, err := tools.CopyWithCallback(dlFile, hasher, res.ContentLength, ccb)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cannot write data to tempfile %q\", dlfilename)\n\t}\n\tif err := dlFile.Close(); err != nil {\n\t\treturn fmt.Errorf(\"can't close tempfile %q: %v\", dlfilename, err)\n\t}\n\n\tif actual := hasher.Hash(); actual != t.Oid {\n\t\treturn fmt.Errorf(\"Expected OID %s, got %s after %d bytes written\", t.Oid, actual, written)\n\t}\n\n\terr = tools.RenameFileCopyPermissions(dlfilename, t.Path)\n\tif _, err2 := os.Stat(t.Path); err2 == nil {\n\t\t\/\/ Target file already exists, possibly was downloaded by other git-lfs process\n\t\treturn nil\n\t}\n\treturn err\n}\n\nfunc configureBasicDownloadAdapter(m *Manifest) {\n\tm.RegisterNewAdapterFunc(BasicAdapterName, Download, func(name string, dir Direction) Adapter {\n\t\tswitch dir {\n\t\tcase Download:\n\t\t\tbd := &basicDownloadAdapter{newAdapterBase(m.fs, name, dir, nil)}\n\t\t\t\/\/ self implements impl\n\t\t\tbd.transferImpl = bd\n\t\t\treturn bd\n\t\tcase Upload:\n\t\t\tpanic(\"Should never ask this func to upload\")\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (a *basicDownloadAdapter) makeRequest(t *Transfer, req *http.Request) (*http.Response, error) {\n\tres, err := a.doHTTP(t, req)\n\tif errors.IsAuthError(err) && len(req.Header.Get(\"Authorization\")) == 0 {\n\t\treturn a.makeRequest(t, req)\n\t}\n\n\treturn res, err\n}\nMore robust handling of parallel attempts to download the same filepackage tq\n\nimport (\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/git-lfs\/git-lfs\/errors\"\n\t\"github.com\/git-lfs\/git-lfs\/tools\"\n\t\"github.com\/rubyist\/tracerx\"\n)\n\n\/\/ Adapter for basic HTTP downloads, includes resuming via HTTP Range\ntype basicDownloadAdapter struct {\n\t*adapterBase\n}\n\nfunc (a *basicDownloadAdapter) ClearTempStorage() error {\n\treturn os.RemoveAll(a.tempDir())\n}\n\nfunc (a *basicDownloadAdapter) tempDir() string {\n\t\/\/ Must be dedicated to this adapter as deleted by ClearTempStorage\n\t\/\/ Also make local to this repo not global, and separate to localstorage temp,\n\t\/\/ which gets cleared at the end of every invocation\n\td := filepath.Join(a.fs.LFSStorageDir, \"incomplete\")\n\tif err := tools.MkdirAll(d, a.fs); err != nil {\n\t\treturn os.TempDir()\n\t}\n\treturn d\n}\n\nfunc (a *basicDownloadAdapter) WorkerStarting(workerNum int) (interface{}, error) {\n\treturn nil, nil\n}\nfunc (a *basicDownloadAdapter) WorkerEnding(workerNum int, ctx interface{}) {\n}\n\nfunc (a *basicDownloadAdapter) DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error {\n\t\/\/ Reserve a temporary filename. We need to make sure nobody operates on the file simultaneously with us.\n\tf, err := tools.TempFile(a.tempDir(), t.Oid, a.fs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tf.Close()\n\t\t\/\/ This will delete temp file if:\n\t\t\/\/ - we failed to fully download file and move it to final location including the case when final location already\n\t\t\/\/ exists because other parallel git-lfs processes downloaded file\n\t\t\/\/ - we also failed to move it to a partially-downloaded location\n\t\tos.Remove(f.Name())\n\t}()\n\n\t\/\/ Close file because we will attempt to move partially-downloaded one on top of it\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Attempt to resume download. No error checking here. If we fail, we'll simply download from the start\n\tos.Rename(a.downloadFilename(t), f.Name())\n\n\t\/\/ Open temp file. It is either empty or partially downloaded\n\tf, err = os.OpenFile(f.Name(), os.O_RDWR, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Read any existing data into hash\n\thash := tools.NewLfsContentHash()\n\tfromByte, err := io.Copy(hash, f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Ensure that partial file seems valid\n\tif fromByte > 0 {\n\t\tif fromByte < t.Size-1 {\n\t\t\ttracerx.Printf(\"xfer: Attempting to resume download of %q from byte %d\", t.Oid, fromByte)\n\t\t} else {\n\t\t\t\/\/ Somehow we have more data than expected. Let's retry from the beginning.\n\t\t\tif _, err := f.Seek(0, io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := f.Truncate(0); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfromByte = 0\n\t\t\thash = nil\n\t\t}\n\t}\n\n\terr = a.download(t, cb, authOkFunc, f, fromByte, hash)\n\n\tif err != nil {\n\t\tf.Close()\n\t\t\/\/ Rename file so next download can resume from where we stopped.\n\t\t\/\/ No error checking here, if rename fails then file will be deleted and there just will be no download resuming\n\t\tos.Rename(f.Name(), a.downloadFilename(t))\n\t}\n\n\treturn err\n}\n\n\/\/ Returns path where partially downloaded file should be stored for download resuming\nfunc (a *basicDownloadAdapter) downloadFilename(t *Transfer) string {\n\treturn filepath.Join(a.tempDir(), t.Oid+\".part\")\n}\n\n\/\/ download starts or resumes and download. dlFile is expected to be an existing file open in RW mode\nfunc (a *basicDownloadAdapter) download(t *Transfer, cb ProgressCallback, authOkFunc func(), dlFile *os.File, fromByte int64, hash hash.Hash) error {\n\trel, err := t.Rel(\"download\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif rel == nil {\n\t\treturn errors.Errorf(\"Object %s not found on the server.\", t.Oid)\n\t}\n\n\treq, err := a.newHTTPRequest(\"GET\", rel)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fromByte > 0 {\n\t\t\/\/ We could just use a start byte, but since we know the length be specific\n\t\treq.Header.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", fromByte, t.Size-1))\n\t}\n\n\treq = a.apiClient.LogRequest(req, \"lfs.data.download\")\n\tres, err := a.makeRequest(t, req)\n\tif err != nil {\n\t\tif res == nil {\n\t\t\t\/\/ We encountered a network or similar error which caused us\n\t\t\t\/\/ to not receive a response at all.\n\t\t\treturn errors.NewRetriableError(err)\n\t\t}\n\n\t\t\/\/ Special-case status code 416 () - fall back\n\t\tif fromByte > 0 && dlFile != nil && res.StatusCode == 416 {\n\t\t\ttracerx.Printf(\"xfer: server rejected resume download request for %q from byte %d; re-downloading from start\", t.Oid, fromByte)\n\t\t\tif _, err := dlFile.Seek(0, io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := dlFile.Truncate(0); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn a.download(t, cb, authOkFunc, dlFile, 0, nil)\n\t\t}\n\n\t\t\/\/ Special-cae status code 429 - retry after certain time\n\t\tif res.StatusCode == 429 {\n\t\t\tretLaterErr := errors.NewRetriableLaterError(err, res.Header[\"Retry-After\"][0])\n\t\t\tif retLaterErr != nil {\n\t\t\t\treturn retLaterErr\n\t\t\t}\n\t\t}\n\n\t\treturn errors.NewRetriableError(err)\n\t}\n\n\tdefer res.Body.Close()\n\n\t\/\/ Range request must return 206 & content range to confirm\n\tif fromByte > 0 {\n\t\trangeRequestOk := false\n\t\tvar failReason string\n\t\t\/\/ check 206 and Content-Range, fall back if either not as expected\n\t\tif res.StatusCode == 206 {\n\t\t\t\/\/ Probably a successful range request, check Content-Range\n\t\t\tif rangeHdr := res.Header.Get(\"Content-Range\"); rangeHdr != \"\" {\n\t\t\t\tregex := regexp.MustCompile(`bytes (\\d+)\\-.*`)\n\t\t\t\tmatch := regex.FindStringSubmatch(rangeHdr)\n\t\t\t\tif match != nil && len(match) > 1 {\n\t\t\t\t\tcontentStart, _ := strconv.ParseInt(match[1], 10, 64)\n\t\t\t\t\tif contentStart == fromByte {\n\t\t\t\t\t\trangeRequestOk = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailReason = fmt.Sprintf(\"Content-Range start byte incorrect: %s expected %d\", match[1], fromByte)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfailReason = fmt.Sprintf(\"badly formatted Content-Range header: %q\", rangeHdr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfailReason = \"missing Content-Range header in response\"\n\t\t\t}\n\t\t} else {\n\t\t\tfailReason = fmt.Sprintf(\"expected status code 206, received %d\", res.StatusCode)\n\t\t}\n\t\tif rangeRequestOk {\n\t\t\ttracerx.Printf(\"xfer: server accepted resume download request: %q from byte %d\", t.Oid, fromByte)\n\t\t\tadvanceCallbackProgress(cb, t, fromByte)\n\t\t} else {\n\t\t\t\/\/ Abort resume, perform regular download\n\t\t\ttracerx.Printf(\"xfer: failed to resume download for %q from byte %d: %s. Re-downloading from start\", t.Oid, fromByte, failReason)\n\n\t\t\tif _, err := dlFile.Seek(0, io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := dlFile.Truncate(0); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfromByte = 0\n\t\t\thash = nil\n\n\t\t\tif res.StatusCode == 200 {\n\t\t\t\t\/\/ If status code was 200 then server just ignored Range header and\n\t\t\t\t\/\/ sent everything. Don't re-request, use this one from byte 0\n\t\t\t} else {\n\t\t\t\t\/\/ re-request needed\n\t\t\t\treturn a.download(t, cb, authOkFunc, dlFile, fromByte, hash)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Signal auth OK on success response, before starting download to free up\n\t\/\/ other workers immediately\n\tif authOkFunc != nil {\n\t\tauthOkFunc()\n\t}\n\n\tvar hasher *tools.HashingReader\n\thttpReader := tools.NewRetriableReader(res.Body)\n\n\tif fromByte > 0 && hash != nil {\n\t\t\/\/ pre-load hashing reader with previous content\n\t\thasher = tools.NewHashingReaderPreloadHash(httpReader, hash)\n\t} else {\n\t\thasher = tools.NewHashingReader(httpReader)\n\t}\n\n\tdlfilename := dlFile.Name()\n\t\/\/ Wrap callback to give name context\n\tccb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tif cb != nil {\n\t\t\treturn cb(t.Name, totalSize, readSoFar+fromByte, readSinceLast)\n\t\t}\n\t\treturn nil\n\t}\n\twritten, err := tools.CopyWithCallback(dlFile, hasher, res.ContentLength, ccb)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cannot write data to tempfile %q\", dlfilename)\n\t}\n\n\tif actual := hasher.Hash(); actual != t.Oid {\n\t\treturn fmt.Errorf(\"expected OID %s, got %s after %d bytes written\", t.Oid, actual, written)\n\t}\n\n\tif err := dlFile.Close(); err != nil {\n\t\treturn fmt.Errorf(\"can't close tempfile %q: %v\", dlfilename, err)\n\t}\n\n\terr = tools.RenameFileCopyPermissions(dlfilename, t.Path)\n\tif _, err2 := os.Stat(t.Path); err2 == nil {\n\t\t\/\/ Target file already exists, possibly was downloaded by other git-lfs process\n\t\treturn nil\n\t}\n\treturn err\n}\n\nfunc configureBasicDownloadAdapter(m *Manifest) {\n\tm.RegisterNewAdapterFunc(BasicAdapterName, Download, func(name string, dir Direction) Adapter {\n\t\tswitch dir {\n\t\tcase Download:\n\t\t\tbd := &basicDownloadAdapter{newAdapterBase(m.fs, name, dir, nil)}\n\t\t\t\/\/ self implements impl\n\t\t\tbd.transferImpl = bd\n\t\t\treturn bd\n\t\tcase Upload:\n\t\t\tpanic(\"Should never ask this func to upload\")\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (a *basicDownloadAdapter) makeRequest(t *Transfer, req *http.Request) (*http.Response, error) {\n\tres, err := a.doHTTP(t, req)\n\tif errors.IsAuthError(err) && len(req.Header.Get(\"Authorization\")) == 0 {\n\t\treturn a.makeRequest(t, req)\n\t}\n\n\treturn res, err\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 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\/\/ +build darwin dragonfly freebsd linux netbsd openbsd\n\npackage syscall_test\n\nimport (\n\t\"syscall\"\n\t\"testing\"\n)\n\nfunc TestRlimit(t *testing.T) {\n\tvar rlimit, zero syscall.Rlimit\n\terr := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)\n\tif err != nil {\n\t\tt.Fatalf(\"Getrlimit: save failed: %v\", err)\n\t}\n\tif zero == rlimit {\n\t\tt.Fatalf(\"Getrlimit: save failed: got zero value %#v\", rlimit)\n\t}\n\tset := rlimit\n\tset.Cur = set.Max - 1\n\terr = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &set)\n\tif err != nil {\n\t\tt.Fatalf(\"Setrlimit: set failed: %#v %v\", set, err)\n\t}\n\tvar get syscall.Rlimit\n\terr = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &get)\n\tif err != nil {\n\t\tt.Fatalf(\"Getrlimit: get failed: %v\", err)\n\t}\n\tset = rlimit\n\tset.Cur = set.Max - 1\n\tif set != get {\n\t\tt.Fatalf(\"Rlimit: change failed: wanted %#v got %#v\", set, get)\n\t}\n\terr = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)\n\tif err != nil {\n\t\tt.Fatalf(\"Setrlimit: restore failed: %#v %v\", rlimit, err)\n\t}\n}\nsyscall: fix build\/\/ Copyright 2013 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\/\/ +build darwin dragonfly freebsd linux netbsd openbsd\n\npackage syscall_test\n\nimport (\n\t\"runtime\"\n\t\"syscall\"\n\t\"testing\"\n)\n\nfunc TestRlimit(t *testing.T) {\n\tvar rlimit, zero syscall.Rlimit\n\terr := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)\n\tif err != nil {\n\t\tt.Fatalf(\"Getrlimit: save failed: %v\", err)\n\t}\n\tif zero == rlimit {\n\t\tt.Fatalf(\"Getrlimit: save failed: got zero value %#v\", rlimit)\n\t}\n\tset := rlimit\n\tset.Cur = set.Max - 1\n\terr = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &set)\n\tif err != nil {\n\t\tt.Fatalf(\"Setrlimit: set failed: %#v %v\", set, err)\n\t}\n\tvar get syscall.Rlimit\n\terr = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &get)\n\tif err != nil {\n\t\tt.Fatalf(\"Getrlimit: get failed: %v\", err)\n\t}\n\tset = rlimit\n\tset.Cur = set.Max - 1\n\tif set != get {\n\t\t\/\/ Seems like Darwin requires some privilege to\n\t\t\/\/ increse the soft limit of rlimit sandbox, though\n\t\t\/\/ Setrlimit never reports error.\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\":\n\t\tdefault:\n\t\t\tt.Fatalf(\"Rlimit: change failed: wanted %#v got %#v\", set, get)\n\t\t}\n\t}\n\terr = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)\n\tif err != nil {\n\t\tt.Fatalf(\"Setrlimit: restore failed: %#v %v\", rlimit, err)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2009 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 websocket\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"http\"\n\t\"http\/httptest\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n)\n\nvar serverAddr string\nvar once sync.Once\n\nfunc echoServer(ws *Conn) { io.Copy(ws, ws) }\n\nfunc startServer() {\n\thttp.Handle(\"\/echo\", Handler(echoServer))\n\thttp.Handle(\"\/echoDraft75\", Draft75Handler(echoServer))\n\tserver := httptest.NewServer(nil)\n\tserverAddr = server.Listener.Addr().String()\n\tlog.Print(\"Test WebSocket server listening on \", serverAddr)\n}\n\n\/\/ Test the getChallengeResponse function with values from section\n\/\/ 5.1 of the specification steps 18, 26, and 43 from\n\/\/ http:\/\/www.whatwg.org\/specs\/web-socket-protocol\/\nfunc TestChallenge(t *testing.T) {\n\tvar part1 uint32 = 777007543\n\tvar part2 uint32 = 114997259\n\tkey3 := []byte{0x47, 0x30, 0x22, 0x2D, 0x5A, 0x3F, 0x47, 0x58}\n\texpected := []byte(\"0st3Rl&q-2ZU^weu\")\n\n\tresponse, err := getChallengeResponse(part1, part2, key3)\n\tif err != nil {\n\t\tt.Errorf(\"getChallengeResponse: returned error %v\", err)\n\t\treturn\n\t}\n\tif !bytes.Equal(expected, response) {\n\t\tt.Errorf(\"getChallengeResponse: expected %q got %q\", expected, response)\n\t}\n}\n\nfunc TestEcho(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake error: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: %v\", err)\n\t}\n\tvar actual_msg = make([]byte, 512)\n\tn, err := ws.Read(actual_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tactual_msg = actual_msg[0:n]\n\tif !bytes.Equal(msg, actual_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg, actual_msg)\n\t}\n\tws.Close()\n}\n\nfunc TestEchoDraft75(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echoDraft75\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echoDraft75\", \"\", client, draft75handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: error %v\", err)\n\t}\n\tvar actual_msg = make([]byte, 512)\n\tn, err := ws.Read(actual_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: error %v\", err)\n\t}\n\tactual_msg = actual_msg[0:n]\n\tif !bytes.Equal(msg, actual_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg, actual_msg)\n\t}\n\tws.Close()\n}\n\nfunc TestWithQuery(t *testing.T) {\n\tonce.Do(startServer)\n\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\n\tws, err := newClient(\"\/echo?q=v\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo?q=v\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\tws.Close()\n}\n\nfunc TestWithProtocol(t *testing.T) {\n\tonce.Do(startServer)\n\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"test\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\tws.Close()\n}\n\nfunc TestHTTP(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ If the client did not send a handshake that matches the protocol\n\t\/\/ specification, the server should abort the WebSocket connection.\n\t_, _, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/echo\", serverAddr))\n\tif err == nil {\n\t\tt.Error(\"Get: unexpected success\")\n\t\treturn\n\t}\n\turlerr, ok := err.(*http.URLError)\n\tif !ok {\n\t\tt.Errorf(\"Get: not URLError %#v\", err)\n\t\treturn\n\t}\n\tif urlerr.Error != io.ErrUnexpectedEOF {\n\t\tt.Errorf(\"Get: error %#v\", err)\n\t\treturn\n\t}\n}\n\nfunc TestHTTPDraft75(t *testing.T) {\n\tonce.Do(startServer)\n\n\tr, _, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/echoDraft75\", serverAddr))\n\tif err != nil {\n\t\tt.Errorf(\"Get: error %#v\", err)\n\t\treturn\n\t}\n\tif r.StatusCode != http.StatusBadRequest {\n\t\tt.Errorf(\"Get: got status %d\", r.StatusCode)\n\t}\n}\n\nfunc TestTrailingSpaces(t *testing.T) {\n\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=955\n\t\/\/ The last runs of this create keys with trailing spaces that should not be\n\t\/\/ generated by the client.\n\tonce.Do(startServer)\n\tfor i := 0; i < 30; i++ {\n\t\t\/\/ body\n\t\t_, err := Dial(fmt.Sprintf(\"ws:\/\/%s\/echo\", serverAddr), \"\",\n\t\t\t\"http:\/\/localhost\/\")\n\t\tif err != nil {\n\t\t\tpanic(\"Dial failed: \" + err.String())\n\t\t}\n\t}\n}\n\nfunc TestSmallBuffer(t *testing.T) {\n\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=1145\n\t\/\/ Read should be able to handle reading a fragment of a frame.\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake error: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: %v\", err)\n\t}\n\tvar small_msg = make([]byte, 8)\n\tn, err := ws.Read(small_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(msg[:len(small_msg)], small_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg[:len(small_msg)], small_msg)\n\t}\n\tvar second_msg = make([]byte, len(msg))\n\tn, err = ws.Read(second_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tsecond_msg = second_msg[0:n]\n\tif !bytes.Equal(msg[len(small_msg):], second_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg[len(small_msg):], second_msg)\n\t}\n\tws.Close()\n\n}\n\nfunc testSkipLengthFrame(t *testing.T) {\n\tb := []byte{'\\x80', '\\x01', 'x', 0, 'h', 'e', 'l', 'l', 'o', '\\xff'}\n\tbuf := bytes.NewBuffer(b)\n\tbr := bufio.NewReader(buf)\n\tbw := bufio.NewWriter(buf)\n\tws := newConn(\"http:\/\/127.0.0.1\/\", \"ws:\/\/127.0.0.1\/\", \"\", bufio.NewReadWriter(br, bw), nil)\n\tmsg := make([]byte, 5)\n\tn, err := ws.Read(msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(b[4:8], msg[0:n]) {\n\t\tt.Errorf(\"Read: expected %q got %q\", msg[4:8], msg[0:n])\n\t}\n}\n\nfunc testSkipNoUTF8Frame(t *testing.T) {\n\tb := []byte{'\\x01', 'n', '\\xff', 0, 'h', 'e', 'l', 'l', 'o', '\\xff'}\n\tbuf := bytes.NewBuffer(b)\n\tbr := bufio.NewReader(buf)\n\tbw := bufio.NewWriter(buf)\n\tws := newConn(\"http:\/\/127.0.0.1\/\", \"ws:\/\/127.0.0.1\/\", \"\", bufio.NewReadWriter(br, bw), nil)\n\tmsg := make([]byte, 5)\n\tn, err := ws.Read(msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(b[4:8], msg[0:n]) {\n\t\tt.Errorf(\"Read: expected %q got %q\", msg[4:8], msg[0:n])\n\t}\n}\nwebsocket: fix socket leak in test\/\/ Copyright 2009 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 websocket\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"http\"\n\t\"http\/httptest\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n)\n\nvar serverAddr string\nvar once sync.Once\n\nfunc echoServer(ws *Conn) { io.Copy(ws, ws) }\n\nfunc startServer() {\n\thttp.Handle(\"\/echo\", Handler(echoServer))\n\thttp.Handle(\"\/echoDraft75\", Draft75Handler(echoServer))\n\tserver := httptest.NewServer(nil)\n\tserverAddr = server.Listener.Addr().String()\n\tlog.Print(\"Test WebSocket server listening on \", serverAddr)\n}\n\n\/\/ Test the getChallengeResponse function with values from section\n\/\/ 5.1 of the specification steps 18, 26, and 43 from\n\/\/ http:\/\/www.whatwg.org\/specs\/web-socket-protocol\/\nfunc TestChallenge(t *testing.T) {\n\tvar part1 uint32 = 777007543\n\tvar part2 uint32 = 114997259\n\tkey3 := []byte{0x47, 0x30, 0x22, 0x2D, 0x5A, 0x3F, 0x47, 0x58}\n\texpected := []byte(\"0st3Rl&q-2ZU^weu\")\n\n\tresponse, err := getChallengeResponse(part1, part2, key3)\n\tif err != nil {\n\t\tt.Errorf(\"getChallengeResponse: returned error %v\", err)\n\t\treturn\n\t}\n\tif !bytes.Equal(expected, response) {\n\t\tt.Errorf(\"getChallengeResponse: expected %q got %q\", expected, response)\n\t}\n}\n\nfunc TestEcho(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake error: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: %v\", err)\n\t}\n\tvar actual_msg = make([]byte, 512)\n\tn, err := ws.Read(actual_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tactual_msg = actual_msg[0:n]\n\tif !bytes.Equal(msg, actual_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg, actual_msg)\n\t}\n\tws.Close()\n}\n\nfunc TestEchoDraft75(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echoDraft75\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echoDraft75\", \"\", client, draft75handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: error %v\", err)\n\t}\n\tvar actual_msg = make([]byte, 512)\n\tn, err := ws.Read(actual_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: error %v\", err)\n\t}\n\tactual_msg = actual_msg[0:n]\n\tif !bytes.Equal(msg, actual_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg, actual_msg)\n\t}\n\tws.Close()\n}\n\nfunc TestWithQuery(t *testing.T) {\n\tonce.Do(startServer)\n\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\n\tws, err := newClient(\"\/echo?q=v\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo?q=v\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\tws.Close()\n}\n\nfunc TestWithProtocol(t *testing.T) {\n\tonce.Do(startServer)\n\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"test\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake: %v\", err)\n\t\treturn\n\t}\n\tws.Close()\n}\n\nfunc TestHTTP(t *testing.T) {\n\tonce.Do(startServer)\n\n\t\/\/ If the client did not send a handshake that matches the protocol\n\t\/\/ specification, the server should abort the WebSocket connection.\n\t_, _, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/echo\", serverAddr))\n\tif err == nil {\n\t\tt.Error(\"Get: unexpected success\")\n\t\treturn\n\t}\n\turlerr, ok := err.(*http.URLError)\n\tif !ok {\n\t\tt.Errorf(\"Get: not URLError %#v\", err)\n\t\treturn\n\t}\n\tif urlerr.Error != io.ErrUnexpectedEOF {\n\t\tt.Errorf(\"Get: error %#v\", err)\n\t\treturn\n\t}\n}\n\nfunc TestHTTPDraft75(t *testing.T) {\n\tonce.Do(startServer)\n\n\tr, _, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/echoDraft75\", serverAddr))\n\tif err != nil {\n\t\tt.Errorf(\"Get: error %#v\", err)\n\t\treturn\n\t}\n\tif r.StatusCode != http.StatusBadRequest {\n\t\tt.Errorf(\"Get: got status %d\", r.StatusCode)\n\t}\n}\n\nfunc TestTrailingSpaces(t *testing.T) {\n\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=955\n\t\/\/ The last runs of this create keys with trailing spaces that should not be\n\t\/\/ generated by the client.\n\tonce.Do(startServer)\n\tfor i := 0; i < 30; i++ {\n\t\t\/\/ body\n\t\tws, err := Dial(fmt.Sprintf(\"ws:\/\/%s\/echo\", serverAddr), \"\", \"http:\/\/localhost\/\")\n\t\tif err != nil {\n\t\t\tt.Error(\"Dial failed:\", err.String())\n\t\t\tbreak\n\t\t}\n\t\tws.Close()\n\t}\n}\n\nfunc TestSmallBuffer(t *testing.T) {\n\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=1145\n\t\/\/ Read should be able to handle reading a fragment of a frame.\n\tonce.Do(startServer)\n\n\t\/\/ websocket.Dial()\n\tclient, err := net.Dial(\"tcp\", serverAddr)\n\tif err != nil {\n\t\tt.Fatal(\"dialing\", err)\n\t}\n\tws, err := newClient(\"\/echo\", \"localhost\", \"http:\/\/localhost\",\n\t\t\"ws:\/\/localhost\/echo\", \"\", client, handshake)\n\tif err != nil {\n\t\tt.Errorf(\"WebSocket handshake error: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := []byte(\"hello, world\\n\")\n\tif _, err := ws.Write(msg); err != nil {\n\t\tt.Errorf(\"Write: %v\", err)\n\t}\n\tvar small_msg = make([]byte, 8)\n\tn, err := ws.Read(small_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(msg[:len(small_msg)], small_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg[:len(small_msg)], small_msg)\n\t}\n\tvar second_msg = make([]byte, len(msg))\n\tn, err = ws.Read(second_msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tsecond_msg = second_msg[0:n]\n\tif !bytes.Equal(msg[len(small_msg):], second_msg) {\n\t\tt.Errorf(\"Echo: expected %q got %q\", msg[len(small_msg):], second_msg)\n\t}\n\tws.Close()\n\n}\n\nfunc testSkipLengthFrame(t *testing.T) {\n\tb := []byte{'\\x80', '\\x01', 'x', 0, 'h', 'e', 'l', 'l', 'o', '\\xff'}\n\tbuf := bytes.NewBuffer(b)\n\tbr := bufio.NewReader(buf)\n\tbw := bufio.NewWriter(buf)\n\tws := newConn(\"http:\/\/127.0.0.1\/\", \"ws:\/\/127.0.0.1\/\", \"\", bufio.NewReadWriter(br, bw), nil)\n\tmsg := make([]byte, 5)\n\tn, err := ws.Read(msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(b[4:8], msg[0:n]) {\n\t\tt.Errorf(\"Read: expected %q got %q\", msg[4:8], msg[0:n])\n\t}\n}\n\nfunc testSkipNoUTF8Frame(t *testing.T) {\n\tb := []byte{'\\x01', 'n', '\\xff', 0, 'h', 'e', 'l', 'l', 'o', '\\xff'}\n\tbuf := bytes.NewBuffer(b)\n\tbr := bufio.NewReader(buf)\n\tbw := bufio.NewWriter(buf)\n\tws := newConn(\"http:\/\/127.0.0.1\/\", \"ws:\/\/127.0.0.1\/\", \"\", bufio.NewReadWriter(br, bw), nil)\n\tmsg := make([]byte, 5)\n\tn, err := ws.Read(msg)\n\tif err != nil {\n\t\tt.Errorf(\"Read: %v\", err)\n\t}\n\tif !bytes.Equal(b[4:8], msg[0:n]) {\n\t\tt.Errorf(\"Read: expected %q got %q\", msg[4:8], msg[0:n])\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Krister Svanlund\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\/\/ The rest\/utils package supplies some tools that are useful when processing\n\/\/ REST requests and generating their responses.\npackage utils\n\nimport (\n \"github.com\/gorilla\/mux\"\n \"net\/http\"\n \"strconv\"\n \/\/ \"strings\"\n)\n\nvar (\n prevrequest = map[string]uint64{}\n)\n\n\/\/ Check if a certain request is a PUT and has a txnId in their request. If it\n\/\/ does and the access token of the requests hasn't already made a request with\n\/\/ the same txnId `true` is returned, otherwise `false`.\nfunc CheckTxnId(r *http.Request) bool {\n vars := mux.Vars(r)\n token := r.URL.Query().Get(\"access_token\")\n if stxnId := vars[\"txnId\"]; r.Method == \"PUT\" && stxnId != \"\" {\n if txnId, err := strconv.ParseUint(stxnId, 10, 64); err == nil {\n \/\/ ip := strings.Split(r.RemoteAddr, \":\")[0]\n \/\/ if prevrequest[ip] == txnId {\n if prevrequest[token] == txnId {\n return false\n } else {\n \/\/ prevrequest[ip] = txnId\n prevrequest[token] = txnId\n }\n }\n }\n return true\n}\n\n\/\/ By calling this in a request handler the http:\/\/matrix.org live test tool\n\/\/ is able to make requests.\nfunc AllowMatrixOrg(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"http:\/\/matrix.org\")\n w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n w.WriteHeader(200)\n}\nEnsure that the TxnID check doesn't panic\/\/ Copyright 2014 Krister Svanlund\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\/\/ The rest\/utils package supplies some tools that are useful when processing\n\/\/ REST requests and generating their responses.\npackage utils\n\nimport (\n \"github.com\/gorilla\/mux\"\n \"net\/http\"\n \"strconv\"\n \/\/ \"strings\"\n)\n\nvar (\n prevrequest = map[string]uint64{}\n)\n\n\/\/ Check if a certain request is a PUT and has a txnId in their request. If it\n\/\/ does and the access token of the requests hasn't already made a request with\n\/\/ the same txnId `true` is returned, otherwise `false`.\nfunc CheckTxnId(r *http.Request) bool {\n vars := mux.Vars(r)\n token := r.URL.Query().Get(\"access_token\")\n if stxnId, ok := vars[\"txnId\"]; ok && r.Method == \"PUT\" && stxnId != \"\" {\n if txnId, err := strconv.ParseUint(stxnId, 10, 64); err == nil {\n \/\/ ip := strings.Split(r.RemoteAddr, \":\")[0]\n \/\/ if prevrequest[ip] == txnId {\n if prevrequest[token] == txnId {\n return false\n } else {\n \/\/ prevrequest[ip] = txnId\n prevrequest[token] = txnId\n }\n }\n }\n return true\n}\n\n\/\/ By calling this in a request handler the http:\/\/matrix.org live test tool\n\/\/ is able to make requests.\nfunc AllowMatrixOrg(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"http:\/\/matrix.org\")\n w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n w.WriteHeader(200)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/go:build !gogit\n\/\/ +build !gogit\n\npackage pipeline\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"code.gitea.io\/gitea\/modules\/git\"\n)\n\n\/\/ LFSResult represents commits found using a provided pointer file hash\ntype LFSResult struct {\n\tName string\n\tSHA string\n\tSummary string\n\tWhen time.Time\n\tParentHashes []git.SHA1\n\tBranchName string\n\tFullCommitName string\n}\n\ntype lfsResultSlice []*LFSResult\n\nfunc (a lfsResultSlice) Len() int { return len(a) }\nfunc (a lfsResultSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a lfsResultSlice) Less(i, j int) bool { return a[j].When.After(a[i].When) }\n\n\/\/ FindLFSFile finds commits that contain a provided pointer file hash\nfunc FindLFSFile(repo *git.Repository, hash git.SHA1) ([]*LFSResult, error) {\n\tresultsMap := map[string]*LFSResult{}\n\tresults := make([]*LFSResult, 0)\n\n\tbasePath := repo.Path\n\n\t\/\/ Use rev-list to provide us with all commits in order\n\trevListReader, revListWriter := io.Pipe()\n\tdefer func() {\n\t\t_ = revListWriter.Close()\n\t\t_ = revListReader.Close()\n\t}()\n\n\tgo func() {\n\t\tstderr := strings.Builder{}\n\t\terr := git.NewCommand(\"rev-list\", \"--all\").RunInDirPipeline(repo.Path, revListWriter, &stderr)\n\t\tif err != nil {\n\t\t\t_ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String()))\n\t\t} else {\n\t\t\t_ = revListWriter.Close()\n\t\t}\n\t}()\n\n\t\/\/ Next feed the commits in order into cat-file --batch, followed by their trees and sub trees as necessary.\n\t\/\/ so let's create a batch stdin and stdout\n\tbatchStdinWriter, batchReader, cancel := repo.CatFileBatch()\n\tdefer cancel()\n\n\t\/\/ We'll use a scanner for the revList because it's simpler than a bufio.Reader\n\tscan := bufio.NewScanner(revListReader)\n\ttrees := [][]byte{}\n\tpaths := []string{}\n\n\tfnameBuf := make([]byte, 4096)\n\tmodeBuf := make([]byte, 40)\n\tworkingShaBuf := make([]byte, 20)\n\n\tfor scan.Scan() {\n\t\t\/\/ Get the next commit ID\n\t\tcommitID := scan.Bytes()\n\n\t\t\/\/ push the commit to the cat-file --batch process\n\t\t_, err := batchStdinWriter.Write(commitID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, err = batchStdinWriter.Write([]byte{'\\n'})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar curCommit *git.Commit\n\t\tcurPath := \"\"\n\n\tcommitReadingLoop:\n\t\tfor {\n\t\t\t_, typ, size, err := git.ReadBatchLine(batchReader)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tswitch typ {\n\t\t\tcase \"tag\":\n\t\t\t\t\/\/ This shouldn't happen but if it does well just get the commit and try again\n\t\t\t\tid, err := git.ReadTagObjectID(batchReader, size)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t_, err = batchStdinWriter.Write([]byte(id + \"\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"commit\":\n\t\t\t\t\/\/ Read in the commit to get its tree and in case this is one of the last used commits\n\t\t\t\tcurCommit, err = git.CommitFromReader(repo, git.MustIDFromString(string(commitID)), io.LimitReader(batchReader, int64(size)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif _, err := batchReader.Discard(1); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t_, err := batchStdinWriter.Write([]byte(curCommit.Tree.ID.String() + \"\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcurPath = \"\"\n\t\t\tcase \"tree\":\n\t\t\t\tvar n int64\n\t\t\t\tfor n < size {\n\t\t\t\t\tmode, fname, sha20byte, count, err := git.ParseTreeLine(batchReader, modeBuf, fnameBuf, workingShaBuf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tn += int64(count)\n\t\t\t\t\tif bytes.Equal(sha20byte, hash[:]) {\n\t\t\t\t\t\tresult := LFSResult{\n\t\t\t\t\t\t\tName: curPath + string(fname),\n\t\t\t\t\t\t\tSHA: curCommit.ID.String(),\n\t\t\t\t\t\t\tSummary: strings.Split(strings.TrimSpace(curCommit.CommitMessage), \"\\n\")[0],\n\t\t\t\t\t\t\tWhen: curCommit.Author.When,\n\t\t\t\t\t\t\tParentHashes: curCommit.Parents,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresultsMap[curCommit.ID.String()+\":\"+curPath+string(fname)] = &result\n\t\t\t\t\t} else if string(mode) == git.EntryModeTree.String() {\n\t\t\t\t\t\tsha40Byte := make([]byte, 40)\n\t\t\t\t\t\tgit.To40ByteSHA(sha20byte, sha40Byte)\n\t\t\t\t\t\ttrees = append(trees, sha40Byte)\n\t\t\t\t\t\tpaths = append(paths, curPath+string(fname)+\"\/\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif _, err := batchReader.Discard(1); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif len(trees) > 0 {\n\t\t\t\t\t_, err := batchStdinWriter.Write(trees[len(trees)-1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\t_, err = batchStdinWriter.Write([]byte(\"\\n\"))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tcurPath = paths[len(paths)-1]\n\t\t\t\t\ttrees = trees[:len(trees)-1]\n\t\t\t\t\tpaths = paths[:len(paths)-1]\n\t\t\t\t} else {\n\t\t\t\t\tbreak commitReadingLoop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := scan.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, result := range resultsMap {\n\t\thasParent := false\n\t\tfor _, parentHash := range result.ParentHashes {\n\t\t\tif _, hasParent = resultsMap[parentHash.String()+\":\"+result.Name]; hasParent {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hasParent {\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\tsort.Sort(lfsResultSlice(results))\n\n\t\/\/ Should really use a go-git function here but name-rev is not completed and recapitulating it is not simple\n\tshasToNameReader, shasToNameWriter := io.Pipe()\n\tnameRevStdinReader, nameRevStdinWriter := io.Pipe()\n\terrChan := make(chan error, 1)\n\twg := sync.WaitGroup{}\n\twg.Add(3)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tscanner := bufio.NewScanner(nameRevStdinReader)\n\t\ti := 0\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif len(line) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult := results[i]\n\t\t\tresult.FullCommitName = line\n\t\t\tresult.BranchName = strings.Split(line, \"~\")[0]\n\t\t\ti++\n\t\t}\n\t}()\n\tgo NameRevStdin(shasToNameReader, nameRevStdinWriter, &wg, basePath)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer shasToNameWriter.Close()\n\t\tfor _, result := range results {\n\t\t\ti := 0\n\t\t\tif i < len(result.SHA) {\n\t\t\t\tn, err := shasToNameWriter.Write([]byte(result.SHA)[i:])\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ti += n\n\t\t\t}\n\t\t\tvar err error\n\t\t\tn := 0\n\t\t\tfor n < 1 {\n\t\t\t\tn, err = shasToNameWriter.Write([]byte{'\\n'})\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tselect {\n\tcase err, has := <-errChan:\n\t\tif has {\n\t\t\treturn nil, fmt.Errorf(\"Unable to obtain name for LFS files. Error: %w\", err)\n\t\t}\n\tdefault:\n\t}\n\n\treturn results, nil\n}\nSimplify code for wrting SHA to name-rev (#17696)\/\/ Copyright 2020 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/go:build !gogit\n\/\/ +build !gogit\n\npackage pipeline\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"code.gitea.io\/gitea\/modules\/git\"\n)\n\n\/\/ LFSResult represents commits found using a provided pointer file hash\ntype LFSResult struct {\n\tName string\n\tSHA string\n\tSummary string\n\tWhen time.Time\n\tParentHashes []git.SHA1\n\tBranchName string\n\tFullCommitName string\n}\n\ntype lfsResultSlice []*LFSResult\n\nfunc (a lfsResultSlice) Len() int { return len(a) }\nfunc (a lfsResultSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a lfsResultSlice) Less(i, j int) bool { return a[j].When.After(a[i].When) }\n\n\/\/ FindLFSFile finds commits that contain a provided pointer file hash\nfunc FindLFSFile(repo *git.Repository, hash git.SHA1) ([]*LFSResult, error) {\n\tresultsMap := map[string]*LFSResult{}\n\tresults := make([]*LFSResult, 0)\n\n\tbasePath := repo.Path\n\n\t\/\/ Use rev-list to provide us with all commits in order\n\trevListReader, revListWriter := io.Pipe()\n\tdefer func() {\n\t\t_ = revListWriter.Close()\n\t\t_ = revListReader.Close()\n\t}()\n\n\tgo func() {\n\t\tstderr := strings.Builder{}\n\t\terr := git.NewCommand(\"rev-list\", \"--all\").RunInDirPipeline(repo.Path, revListWriter, &stderr)\n\t\tif err != nil {\n\t\t\t_ = revListWriter.CloseWithError(git.ConcatenateError(err, (&stderr).String()))\n\t\t} else {\n\t\t\t_ = revListWriter.Close()\n\t\t}\n\t}()\n\n\t\/\/ Next feed the commits in order into cat-file --batch, followed by their trees and sub trees as necessary.\n\t\/\/ so let's create a batch stdin and stdout\n\tbatchStdinWriter, batchReader, cancel := repo.CatFileBatch()\n\tdefer cancel()\n\n\t\/\/ We'll use a scanner for the revList because it's simpler than a bufio.Reader\n\tscan := bufio.NewScanner(revListReader)\n\ttrees := [][]byte{}\n\tpaths := []string{}\n\n\tfnameBuf := make([]byte, 4096)\n\tmodeBuf := make([]byte, 40)\n\tworkingShaBuf := make([]byte, 20)\n\n\tfor scan.Scan() {\n\t\t\/\/ Get the next commit ID\n\t\tcommitID := scan.Bytes()\n\n\t\t\/\/ push the commit to the cat-file --batch process\n\t\t_, err := batchStdinWriter.Write(commitID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, err = batchStdinWriter.Write([]byte{'\\n'})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar curCommit *git.Commit\n\t\tcurPath := \"\"\n\n\tcommitReadingLoop:\n\t\tfor {\n\t\t\t_, typ, size, err := git.ReadBatchLine(batchReader)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tswitch typ {\n\t\t\tcase \"tag\":\n\t\t\t\t\/\/ This shouldn't happen but if it does well just get the commit and try again\n\t\t\t\tid, err := git.ReadTagObjectID(batchReader, size)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t_, err = batchStdinWriter.Write([]byte(id + \"\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"commit\":\n\t\t\t\t\/\/ Read in the commit to get its tree and in case this is one of the last used commits\n\t\t\t\tcurCommit, err = git.CommitFromReader(repo, git.MustIDFromString(string(commitID)), io.LimitReader(batchReader, int64(size)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif _, err := batchReader.Discard(1); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t_, err := batchStdinWriter.Write([]byte(curCommit.Tree.ID.String() + \"\\n\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcurPath = \"\"\n\t\t\tcase \"tree\":\n\t\t\t\tvar n int64\n\t\t\t\tfor n < size {\n\t\t\t\t\tmode, fname, sha20byte, count, err := git.ParseTreeLine(batchReader, modeBuf, fnameBuf, workingShaBuf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tn += int64(count)\n\t\t\t\t\tif bytes.Equal(sha20byte, hash[:]) {\n\t\t\t\t\t\tresult := LFSResult{\n\t\t\t\t\t\t\tName: curPath + string(fname),\n\t\t\t\t\t\t\tSHA: curCommit.ID.String(),\n\t\t\t\t\t\t\tSummary: strings.Split(strings.TrimSpace(curCommit.CommitMessage), \"\\n\")[0],\n\t\t\t\t\t\t\tWhen: curCommit.Author.When,\n\t\t\t\t\t\t\tParentHashes: curCommit.Parents,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresultsMap[curCommit.ID.String()+\":\"+curPath+string(fname)] = &result\n\t\t\t\t\t} else if string(mode) == git.EntryModeTree.String() {\n\t\t\t\t\t\tsha40Byte := make([]byte, 40)\n\t\t\t\t\t\tgit.To40ByteSHA(sha20byte, sha40Byte)\n\t\t\t\t\t\ttrees = append(trees, sha40Byte)\n\t\t\t\t\t\tpaths = append(paths, curPath+string(fname)+\"\/\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif _, err := batchReader.Discard(1); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif len(trees) > 0 {\n\t\t\t\t\t_, err := batchStdinWriter.Write(trees[len(trees)-1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\t_, err = batchStdinWriter.Write([]byte(\"\\n\"))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tcurPath = paths[len(paths)-1]\n\t\t\t\t\ttrees = trees[:len(trees)-1]\n\t\t\t\t\tpaths = paths[:len(paths)-1]\n\t\t\t\t} else {\n\t\t\t\t\tbreak commitReadingLoop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := scan.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, result := range resultsMap {\n\t\thasParent := false\n\t\tfor _, parentHash := range result.ParentHashes {\n\t\t\tif _, hasParent = resultsMap[parentHash.String()+\":\"+result.Name]; hasParent {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hasParent {\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\tsort.Sort(lfsResultSlice(results))\n\n\t\/\/ Should really use a go-git function here but name-rev is not completed and recapitulating it is not simple\n\tshasToNameReader, shasToNameWriter := io.Pipe()\n\tnameRevStdinReader, nameRevStdinWriter := io.Pipe()\n\terrChan := make(chan error, 1)\n\twg := sync.WaitGroup{}\n\twg.Add(3)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tscanner := bufio.NewScanner(nameRevStdinReader)\n\t\ti := 0\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif len(line) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult := results[i]\n\t\t\tresult.FullCommitName = line\n\t\t\tresult.BranchName = strings.Split(line, \"~\")[0]\n\t\t\ti++\n\t\t}\n\t}()\n\tgo NameRevStdin(shasToNameReader, nameRevStdinWriter, &wg, basePath)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer shasToNameWriter.Close()\n\t\tfor _, result := range results {\n\t\t\t_, err := shasToNameWriter.Write([]byte(result.SHA))\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t_, err = shasToNameWriter.Write([]byte{'\\n'})\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tselect {\n\tcase err, has := <-errChan:\n\t\tif has {\n\t\t\treturn nil, fmt.Errorf(\"Unable to obtain name for LFS files. Error: %w\", err)\n\t\t}\n\tdefault:\n\t}\n\n\treturn results, nil\n}\n<|endoftext|>"} {"text":"\/\/ +build tools\n\n\/*\nCopyright 2019 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 hack\n\n\/\/ Add tools that hack scripts depend on here, to ensure they are vendored.\nimport (\n\t_ \"github.com\/bazelbuild\/bazel-gazelle\/cmd\/gazelle\"\n\t_ \"github.com\/client9\/misspell\/cmd\/misspell\"\n\t_ \"k8s.io\/code-generator\/cmd\/client-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/deepcopy-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/informer-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/lister-gen\"\n\t_ \"k8s.io\/repo-infra\/cmd\/kazel\"\n)\nRemove tools that repo-infra now handles\/\/ +build tools\n\n\/*\nCopyright 2019 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 hack\n\n\/\/ Add tools that hack scripts depend on here, to ensure they are vendored.\nimport (\n\t_ \"github.com\/client9\/misspell\/cmd\/misspell\"\n\t_ \"k8s.io\/code-generator\/cmd\/client-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/deepcopy-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/informer-gen\"\n\t_ \"k8s.io\/code-generator\/cmd\/lister-gen\"\n)\n<|endoftext|>"} {"text":"package LevenshteinTrie\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"unicode\/utf8\"\n)\n\nfunc Min(a ...int) int {\n\tmin := int(^uint(0) >> 1) \/\/ largest int\n\tfor _, i := range a {\n\t\tif i < min {\n\t\t\tmin = i\n\t\t}\n\t}\n\treturn min\n}\nfunc Max(a ...int) int {\n\tmax := int(0)\n\tfor _, i := range a {\n\t\tif i > max {\n\t\t\tmax = i\n\t\t}\n\t}\n\treturn max\n}\n\ntype TrieNode struct {\n\tletter rune \/\/Equivalent to int32\n\tchildren map[rune]*TrieNode\n\tfinal bool\n\ttext string\n}\n\nfunc NewTrie() *TrieNode {\n\treturn &TrieNode{children: make(map[rune]*TrieNode)}\n}\n\nfunc (root *TrieNode) InsertText(text string) {\n\n\tif root == nil {\n\t\treturn\n\t}\n\n\tcurrNode := root \/\/Starts at root\n\tfor i, w := 0, 0; i < len(text); i += w {\n\t\truneValue, width := utf8.DecodeRuneInString(text[i:])\n\t\tfinal := false\n\t\tif width+i == len(text) {\n\t\t\tfinal = true\n\t\t}\n\t\tw = width\n\n\t\tcurrNode = NewTrieNode(currNode, runeValue, final, text)\n\t}\n}\n\nfunc NewTrieNode(t *TrieNode, runeValue rune, final bool, text string) *TrieNode {\n\tnode, exists := t.children[runeValue]\n\tif exists {\n\t\tif final {\n\t\t\tnode.final = true\n\t\t\tnode.text = text\n\t\t}\n\t\treturn node\n\t} else {\n\t\tnode = &TrieNode{letter: runeValue, children: make(map[rune]*TrieNode)}\n\t\tt.children[runeValue] = node\n\t\treturn node\n\t}\n\treturn nil\n}\n\nfunc (t *TrieNode) SearchSuffix(query string) []string {\n\n\tvar curr *TrieNode\n\tvar ok bool\n\t\/\/first, find the end of the prefix\n\tfor _, letter := range query {\n\t\tif curr != nil {\n\t\t\tif curr, ok = curr.children[letter]; ok {\n\t\t\t\t\/\/do nothing\n\t\t\t}\n\n\t\t}\n\t}\n\n\tcandidates := make([]string, 0)\n\n\tvar getAllSuffixes func(n *TrieNode)\n\tgetAllSuffixes = func(n *TrieNode) {\n\t\tif n == nil {\n\t\t\treturn\n\t\t}\n\t\tif n.final == true {\n\t\t\tcandidates = append(candidates, n.text)\n\t\t}\n\n\t\tfor _, childNode := range n.children {\n\t\t\tgetAllSuffixes(childNode)\n\t\t}\n\n\t}\n\tgetAllSuffixes(curr)\n\n\treturn candidates\n}\n\ntype QueryResult struct {\n\tVal string\n\tDistance int\n}\n\nfunc (q QueryResult) String() string {\n\treturn fmt.Sprintf(\"Val: %s\\n\", q.Val)\n}\n\ntype ByDistance []QueryResult\n\nfunc (a ByDistance) Len() int { return len(a) }\nfunc (a ByDistance) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByDistance) Less(i, j int) bool { return a[i].Distance < a[j].Distance }\n\nfunc (n *TrieNode) SearchLevenshtein(text string, distance int) []QueryResult {\n\n\t\/\/initialize the first row for the dynamic programming alg\n\tl := utf8.RuneCount([]byte(text))\n\tcurrentRow := make([]int, l+1)\n\n\tfor i := 0; i < len(currentRow); i++ {\n\t\tcurrentRow[i] = i\n\t}\n\n\tcandidates := make([]QueryResult, 0)\n\n\tvar searchRecursive func(n *TrieNode, prevRow []int, letter rune, text []rune, maxDistance int)\n\tsearchRecursive = func(n *TrieNode, prevRow []int, letter rune, text []rune, maxDistance int) {\n\t\tcolumns := len(text) + 1\n\t\tcurrentRow := make([]int, columns)\n\n\t\tcurrentRow[0] = prevRow[0] + 1\n\n\t\tfor col := 1; col < columns; col++ {\n\t\t\tinsertCost := currentRow[col-1] + 1\n\t\t\tdeleteCost := currentRow[col] + 1\n\t\t\tvar replaceCost int\n\t\t\tif text[col-1] != letter {\n\t\t\t\tif text[col-1] != letter {\n\t\t\t\t\treplaceCost = prevRow[col-1] + 1\n\t\t\t\t} else {\n\t\t\t\t\treplaceCost = prevRow[col-1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentRow[col] = Min(insertCost, deleteCost, replaceCost)\n\t\t}\n\n\t\tdistance := currentRow[len(currentRow)-1]\n\t\tif distance <= maxDistance && len(n.text) > 0 {\n\t\t\tcandidates = append(candidates, QueryResult{Val: n.text, Distance: distance})\n\t\t}\n\n\t\tif Min(currentRow...) <= maxDistance {\n\t\t\tfor letter, childNode := range n.children {\n\t\t\t\tsearchRecursive(childNode, currentRow, letter, []rune(text), maxDistance)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor letter, childNode := range n.children {\n\t\tsearchRecursive(childNode, currentRow, letter, []rune(text), distance)\n\t}\n\tsort.Sort(ByDistance(candidates))\n\treturn candidates\n}\nfixed issues with recursion. search works well now.package LevenshteinTrie\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"unicode\/utf8\"\n)\n\nfunc Min(a ...int) int {\n\tmin := int(^uint(0) >> 1) \/\/ largest int\n\tfor _, i := range a {\n\t\tif i < min {\n\t\t\tmin = i\n\t\t}\n\t}\n\treturn min\n}\nfunc Max(a ...int) int {\n\tmax := int(0)\n\tfor _, i := range a {\n\t\tif i > max {\n\t\t\tmax = i\n\t\t}\n\t}\n\treturn max\n}\n\ntype TrieNode struct {\n\tletter rune \/\/Equivalent to int32\n\tchildren map[rune]*TrieNode\n\tfinal bool\n\ttext string\n}\n\nfunc (t *TrieNode) String() string {\n\ts := fmt.Sprintf(\"%s\\n\", t.letter)\n\tfor _, v := range t.children {\n\t\ts += fmt.Sprintf(\"-%s\\n\", v)\n\t}\n\treturn s\n}\n\nfunc NewTrie() *TrieNode {\n\treturn &TrieNode{children: make(map[rune]*TrieNode)}\n}\n\nfunc (root *TrieNode) InsertText(text string) {\n\tif root == nil {\n\t\treturn\n\t}\n\n\tcurrNode := root \/\/Starts at root\n\tfor i, w := 0, 0; i < len(text); i += w {\n\t\truneValue, width := utf8.DecodeRuneInString(text[i:])\n\t\tfinal := false\n\t\tif width+i == len(text) {\n\t\t\tfinal = true\n\t\t}\n\t\tw = width\n\n\t\tcurrNode = NewTrieNode(currNode, runeValue, final, text)\n\t}\n}\n\nfunc NewTrieNode(t *TrieNode, runeValue rune, final bool, text string) *TrieNode {\n\tnode, exists := t.children[runeValue]\n\tif !exists {\n\t\tnode = &TrieNode{letter: runeValue, children: make(map[rune]*TrieNode)}\n\t\tt.children[runeValue] = node\n\t}\n\tif final {\n\t\tnode.final = true\n\t\tnode.text = text\n\t}\n\treturn node\n}\n\nfunc (t *TrieNode) SearchSuffix(query string) []string {\n\tvar curr *TrieNode\n\tvar ok bool\n\n\tcurr = t\n\t\/\/first, find the end of the prefix\n\tfor _, letter := range query {\n\t\tif curr != nil {\n\t\t\tcurr, ok = curr.children[letter]\n\t\t\tif ok {\n\t\t\t\t\/\/do nothing\n\t\t\t}\n\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcandidates := getsuffixr(curr)\n\n\treturn candidates\n}\n\nfunc getsuffixr(n *TrieNode) []string {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tcandidates := make([]string, 0)\n\tif n.final == true {\n\t\tcandidates = append(candidates, n.text)\n\t}\n\n\tfor _, childNode := range n.children {\n\t\tcandidates = append(candidates, getsuffixr(childNode)...)\n\t}\n\treturn candidates\n}\n\ntype QueryResult struct {\n\tVal string\n\tDistance int\n}\n\nfunc (q QueryResult) String() string {\n\treturn fmt.Sprintf(\"Val: %s\\n\", q.Val)\n}\n\ntype ByDistance []QueryResult\n\nfunc (a ByDistance) Len() int { return len(a) }\nfunc (a ByDistance) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a ByDistance) Less(i, j int) bool { return a[i].Distance < a[j].Distance }\n\nfunc (n *TrieNode) SearchLevenshtein(text string, distance int) []QueryResult {\n\n\t\/\/initialize the first row for the dynamic programming alg\n\tl := utf8.RuneCount([]byte(text))\n\tcurrentRow := make([]int, l+1)\n\n\tfor i := 0; i < len(currentRow); i++ {\n\t\tcurrentRow[i] = i\n\t}\n\n\tcandidates := make([]QueryResult, 0)\n\n\tfor letter, childNode := range n.children {\n\t\tcandidates = append(candidates, searchlevr(childNode, currentRow, letter, []rune(text), distance)...)\n\t}\n\n\tsort.Sort(ByDistance(candidates))\n\treturn candidates\n}\n\nfunc searchlevr(n *TrieNode, prevRow []int, letter rune, text []rune, maxDistance int) []QueryResult {\n\tcolumns := len(prevRow)\n\tcurrentRow := make([]int, columns)\n\n\tcurrentRow[0] = prevRow[0] + 1\n\n\tfor col := 1; col < columns; col++ {\n\t\tif text[col-1] == letter {\n\t\t\tcurrentRow[col] = prevRow[col-1]\n\t\t\tcontinue\n\t\t}\n\t\tinsertCost := currentRow[col-1] + 1\n\t\tdeleteCost := prevRow[col] + 1\n\t\treplaceCost := prevRow[col-1] + 1\n\n\t\tcurrentRow[col] = Min(insertCost, deleteCost, replaceCost)\n\t}\n\n\tcandidates := make([]QueryResult, 0)\n\n\tdistance := currentRow[len(currentRow)-1]\n\tif distance <= maxDistance && n.final == true {\n\t\tcandidates = append(candidates, QueryResult{Val: n.text, Distance: distance})\n\t}\n\tmi := Min(currentRow[1:]...)\n\tif mi <= maxDistance {\n\t\tfor l, childNode := range n.children {\n\t\t\tcandidates = append(candidates, searchlevr(childNode, currentRow, l, text, maxDistance)...)\n\t\t}\n\t}\n\treturn candidates\n}\n<|endoftext|>"} {"text":"package handler\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ghophp\/buildbot-dashing\/container\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\ntype (\n\tWsHandler struct {\n\t\tc *container.ContainerBag\n\t}\n\n\tClientConn struct {\n\t\twebsocket *websocket.Conn\n\t\tclientIP net.Addr\n\t}\n)\n\nvar (\n\tActiveClients = make(map[ClientConn]int)\n\twsMutex sync.RWMutex\n)\n\nfunc addClient(cc ClientConn) {\n\twsMutex.Lock()\n\tActiveClients[cc] = 0\n\twsMutex.Unlock()\n}\n\nfunc deleteClient(cc ClientConn) {\n\twsMutex.Lock()\n\tdelete(ActiveClients, cc)\n\twsMutex.Unlock()\n}\n\nfunc broadcastMessage(messageType int, message []byte) {\n\tfor client, _ := range ActiveClients {\n\t\tif err := client.websocket.WriteMessage(messageType, message); err != nil {\n\t\t\tdeleteClient(client)\n\t\t}\n\t}\n}\n\nfunc MonitorBuilders(c *container.ContainerBag) {\n\tfor {\n\t\tif len(ActiveClients) > 0 {\n\t\t\tbuilders, err := GetBuilders(c)\n\t\t\tif err != nil || len(builders) <= 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor id, builder := range builders {\n\t\t\t\tif len(builder.CachedBuilds) > 0 {\n\t\t\t\t\tb, err := GetBuilder(c, id, builder)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tif r, err := json.Marshal(b); err == nil {\n\t\t\t\t\t\t\tbroadcastMessage(websocket.TextMessage, r)\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}\n\n\t\ttime.Sleep(time.Second * time.Duration(c.RefreshSec))\n\t}\n}\n\nfunc NewWsHandler(c *container.ContainerBag) *WsHandler {\n\tgo MonitorBuilders(c)\n\n\treturn &WsHandler{\n\t\tc: c,\n\t}\n}\n\nfunc (h WsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tws, err := websocket.Upgrade(w, r, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tsockCli := ClientConn{ws, ws.RemoteAddr()}\n\taddClient(sockCli)\n}\nimprovement on the performance, spanning the goroutines all at once to fetch the builderspackage handler\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ghophp\/buildbot-dashing\/container\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\ntype (\n\tWsHandler struct {\n\t\tc *container.ContainerBag\n\t}\n\n\tClientConn struct {\n\t\twebsocket *websocket.Conn\n\t\tclientIP net.Addr\n\t}\n)\n\nvar (\n\tActiveClients = make(map[ClientConn]int)\n\twsMutex sync.RWMutex\n)\n\nfunc addClient(cc ClientConn) {\n\twsMutex.Lock()\n\tActiveClients[cc] = 0\n\twsMutex.Unlock()\n}\n\nfunc deleteClient(cc ClientConn) {\n\twsMutex.Lock()\n\tdelete(ActiveClients, cc)\n\twsMutex.Unlock()\n}\n\nfunc broadcastMessage(messageType int, message []byte) {\n\twsMutex.RLock()\n\tfor client, _ := range ActiveClients {\n\t\tclient.websocket.WriteMessage(messageType, message)\n\t}\n\twsMutex.RUnlock()\n}\n\nfunc MonitorBuilders(c *container.ContainerBag) {\n\tresponses := make(chan string)\n\n\tfor {\n\t\tif len(ActiveClients) > 0 {\n\t\t\tbuilders, err := GetBuilders(c)\n\t\t\tif err != nil || len(builders) <= 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfiltered := make(map[string]Builder)\n\t\t\tfor id, builder := range builders {\n\t\t\t\tif len(builder.CachedBuilds) > 0 {\n\t\t\t\t\tfiltered[id] = builder\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(len(filtered))\n\n\t\t\tfor id, builder := range filtered {\n\t\t\t\tgo func(id string, builder Builder) {\n\t\t\t\t\tdefer wg.Done()\n\n\t\t\t\t\tb, err := GetBuilder(c, id, builder)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tif r, err := json.Marshal(b); err == nil {\n\t\t\t\t\t\t\tresponses <- string(r)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}(id, builder)\n\t\t\t}\n\n\t\t\tgo func() {\n\t\t\t\tfor response := range responses {\n\t\t\t\t\tbroadcastMessage(websocket.TextMessage, []byte(response))\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\twg.Wait()\n\t\t}\n\n\t\ttime.Sleep(time.Second * time.Duration(c.RefreshSec))\n\t}\n}\n\nfunc NewWsHandler(c *container.ContainerBag) *WsHandler {\n\tgo MonitorBuilders(c)\n\n\treturn &WsHandler{\n\t\tc: c,\n\t}\n}\n\nfunc (h WsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tws, err := websocket.Upgrade(w, r, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tsockCli := ClientConn{ws, ws.RemoteAddr()}\n\taddClient(sockCli)\n}\n<|endoftext|>"} {"text":"package main\r\n\r\nimport (\r\n\t\"io\"\r\n\t\"net\/http\"\r\n\t\"path\"\r\n\t\"bytes\"\r\n\t\"crypto\/md5\"\r\n\t\"encoding\/hex\"\r\n\t\"encoding\/json\"\r\n\t\"flag\"\r\n\t\"fmt\"\r\n\t\"io\/ioutil\"\r\n\t\"os\"\r\n\t\"os\/exec\"\r\n\t\"path\/filepath\"\r\n\t\"sort\"\r\n\t\"strings\"\r\n)\r\n\r\ntype DirEntry struct {\r\n\tpth string\r\n\tfi os.FileInfo\r\n\tchecksum string\r\n}\r\n\r\ntype DirEntries []DirEntry\r\n\r\nfunc (a DirEntries) Len() int { return len(a) }\r\nfunc (a DirEntries) Less(i, j int) bool { return a[i].pth < a[j].pth }\r\nfunc (a DirEntries) Swap(i, j int) {\r\n\ta[i], a[j] = a[j], a[i]\r\n}\r\n\r\ntype AppConfig struct {\r\n\tName string\r\n\tInputRoot string\r\n\tOutputDir string\r\n\tBuildCmd string\r\n\tArchiveLocal string\r\n\tArchiveRemote string\r\n\tInclude\t\t[]string\r\n\tExclude\t\t[]string\r\n}\r\n\r\nfunc countFullChecksum(ents *DirEntries) {\r\n\tfor i, v := range *ents {\r\n\t\tst, err := os.Stat(v.pth)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"SKIP bad file [%s]\\n\", v.pth)\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tv.fi = st\r\n\r\n\t\tif v.fi.IsDir() {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif v.fi.Size() == 0 {\r\n\t\t\tv.checksum = \"0000\"\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tdat, err := ioutil.ReadFile(v.pth)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t\tvar csum = md5.Sum(dat)\r\n\t\tv.checksum = hex.EncodeToString(csum[:])\r\n\t\t\/\/fmt.Printf(\"%s\\n %x\", v.checksum, csum)\r\n\t\t(*ents)[i] = v\r\n\t}\r\n}\r\n\r\nfunc shouldIgnore(config *AppConfig, pth string) bool {\r\n\tfor _,v := range config.Exclude {\r\n\t\tif strings.HasPrefix(pth, v) {\r\n\t\t\treturn true\r\n\t\t}\r\n\t}\r\n\r\n\tif len(config.Include) == 0 {\r\n\t\treturn false\r\n\t}\r\n\r\n\tfor _, v := range config.Include {\r\n\t\tif strings.HasPrefix(pth, v) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}\r\n\r\n\r\nfunc collectWithGit(config *AppConfig) DirEntries{\r\n\tcmd := exec.Command(\"git\", \"ls-files\")\r\n\t\r\n\tcmd.Dir = config.InputRoot\r\n\tout, err := cmd.Output()\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\tasStr := string(out)\r\n\tlines := strings.Split(asStr, \"\\n\")\r\n\tvar all DirEntries\r\n\t\r\n\tfor _, v := range lines {\r\n\t\tif shouldIgnore(config, v) {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tall = append(all, DirEntry { pth: path.Join(config.InputRoot ,v)})\r\n\t}\r\n\treturn all\r\n}\r\n\r\nfunc normalizePaths(ents *DirEntries, rootPath string) {\r\n\tfor i, v := range *ents {\r\n\t\toldpath := v.pth\r\n\t\tnewpath := strings.Replace(strings.TrimPrefix(oldpath, rootPath+\"\/\"), \"\\\\\", \"\/\", -1)\r\n\t\tv.pth = newpath\r\n\t\t(*ents)[i] = v\r\n\t}\r\n}\r\n\r\nfunc collectByConfig(config *AppConfig) DirEntries {\r\n\treturn collectWithGit(config)\r\n}\r\n\r\nfunc getCheckSumForFiles(config *AppConfig) (DirEntries, string) {\t\t\r\n\tall := collectByConfig(config)\r\n\tsort.Sort(all)\r\n\tcountFullChecksum(&all)\r\n\tnormalizePaths(&all, config.InputRoot)\r\n\tvar manifest bytes.Buffer\r\n\tfor _, v := range all {\r\n\t\tmanifest.WriteString(v.pth)\r\n\t\tmanifest.WriteString(v.checksum)\r\n\t\t\/\/fmt.Printf(\"%s %s\\n\", v.pth, v.checksum)\r\n\t}\r\n\tmanifestSum := md5.Sum(manifest.Bytes())\r\n\treturn all, hex.EncodeToString(manifestSum[:])\r\n}\r\n\r\nfunc run(bin string, arg ...string) {\r\n\tfmt.Printf(\"> %s %s\", bin, arg)\t\r\n\t\t\r\n\tcmd := exec.Command(bin, arg...)\r\n\tout, err := cmd.CombinedOutput()\t\r\n\tfmt.Printf(\"%s\", string(out))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n}\r\nfunc zipOutput(path string, zipfile string) {\r\n\trun(\"zip\", \"-r\", zipfile, path+\"\/*\")\r\n}\r\n\r\nfunc unzipOutput(pth string, zipfile string) {\r\n\t\/\/ we will replace the old path completely\t\r\n\tensureDir(path.Dir(pth))\r\n\tos.RemoveAll(pth)\r\n\trun(\"unzip\", zipfile, \"-d\"+pth)\r\n}\r\n\r\nfunc runBuildCommand(config *AppConfig) {\r\n\tfmt.Printf(\"Running build command '%s' in %s\\n\", config.BuildCmd, config.InputRoot)\r\n\tparts := strings.Fields(config.BuildCmd)\r\n\tcmd := exec.Command(parts[0], parts[1:]...)\r\n\tcmd.Dir = config.InputRoot\r\n\tout, err := cmd.CombinedOutput()\r\n\tfmt.Println(string(out))\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"Build failed with error!\")\r\n\t\tpanic(err)\r\n\t}\r\n}\r\n\r\nfunc fetchTo(url string, to string) bool {\r\n\tfmt.Printf(\"GET %s\\n\", url)\t\r\n\tresp, err := http.Get(url)\r\n\tif err != nil || resp.StatusCode != 200 {\r\n\t\tfmt.Printf(\"Not available: %s\\n\", url)\r\n\t\treturn false\t\t\r\n\t}\r\n\tdefer resp.Body.Close()\r\n\tout, err := os.Create(to)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tdefer out.Close()\r\n\t_, err = io.Copy(out, resp.Body)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\treturn true\r\n}\r\n\r\nfunc discoverArchive(config *AppConfig, checksum string) (string,bool) {\r\n\tarchiveRoot := config.ArchiveLocal\t\r\n\tzipName := config.Name + \"_\" + checksum + \".zip\"\r\n\r\n\t\/\/ 1. just try local\r\n\tlocalZipName := filepath.Join(archiveRoot, zipName)\r\n\t_, err := os.Stat(localZipName)\r\n\tif err == nil {\r\n\t\treturn localZipName, true\r\n\t}\r\n\r\n\t\/\/ 2. try remote if applicable\r\n\r\n\tremoteArchive := config.ArchiveRemote\r\n\r\n\tif remoteArchive == \"\" {\r\n\t\treturn localZipName, false\r\n\t}\r\n\tif strings.Index(remoteArchive, \"[ZIP]\") == -1 {\r\n\t\tfmt.Printf(\"Error: remote archive template %s does not contain [ZIP]\\n\", remoteArchive)\r\n\t\treturn \"\", false\r\n\t}\r\n\tremoteUrl := strings.Replace(remoteArchive, \"[ZIP]\", zipName, -1)\r\n\tfetched := fetchTo(remoteUrl, localZipName)\r\n\tif !fetched {\r\n\t\treturn localZipName, false\r\n\t}\r\n\treturn localZipName, true\r\n}\t\r\n\r\nfunc buildWithConfig(config *AppConfig) {\r\n\t\/\/ check input checksum\r\n\tfmt.Printf(\"Config %s\\n\", config)\r\n\tarchiveRoot := config.ArchiveLocal\r\n\r\n\tif archiveRoot == \"\" {\r\n\t\tfmt.Println(\"HASHIBUILD_ARCHIVE not set, building without artifact caching\")\r\n\t\trunBuildCommand(config)\r\n\t\treturn\r\n\t}\r\n\r\n\t_, inputChecksum := getCheckSumForFiles(config)\r\n\t\/\/ if finding archive found, unzip it and we are ready\r\n\tensureDir(archiveRoot)\r\n\t\r\n\tzipName, found := discoverArchive(config, inputChecksum)\r\n\r\n\tif found {\r\n\t\tfmt.Printf(\"Unzip %s to %s\\n\", zipName, config.OutputDir)\r\n\t\tunzipOutput(config.OutputDir, zipName)\r\n\t\treturn\r\n\t}\r\n\t\r\n\t\/\/ run build if mismatch\r\n\r\n\trunBuildCommand(config)\r\n\r\n\t\/\/ zip the results\r\n\tfmt.Printf(\"Zipping %s to %s\\n\", config.OutputDir, zipName)\r\n\tzipOutput(config.OutputDir, zipName)\r\n}\r\n\r\nfunc checkDir(pth string) {\r\n\tif _, err := os.Stat(pth); os.IsNotExist(err) {\r\n\t\tfmt.Printf(\"Path does not exist: %s\", pth)\r\n\t\tpanic(err)\r\n\t}\r\n}\r\n\r\nfunc ensureDir(pth string) {\r\n\tif _, err := os.Stat(pth); os.IsNotExist(err) {\r\n\t\tfmt.Printf(\"Creating dir: %s\\n\", pth)\r\n\t\tos.MkdirAll(pth, 0777)\r\n\t}\t\r\n}\r\n\r\nfunc parseConfig(configPath string) AppConfig {\r\n\tcont, err := ioutil.ReadFile(configPath)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tconfig := AppConfig{}\r\n\terr = json.Unmarshal(cont, &config)\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\t\/\/ fixup paths to be relative to config file\r\n\tconfigDir, _ := filepath.Abs(filepath.Dir(configPath))\r\n\tconfig.InputRoot = filepath.Join(configDir, config.InputRoot)\r\n\tconfig.OutputDir = filepath.Join(configDir, config.OutputDir)\r\n\t\r\n\tcheckDir(config.InputRoot)\r\n\r\n\treturn config\r\n}\r\n\r\nfunc dumpManifest(config *AppConfig) {\r\n\r\n\tall, csum := getCheckSumForFiles(config)\r\n\tfor _, v := range all {\r\n\t\tfmt.Printf(\"%s %s\\n\", v.pth, v.checksum)\r\n\t}\r\n\tfmt.Printf(\"Total: %s\\n\", csum)\r\n}\r\n\r\nfunc main() {\r\n\tmanifest := flag.Bool(\"manifest\", false, \"Show manifest (requires --config)\")\r\n\ttreeHash := flag.String(\"treehash\", \"\", \"Show manifest for specified path (no config needed)\")\r\n\ttoParse := flag.String(\"config\", \"\", \"Json config file\")\r\n\tstartBuild := flag.Bool(\"build\", false, \"Run build\")\r\n\tarchiveDir := flag.String(\"archive\", \"\", \"Archive root dir (needed if HASHIBUILD_ARCHIVE env var is not set)\")\r\n\tfetch := flag.String(\"fetch\", \"\", \"Fetch remote archive file to local archive\")\r\n\tif len(os.Args) < 2 {\r\n\t\tflag.Usage()\r\n\t\treturn\r\n\t}\r\n\r\n\tflag.Parse()\r\n\r\n\tvar config AppConfig\r\n\tif (*toParse) != \"\" {\r\n\t\tconfig = parseConfig(*toParse)\r\n\t\tif *archiveDir != \"\" {\r\n\t\t\tconfig.ArchiveLocal = *archiveDir\r\n\t\t}\r\n\t\tif config.ArchiveLocal == \"\" {\r\n\t\t\tconfig.ArchiveLocal = os.Getenv(\"HASHIBUILD_ARCHIVE\")\r\n\t\t}\r\n\t\tif config.ArchiveRemote == \"\" {\r\n\t\t\tconfig.ArchiveRemote = os.Getenv(\"HASHIBUILD_ARCHIVE_REMOTE\")\r\n\t\t}\r\n\t}\r\n\r\n\tif *fetch != \"\" {\r\n\t\t_, inputChecksum := getCheckSumForFiles(&config)\r\n\t\t\/\/ if finding archive found, unzip it and we are ready\r\n\t\tzipName, _ := discoverArchive(&config, inputChecksum)\r\n\t\tfmt.Printf(\"%s\", zipName)\r\n\t}\r\n\r\n\tif *manifest {\r\n\t\tdumpManifest(&config)\r\n\t}\r\n\r\n\tif *startBuild {\r\n\t\tbuildWithConfig(&config)\r\n\t}\r\n\r\n\tif len(*treeHash) > 0 {\r\n\t\tpth, _ := filepath.Abs(*treeHash)\r\n\t\t\r\n\t\tconfig := AppConfig{InputRoot: pth }\r\n\t\tdumpManifest(&config)\r\n\t}\r\n\r\n}\r\nchange to zip \/ unzippackage main\r\n\r\nimport (\r\n\t\"io\"\r\n\t\"net\/http\"\r\n\t\"path\"\r\n\t\"bytes\"\r\n\t\"crypto\/md5\"\r\n\t\"encoding\/hex\"\r\n\t\"encoding\/json\"\r\n\t\"flag\"\r\n\t\"fmt\"\r\n\t\"io\/ioutil\"\r\n\t\"os\"\r\n\t\"os\/exec\"\r\n\t\"path\/filepath\"\r\n\t\"sort\"\r\n\t\"strings\"\r\n)\r\n\r\ntype DirEntry struct {\r\n\tpth string\r\n\tfi os.FileInfo\r\n\tchecksum string\r\n}\r\n\r\ntype DirEntries []DirEntry\r\n\r\nfunc (a DirEntries) Len() int { return len(a) }\r\nfunc (a DirEntries) Less(i, j int) bool { return a[i].pth < a[j].pth }\r\nfunc (a DirEntries) Swap(i, j int) {\r\n\ta[i], a[j] = a[j], a[i]\r\n}\r\n\r\ntype AppConfig struct {\r\n\tName string\r\n\tInputRoot string\r\n\tOutputDir string\r\n\tBuildCmd string\r\n\tArchiveLocal string\r\n\tArchiveRemote string\r\n\tInclude\t\t[]string\r\n\tExclude\t\t[]string\r\n}\r\n\r\nfunc countFullChecksum(ents *DirEntries) {\r\n\tfor i, v := range *ents {\r\n\t\tst, err := os.Stat(v.pth)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"SKIP bad file [%s]\\n\", v.pth)\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tv.fi = st\r\n\r\n\t\tif v.fi.IsDir() {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif v.fi.Size() == 0 {\r\n\t\t\tv.checksum = \"0000\"\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tdat, err := ioutil.ReadFile(v.pth)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t\tvar csum = md5.Sum(dat)\r\n\t\tv.checksum = hex.EncodeToString(csum[:])\r\n\t\t\/\/fmt.Printf(\"%s\\n %x\", v.checksum, csum)\r\n\t\t(*ents)[i] = v\r\n\t}\r\n}\r\n\r\nfunc shouldIgnore(config *AppConfig, pth string) bool {\r\n\tfor _,v := range config.Exclude {\r\n\t\tif strings.HasPrefix(pth, v) {\r\n\t\t\treturn true\r\n\t\t}\r\n\t}\r\n\r\n\tif len(config.Include) == 0 {\r\n\t\treturn false\r\n\t}\r\n\r\n\tfor _, v := range config.Include {\r\n\t\tif strings.HasPrefix(pth, v) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}\r\n\r\n\r\nfunc collectWithGit(config *AppConfig) DirEntries{\r\n\tcmd := exec.Command(\"git\", \"ls-files\")\r\n\t\r\n\tcmd.Dir = config.InputRoot\r\n\tout, err := cmd.Output()\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\tasStr := string(out)\r\n\tlines := strings.Split(asStr, \"\\n\")\r\n\tvar all DirEntries\r\n\t\r\n\tfor _, v := range lines {\r\n\t\tif shouldIgnore(config, v) {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tall = append(all, DirEntry { pth: path.Join(config.InputRoot ,v)})\r\n\t}\r\n\treturn all\r\n}\r\n\r\nfunc normalizePaths(ents *DirEntries, rootPath string) {\r\n\tfor i, v := range *ents {\r\n\t\toldpath := v.pth\r\n\t\tnewpath := strings.Replace(strings.TrimPrefix(oldpath, rootPath+\"\/\"), \"\\\\\", \"\/\", -1)\r\n\t\tv.pth = newpath\r\n\t\t(*ents)[i] = v\r\n\t}\r\n}\r\n\r\nfunc collectByConfig(config *AppConfig) DirEntries {\r\n\treturn collectWithGit(config)\r\n}\r\n\r\nfunc getCheckSumForFiles(config *AppConfig) (DirEntries, string) {\t\t\r\n\tall := collectByConfig(config)\r\n\tsort.Sort(all)\r\n\tcountFullChecksum(&all)\r\n\tnormalizePaths(&all, config.InputRoot)\r\n\tvar manifest bytes.Buffer\r\n\tfor _, v := range all {\r\n\t\tmanifest.WriteString(v.pth)\r\n\t\tmanifest.WriteString(v.checksum)\r\n\t\t\/\/fmt.Printf(\"%s %s\\n\", v.pth, v.checksum)\r\n\t}\r\n\tmanifestSum := md5.Sum(manifest.Bytes())\r\n\treturn all, hex.EncodeToString(manifestSum[:])\r\n}\r\n\r\nfunc run(cwd string, bin string, arg ...string) {\r\n\tfmt.Printf(\"> %s %s\", bin, arg)\t\t\t\r\n\tcmd := exec.Command(bin, arg...)\r\n\tcmd.Dir = cwd\r\n\tout, err := cmd.CombinedOutput()\t\r\n\tfmt.Printf(\"%s\", string(out))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n}\r\n\r\n\r\nfunc zipOutput(path string, zipfile string) {\r\n\trun(path, \"zip\", \"-r\", zipfile, \"*\")\r\n}\r\n\r\nfunc unzipOutput(pth string, zipfile string) {\r\n\t\/\/ we will replace the old path completely\t\r\n\tensureDir(pth)\r\n\terr := os.RemoveAll(pth)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tensureDir(pth)\r\n\trun(\".\", \"unzip\", zipfile, \"-d\"+pth)\r\n}\r\n\r\nfunc runBuildCommand(config *AppConfig) {\r\n\tfmt.Printf(\"Running build command '%s' in %s\\n\", config.BuildCmd, config.InputRoot)\r\n\tparts := strings.Fields(config.BuildCmd)\r\n\tcmd := exec.Command(parts[0], parts[1:]...)\r\n\tcmd.Dir = config.InputRoot\r\n\tout, err := cmd.CombinedOutput()\r\n\tfmt.Println(string(out))\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"Build failed with error!\")\r\n\t\tpanic(err)\r\n\t}\r\n}\r\n\r\nfunc fetchTo(url string, to string) bool {\r\n\tfmt.Printf(\"GET %s\\n\", url)\t\r\n\tresp, err := http.Get(url)\r\n\tif err != nil || resp.StatusCode != 200 {\r\n\t\tfmt.Printf(\"Not available: %s\\n\", url)\r\n\t\treturn false\t\t\r\n\t}\r\n\tdefer resp.Body.Close()\r\n\tout, err := os.Create(to)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tdefer out.Close()\r\n\t_, err = io.Copy(out, resp.Body)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\treturn true\r\n}\r\n\r\nfunc discoverArchive(config *AppConfig, checksum string) (string,bool) {\r\n\tarchiveRoot := config.ArchiveLocal\t\r\n\tzipName := config.Name + \"_\" + checksum + \".zip\"\r\n\r\n\t\/\/ 1. just try local\r\n\tlocalZipName := filepath.Join(archiveRoot, zipName)\r\n\t_, err := os.Stat(localZipName)\r\n\tif err == nil {\r\n\t\treturn localZipName, true\r\n\t}\r\n\r\n\t\/\/ 2. try remote if applicable\r\n\r\n\tremoteArchive := config.ArchiveRemote\r\n\r\n\tif remoteArchive == \"\" {\r\n\t\treturn localZipName, false\r\n\t}\r\n\tif strings.Index(remoteArchive, \"[ZIP]\") == -1 {\r\n\t\tfmt.Printf(\"Error: remote archive template %s does not contain [ZIP]\\n\", remoteArchive)\r\n\t\treturn \"\", false\r\n\t}\r\n\tremoteUrl := strings.Replace(remoteArchive, \"[ZIP]\", zipName, -1)\r\n\tfetched := fetchTo(remoteUrl, localZipName)\r\n\tif !fetched {\r\n\t\treturn localZipName, false\r\n\t}\r\n\treturn localZipName, true\r\n}\t\r\n\r\nfunc buildWithConfig(config *AppConfig) {\r\n\t\/\/ check input checksum\r\n\tfmt.Printf(\"Config %s\\n\", config)\r\n\tarchiveRoot := config.ArchiveLocal\r\n\r\n\tif archiveRoot == \"\" {\r\n\t\tfmt.Println(\"HASHIBUILD_ARCHIVE not set, building without artifact caching\")\r\n\t\trunBuildCommand(config)\r\n\t\treturn\r\n\t}\r\n\r\n\t_, inputChecksum := getCheckSumForFiles(config)\r\n\t\/\/ if finding archive found, unzip it and we are ready\r\n\tensureDir(archiveRoot)\r\n\t\r\n\tzipName, found := discoverArchive(config, inputChecksum)\r\n\r\n\tif found {\r\n\t\tfmt.Printf(\"Unzip %s to %s\\n\", zipName, config.OutputDir)\r\n\t\tunzipOutput(config.OutputDir, zipName)\r\n\t\treturn\r\n\t}\r\n\t\r\n\t\/\/ run build if mismatch\r\n\r\n\trunBuildCommand(config)\r\n\r\n\t\/\/ zip the results\r\n\tfmt.Printf(\"Zipping %s to %s\\n\", config.OutputDir, zipName)\r\n\tzipOutput(config.OutputDir, zipName)\r\n}\r\n\r\nfunc checkDir(pth string) {\r\n\tif _, err := os.Stat(pth); os.IsNotExist(err) {\r\n\t\tfmt.Printf(\"Path does not exist: %s\", pth)\r\n\t\tpanic(err)\r\n\t}\r\n}\r\n\r\nfunc ensureDir(pth string) {\r\n\tif _, err := os.Stat(pth); os.IsNotExist(err) {\r\n\t\tfmt.Printf(\"Creating dir: %s\\n\", pth)\r\n\t\tos.MkdirAll(pth, 0777)\t\t\r\n\t} else {\r\n\t\tfmt.Printf(\"Path exists: %s\\n\", pth)\r\n\t}\r\n\r\n}\r\n\r\nfunc parseConfig(configPath string) AppConfig {\r\n\tcont, err := ioutil.ReadFile(configPath)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tconfig := AppConfig{}\r\n\terr = json.Unmarshal(cont, &config)\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\t\/\/ fixup paths to be relative to config file\r\n\tconfigDir, _ := filepath.Abs(filepath.Dir(configPath))\r\n\tconfig.InputRoot = filepath.Join(configDir, config.InputRoot)\r\n\tconfig.OutputDir = filepath.Join(configDir, config.OutputDir)\r\n\t\r\n\tcheckDir(config.InputRoot)\r\n\r\n\treturn config\r\n}\r\n\r\nfunc dumpManifest(config *AppConfig) {\r\n\r\n\tall, csum := getCheckSumForFiles(config)\r\n\tfor _, v := range all {\r\n\t\tfmt.Printf(\"%s %s\\n\", v.pth, v.checksum)\r\n\t}\r\n\tfmt.Printf(\"Total: %s\\n\", csum)\r\n}\r\n\r\nfunc main() {\r\n\tmanifest := flag.Bool(\"manifest\", false, \"Show manifest (requires --config)\")\r\n\ttreeHash := flag.String(\"treehash\", \"\", \"Show manifest for specified path (no config needed)\")\r\n\ttoParse := flag.String(\"config\", \"\", \"Json config file\")\r\n\tstartBuild := flag.Bool(\"build\", false, \"Run build\")\r\n\tarchiveDir := flag.String(\"archive\", \"\", \"Archive root dir (needed if HASHIBUILD_ARCHIVE env var is not set)\")\r\n\tfetch := flag.String(\"fetch\", \"\", \"Fetch remote archive file to local archive\")\r\n\tif len(os.Args) < 2 {\r\n\t\tflag.Usage()\r\n\t\treturn\r\n\t}\r\n\r\n\tflag.Parse()\r\n\r\n\tvar config AppConfig\r\n\tif (*toParse) != \"\" {\r\n\t\tconfig = parseConfig(*toParse)\r\n\t\tif *archiveDir != \"\" {\r\n\t\t\tconfig.ArchiveLocal = *archiveDir\r\n\t\t}\r\n\t\tif config.ArchiveLocal == \"\" {\r\n\t\t\tconfig.ArchiveLocal = os.Getenv(\"HASHIBUILD_ARCHIVE\")\r\n\t\t}\r\n\t\tif config.ArchiveRemote == \"\" {\r\n\t\t\tconfig.ArchiveRemote = os.Getenv(\"HASHIBUILD_ARCHIVE_REMOTE\")\r\n\t\t}\r\n\t}\r\n\r\n\tif *fetch != \"\" {\r\n\t\t_, inputChecksum := getCheckSumForFiles(&config)\r\n\t\t\/\/ if finding archive found, unzip it and we are ready\r\n\t\tzipName, _ := discoverArchive(&config, inputChecksum)\r\n\t\tfmt.Printf(\"%s\", zipName)\r\n\t}\r\n\r\n\tif *manifest {\r\n\t\tdumpManifest(&config)\r\n\t}\r\n\r\n\tif *startBuild {\r\n\t\tbuildWithConfig(&config)\r\n\t}\r\n\r\n\tif len(*treeHash) > 0 {\r\n\t\tpth, _ := filepath.Abs(*treeHash)\r\n\t\t\r\n\t\tconfig := AppConfig{InputRoot: pth }\r\n\t\tdumpManifest(&config)\r\n\t}\r\n\r\n}\r\n<|endoftext|>"} {"text":"package trousseau\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/oleiade\/trousseau\/crypto\"\n\t\"github.com\/oleiade\/trousseau\/dsn\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc CreateAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'configure' command\")\n\t}\n\n\trecipients := strings.Split(c.Args()[0], \",\")\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t\tRecipients: recipients,\n\t}\n\n\tmeta := Meta{\n\t\tCreatedAt: time.Now().String(),\n\t\tLastModifiedAt: time.Now().String(),\n\t\tRecipients: recipients,\n\t\tTrousseauVersion: TROUSSEAU_VERSION,\n\t}\n\n\t\/\/ Create and write empty store file\n\terr := CreateStoreFile(gStorePath, opts, &meta)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Trousseau data store succesfully created\")\n}\n\nfunc PushAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'push' command\")\n\t}\n\n\tendpointDsn, err := dsn.Parse(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tswitch endpointDsn.Scheme {\n\tcase \"s3\":\n\t\terr := endpointDsn.SetDefaults(gS3Defaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\terr = uploadUsingS3(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to s3\")\n\tcase \"scp\":\n\t\tprivateKey := c.String(\"ssh-private-key\")\n\n\t\terr := endpointDsn.SetDefaults(gScpDefaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif c.Bool(\"ask-password\") == true {\n\t\t\tpassword := PromptForPassword()\n\t\t\tendpointDsn.Secret = password\n\t\t}\n\n\t\terr = uploadUsingScp(endpointDsn, privateKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to ssh remote storage\")\n\tcase \"gist\":\n\t\terr = uploadUsingGist(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to gist\")\n\t}\n}\n\nfunc PullAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'pull' command\")\n\t}\n\n\tendpointDsn, err := dsn.Parse(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tswitch endpointDsn.Scheme {\n\tcase \"s3\":\n\t\terr := endpointDsn.SetDefaults(gS3Defaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\terr = DownloadUsingS3(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from S3\")\n\tcase \"scp\":\n\t\tprivateKey := c.String(\"ssh-private-key\")\n\n\t\terr := endpointDsn.SetDefaults(gScpDefaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif c.Bool(\"ask-password\") == true {\n\t\t\tpassword := PromptForPassword()\n\t\t\tendpointDsn.Secret = password\n\t\t}\n\n\t\terr = DownloadUsingScp(endpointDsn, privateKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from ssh remote storage\")\n\tcase \"gist\":\n\t\terr = DownloadUsingGist(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from gist\")\n\tdefault:\n\t\tif endpointDsn.Scheme == \"\" {\n\t\t\tlog.Fatalf(\"No dsn scheme supplied\")\n\t\t} else {\n\t\t\tlog.Fatalf(\"Invalid dsn scheme supplied: %s\", endpointDsn.Scheme)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Trousseau data store succesfully pulled from remote storage\")\n}\n\nfunc ExportAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'export' command\")\n\t}\n\n\tvar err error\n\tvar inputFilePath string = gStorePath\n\tvar outputFilePath string = c.Args()[0]\n\n\tinputFile, err := os.Open(inputFilePath)\n\tdefer inputFile.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\toutputFile, err := os.Create(outputFilePath)\n\tdefer outputFile.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = io.Copy(outputFile, inputFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Trousseau data store exported to %s\", outputFilePath)\n}\n\nfunc ImportAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'import' command\")\n\t}\n\n\tvar err error\n\tvar importedFilePath string = c.Args()[0]\n\tvar localFilePath string = gStorePath\n\tvar strategy *ImportStrategy = new(ImportStrategy)\n\n\t\/\/ Transform provided merging startegy flags\n\t\/\/ into a proper ImportStrategy byte.\n\terr = strategy.FromCliContext(c)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tlocalStore, err := LoadStore(localFilePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\timportedStore, err := LoadStore(importedFilePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = ImportStore(importedStore, localStore, *strategy)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = localStore.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Trousseau data store imported\")\n}\n\nfunc AddRecipientAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'add-recipient' command\")\n\t}\n\n\trecipient := c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.DataStore.Meta.AddRecipient(recipient)\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s recipient added to trousseau data store\", recipient)\n}\n\nfunc RemoveRecipientAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'remove-recipient' command\")\n\t}\n\n\trecipient := c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Meta.RemoveRecipient(recipient)\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s recipient removed from trousseau data store\", recipient)\n}\n\nfunc GetAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'get' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvalue, err := store.Get(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s key's value: %s\\n\", c.Args()[0], value)\n}\n\nfunc SetAction(c *cli.Context) {\n\tvar key string\n\tvar value interface{}\n\tvar err error\n\n\t\/\/ If the --file flag is provided\n\tif c.String(\"file\") != \"\" && hasExpectedArgs(c.Args(), 1) {\n\t\t\/\/ And the file actually exists on file system\n\t\tif pathExists(c.String(\"file\")) {\n\t\t\t\/\/ Then load it's content\n\t\t\tvalue, err = ioutil.ReadFile(c.String(\"file\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatalf(\"Cannot open %s because it doesn't exist\", c.String(\"file\"))\n\t\t}\n\t} else if c.String(\"file\") == \"\" && hasExpectedArgs(c.Args(), 2) {\n\t\tvalue = c.Args()[1]\n\t} else {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'set' command\")\n\t}\n\n key = c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Set(key, value)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"key-value pair set: %s:%s\\n\", key, value)\n}\n\nfunc DelAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'del' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Del(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s key deleted\\n\", c.Args()[0])\n}\n\nfunc KeysAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'keys' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tkeys, err := store.Keys()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tfor _, k := range keys {\n\t\t\tfmt.Println(k)\n\t\t}\n\t}\n}\n\nfunc ShowAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'show' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpairs, err := store.Items()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tfor _, pair := range pairs {\n\t\t\tfmt.Printf(\"%s: %s\\n\", pair.Key, pair.Value)\n\t\t}\n\t}\n}\n\nfunc MetaAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'meta' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpairs, err := store.Metadata()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, pair := range pairs {\n\t\tfmt.Printf(\"%s: %s\\n\", pair.Key, pair.Value)\n\t}\n}\n\n\/\/ hasExpectedArgs checks whether the number of args are as expected.\nfunc hasExpectedArgs(args []string, expected int) bool {\n\tswitch expected {\n\tcase -1:\n\t\tif len(args) > 0 {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\tif len(args) == expected {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n}\nFix #69 clean command-line output for its parsing to be easierpackage trousseau\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/oleiade\/trousseau\/crypto\"\n\t\"github.com\/oleiade\/trousseau\/dsn\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc CreateAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'configure' command\")\n\t}\n\n\trecipients := strings.Split(c.Args()[0], \",\")\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t\tRecipients: recipients,\n\t}\n\n\tmeta := Meta{\n\t\tCreatedAt: time.Now().String(),\n\t\tLastModifiedAt: time.Now().String(),\n\t\tRecipients: recipients,\n\t\tTrousseauVersion: TROUSSEAU_VERSION,\n\t}\n\n\t\/\/ Create and write empty store file\n\terr := CreateStoreFile(gStorePath, opts, &meta)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Trousseau data store succesfully created\")\n}\n\nfunc PushAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'push' command\")\n\t}\n\n\tendpointDsn, err := dsn.Parse(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tswitch endpointDsn.Scheme {\n\tcase \"s3\":\n\t\terr := endpointDsn.SetDefaults(gS3Defaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\terr = uploadUsingS3(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to s3\")\n\tcase \"scp\":\n\t\tprivateKey := c.String(\"ssh-private-key\")\n\n\t\terr := endpointDsn.SetDefaults(gScpDefaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif c.Bool(\"ask-password\") == true {\n\t\t\tpassword := PromptForPassword()\n\t\t\tendpointDsn.Secret = password\n\t\t}\n\n\t\terr = uploadUsingScp(endpointDsn, privateKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to ssh remote storage\")\n\tcase \"gist\":\n\t\terr = uploadUsingGist(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pushed to gist\")\n\t}\n}\n\nfunc PullAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'pull' command\")\n\t}\n\n\tendpointDsn, err := dsn.Parse(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tswitch endpointDsn.Scheme {\n\tcase \"s3\":\n\t\terr := endpointDsn.SetDefaults(gS3Defaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\terr = DownloadUsingS3(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from S3\")\n\tcase \"scp\":\n\t\tprivateKey := c.String(\"ssh-private-key\")\n\n\t\terr := endpointDsn.SetDefaults(gScpDefaults)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif c.Bool(\"ask-password\") == true {\n\t\t\tpassword := PromptForPassword()\n\t\t\tendpointDsn.Secret = password\n\t\t}\n\n\t\terr = DownloadUsingScp(endpointDsn, privateKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from ssh remote storage\")\n\tcase \"gist\":\n\t\terr = DownloadUsingGist(endpointDsn)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Trousseau data store succesfully pulled from gist\")\n\tdefault:\n\t\tif endpointDsn.Scheme == \"\" {\n\t\t\tlog.Fatalf(\"No dsn scheme supplied\")\n\t\t} else {\n\t\t\tlog.Fatalf(\"Invalid dsn scheme supplied: %s\", endpointDsn.Scheme)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Trousseau data store succesfully pulled from remote storage\")\n}\n\nfunc ExportAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'export' command\")\n\t}\n\n\tvar err error\n\tvar inputFilePath string = gStorePath\n\tvar outputFilePath string = c.Args()[0]\n\n\tinputFile, err := os.Open(inputFilePath)\n\tdefer inputFile.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\toutputFile, err := os.Create(outputFilePath)\n\tdefer outputFile.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = io.Copy(outputFile, inputFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Trousseau data store exported to: %s\\n\", outputFilePath)\n}\n\nfunc ImportAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'import' command\")\n\t}\n\n\tvar err error\n\tvar importedFilePath string = c.Args()[0]\n\tvar localFilePath string = gStorePath\n\tvar strategy *ImportStrategy = new(ImportStrategy)\n\n\t\/\/ Transform provided merging startegy flags\n\t\/\/ into a proper ImportStrategy byte.\n\terr = strategy.FromCliContext(c)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tlocalStore, err := LoadStore(localFilePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\timportedStore, err := LoadStore(importedFilePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = ImportStore(importedStore, localStore, *strategy)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = localStore.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Trousseau data store imported: %s\\n\", importedFilePath)\n}\n\nfunc AddRecipientAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'add-recipient' command\")\n\t}\n\n\trecipient := c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.DataStore.Meta.AddRecipient(recipient)\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Recipient added to trousseau data store: %s\\n\", recipient)\n}\n\nfunc RemoveRecipientAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'remove-recipient' command\")\n\t}\n\n\trecipient := c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Meta.RemoveRecipient(recipient)\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"Recipient removed from trousseau data store: %s\\n\", recipient)\n}\n\nfunc GetAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'get' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvalue, err := store.Get(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s\\n\", value)\n}\n\nfunc SetAction(c *cli.Context) {\n\tvar key string\n\tvar value interface{}\n\tvar err error\n\n\t\/\/ If the --file flag is provided\n\tif c.String(\"file\") != \"\" && hasExpectedArgs(c.Args(), 1) {\n\t\t\/\/ And the file actually exists on file system\n\t\tif pathExists(c.String(\"file\")) {\n\t\t\t\/\/ Then load it's content\n\t\t\tvalue, err = ioutil.ReadFile(c.String(\"file\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatalf(\"Cannot open %s because it doesn't exist\", c.String(\"file\"))\n\t\t}\n\t} else if c.String(\"file\") == \"\" && hasExpectedArgs(c.Args(), 2) {\n\t\tvalue = c.Args()[1]\n\t} else {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'set' command\")\n\t}\n\n\tkey = c.Args()[0]\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Set(key, value)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"%s:%s\\n\", key, value)\n}\n\nfunc DelAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 1) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'del' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Del(c.Args()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = store.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"deleted: %s\\n\", c.Args()[0])\n}\n\nfunc KeysAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'keys' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tkeys, err := store.Keys()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tfor _, k := range keys {\n\t\t\tfmt.Println(k)\n\t\t}\n\t}\n}\n\nfunc ShowAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'show' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpairs, err := store.Items()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tfor _, pair := range pairs {\n\t\t\tfmt.Printf(\"%s : %s\\n\", pair.Key, pair.Value)\n\t\t}\n\t}\n}\n\nfunc MetaAction(c *cli.Context) {\n\tif !hasExpectedArgs(c.Args(), 0) {\n\t\tlog.Fatal(\"Incorrect number of arguments to 'meta' command\")\n\t}\n\n\topts := &crypto.Options{\n\t\tAlgorithm: crypto.GPG_ENCRYPTION,\n\t\tPassphrase: gPasshphrase,\n\t}\n\n\tstore, err := LoadStore(gStorePath, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpairs, err := store.Metadata()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, pair := range pairs {\n\t\tfmt.Printf(\"%s : %s\\n\", pair.Key, pair.Value)\n\t}\n}\n\n\/\/ hasExpectedArgs checks whether the number of args are as expected.\nfunc hasExpectedArgs(args []string, expected int) bool {\n\tswitch expected {\n\tcase -1:\n\t\tif len(args) > 0 {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\tif len(args) == expected {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015 Niklas Wolber\n\/\/ This file is licensed under the MIT license.\n\/\/ See the LICENSE file for more information.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\n\ttwitter \"github.com\/ChimeraCoder\/anaconda\"\n\tr \"github.com\/dancannon\/gorethink\"\n)\n\ntype followerExplorer struct {\n\tid int64\n\tfollowers []int64\n}\n\nfunc newFollowerTask(session *r.Session, api *twitter.TwitterApi) *task {\n\tselectUncrawledExplorers := func(row r.Term) interface{} {\n\t\treturn row.HasFields(\"followers\").Not()\n\t}\n\tquery := r.\n\t\tTable(\"pi\").\n\t\tFilter(selectUncrawledExplorers).\n\t\tOrderBy(r.Desc(\"tweets\"))\n\n\textractor := func(row map[string]interface{}) interface{} {\n\t\tvar exp followerExplorer\n\t\texp.id = int64(row[\"explorer\"].(float64))\n\t\treturn exp\n\t}\n\n\tprocessor := func(entity interface{}) {\n\t\texp := entity.(followerExplorer)\n\n\t\tvar followers []int64\n\t\tvar nextCursor int64\n\t\tlog.Println(\"Fetching followers of\", exp.id)\n\t\tfor {\n\t\t\tparams := url.Values{}\n\t\t\tparams.Add(\"user_id\", fmt.Sprintf(\"%d\", exp.id))\n\t\t\tparams.Add(\"count\", \"5000\")\n\t\t\tif nextCursor > 0 {\n\t\t\t\tparams.Add(\"cursor\", fmt.Sprintf(\"%d\", nextCursor))\n\t\t\t}\n\n\t\t\tcursor, err := api.GetFollowersIds(params)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\n\t\t\tlog.Println(\"Fetched\", len(cursor.Ids), \"followers of\", exp.id)\n\t\t\tfollowers = append(followers, cursor.Ids...)\n\n\t\t\tnextCursor = cursor.Next_cursor\n\n\t\t\tif nextCursor == 0 {\n\t\t\t\texp.storeFollowers(session, followers)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn newTask(query, extractor, processor, false)\n}\n\nfunc (exp *followerExplorer) storeFollowers(session *r.Session, followers []int64) {\n\tresult, err := r.\n\t\tTable(\"pi\").\n\t\tInsert(map[string]interface{}{\n\t\t\"explorer\": exp.id,\n\t\t\"followers\": followers,\n\t}, r.InsertOpts{Conflict: \"update\"}).\n\t\tRunWrite(session)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif result.Errors > 0 {\n\t\tlog.Println(result.FirstError)\n\t}\n}\nDon't fail when a Twitter requests errrors\/\/ Copyright (c) 2015 Niklas Wolber\n\/\/ This file is licensed under the MIT license.\n\/\/ See the LICENSE file for more information.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"time\"\n\n\ttwitter \"github.com\/ChimeraCoder\/anaconda\"\n\tr \"github.com\/dancannon\/gorethink\"\n)\n\ntype followerExplorer struct {\n\tid int64\n\tfollowers []int64\n}\n\nfunc newFollowerTask(session *r.Session, api *twitter.TwitterApi) *task {\n\tselectUncrawledExplorers := func(row r.Term) interface{} {\n\t\treturn row.HasFields(\"followers\").Not()\n\t}\n\tquery := r.\n\t\tTable(\"pi\").\n\t\tFilter(selectUncrawledExplorers).\n\t\tOrderBy(r.Desc(\"tweets\"))\n\n\textractor := func(row map[string]interface{}) interface{} {\n\t\tvar exp followerExplorer\n\t\texp.id = int64(row[\"explorer\"].(float64))\n\t\treturn exp\n\t}\n\n\tprocessor := func(entity interface{}) {\n\t\texp := entity.(followerExplorer)\n\n\t\tvar followers []int64\n\t\tvar nextCursor int64\n\t\tlog.Println(\"Fetching followers of\", exp.id)\n\t\tfor {\n\t\t\tparams := url.Values{}\n\t\t\tparams.Add(\"user_id\", fmt.Sprintf(\"%d\", exp.id))\n\t\t\tparams.Add(\"count\", \"5000\")\n\t\t\tif nextCursor > 0 {\n\t\t\t\tparams.Add(\"cursor\", fmt.Sprintf(\"%d\", nextCursor))\n\t\t\t}\n\n\t\t\tcursor, err := api.GetFollowersIds(params)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\ttime.Sleep(time.Minute)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Println(\"Fetched\", len(cursor.Ids), \"followers of\", exp.id)\n\t\t\tfollowers = append(followers, cursor.Ids...)\n\n\t\t\tnextCursor = cursor.Next_cursor\n\n\t\t\tif nextCursor == 0 {\n\t\t\t\texp.storeFollowers(session, followers)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn newTask(query, extractor, processor, false)\n}\n\nfunc (exp *followerExplorer) storeFollowers(session *r.Session, followers []int64) {\n\tresult, err := r.\n\t\tTable(\"pi\").\n\t\tInsert(map[string]interface{}{\n\t\t\"explorer\": exp.id,\n\t\t\"followers\": followers,\n\t}, r.InsertOpts{Conflict: \"update\"}).\n\t\tRunWrite(session)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif result.Errors > 0 {\n\t\tlog.Println(result.FirstError)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Package bot provides the internal machinery for most of Gopherbot.\npackage bot\n\n\/* bot.go defines core data structures and public methods for startup.\n handler.go has the methods for callbacks from the connector, *\/\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/lnxjedi\/gopherbot\/robot\"\n)\n\n\/\/ VersionInfo holds information about the version, duh. (stupid linter)\ntype VersionInfo struct {\n\tVersion, Commit string\n}\n\n\/\/ global values for GOPHER_HOME, GOPHER_CONFIGDIR and GOPHER_INSTALLDIR\nvar homePath, configPath, installPath string\n\nvar botVersion VersionInfo\n\nvar random *rand.Rand\n\nvar connectors = make(map[string]func(robot.Handler, *log.Logger) robot.Connector)\n\n\/\/ RegisterConnector should be called in an init function to register a type\n\/\/ of connector. Currently only Slack is implemented.\nfunc RegisterConnector(name string, connstarter func(robot.Handler, *log.Logger) robot.Connector) {\n\tif stopRegistrations {\n\t\treturn\n\t}\n\tif connectors[name] != nil {\n\t\tlog.Fatal(\"Attempted registration of duplicate connector:\", name)\n\t}\n\tconnectors[name] = connstarter\n}\n\n\/\/ Interfaces to external stuff, items should be set while single-threaded and never change\nvar interfaces struct {\n\trobot.Connector \/\/ Connector interface, implemented by each specific protocol\n\tbrain robot.SimpleBrain \/\/ Interface for robot to Store and Retrieve data\n\thistory robot.HistoryProvider \/\/ Provider for storing and retrieving job \/ plugin histories\n\tstop chan struct{} \/\/ stop channel for stopping the connector\n\tdone chan bool \/\/ shutdown channel, true to restart\n}\n\n\/\/ internal state tracking\nvar state struct {\n\tshuttingDown bool \/\/ to prevent new plugins from starting\n\trestart bool \/\/ indicate stop and restart vs. stop only, for bootstrapping\n\tpluginsRunning int \/\/ a count of how many plugins are currently running\n\tsync.WaitGroup \/\/ for keeping track of running plugins\n\tsync.RWMutex \/\/ for safe updating of bot data structures\n}\n\n\/\/ regexes the bot uses to determine if it's being spoken to\nvar regexes struct {\n\tpreRegex *regexp.Regexp \/\/ regex for matching prefixed commands, e.g. \"Gort, drop your weapon\"\n\tpostRegex *regexp.Regexp \/\/ regex for matching, e.g. \"open the pod bay doors, hal\"\n\tbareRegex *regexp.Regexp \/\/ regex for matching the robot's bare name, if you forgot it in the previous command\n\tsync.RWMutex\n}\n\n\/\/ configuration struct holds all the interal data relevant to the Bot. Most of it is digested\n\/\/ and populated by loadConfig.\ntype configuration struct {\n\tadminUsers []string \/\/ List of users with access to administrative commands\n\talias rune \/\/ single-char alias for addressing the bot\n\tbotinfo UserInfo \/\/ robot's name, ID, email, etc.\n\tadminContact string \/\/ who to contact for problems with the bot\n\tmailConf botMailer \/\/ configuration to use when sending email\n\tignoreUsers []string \/\/ list of users to never listen to, like other bots\n\tjoinChannels []string \/\/ list of channels to join\n\tdefaultAllowDirect bool \/\/ whether plugins are available in DM by default\n\tdefaultMessageFormat robot.MessageFormat \/\/ Raw unless set to Variable or Fixed\n\tplugChannels []string \/\/ list of channels where plugins are available by default\n\tprotocol string \/\/ Name of the protocol, e.g. \"slack\"\n\tbrainProvider string \/\/ Type of Brain provider to use\n\tencryptionKey string \/\/ Key for encrypting data (unlocks \"real\" key in brain)\n\thistoryProvider string \/\/ Name of the history provider to use\n\tworkSpace string \/\/ Read\/Write directory where the robot does work\n\tdefaultElevator string \/\/ Plugin name for performing elevation\n\tdefaultAuthorizer string \/\/ Plugin name for performing authorization\n\texternalPlugins []TaskSettings \/\/ List of external plugins to load\n\texternalJobs []TaskSettings \/\/ List of external jobs to load\n\texternalTasks []TaskSettings \/\/ List of external tasks to load\n\tgoPlugins []TaskSettings \/\/ Settings for goPlugins: Name(match), Description, NameSpace, Parameters, Disabled\n\tgoJobs []TaskSettings \/\/ Settings for goJobs: Name(match), Description, NameSpace, Parameters, Disabled\n\tgoTasks []TaskSettings \/\/ Settings for goTasks: Name(match), Description, NameSpace, Parameters, Disabled\n\tnsList []TaskSettings \/\/ loaded NameSpaces for shared parameters\n\tloadableModules []LoadableModule \/\/ List of loadable modules to load\n\tScheduledJobs []ScheduledTask \/\/ List of scheduled tasks\n\tport string \/\/ Configured localhost port to listen on, or 0 for first open\n\ttimeZone *time.Location \/\/ for forcing the TimeZone, Unix only\n\tdefaultJobChannel string \/\/ where job statuses will post if not otherwise specified\n}\n\n\/\/ The current configuration and task list\nvar currentCfg = struct {\n\t*configuration\n\t*taskList\n\tsync.RWMutex\n}{\n\tconfiguration: &configuration{},\n\ttaskList: &taskList{\n\t\tt: []interface{}{struct{}{}}, \/\/ initialize 0 to \"nothing\", for namespaces only\n\t\tnameMap: make(map[string]int),\n\t\tidMap: make(map[string]int),\n\t\tnameSpaces: make(map[string]NameSpace),\n\t},\n\tRWMutex: sync.RWMutex{},\n}\n\nvar listening bool \/\/ for tests where initBot runs multiple times\nvar listenPort string \/\/ actual listening port\n\n\/\/ initBot sets up the global robot; when cli is false it also loads configuration.\n\/\/ cli indicates that a CLI command is being processed, as opposed to actually running\n\/\/ a robot.\nfunc initBot(cpath, epath string, logger *log.Logger) {\n\t\/\/ Seed the pseudo-random number generator, for plugin IDs, RandomString, etc.\n\trandom = rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\/\/ Initialize current config with an empty struct (to be loaded)\n\tcurrentCfg.configuration = &configuration{}\n\n\tbotLogger.l = logger\n\n\tvar err error\n\thomePath, err = os.Getwd()\n\tif err != nil {\n\t\tLog(robot.Warn, \"Unable to get cwd\")\n\t}\n\th := handler{}\n\tif err := h.GetDirectory(cpath); err != nil {\n\t\tLog(robot.Fatal, \"Unable to get\/create config path: %s\", cpath)\n\t}\n\tconfigPath = cpath\n\tinstallPath = epath\n\tinterfaces.stop = make(chan struct{})\n\tinterfaces.done = make(chan bool)\n\tstate.shuttingDown = false\n\n\tif cliOp {\n\t\tsetLogLevel(robot.Warn)\n\t}\n\n\tencryptionInitialized := initCrypt()\n\n\tc := &botContext{\n\t\tenvironment: make(map[string]string),\n\t}\n\tif err := c.loadConfig(true); err != nil {\n\t\tLog(robot.Fatal, \"Loading initial configuration: %v\", err)\n\t}\n\tos.Unsetenv(keyEnv)\n\n\tif cliOp {\n\t\tif fileLog {\n\t\t\tsetLogLevel(robot.Debug)\n\t\t} else {\n\t\t\tsetLogLevel(robot.Warn)\n\t\t}\n\t}\n\n\t\/\/ loadModules for go loadable modules; a no-op for static builds\n\tloadModules()\n\n\t\/\/ All pluggables registered, ok to stop registrations\n\tstopRegistrations = true\n\n\tif len(currentCfg.brainProvider) > 0 {\n\t\tif bprovider, ok := brains[currentCfg.brainProvider]; !ok {\n\t\t\tLog(robot.Fatal, \"No provider registered for brain: \\\"%s\\\"\", currentCfg.brainProvider)\n\t\t} else {\n\t\t\tbrain := bprovider(handle)\n\t\t\tinterfaces.brain = brain\n\t\t\tLog(robot.Info, \"Initialized brain provider '%s'\", currentCfg.brainProvider)\n\t\t}\n\t} else {\n\t\tbprovider, _ := brains[\"mem\"]\n\t\tinterfaces.brain = bprovider(handle)\n\t\tLog(robot.Error, \"No brain configured, falling back to default 'mem' brain - no memories will persist\")\n\t}\n\tif !encryptionInitialized && len(currentCfg.encryptionKey) > 0 {\n\t\tif initializeEncryptionFromBrain(currentCfg.encryptionKey) {\n\t\t\tLog(robot.Info, \"Successfully initialized encryption from configured key\")\n\t\t\tencryptionInitialized = true\n\t\t} else {\n\t\t\tLog(robot.Error, \"Failed to initialize brain encryption with configured EncryptionKey\")\n\t\t}\n\t}\n\tif encryptBrain && !encryptionInitialized {\n\t\tLog(robot.Warn, \"Brain encryption specified but not initialized; use 'initialize brain ' to initialize the encrypted brain interactively\")\n\t}\n\n\t\/\/ cli commands don't need an http listener\n\tif cliOp {\n\t\treturn\n\t}\n\n\tif !listening {\n\t\tlistening = true\n\t\tlistener, err := net.Listen(\"tcp4\", fmt.Sprintf(\"127.0.0.1:%s\", currentCfg.port))\n\t\tif err != nil {\n\t\t\tLog(robot.Fatal, \"Listening on tcp4 port 127.0.0.1:%s: %v\", currentCfg.port, err)\n\t\t}\n\t\tlistenPort = listener.Addr().String()\n\t\tgo func() {\n\t\t\traiseThreadPriv(\"http handler\")\n\t\t\thttp.Handle(\"\/json\", handle)\n\t\t\tLog(robot.Info, \"Listening for external plugin connections on http:\/\/%s\", listenPort)\n\t\t\tLog(robot.Fatal, \"Error serving '\/json': %s\", http.Serve(listener, nil))\n\t\t}()\n\t}\n}\n\n\/\/ set connector sets the connector, which should already be initialized\nfunc setConnector(c robot.Connector) {\n\tinterfaces.Connector = c\n}\n\nvar keyEnv = \"GOPHER_ENCRYPTION_KEY\"\n\nfunc initCrypt() bool {\n\t\/\/ Initialize encryption (new style for v2)\n\tkeyFile := filepath.Join(configPath, encryptedKeyFile)\n\tencryptionInitialized := false\n\tif ek, ok := os.LookupEnv(keyEnv); ok {\n\t\tik := []byte(ek)[0:32]\n\t\tif bkf, err := ioutil.ReadFile(keyFile); err == nil {\n\t\t\tif bke, err := base64.StdEncoding.DecodeString(string(bkf)); err == nil {\n\t\t\t\tif key, err := decrypt(bke, ik); err == nil {\n\t\t\t\t\tcryptKey.key = key\n\t\t\t\t\tcryptKey.initialized = true\n\t\t\t\t\tencryptionInitialized = true\n\t\t\t\t\tLog(robot.Info, \"Successfully decrypted binary encryption key '%s'\", keyFile)\n\t\t\t\t} else {\n\t\t\t\t\tLog(robot.Error, \"Decrypting binary encryption key '%s' from environment key '%s': %v\", keyFile, keyEnv, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tLog(robot.Error, \"Base64 decoding '%s': %v\", keyFile, err)\n\t\t\t}\n\t\t} else {\n\t\t\tLog(robot.Warn, \"Binary encryption key not loaded from '%s': %v\", keyFile, err)\n\t\t}\n\t\tos.Unsetenv(keyEnv)\n\t} else {\n\t\tLog(robot.Warn, \"GOPHER_ENCRYPTION_KEY not set in environment\")\n\t}\n\treturn encryptionInitialized\n}\n\n\/\/ run starts all the loops and returns a channel that closes when the robot\n\/\/ shuts down. It should return after the connector loop has started and\n\/\/ plugins are initialized.\nfunc run() <-chan bool {\n\t\/\/ Start the brain loop\n\tgo runBrain()\n\n\tvar cl []string\n\tcl = append(cl, currentCfg.joinChannels...)\n\tcl = append(cl, currentCfg.plugChannels...)\n\tcl = append(cl, currentCfg.defaultJobChannel)\n\tjc := make(map[string]bool)\n\tfor _, channel := range cl {\n\t\tif _, ok := jc[channel]; !ok {\n\t\t\tjc[channel] = true\n\t\t\tinterfaces.JoinChannel(channel)\n\t\t}\n\t}\n\n\t\/\/ signal handler\n\tgo func() {\n\t\tdone := interfaces.done\n\t\tsigs := make(chan os.Signal, 1)\n\n\t\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase sig := <-sigs:\n\t\t\t\tstate.Lock()\n\t\t\t\tif state.shuttingDown {\n\t\t\t\t\tLog(robot.Warn, \"Received SIGINT\/SIGTERM while shutdown in progress\")\n\t\t\t\t\tstate.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tstate.shuttingDown = true\n\t\t\t\t\tstate.Unlock()\n\t\t\t\t\tsignal.Stop(sigs)\n\t\t\t\t\tLog(robot.Info, \"Exiting on signal: %s\", sig)\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\tcase <-done:\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ connector loop\n\tgo func(conn robot.Connector, stop <-chan struct{}, done chan<- bool) {\n\t\traiseThreadPriv(\"connector loop\")\n\t\tconn.Run(stop)\n\t\tstate.RLock()\n\t\trestart := state.restart\n\t\tstate.RUnlock()\n\t\tif restart {\n\t\t\tLog(robot.Info, \"Restarting...\")\n\t\t}\n\t\tdone <- restart\n\t\t\/\/ NOTE!! Black Magic Ahead - for some reason, the read on the done channel\n\t\t\/\/ keeps blocking without this close.\n\t\tclose(done)\n\t}(interfaces.Connector, interfaces.stop, interfaces.done)\n\tc := &botContext{\n\t\tenvironment: make(map[string]string),\n\t}\n\tc.registerActive(nil)\n\tc.loadConfig(false)\n\tc.deregister()\n\treturn interfaces.done\n}\n\n\/\/ stop is called whenever the robot needs to shut down gracefully. All callers\n\/\/ should lock the bot and check the value of botCfg.shuttingDown; see\n\/\/ builtins.go.\nfunc stop() {\n\tstate.RLock()\n\tpr := state.pluginsRunning\n\tstop := interfaces.stop\n\tstate.RUnlock()\n\tLog(robot.Debug, \"stop called with %d plugins running\", pr)\n\tstate.Wait()\n\tbrainQuit()\n\tclose(stop)\n}\nGenerate new-style key if old-style not configured\/\/ Package bot provides the internal machinery for most of Gopherbot.\npackage bot\n\n\/* bot.go defines core data structures and public methods for startup.\n handler.go has the methods for callbacks from the connector, *\/\n\nimport (\n\tcrand \"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/lnxjedi\/gopherbot\/robot\"\n)\n\n\/\/ VersionInfo holds information about the version, duh. (stupid linter)\ntype VersionInfo struct {\n\tVersion, Commit string\n}\n\n\/\/ global values for GOPHER_HOME, GOPHER_CONFIGDIR and GOPHER_INSTALLDIR\nvar homePath, configPath, installPath string\n\nvar botVersion VersionInfo\n\nvar random *rand.Rand\n\nvar connectors = make(map[string]func(robot.Handler, *log.Logger) robot.Connector)\n\n\/\/ RegisterConnector should be called in an init function to register a type\n\/\/ of connector. Currently only Slack is implemented.\nfunc RegisterConnector(name string, connstarter func(robot.Handler, *log.Logger) robot.Connector) {\n\tif stopRegistrations {\n\t\treturn\n\t}\n\tif connectors[name] != nil {\n\t\tlog.Fatal(\"Attempted registration of duplicate connector:\", name)\n\t}\n\tconnectors[name] = connstarter\n}\n\n\/\/ Interfaces to external stuff, items should be set while single-threaded and never change\nvar interfaces struct {\n\trobot.Connector \/\/ Connector interface, implemented by each specific protocol\n\tbrain robot.SimpleBrain \/\/ Interface for robot to Store and Retrieve data\n\thistory robot.HistoryProvider \/\/ Provider for storing and retrieving job \/ plugin histories\n\tstop chan struct{} \/\/ stop channel for stopping the connector\n\tdone chan bool \/\/ shutdown channel, true to restart\n}\n\n\/\/ internal state tracking\nvar state struct {\n\tshuttingDown bool \/\/ to prevent new plugins from starting\n\trestart bool \/\/ indicate stop and restart vs. stop only, for bootstrapping\n\tpluginsRunning int \/\/ a count of how many plugins are currently running\n\tsync.WaitGroup \/\/ for keeping track of running plugins\n\tsync.RWMutex \/\/ for safe updating of bot data structures\n}\n\n\/\/ regexes the bot uses to determine if it's being spoken to\nvar regexes struct {\n\tpreRegex *regexp.Regexp \/\/ regex for matching prefixed commands, e.g. \"Gort, drop your weapon\"\n\tpostRegex *regexp.Regexp \/\/ regex for matching, e.g. \"open the pod bay doors, hal\"\n\tbareRegex *regexp.Regexp \/\/ regex for matching the robot's bare name, if you forgot it in the previous command\n\tsync.RWMutex\n}\n\n\/\/ configuration struct holds all the interal data relevant to the Bot. Most of it is digested\n\/\/ and populated by loadConfig.\ntype configuration struct {\n\tadminUsers []string \/\/ List of users with access to administrative commands\n\talias rune \/\/ single-char alias for addressing the bot\n\tbotinfo UserInfo \/\/ robot's name, ID, email, etc.\n\tadminContact string \/\/ who to contact for problems with the bot\n\tmailConf botMailer \/\/ configuration to use when sending email\n\tignoreUsers []string \/\/ list of users to never listen to, like other bots\n\tjoinChannels []string \/\/ list of channels to join\n\tdefaultAllowDirect bool \/\/ whether plugins are available in DM by default\n\tdefaultMessageFormat robot.MessageFormat \/\/ Raw unless set to Variable or Fixed\n\tplugChannels []string \/\/ list of channels where plugins are available by default\n\tprotocol string \/\/ Name of the protocol, e.g. \"slack\"\n\tbrainProvider string \/\/ Type of Brain provider to use\n\tencryptionKey string \/\/ Key for encrypting data (unlocks \"real\" key in brain)\n\thistoryProvider string \/\/ Name of the history provider to use\n\tworkSpace string \/\/ Read\/Write directory where the robot does work\n\tdefaultElevator string \/\/ Plugin name for performing elevation\n\tdefaultAuthorizer string \/\/ Plugin name for performing authorization\n\texternalPlugins []TaskSettings \/\/ List of external plugins to load\n\texternalJobs []TaskSettings \/\/ List of external jobs to load\n\texternalTasks []TaskSettings \/\/ List of external tasks to load\n\tgoPlugins []TaskSettings \/\/ Settings for goPlugins: Name(match), Description, NameSpace, Parameters, Disabled\n\tgoJobs []TaskSettings \/\/ Settings for goJobs: Name(match), Description, NameSpace, Parameters, Disabled\n\tgoTasks []TaskSettings \/\/ Settings for goTasks: Name(match), Description, NameSpace, Parameters, Disabled\n\tnsList []TaskSettings \/\/ loaded NameSpaces for shared parameters\n\tloadableModules []LoadableModule \/\/ List of loadable modules to load\n\tScheduledJobs []ScheduledTask \/\/ List of scheduled tasks\n\tport string \/\/ Configured localhost port to listen on, or 0 for first open\n\ttimeZone *time.Location \/\/ for forcing the TimeZone, Unix only\n\tdefaultJobChannel string \/\/ where job statuses will post if not otherwise specified\n}\n\n\/\/ The current configuration and task list\nvar currentCfg = struct {\n\t*configuration\n\t*taskList\n\tsync.RWMutex\n}{\n\tconfiguration: &configuration{},\n\ttaskList: &taskList{\n\t\tt: []interface{}{struct{}{}}, \/\/ initialize 0 to \"nothing\", for namespaces only\n\t\tnameMap: make(map[string]int),\n\t\tidMap: make(map[string]int),\n\t\tnameSpaces: make(map[string]NameSpace),\n\t},\n\tRWMutex: sync.RWMutex{},\n}\n\nvar listening bool \/\/ for tests where initBot runs multiple times\nvar listenPort string \/\/ actual listening port\n\n\/\/ initBot sets up the global robot; when cli is false it also loads configuration.\n\/\/ cli indicates that a CLI command is being processed, as opposed to actually running\n\/\/ a robot.\nfunc initBot(cpath, epath string, logger *log.Logger) {\n\t\/\/ Seed the pseudo-random number generator, for plugin IDs, RandomString, etc.\n\trandom = rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\/\/ Initialize current config with an empty struct (to be loaded)\n\tcurrentCfg.configuration = &configuration{}\n\n\tbotLogger.l = logger\n\n\tvar err error\n\thomePath, err = os.Getwd()\n\tif err != nil {\n\t\tLog(robot.Warn, \"Unable to get cwd\")\n\t}\n\th := handler{}\n\tif err := h.GetDirectory(cpath); err != nil {\n\t\tLog(robot.Fatal, \"Unable to get\/create config path: %s\", cpath)\n\t}\n\tconfigPath = cpath\n\tinstallPath = epath\n\tinterfaces.stop = make(chan struct{})\n\tinterfaces.done = make(chan bool)\n\tstate.shuttingDown = false\n\n\tif cliOp {\n\t\tsetLogLevel(robot.Warn)\n\t}\n\n\tencryptionInitialized := initCrypt()\n\n\tc := &botContext{\n\t\tenvironment: make(map[string]string),\n\t}\n\tif err := c.loadConfig(true); err != nil {\n\t\tLog(robot.Fatal, \"Loading initial configuration: %v\", err)\n\t}\n\tos.Unsetenv(keyEnv)\n\n\tif cliOp {\n\t\tif fileLog {\n\t\t\tsetLogLevel(robot.Debug)\n\t\t} else {\n\t\t\tsetLogLevel(robot.Warn)\n\t\t}\n\t}\n\n\t\/\/ loadModules for go loadable modules; a no-op for static builds\n\tloadModules()\n\n\t\/\/ All pluggables registered, ok to stop registrations\n\tstopRegistrations = true\n\n\tif len(currentCfg.brainProvider) > 0 {\n\t\tif bprovider, ok := brains[currentCfg.brainProvider]; !ok {\n\t\t\tLog(robot.Fatal, \"No provider registered for brain: \\\"%s\\\"\", currentCfg.brainProvider)\n\t\t} else {\n\t\t\tbrain := bprovider(handle)\n\t\t\tinterfaces.brain = brain\n\t\t\tLog(robot.Info, \"Initialized brain provider '%s'\", currentCfg.brainProvider)\n\t\t}\n\t} else {\n\t\tbprovider, _ := brains[\"mem\"]\n\t\tinterfaces.brain = bprovider(handle)\n\t\tLog(robot.Error, \"No brain configured, falling back to default 'mem' brain - no memories will persist\")\n\t}\n\tif !encryptionInitialized && len(currentCfg.encryptionKey) > 0 {\n\t\tif initializeEncryptionFromBrain(currentCfg.encryptionKey) {\n\t\t\tLog(robot.Info, \"Successfully initialized encryption from configured key\")\n\t\t\tencryptionInitialized = true\n\t\t} else {\n\t\t\tLog(robot.Error, \"Failed to initialize brain encryption with configured EncryptionKey\")\n\t\t}\n\t}\n\tif encryptBrain && !encryptionInitialized {\n\t\tLog(robot.Warn, \"Brain encryption specified but not initialized; use 'initialize brain ' to initialize the encrypted brain interactively\")\n\t}\n\n\t\/\/ cli commands don't need an http listener\n\tif cliOp {\n\t\treturn\n\t}\n\n\tif !listening {\n\t\tlistening = true\n\t\tlistener, err := net.Listen(\"tcp4\", fmt.Sprintf(\"127.0.0.1:%s\", currentCfg.port))\n\t\tif err != nil {\n\t\t\tLog(robot.Fatal, \"Listening on tcp4 port 127.0.0.1:%s: %v\", currentCfg.port, err)\n\t\t}\n\t\tlistenPort = listener.Addr().String()\n\t\tgo func() {\n\t\t\traiseThreadPriv(\"http handler\")\n\t\t\thttp.Handle(\"\/json\", handle)\n\t\t\tLog(robot.Info, \"Listening for external plugin connections on http:\/\/%s\", listenPort)\n\t\t\tLog(robot.Fatal, \"Error serving '\/json': %s\", http.Serve(listener, nil))\n\t\t}()\n\t}\n}\n\n\/\/ set connector sets the connector, which should already be initialized\nfunc setConnector(c robot.Connector) {\n\tinterfaces.Connector = c\n}\n\nvar keyEnv = \"GOPHER_ENCRYPTION_KEY\"\n\nfunc initCrypt() bool {\n\t\/\/ Initialize encryption (new style for v2)\n\tkeyFile := filepath.Join(configPath, encryptedKeyFile)\n\tencryptionInitialized := false\n\tif ek, ok := os.LookupEnv(keyEnv); ok {\n\t\tik := []byte(ek)[0:32]\n\t\tif bkf, err := ioutil.ReadFile(keyFile); err == nil {\n\t\t\tif bke, err := base64.StdEncoding.DecodeString(string(bkf)); err == nil {\n\t\t\t\tif key, err := decrypt(bke, ik); err == nil {\n\t\t\t\t\tcryptKey.key = key\n\t\t\t\t\tcryptKey.initialized = true\n\t\t\t\t\tencryptionInitialized = true\n\t\t\t\t\tLog(robot.Info, \"Successfully decrypted binary encryption key '%s'\", keyFile)\n\t\t\t\t} else {\n\t\t\t\t\tLog(robot.Error, \"Decrypting binary encryption key '%s' from environment key '%s': %v\", keyFile, keyEnv, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tLog(robot.Error, \"Base64 decoding '%s': %v\", keyFile, err)\n\t\t\t}\n\t\t} else {\n\t\t\tLog(robot.Warn, \"Binary encryption key not loaded from '%s': %v\", keyFile, err)\n\t\t\tif len(currentCfg.encryptionKey) == 0 {\n\t\t\t\t\/\/ No encryptionKey in config, create new-style key\n\t\t\t\tbk := make([]byte, 32)\n\t\t\t\t_, err := crand.Read(bk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLog(robot.Error, \"Generating new random encryption key: %v\", err)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tbek, err := encrypt(bk, ik)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLog(robot.Error, \"Encrypting new random key: %v\", err)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tbeks := base64.StdEncoding.EncodeToString(bek)\n\t\t\t\terr = ioutil.WriteFile(keyFile, []byte(beks), 0444)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLog(robot.Error, \"Writing out generated key: %v\", err)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tLog(robot.Info, \"Successfully wrote new binary encryption key to '%s'\", keyFile)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tos.Unsetenv(keyEnv)\n\t} else {\n\t\tLog(robot.Warn, \"GOPHER_ENCRYPTION_KEY not set in environment\")\n\t}\n\treturn encryptionInitialized\n}\n\n\/\/ run starts all the loops and returns a channel that closes when the robot\n\/\/ shuts down. It should return after the connector loop has started and\n\/\/ plugins are initialized.\nfunc run() <-chan bool {\n\t\/\/ Start the brain loop\n\tgo runBrain()\n\n\tvar cl []string\n\tcl = append(cl, currentCfg.joinChannels...)\n\tcl = append(cl, currentCfg.plugChannels...)\n\tcl = append(cl, currentCfg.defaultJobChannel)\n\tjc := make(map[string]bool)\n\tfor _, channel := range cl {\n\t\tif _, ok := jc[channel]; !ok {\n\t\t\tjc[channel] = true\n\t\t\tinterfaces.JoinChannel(channel)\n\t\t}\n\t}\n\n\t\/\/ signal handler\n\tgo func() {\n\t\tdone := interfaces.done\n\t\tsigs := make(chan os.Signal, 1)\n\n\t\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase sig := <-sigs:\n\t\t\t\tstate.Lock()\n\t\t\t\tif state.shuttingDown {\n\t\t\t\t\tLog(robot.Warn, \"Received SIGINT\/SIGTERM while shutdown in progress\")\n\t\t\t\t\tstate.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tstate.shuttingDown = true\n\t\t\t\t\tstate.Unlock()\n\t\t\t\t\tsignal.Stop(sigs)\n\t\t\t\t\tLog(robot.Info, \"Exiting on signal: %s\", sig)\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\tcase <-done:\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ connector loop\n\tgo func(conn robot.Connector, stop <-chan struct{}, done chan<- bool) {\n\t\traiseThreadPriv(\"connector loop\")\n\t\tconn.Run(stop)\n\t\tstate.RLock()\n\t\trestart := state.restart\n\t\tstate.RUnlock()\n\t\tif restart {\n\t\t\tLog(robot.Info, \"Restarting...\")\n\t\t}\n\t\tdone <- restart\n\t\t\/\/ NOTE!! Black Magic Ahead - for some reason, the read on the done channel\n\t\t\/\/ keeps blocking without this close.\n\t\tclose(done)\n\t}(interfaces.Connector, interfaces.stop, interfaces.done)\n\tc := &botContext{\n\t\tenvironment: make(map[string]string),\n\t}\n\tc.registerActive(nil)\n\tc.loadConfig(false)\n\tc.deregister()\n\treturn interfaces.done\n}\n\n\/\/ stop is called whenever the robot needs to shut down gracefully. All callers\n\/\/ should lock the bot and check the value of botCfg.shuttingDown; see\n\/\/ builtins.go.\nfunc stop() {\n\tstate.RLock()\n\tpr := state.pluginsRunning\n\tstop := interfaces.stop\n\tstate.RUnlock()\n\tLog(robot.Debug, \"stop called with %d plugins running\", pr)\n\tstate.Wait()\n\tbrainQuit()\n\tclose(stop)\n}\n<|endoftext|>"} {"text":"package golangQL\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype filterFunc func(val reflect.Value, tree *node) (interface{}, error)\n\nfunc (g *golangQL) filter(v interface{}, query string) (interface{}, error) {\n\tif len(query) == 0 {\n\t\treturn v, nil\n\t}\n\n\ttree, err := parse(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tval := reflect.ValueOf(v)\n\tfilter := g.getFilter(val, tree)\n\n\tresult, err := filter(val, tree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (g *golangQL) getFilter(val reflect.Value, tree *node) filterFunc {\n\tkey := newCacheKey(val.Type(), tree)\n\n\tg.RLock()\n\tf := g.filters[key]\n\tg.RUnlock()\n\tif f != nil {\n\t\treturn f\n\t}\n\n\tg.Lock()\n\tf = g.filters[key]\n\tif f != nil {\n\t\tg.Unlock()\n\t\treturn f\n\t}\n\n\trecursive := sync.WaitGroup{}\n\trecursive.Add(1)\n\tg.filters[key] = func(val reflect.Value, tree *node) (interface{}, error) {\n\t\trecursive.Wait()\n\t\treturn f(val, tree)\n\t}\n\tg.Unlock()\n\n\tf = g.newFilter(val.Type(), tree)\n\tg.Lock()\n\tg.filters[key] = f\n\tg.Unlock()\n\n\trecursive.Done()\n\treturn f\n}\n\nfunc (g *golangQL) newFilter(typ reflect.Type, tree *node) filterFunc {\n\tswitch typ.Kind() {\n\tcase reflect.Ptr:\n\t\treturn g.newPtrFilter(typ, tree)\n\tcase reflect.Struct:\n\t\treturn g.newStructFilter(typ, tree)\n\tcase reflect.Slice:\n\t\treturn g.newSliceFilter(typ, tree)\n\tdefault:\n\t\treturn defaultFilter()\n\t}\n}\n\n\/\/ Filter constructors\n\nfunc defaultFilter() filterFunc {\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\treturn val.Interface(), nil\n\t}\n}\n\nfunc (g *golangQL) newPtrFilter(typ reflect.Type, tree *node) filterFunc {\n\telemFilter := g.newFilter(typ.Elem(), tree)\n\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\tv := val.Elem()\n\n\t\treturn elemFilter(v, tree)\n\t}\n}\n\nfunc (g *golangQL) newSliceFilter(typ reflect.Type, tree *node) filterFunc {\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\tresultMap := make([]map[string]interface{}, val.Len())\n\t\tresultMapValue := reflect.ValueOf(resultMap)\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\tv := val.Index(i)\n\n\t\t\telementType := v.Type()\n\t\t\telemFilter := g.newFilter(elementType, tree)\n\n\t\t\tfilteredStruct, err := elemFilter(v, tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfilteredValue := reflect.ValueOf(filteredStruct)\n\n\t\t\tresultMapValue.Index(i).Set(filteredValue)\n\t\t}\n\n\t\treturn resultMap, nil\n\t}\n}\n\nfunc (g *golangQL) newStructFilter(typ reflect.Type, tree *node) filterFunc {\n\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\ttyp := val.Type()\n\t\tresultMap := make(map[string]interface{}, typ.NumField())\n\n\t\tfor i := 0; i < typ.NumField(); i++ {\n\t\t\tfield := typ.Field(i)\n\t\t\ttag, ok := field.Tag.Lookup(\"json\")\n\t\t\ttagName := g.fieldParseTag(tag)\n\n\t\t\tif !ok {\n\t\t\t\telemFilter := g.newFilter(field.Type, tree)\n\n\t\t\t\tembeded, err := elemFilter(val.Field(i), tree)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif reflect.TypeOf(embeded).Kind() != reflect.Map {\n\t\t\t\t\tresultMap[tagName] = val\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tembededMapValue := reflect.ValueOf(embeded)\n\t\t\t\tfor _, key := range embededMapValue.MapKeys() {\n\t\t\t\t\tresultMap[key.String()] = embededMapValue.MapIndex(key).Interface()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchild := tree.findChildByName(tagName)\n\t\t\tif child != nil {\n\t\t\t\telemFilter := g.newFilter(typ, child)\n\n\t\t\t\tchildStruct, err := elemFilter(val.Field(i).Elem(), child)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tresultMap[tagName] = childStruct\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif tree.containsField(tagName) {\n\t\t\t\tresultMap[tagName] = val.Field(i).Interface()\n\t\t\t}\n\t\t}\n\n\t\treturn resultMap, nil\n\t}\n}\n\nfunc (g *golangQL) fieldParseTag(tag string) string {\n\tif i := strings.Index(tag, \",\"); i != -1 {\n\t\tname := tag[:i]\n\t\ttag = tag[i+1:]\n\t\treturn name\n\t}\n\treturn tag\n}\nfix cachepackage golangQL\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype filterFunc func(val reflect.Value, tree *node) (interface{}, error)\n\nfunc (g *golangQL) filter(v interface{}, query string) (interface{}, error) {\n\tif len(query) == 0 {\n\t\treturn v, nil\n\t}\n\n\ttree, err := parse(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tval := reflect.ValueOf(v)\n\tfilter := g.getFilter(val.Type(), tree)\n\n\tresult, err := filter(val, tree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (g *golangQL) getFilter(typ reflect.Type, tree *node) filterFunc {\n\tg.RLock()\n\tkey := newCacheKey(typ, tree)\n\tf := g.filters[key]\n\tg.RUnlock()\n\tif f != nil {\n\t\treturn f\n\t}\n\n\tg.Lock()\n\tf = g.filters[key]\n\tif f != nil {\n\t\tg.Unlock()\n\t\treturn f\n\t}\n\n\trecursive := sync.WaitGroup{}\n\trecursive.Add(1)\n\tg.filters[key] = func(val reflect.Value, tree *node) (interface{}, error) {\n\t\trecursive.Wait()\n\t\treturn f(val, tree)\n\t}\n\tg.Unlock()\n\n\tf = g.newFilter(typ, tree)\n\tg.Lock()\n\tg.filters[key] = f\n\tg.Unlock()\n\n\trecursive.Done()\n\treturn f\n}\n\nfunc (g *golangQL) newFilter(typ reflect.Type, tree *node) filterFunc {\n\tswitch typ.Kind() {\n\tcase reflect.Ptr:\n\t\treturn g.newPtrFilter(typ, tree)\n\tcase reflect.Struct:\n\t\treturn g.newStructFilter(typ, tree)\n\tcase reflect.Slice:\n\t\treturn g.newSliceFilter(typ, tree)\n\tdefault:\n\t\treturn defaultFilter()\n\t}\n}\n\n\/\/ Filter constructors\n\nfunc defaultFilter() filterFunc {\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\treturn val.Interface(), nil\n\t}\n}\n\nfunc (g *golangQL) newPtrFilter(typ reflect.Type, tree *node) filterFunc {\n\telemFilter := g.getFilter(typ.Elem(), tree)\n\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\tv := val.Elem()\n\n\t\treturn elemFilter(v, tree)\n\t}\n}\n\nfunc (g *golangQL) newSliceFilter(typ reflect.Type, tree *node) filterFunc {\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\tresultMap := make([]map[string]interface{}, val.Len())\n\t\tresultMapValue := reflect.ValueOf(resultMap)\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\tv := val.Index(i)\n\n\t\t\telementType := v.Type()\n\t\t\telemFilter := g.getFilter(elementType, tree)\n\n\t\t\tfilteredStruct, err := elemFilter(v, tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfilteredValue := reflect.ValueOf(filteredStruct)\n\n\t\t\tresultMapValue.Index(i).Set(filteredValue)\n\t\t}\n\n\t\treturn resultMap, nil\n\t}\n}\n\nfunc (g *golangQL) newStructFilter(typ reflect.Type, tree *node) filterFunc {\n\n\treturn func(val reflect.Value, tree *node) (interface{}, error) {\n\t\ttyp := val.Type()\n\t\tresultMap := make(map[string]interface{}, typ.NumField())\n\n\t\tfor i := 0; i < typ.NumField(); i++ {\n\t\t\tfield := typ.Field(i)\n\t\t\ttag, ok := field.Tag.Lookup(\"json\")\n\t\t\ttagName := g.fieldParseTag(tag)\n\n\t\t\tif !ok {\n\t\t\t\telemFilter := g.getFilter(field.Type, tree)\n\n\t\t\t\tembeded, err := elemFilter(val.Field(i), tree)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif reflect.TypeOf(embeded).Kind() != reflect.Map {\n\t\t\t\t\tresultMap[tagName] = val\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tembededMapValue := reflect.ValueOf(embeded)\n\t\t\t\tfor _, key := range embededMapValue.MapKeys() {\n\t\t\t\t\tresultMap[key.String()] = embededMapValue.MapIndex(key).Interface()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchild := tree.findChildByName(tagName)\n\t\t\tif child != nil {\n\t\t\t\telemFilter := g.getFilter(typ, child)\n\n\t\t\t\tchildStruct, err := elemFilter(val.Field(i).Elem(), child)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tresultMap[tagName] = childStruct\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif tree.containsField(tagName) {\n\t\t\t\tresultMap[tagName] = val.Field(i).Interface()\n\t\t\t}\n\t\t}\n\n\t\treturn resultMap, nil\n\t}\n}\n\nfunc (g *golangQL) fieldParseTag(tag string) string {\n\tif i := strings.Index(tag, \",\"); i != -1 {\n\t\tname := tag[:i]\n\t\ttag = tag[i+1:]\n\t\treturn name\n\t}\n\treturn tag\n}\n<|endoftext|>"} {"text":"package i\n\n\/\/ Filter iterator\ntype FilterFunc func(Iterator) bool\n\ntype filter struct {\n\twforward\n\tff FilterFunc\n}\n\nfunc Filter(ff FilterFunc, itr Forward) Forward {\n\tf := filter{ff: ff}\n\tf.wforward = *(WrapForward(itr))\n\treturn &f\n}\n\nfunc (f *filter) AtEnd() bool {\n\tfor !f.wforward.AtEnd() {\n\t\tif f.ff(&f.wforward) {\n\t\t\treturn false\n\t\t}\n\t\tf.wforward.Next()\n\t}\n\treturn true\n}\ni.Filter: remove AtEnd implementation, move it to Next. AtEnd is now idempotent as it should bepackage i\n\nimport \"fmt\"\n\n\/\/ Filter iterator\ntype FilterFunc func(Iterator) bool\n\ntype filter struct {\n\tWForward\n\tff FilterFunc\n}\n\nfunc Filter(ff FilterFunc, itr Forward) Forward {\n\tf := filter{ff: ff}\n\tf.WForward = *(WrapForward(itr))\n\treturn &f\n}\n\nfunc (f *filter) Next() error {\n\tif f.WForward.AtEnd() {\n\t\tf.WForward.SetError(fmt.Errorf(\"Calling Next() after end\"))\n\t\treturn f.WForward.Error()\n\t}\n\tfor !f.WForward.AtEnd() {\n\t\tf.WForward.Next()\n\t\tif !f.WForward.AtEnd() && f.ff(&f.WForward) {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn f.WForward.Error()\n}\n<|endoftext|>"} {"text":"\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage router\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/networking\/handler\"\n\t\"github.com\/ava-labs\/gecko\/snow\/networking\/timeout\"\n\t\"github.com\/ava-labs\/gecko\/utils\/logging\"\n\t\"github.com\/ava-labs\/gecko\/utils\/timer\"\n)\n\n\/\/ ChainRouter routes incoming messages from the validator network\n\/\/ to the consensus engines that the messages are intended for.\n\/\/ Note that consensus engines are uniquely identified by the ID of the chain\n\/\/ that they are working on.\ntype ChainRouter struct {\n\tlog logging.Logger\n\tlock sync.RWMutex\n\tchains map[[32]byte]*handler.Handler\n\ttimeouts *timeout.Manager\n\tgossiper *timer.Repeater\n}\n\n\/\/ Initialize the router\n\/\/ When this router receives an incoming message, it cancels the timeout in [timeouts]\n\/\/ associated with the request that caused the incoming message, if applicable\nfunc (sr *ChainRouter) Initialize(log logging.Logger, timeouts *timeout.Manager, gossipFrequency time.Duration) {\n\tsr.log = log\n\tsr.chains = make(map[[32]byte]*handler.Handler)\n\tsr.timeouts = timeouts\n\tsr.gossiper = timer.NewRepeater(sr.Gossip, gossipFrequency)\n\n\tgo log.RecoverAndPanic(sr.gossiper.Dispatch)\n}\n\n\/\/ AddChain registers the specified chain so that incoming\n\/\/ messages can be routed to it\nfunc (sr *ChainRouter) AddChain(chain *handler.Handler) {\n\tsr.lock.Lock()\n\tdefer sr.lock.Unlock()\n\n\tchainID := chain.Context().ChainID\n\tsr.log.Debug(\"Adding %s to the routing table\", chainID)\n\tsr.chains[chainID.Key()] = chain\n}\n\n\/\/ RemoveChain removes the specified chain so that incoming\n\/\/ messages can't be routed to it\nfunc (sr *ChainRouter) RemoveChain(chainID ids.ID) {\n\tsr.lock.Lock()\n\tdefer sr.lock.Unlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Shutdown()\n\t\tdelete(sr.chains, chainID.Key())\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFrontier routes an incoming GetAcceptedFrontier request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFrontier(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFrontier(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ AcceptedFrontier routes an incoming AcceptedFrontier request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) AcceptedFrontier(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.AcceptedFrontier(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFrontierFailed routes an incoming GetAcceptedFrontierFailed\n\/\/ request from the validator with ID [validatorID] to the consensus engine\n\/\/ working on the chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFrontierFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFrontierFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAccepted routes an incoming GetAccepted request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAccepted(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAccepted(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Accepted routes an incoming Accepted request from the validator with ID\n\/\/ [validatorID] to the consensus engine working on the chain with ID\n\/\/ [chainID]\nfunc (sr *ChainRouter) Accepted(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Accepted(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFailed routes an incoming GetAcceptedFailed request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Get routes an incoming Get request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Get(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Get(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Put routes an incoming Put request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Put(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID, container []byte) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\t\/\/ This message came in response to a Get message from this node, and when we sent that Get\n\t\/\/ message we set a timeout. Since we got a response, cancel the timeout.\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Put(validatorID, requestID, containerID, container)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetFailed routes an incoming GetFailed message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) GetFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetFailed(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ PushQuery routes an incoming PushQuery request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) PushQuery(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID, container []byte) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.PushQuery(validatorID, requestID, containerID, container)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ PullQuery routes an incoming PullQuery request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) PullQuery(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.PullQuery(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Chits routes an incoming Chits message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Chits(validatorID ids.ShortID, chainID ids.ID, requestID uint32, votes ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\t\/\/ Cancel timeout we set when sent the message asking for these Chits\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Chits(validatorID, requestID, votes)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ QueryFailed routes an incoming QueryFailed message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) QueryFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.QueryFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Shutdown shuts down this router\nfunc (sr *ChainRouter) Shutdown() {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.shutdown()\n}\n\nfunc (sr *ChainRouter) shutdown() {\n\tfor _, chain := range sr.chains {\n\t\tchain.Shutdown()\n\t}\n\tsr.gossiper.Stop()\n}\n\n\/\/ Gossip accepted containers\nfunc (sr *ChainRouter) Gossip() {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.gossip()\n}\n\nfunc (sr *ChainRouter) gossip() {\n\tfor _, chain := range sr.chains {\n\t\tchain.Gossip()\n\t}\n}\nAdded gossip frequency docs\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage router\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/networking\/handler\"\n\t\"github.com\/ava-labs\/gecko\/snow\/networking\/timeout\"\n\t\"github.com\/ava-labs\/gecko\/utils\/logging\"\n\t\"github.com\/ava-labs\/gecko\/utils\/timer\"\n)\n\n\/\/ ChainRouter routes incoming messages from the validator network\n\/\/ to the consensus engines that the messages are intended for.\n\/\/ Note that consensus engines are uniquely identified by the ID of the chain\n\/\/ that they are working on.\ntype ChainRouter struct {\n\tlog logging.Logger\n\tlock sync.RWMutex\n\tchains map[[32]byte]*handler.Handler\n\ttimeouts *timeout.Manager\n\tgossiper *timer.Repeater\n}\n\n\/\/ Initialize the router.\n\/\/\n\/\/ When this router receives an incoming message, it cancels the timeout in\n\/\/ [timeouts] associated with the request that caused the incoming message, if\n\/\/ applicable.\n\/\/\n\/\/ This router also fires a gossip event every [gossipFrequency] to the engine,\n\/\/ notifying the engine it should gossip it's accepted set.\nfunc (sr *ChainRouter) Initialize(log logging.Logger, timeouts *timeout.Manager, gossipFrequency time.Duration) {\n\tsr.log = log\n\tsr.chains = make(map[[32]byte]*handler.Handler)\n\tsr.timeouts = timeouts\n\tsr.gossiper = timer.NewRepeater(sr.Gossip, gossipFrequency)\n\n\tgo log.RecoverAndPanic(sr.gossiper.Dispatch)\n}\n\n\/\/ AddChain registers the specified chain so that incoming\n\/\/ messages can be routed to it\nfunc (sr *ChainRouter) AddChain(chain *handler.Handler) {\n\tsr.lock.Lock()\n\tdefer sr.lock.Unlock()\n\n\tchainID := chain.Context().ChainID\n\tsr.log.Debug(\"Adding %s to the routing table\", chainID)\n\tsr.chains[chainID.Key()] = chain\n}\n\n\/\/ RemoveChain removes the specified chain so that incoming\n\/\/ messages can't be routed to it\nfunc (sr *ChainRouter) RemoveChain(chainID ids.ID) {\n\tsr.lock.Lock()\n\tdefer sr.lock.Unlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Shutdown()\n\t\tdelete(sr.chains, chainID.Key())\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFrontier routes an incoming GetAcceptedFrontier request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFrontier(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFrontier(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ AcceptedFrontier routes an incoming AcceptedFrontier request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) AcceptedFrontier(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.AcceptedFrontier(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFrontierFailed routes an incoming GetAcceptedFrontierFailed\n\/\/ request from the validator with ID [validatorID] to the consensus engine\n\/\/ working on the chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFrontierFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFrontierFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAccepted routes an incoming GetAccepted request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAccepted(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAccepted(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Accepted routes an incoming Accepted request from the validator with ID\n\/\/ [validatorID] to the consensus engine working on the chain with ID\n\/\/ [chainID]\nfunc (sr *ChainRouter) Accepted(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerIDs ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Accepted(validatorID, requestID, containerIDs)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetAcceptedFailed routes an incoming GetAcceptedFailed request from the\n\/\/ validator with ID [validatorID] to the consensus engine working on the\n\/\/ chain with ID [chainID]\nfunc (sr *ChainRouter) GetAcceptedFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetAcceptedFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Get routes an incoming Get request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Get(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Get(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Put routes an incoming Put request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Put(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID, container []byte) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\t\/\/ This message came in response to a Get message from this node, and when we sent that Get\n\t\/\/ message we set a timeout. Since we got a response, cancel the timeout.\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Put(validatorID, requestID, containerID, container)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ GetFailed routes an incoming GetFailed message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) GetFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.GetFailed(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ PushQuery routes an incoming PushQuery request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) PushQuery(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID, container []byte) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.PushQuery(validatorID, requestID, containerID, container)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ PullQuery routes an incoming PullQuery request from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) PullQuery(validatorID ids.ShortID, chainID ids.ID, requestID uint32, containerID ids.ID) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.PullQuery(validatorID, requestID, containerID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Chits routes an incoming Chits message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) Chits(validatorID ids.ShortID, chainID ids.ID, requestID uint32, votes ids.Set) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\t\/\/ Cancel timeout we set when sent the message asking for these Chits\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.Chits(validatorID, requestID, votes)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ QueryFailed routes an incoming QueryFailed message from the validator with ID [validatorID]\n\/\/ to the consensus engine working on the chain with ID [chainID]\nfunc (sr *ChainRouter) QueryFailed(validatorID ids.ShortID, chainID ids.ID, requestID uint32) {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.timeouts.Cancel(validatorID, chainID, requestID)\n\tif chain, exists := sr.chains[chainID.Key()]; exists {\n\t\tchain.QueryFailed(validatorID, requestID)\n\t} else {\n\t\tsr.log.Warn(\"Message referenced a chain, %s, this validator is not validating\", chainID)\n\t}\n}\n\n\/\/ Shutdown shuts down this router\nfunc (sr *ChainRouter) Shutdown() {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.shutdown()\n}\n\nfunc (sr *ChainRouter) shutdown() {\n\tfor _, chain := range sr.chains {\n\t\tchain.Shutdown()\n\t}\n\tsr.gossiper.Stop()\n}\n\n\/\/ Gossip accepted containers\nfunc (sr *ChainRouter) Gossip() {\n\tsr.lock.RLock()\n\tdefer sr.lock.RUnlock()\n\n\tsr.gossip()\n}\n\nfunc (sr *ChainRouter) gossip() {\n\tfor _, chain := range sr.chains {\n\t\tchain.Gossip()\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/vlifesystems\/rulehuntersrv\/logger\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSubMain_errors(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"rulehuntersrv\")\n\tif err != nil {\n\t\tt.Fatal(\"TempDir() couldn't create dir\")\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\tcases := []struct {\n\t\tflags *cmdFlags\n\t\twantErr error\n\t\twantExitCode int\n\t}{\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tconfigDir: \"\",\n\t\t\t\tinstall: true,\n\t\t\t},\n\t\t\twantErr: errNoConfigDirArg,\n\t\t\twantExitCode: 1,\n\t\t},\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tconfigDir: tmpDir,\n\t\t\t\tinstall: true,\n\t\t\t},\n\t\t\twantErr: errConfigLoad{\n\t\t\t\tfilename: filepath.Join(tmpDir, \"config.json\"),\n\t\t\t\terr: &os.PathError{\n\t\t\t\t\t\"open\",\n\t\t\t\t\tfilepath.Join(tmpDir, \"config.json\"),\n\t\t\t\t\tsyscall.ENOENT,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantExitCode: 1,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\ttestLogger := logger.NewTestLogger()\n\t\tquitter := newQuitter()\n\t\texitCode, err := subMain(c.flags, testLogger.MakeRun(), quitter)\n\t\tif exitCode != c.wantExitCode {\n\t\t\tt.Errorf(\"subMain(%q) exitCode: %d, want: %d\",\n\t\t\t\tc.flags, exitCode, c.wantExitCode)\n\t\t}\n\t\tif err := checkErrorMatch(err, c.wantErr); err != nil {\n\t\t\tt.Errorf(\"subMain(%q) %s\", c.flags, err)\n\t\t}\n\t\tif len(testLogger.GetEntries()) != 0 {\n\t\t\tt.Errorf(\"GetEntries() got: %s, want: {}\", testLogger.GetEntries())\n\t\t}\n\t}\n}\n\nfunc TestSubMain(t *testing.T) {\n\tcases := []struct {\n\t\tflags *cmdFlags\n\t\twantErr error\n\t\twantExitCode int\n\t\twantEntries []logger.Entry\n\t}{\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tinstall: false,\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\twantExitCode: 0,\n\t\t\twantEntries: []logger.Entry{\n\t\t\t\t{logger.Info, \"Waiting for experiments to process\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tconfigDir, err := buildConfigDirs()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"buildConfigDirs() err: %s\", err)\n\t\t}\n\t\tdefer os.RemoveAll(c.flags.configDir)\n\t\tc.flags.configDir = configDir\n\n\t\ttestLogger := logger.NewTestLogger()\n\t\tquitter := newQuitter()\n\t\tgo func() {\n\t\t\ttryInSeconds := 10\n\t\t\tfor i := 0; i < tryInSeconds*5; i++ {\n\t\t\t\tif reflect.DeepEqual(testLogger.GetEntries(), c.wantEntries) {\n\t\t\t\t\tquitter.Quit()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t}\n\t\t\tquitter.Quit()\n\t\t}()\n\t\texitCode, err := subMain(c.flags, testLogger.MakeRun(), quitter)\n\t\tif exitCode != c.wantExitCode {\n\t\t\tt.Errorf(\"subMain(%q) exitCode: %d, want: %d\",\n\t\t\t\tc.flags, exitCode, c.wantExitCode)\n\t\t}\n\t\tif err := checkErrorMatch(err, c.wantErr); err != nil {\n\t\t\tt.Errorf(\"subMain(%q) %s\", c.flags, err)\n\t\t}\n\t\tif !reflect.DeepEqual(testLogger.GetEntries(), c.wantEntries) {\n\t\t\tt.Errorf(\"GetEntries() got: %s, want: %s\",\n\t\t\t\ttestLogger.GetEntries(), c.wantEntries)\n\t\t}\n\t}\n}\n\n\/*************************************\n * Helper functions\n *************************************\/\n\nfunc buildConfigDirs() (string, error) {\n\t\/\/ File mode permission:\n\t\/\/ No special permission bits\n\t\/\/ User: Read, Write Execute\n\t\/\/ Group: None\n\t\/\/ Other: None\n\tconst modePerm = 0700\n\n\ttmpDir, err := ioutil.TempDir(\"\", \"rulehuntersrv\")\n\tif err != nil {\n\t\treturn \"\", errors.New(\"TempDir() couldn't create dir\")\n\t}\n\n\tsubDirs := []string{\"experiments\", \"www\", \"build\"}\n\tfor _, subDir := range subDirs {\n\t\tif err := os.MkdirAll(subDir, modePerm); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"can't make directory: %s\", subDir)\n\t\t}\n\t}\n\n\terr = copyFile(filepath.Join(\"fixtures\", \"config.json\"), tmpDir)\n\treturn tmpDir, err\n}\n\nfunc checkErrorMatch(got, want error) error {\n\tif got == nil && want == nil {\n\t\treturn nil\n\t}\n\tif got == nil || want == nil {\n\t\treturn fmt.Errorf(\"got err: %s, want err: %s\", got, want)\n\t}\n\tswitch x := want.(type) {\n\tcase *os.PathError:\n\t\treturn checkPathErrorMatch(got, x)\n\tcase errConfigLoad:\n\t\treturn checkErrConfigLoadMatch(got, x)\n\t}\n\tif got.Error() != want.Error() {\n\t\treturn fmt.Errorf(\"got err: %s, want err: %s\", got, want)\n\t}\n\treturn nil\n}\n\nfunc checkPathErrorMatch(checkErr error, wantErr error) error {\n\tcerr, ok := checkErr.(*os.PathError)\n\tif !ok {\n\t\treturn fmt.Errorf(\"got err type: %T, want error type: os.PathError\",\n\t\t\tcheckErr)\n\t}\n\twerr, ok := wantErr.(*os.PathError)\n\tif !ok {\n\t\tpanic(\"wantErr isn't type *os.PathError\")\n\t}\n\tif cerr.Op != werr.Op {\n\t\treturn fmt.Errorf(\"got cerr.Op: %s, want: %s\", cerr.Op, werr.Op)\n\t}\n\tif filepath.Clean(cerr.Path) != filepath.Clean(werr.Path) {\n\t\treturn fmt.Errorf(\"got cerr.Path: %s, want: %s\", cerr.Path, werr.Path)\n\t}\n\tif cerr.Err != werr.Err {\n\t\treturn fmt.Errorf(\"got cerr.Err: %s, want: %s\", cerr.Err, werr.Err)\n\t}\n\treturn nil\n}\n\nfunc checkErrConfigLoadMatch(checkErr error, wantErr errConfigLoad) error {\n\tcerr, ok := checkErr.(errConfigLoad)\n\tif !ok {\n\t\treturn fmt.Errorf(\"got err type: %T, want error type: errConfigLoad\",\n\t\t\tcheckErr)\n\t}\n\tif filepath.Clean(cerr.filename) != filepath.Clean(wantErr.filename) {\n\t\treturn fmt.Errorf(\"got cerr.Path: %s, want: %s\",\n\t\t\tcerr.filename, wantErr.filename)\n\t}\n\treturn checkPathErrorMatch(cerr.err, wantErr.err)\n}\n\nfunc copyFile(srcFilename, dstDir string) error {\n\tcontents, err := ioutil.ReadFile(srcFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := os.Stat(srcFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmode := info.Mode()\n\tdstFilename := filepath.Join(dstDir, filepath.Base(srcFilename))\n\treturn ioutil.WriteFile(dstFilename, contents, mode)\n}\nCreate www\/* and build\/* subdirs in testpackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/vlifesystems\/rulehuntersrv\/logger\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSubMain_errors(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"rulehuntersrv\")\n\tif err != nil {\n\t\tt.Fatal(\"TempDir() couldn't create dir\")\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\tcases := []struct {\n\t\tflags *cmdFlags\n\t\twantErr error\n\t\twantExitCode int\n\t}{\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tconfigDir: \"\",\n\t\t\t\tinstall: true,\n\t\t\t},\n\t\t\twantErr: errNoConfigDirArg,\n\t\t\twantExitCode: 1,\n\t\t},\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tconfigDir: tmpDir,\n\t\t\t\tinstall: true,\n\t\t\t},\n\t\t\twantErr: errConfigLoad{\n\t\t\t\tfilename: filepath.Join(tmpDir, \"config.json\"),\n\t\t\t\terr: &os.PathError{\n\t\t\t\t\t\"open\",\n\t\t\t\t\tfilepath.Join(tmpDir, \"config.json\"),\n\t\t\t\t\tsyscall.ENOENT,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantExitCode: 1,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\ttestLogger := logger.NewTestLogger()\n\t\tquitter := newQuitter()\n\t\texitCode, err := subMain(c.flags, testLogger.MakeRun(), quitter)\n\t\tif exitCode != c.wantExitCode {\n\t\t\tt.Errorf(\"subMain(%q) exitCode: %d, want: %d\",\n\t\t\t\tc.flags, exitCode, c.wantExitCode)\n\t\t}\n\t\tif err := checkErrorMatch(err, c.wantErr); err != nil {\n\t\t\tt.Errorf(\"subMain(%q) %s\", c.flags, err)\n\t\t}\n\t\tif len(testLogger.GetEntries()) != 0 {\n\t\t\tt.Errorf(\"GetEntries() got: %s, want: {}\", testLogger.GetEntries())\n\t\t}\n\t}\n}\n\nfunc TestSubMain(t *testing.T) {\n\tcases := []struct {\n\t\tflags *cmdFlags\n\t\twantErr error\n\t\twantExitCode int\n\t\twantEntries []logger.Entry\n\t}{\n\t\t{\n\t\t\tflags: &cmdFlags{\n\t\t\t\tuser: \"fred\",\n\t\t\t\tinstall: false,\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\twantExitCode: 0,\n\t\t\twantEntries: []logger.Entry{\n\t\t\t\t{logger.Info, \"Waiting for experiments to process\"},\n\t\t\t},\n\t\t},\n\t}\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatalf(\"Getwd() err: \", err)\n\t}\n\tdefer os.Chdir(wd)\n\n\tfor _, c := range cases {\n\t\tconfigDir, err := buildConfigDirs()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"buildConfigDirs() err: %s\", err)\n\t\t}\n\t\tdefer os.RemoveAll(c.flags.configDir)\n\t\tc.flags.configDir = configDir\n\n\t\ttestLogger := logger.NewTestLogger()\n\t\tquitter := newQuitter()\n\t\tgo func() {\n\t\t\ttryInSeconds := 5\n\t\t\tfor i := 0; i < tryInSeconds*5; i++ {\n\t\t\t\tif reflect.DeepEqual(testLogger.GetEntries(), c.wantEntries) {\n\t\t\t\t\tquitter.Quit()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t}\n\t\t\tquitter.Quit()\n\t\t}()\n\t\tif err := os.Chdir(configDir); err != nil {\n\t\t\tt.Fatalf(\"Chdir() err: %s\", err)\n\t\t}\n\t\texitCode, err := subMain(c.flags, testLogger.MakeRun(), quitter)\n\t\tif exitCode != c.wantExitCode {\n\t\t\tt.Errorf(\"subMain(%q) exitCode: %d, want: %d\",\n\t\t\t\tc.flags, exitCode, c.wantExitCode)\n\t\t}\n\t\tif err := checkErrorMatch(err, c.wantErr); err != nil {\n\t\t\tt.Errorf(\"subMain(%q) %s\", c.flags, err)\n\t\t}\n\t\tif !reflect.DeepEqual(testLogger.GetEntries(), c.wantEntries) {\n\t\t\tt.Errorf(\"GetEntries() got: %s, want: %s\",\n\t\t\t\ttestLogger.GetEntries(), c.wantEntries)\n\t\t}\n\t}\n}\n\n\/*************************************\n * Helper functions\n *************************************\/\n\nfunc buildConfigDirs() (string, error) {\n\t\/\/ File mode permission:\n\t\/\/ No special permission bits\n\t\/\/ User: Read, Write Execute\n\t\/\/ Group: None\n\t\/\/ Other: None\n\tconst modePerm = 0700\n\n\ttmpDir, err := ioutil.TempDir(\"\", \"rulehuntersrv\")\n\tif err != nil {\n\t\treturn \"\", errors.New(\"TempDir() couldn't create dir\")\n\t}\n\n\t\/\/ TODO: Create the www\/* and build\/* subdirectories from rulehuntersrv code\n\tsubDirs := []string{\n\t\t\"experiments\",\n\t\tfilepath.Join(\"www\", \"reports\"),\n\t\tfilepath.Join(\"www\", \"progress\"),\n\t\tfilepath.Join(\"build\", \"reports\")}\n\tfor _, subDir := range subDirs {\n\t\tfullSubDir := filepath.Join(tmpDir, subDir)\n\t\tif err := os.MkdirAll(fullSubDir, modePerm); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"can't make directory: %s\", subDir)\n\t\t}\n\t}\n\n\terr = copyFile(filepath.Join(\"fixtures\", \"config.json\"), tmpDir)\n\treturn tmpDir, err\n}\n\nfunc checkErrorMatch(got, want error) error {\n\tif got == nil && want == nil {\n\t\treturn nil\n\t}\n\tif got == nil || want == nil {\n\t\treturn fmt.Errorf(\"got err: %s, want err: %s\", got, want)\n\t}\n\tswitch x := want.(type) {\n\tcase *os.PathError:\n\t\treturn checkPathErrorMatch(got, x)\n\tcase errConfigLoad:\n\t\treturn checkErrConfigLoadMatch(got, x)\n\t}\n\tif got.Error() != want.Error() {\n\t\treturn fmt.Errorf(\"got err: %s, want err: %s\", got, want)\n\t}\n\treturn nil\n}\n\nfunc checkPathErrorMatch(checkErr error, wantErr error) error {\n\tcerr, ok := checkErr.(*os.PathError)\n\tif !ok {\n\t\treturn fmt.Errorf(\"got err type: %T, want error type: os.PathError\",\n\t\t\tcheckErr)\n\t}\n\twerr, ok := wantErr.(*os.PathError)\n\tif !ok {\n\t\tpanic(\"wantErr isn't type *os.PathError\")\n\t}\n\tif cerr.Op != werr.Op {\n\t\treturn fmt.Errorf(\"got cerr.Op: %s, want: %s\", cerr.Op, werr.Op)\n\t}\n\tif filepath.Clean(cerr.Path) != filepath.Clean(werr.Path) {\n\t\treturn fmt.Errorf(\"got cerr.Path: %s, want: %s\", cerr.Path, werr.Path)\n\t}\n\tif cerr.Err != werr.Err {\n\t\treturn fmt.Errorf(\"got cerr.Err: %s, want: %s\", cerr.Err, werr.Err)\n\t}\n\treturn nil\n}\n\nfunc checkErrConfigLoadMatch(checkErr error, wantErr errConfigLoad) error {\n\tcerr, ok := checkErr.(errConfigLoad)\n\tif !ok {\n\t\treturn fmt.Errorf(\"got err type: %T, want error type: errConfigLoad\",\n\t\t\tcheckErr)\n\t}\n\tif filepath.Clean(cerr.filename) != filepath.Clean(wantErr.filename) {\n\t\treturn fmt.Errorf(\"got cerr.Path: %s, want: %s\",\n\t\t\tcerr.filename, wantErr.filename)\n\t}\n\treturn checkPathErrorMatch(cerr.err, wantErr.err)\n}\n\nfunc copyFile(srcFilename, dstDir string) error {\n\tcontents, err := ioutil.ReadFile(srcFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := os.Stat(srcFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmode := info.Mode()\n\tdstFilename := filepath.Join(dstDir, filepath.Base(srcFilename))\n\treturn ioutil.WriteFile(dstFilename, contents, mode)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 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\/\/ https:\/\/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\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/googleapis\/gapic-showcase\/util\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nconst currentAPIVersion = \"v1alpha3\"\nconst currentReleaseVersion = \"0.0.16\"\n\n\/\/ This script updates the release version or API version of files in gapic-showcase.\n\/\/ This script is used on API and release version bumps. This script must be ran in\n\/\/ the root directory of gapic-showcase.\n\/\/\n\/\/ Usage: go run .\/util\/cmd\/bump_version\/main.go -h\nfunc main() {\n\tvar bumpMajor, bumpMinor, bumpPatch bool\n\tvar newAPI string\n\n\tcmd := &cobra.Command{\n\t\tShort: \"Utility script to bump the API and realease versions in all relevant files.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif newAPI == \"\" && !bumpMajor && !bumpMinor && !bumpPatch {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif bumpMajor || bumpMinor || bumpPatch {\n\t\t\t\tif !oneof(bumpMajor, bumpMinor, bumpPatch) {\n\t\t\t\t\tlog.Fatalf(\"Expected only one of --major, --minor, and --patch.\")\n\t\t\t\t}\n\t\t\t\tversions := strings.Split(currentReleaseVersion, \".\")\n\n\t\t\t\tatoi := func(s string) int {\n\t\t\t\t\ti, err := strconv.Atoi(s)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn i\n\t\t\t\t}\n\n\t\t\t\tmajor := atoi(versions[0])\n\t\t\t\tminor := atoi(versions[1])\n\t\t\t\tpatch := atoi(versions[2])\n\n\t\t\t\tif bumpMajor {\n\t\t\t\t\tmajor++\n\t\t\t\t\tminor = 0\n\t\t\t\t\tpatch = 0\n\t\t\t\t}\n\t\t\t\tif bumpMinor {\n\t\t\t\t\tminor++\n\t\t\t\t\tpatch = 0\n\t\t\t\t}\n\t\t\t\tif bumpPatch {\n\t\t\t\t\tpatch++\n\t\t\t\t}\n\t\t\t\treplace(currentReleaseVersion, fmt.Sprintf(\"%d.%d.%d\", major, minor, patch))\n\t\t\t}\n\n\t\t\tif newAPI != \"\" && currentAPIVersion != newAPI {\n\t\t\t\tversionRegexStr := \"^([v]\\\\d+)([p_]\\\\d+)?((alpha|beta)\\\\d*)?\"\n\t\t\t\tversionRegex, err := regexp.Compile(versionRegexStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Unexpected Error compiling version regex: %+v\", err)\n\t\t\t\t}\n\t\t\t\tif !versionRegex.Match([]byte(newAPI)) {\n\t\t\t\t\tlog.Fatalf(\"The API version must conform to the regex: %s\", versionRegexStr)\n\t\t\t\t}\n\n\t\t\t\tschemaDir := filepath.Join(\"schema\", \"google\", \"showcase\")\n\t\t\t\terr = os.Rename(filepath.Join(schemaDir, currentAPIVersion), filepath.Join(schemaDir, newAPI))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to change proto directory: %+v\", err)\n\t\t\t\t}\n\n\t\t\t\treplace(currentAPIVersion, newAPI)\n\t\t\t\tutil.CompileProtos(newAPI)\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVarP(\n\t\t&bumpMajor,\n\t\t\"major\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the major version\")\n\tcmd.Flags().BoolVarP(\n\t\t&bumpMinor,\n\t\t\"minor\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the minor version\")\n\tcmd.Flags().BoolVarP(\n\t\t&bumpPatch,\n\t\t\"patch\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the patch version\")\n\tcmd.Flags().StringVarP(\n\t\t&newAPI,\n\t\t\"api\",\n\t\t\"a\",\n\t\t\"\",\n\t\t\"The new API version to set.\")\n\n\tif err := cmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc replace(old, new string) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: unable to get working dir: %+v\", err)\n\t}\n\n\tfiletypes := []string{\".go\", \".md\", \".yml\"}\n\terr = filepath.Walk(pwd, replacer(filetypes, old, new))\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n}\n\nfunc replacer(filetypes []string, old, new string) filepath.WalkFunc {\n\treturn func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif strings.HasSuffix(fi.Name(), \"CHANGELOG.md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\tmatched := false\n\t\tfor _, t := range filetypes {\n\t\t\tmatched = matched || strings.HasSuffix(path, t)\n\t\t}\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\n\t\toldBytes, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"%v\", err)\n\t\t}\n\n\t\tnewBytes := bytes.Replace(oldBytes, []byte(old), []byte(new), -1)\n\t\tif !bytes.Equal(oldBytes, newBytes) {\n\t\t\tif err = ioutil.WriteFile(path, newBytes, 0); err != nil {\n\t\t\t\tlog.Fatalf(\"%v\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc oneof(bs ...bool) bool {\n\tt := 0\n\tfor _, b := range bs {\n\t\tif b {\n\t\t\tt++\n\t\t}\n\t}\n\treturn t == 1\n}\nSmall bump script fix (#119)\/\/ Copyright 2018 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\/\/ https:\/\/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\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/googleapis\/gapic-showcase\/util\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nconst currentAPIVersion = \"v1alpha3\"\nconst currentReleaseVersion = \"0.0.16\"\n\n\/\/ This script updates the release version or API version of files in gapic-showcase.\n\/\/ This script is used on API and release version bumps. This script must be ran in\n\/\/ the root directory of gapic-showcase.\n\/\/\n\/\/ Usage: go run .\/util\/cmd\/bump_version\/main.go -h\nfunc main() {\n\tvar bumpMajor, bumpMinor, bumpPatch bool\n\tvar newAPI string\n\n\tcmd := &cobra.Command{\n\t\tShort: \"Utility script to bump the API and realease versions in all relevant files.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif newAPI == \"\" && !bumpMajor && !bumpMinor && !bumpPatch {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif bumpMajor || bumpMinor || bumpPatch {\n\t\t\t\tif !oneof(bumpMajor, bumpMinor, bumpPatch) {\n\t\t\t\t\tlog.Fatalf(\"Expected only one of --major, --minor, and --patch.\")\n\t\t\t\t}\n\t\t\t\tversions := strings.Split(currentReleaseVersion, \".\")\n\n\t\t\t\tatoi := func(s string) int {\n\t\t\t\t\ti, err := strconv.Atoi(s)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn i\n\t\t\t\t}\n\n\t\t\t\tmajor := atoi(versions[0])\n\t\t\t\tminor := atoi(versions[1])\n\t\t\t\tpatch := atoi(versions[2])\n\n\t\t\t\tif bumpMajor {\n\t\t\t\t\tmajor++\n\t\t\t\t\tminor = 0\n\t\t\t\t\tpatch = 0\n\t\t\t\t}\n\t\t\t\tif bumpMinor {\n\t\t\t\t\tminor++\n\t\t\t\t\tpatch = 0\n\t\t\t\t}\n\t\t\t\tif bumpPatch {\n\t\t\t\t\tpatch++\n\t\t\t\t}\n\t\t\t\treplace(currentReleaseVersion, fmt.Sprintf(\"%d.%d.%d\", major, minor, patch))\n\t\t\t}\n\n\t\t\tif newAPI != \"\" && currentAPIVersion != newAPI {\n\t\t\t\tversionRegexStr := \"^([v]\\\\d+)([p_]\\\\d+)?((alpha|beta)\\\\d*)?\"\n\t\t\t\tversionRegex, err := regexp.Compile(versionRegexStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Unexpected Error compiling version regex: %+v\", err)\n\t\t\t\t}\n\t\t\t\tif !versionRegex.Match([]byte(newAPI)) {\n\t\t\t\t\tlog.Fatalf(\"The API version must conform to the regex: %s\", versionRegexStr)\n\t\t\t\t}\n\n\t\t\t\tschemaDir := filepath.Join(\"schema\", \"google\", \"showcase\")\n\t\t\t\terr = os.Rename(filepath.Join(schemaDir, currentAPIVersion), filepath.Join(schemaDir, newAPI))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to change proto directory: %+v\", err)\n\t\t\t\t}\n\n\t\t\t\treplace(currentAPIVersion, newAPI)\n\t\t\t\tutil.CompileProtos(newAPI)\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVarP(\n\t\t&bumpMajor,\n\t\t\"major\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the major version\")\n\tcmd.Flags().BoolVarP(\n\t\t&bumpMinor,\n\t\t\"minor\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the minor version\")\n\tcmd.Flags().BoolVarP(\n\t\t&bumpPatch,\n\t\t\"patch\",\n\t\t\"\",\n\t\tfalse,\n\t\t\"Pass this flag to bump the patch version\")\n\tcmd.Flags().StringVarP(\n\t\t&newAPI,\n\t\t\"api\",\n\t\t\"a\",\n\t\t\"\",\n\t\t\"The new API version to set.\")\n\n\tif err := cmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc replace(old, new string) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: unable to get working dir: %+v\", err)\n\t}\n\n\tfiletypes := []string{\".go\", \".md\", \".yml\", \".proto\"}\n\terr = filepath.Walk(pwd, replacer(filetypes, old, new))\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n}\n\nfunc replacer(filetypes []string, old, new string) filepath.WalkFunc {\n\treturn func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif strings.HasSuffix(fi.Name(), \"CHANGELOG.md\") {\n\t\t\treturn nil\n\t\t}\n\n\t\tmatched := false\n\t\tfor _, t := range filetypes {\n\t\t\tmatched = matched || strings.HasSuffix(path, t)\n\t\t}\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\n\t\toldBytes, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"%v\", err)\n\t\t}\n\n\t\tnewBytes := bytes.Replace(oldBytes, []byte(old), []byte(new), -1)\n\t\tif !bytes.Equal(oldBytes, newBytes) {\n\t\t\tif err = ioutil.WriteFile(path, newBytes, 0); err != nil {\n\t\t\t\tlog.Fatalf(\"%v\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc oneof(bs ...bool) bool {\n\tt := 0\n\tfor _, b := range bs {\n\t\tif b {\n\t\t\tt++\n\t\t}\n\t}\n\treturn t == 1\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 gce\n\nimport compute \"google.golang.org\/api\/compute\/v1\"\n\nfunc newTargetPoolMetricContext(request, region string) *metricContext {\n\treturn newGenericMetricContext(\"targetpool\", request, region, unusedMetricLabel, computeV1Version)\n}\n\n\/\/ GetTargetPool returns the TargetPool by name.\nfunc (gce *GCECloud) GetTargetPool(name, region string) (*compute.TargetPool, error) {\n\tmc := newTargetPoolMetricContext(\"get\", region)\n\tv, err := gce.service.TargetPools.Get(gce.projectID, region, name).Do()\n\treturn v, mc.Observe(err)\n}\n\n\/\/ CreateTargetPool creates the passed TargetPool\nfunc (gce *GCECloud) CreateTargetPool(tp *compute.TargetPool, region string) error {\n\tmc := newTargetPoolMetricContext(\"create\", region)\n\top, err := gce.service.TargetPools.Insert(gce.projectID, region, tp).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\n\treturn gce.waitForRegionOp(op, region, mc)\n}\n\n\/\/ DeleteTargetPool deletes TargetPool by name.\nfunc (gce *GCECloud) DeleteTargetPool(name, region string) error {\n\tmc := newTargetPoolMetricContext(\"delete\", region)\n\top, err := gce.service.TargetPools.Delete(gce.projectID, region, name).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForRegionOp(op, region, mc)\n}\n\n\/\/ AddInstancesToTargetPool adds instances by link to the TargetPool\nfunc (gce *GCECloud) AddInstancesToTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\tadd := &compute.TargetPoolsAddInstanceRequest{Instances: instanceRefs}\n\tmc := newTargetPoolMetricContext(\"add_instances\", region)\n\top, err := gce.service.TargetPools.AddInstance(gce.projectID, region, name, add).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForRegionOp(op, region, mc)\n}\n\n\/\/ RemoveInstancesToTargetPool removes instances by link to the TargetPool\nfunc (gce *GCECloud) RemoveInstancesFromTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\tremove := &compute.TargetPoolsRemoveInstanceRequest{Instances: instanceRefs}\n\tmc := newTargetPoolMetricContext(\"remove_instances\", region)\n\top, err := gce.service.TargetPools.RemoveInstance(gce.projectID, region, name, remove).Do()\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\treturn gce.waitForRegionOp(op, region, mc)\n}\nUpdate TargetPool to use generated code\/*\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 gce\n\nimport (\n\t\"context\"\n\n\tcompute \"google.golang.org\/api\/compute\/v1\"\n\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\/providers\/gce\/cloud\/meta\"\n)\n\nfunc newTargetPoolMetricContext(request, region string) *metricContext {\n\treturn newGenericMetricContext(\"targetpool\", request, region, unusedMetricLabel, computeV1Version)\n}\n\n\/\/ GetTargetPool returns the TargetPool by name.\nfunc (gce *GCECloud) GetTargetPool(name, region string) (*compute.TargetPool, error) {\n\tmc := newTargetPoolMetricContext(\"get\", region)\n\tv, err := gce.c.TargetPools().Get(context.Background(), meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}\n\n\/\/ CreateTargetPool creates the passed TargetPool\nfunc (gce *GCECloud) CreateTargetPool(tp *compute.TargetPool, region string) error {\n\tmc := newTargetPoolMetricContext(\"create\", region)\n\treturn mc.Observe(gce.c.TargetPools().Insert(context.Background(), meta.RegionalKey(tp.Name, region), tp))\n}\n\n\/\/ DeleteTargetPool deletes TargetPool by name.\nfunc (gce *GCECloud) DeleteTargetPool(name, region string) error {\n\tmc := newTargetPoolMetricContext(\"delete\", region)\n\treturn mc.Observe(gce.c.TargetPools().Delete(context.Background(), meta.RegionalKey(name, region)))\n}\n\n\/\/ AddInstancesToTargetPool adds instances by link to the TargetPool\nfunc (gce *GCECloud) AddInstancesToTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\treq := &compute.TargetPoolsAddInstanceRequest{\n\t\tInstances: instanceRefs,\n\t}\n\tmc := newTargetPoolMetricContext(\"add_instances\", region)\n\treturn mc.Observe(gce.c.TargetPools().AddInstance(context.Background(), meta.RegionalKey(name, region), req))\n}\n\n\/\/ RemoveInstancesFromTargetPool removes instances by link to the TargetPool\nfunc (gce *GCECloud) RemoveInstancesFromTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\treq := &compute.TargetPoolsRemoveInstanceRequest{\n\t\tInstances: instanceRefs,\n\t}\n\tmc := newTargetPoolMetricContext(\"remove_instances\", region)\n\treturn mc.Observe(gce.c.TargetPools().RemoveInstance(context.Background(), meta.RegionalKey(name, region), req))\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2019 The Skaffold 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 validation\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/testutil\"\n)\n\nvar (\n\tcfgWithErrors = &latest.SkaffoldConfig{\n\t\tPipeline: latest.Pipeline{\n\t\t\tBuild: latest.BuildConfig{\n\t\t\t\tArtifacts: []*latest.Artifact{\n\t\t\t\t\t{\n\t\t\t\t\t\tArtifactType: latest.ArtifactType{\n\t\t\t\t\t\t\tDockerArtifact: &latest.DockerArtifact{},\n\t\t\t\t\t\t\tBazelArtifact: &latest.BazelArtifact{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tArtifactType: latest.ArtifactType{\n\t\t\t\t\t\t\tBazelArtifact: &latest.BazelArtifact{},\n\t\t\t\t\t\t\tKanikoArtifact: &latest.KanikoArtifact{},\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\tDeploy: latest.DeployConfig{\n\t\t\t\tDeployType: latest.DeployType{\n\t\t\t\t\tHelmDeploy: &latest.HelmDeploy{},\n\t\t\t\t\tKubectlDeploy: &latest.KubectlDeploy{},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc TestValidateSchema(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tcfg *latest.SkaffoldConfig\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tname: \"config with errors\",\n\t\t\tcfg: cfgWithErrors,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"empty config\",\n\t\t\tcfg: &latest.SkaffoldConfig{},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"minimal config\",\n\t\t\tcfg: &latest.SkaffoldConfig{\n\t\t\t\tAPIVersion: \"foo\",\n\t\t\t\tKind: \"bar\",\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := Process(tt.cfg)\n\t\t\ttestutil.CheckError(t, tt.shouldErr, err)\n\t\t})\n\t}\n}\n\nfunc alwaysErr(_ interface{}) error {\n\treturn fmt.Errorf(\"always fail\")\n}\n\ntype emptyStruct struct{}\ntype nestedEmptyStruct struct {\n\tN emptyStruct\n}\n\nfunc TestVisitStructs(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput interface{}\n\t\texpectedErrs int\n\t}{\n\t\t{\n\t\t\tname: \"single struct to validate\",\n\t\t\tinput: emptyStruct{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into nested struct\",\n\t\t\tinput: nestedEmptyStruct{},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"check all slice items\",\n\t\t\tinput: struct {\n\t\t\t\tA []emptyStruct\n\t\t\t}{\n\t\t\t\tA: []emptyStruct{{}, {}},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []nestedEmptyStruct\n\t\t\t}{\n\t\t\t\tA: []nestedEmptyStruct{\n\t\t\t\t\t{\n\t\t\t\t\t\tN: emptyStruct{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into ptr slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []*nestedEmptyStruct\n\t\t\t}{\n\t\t\t\tA: []*nestedEmptyStruct{\n\t\t\t\t\t{\n\t\t\t\t\t\tN: emptyStruct{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore empty slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []emptyStruct\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore nil pointers\",\n\t\t\tinput: struct {\n\t\t\t\tA *struct{}\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into members\",\n\t\t\tinput: struct {\n\t\t\t\tA, B emptyStruct\n\t\t\t}{\n\t\t\t\tA: emptyStruct{},\n\t\t\t\tB: emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into ptr members\",\n\t\t\tinput: struct {\n\t\t\t\tA, B *emptyStruct\n\t\t\t}{\n\t\t\t\tA: &emptyStruct{},\n\t\t\t\tB: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore other fields\",\n\t\t\tinput: struct {\n\t\t\t\tA emptyStruct\n\t\t\t\tC int\n\t\t\t}{\n\t\t\t\tA: emptyStruct{},\n\t\t\t\tC: 2,\n\t\t\t},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported fields\",\n\t\t\tinput: struct {\n\t\t\t\ta emptyStruct\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"exported and unexported fields\",\n\t\t\tinput: struct {\n\t\t\t\ta, A, b emptyStruct\n\t\t\t}{},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported nil ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta *emptyStruct\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta *emptyStruct\n\t\t\t}{\n\t\t\t\ta: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported and exported ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta, A, b *emptyStruct\n\t\t\t}{\n\t\t\t\ta: &emptyStruct{},\n\t\t\t\tA: &emptyStruct{},\n\t\t\t\tb: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual := visitStructs(test.input, alwaysErr)\n\n\t\t\ttestutil.CheckDeepEqual(t, test.expectedErrs, len(actual))\n\t\t})\n\t}\n}\nMake linter happy\/*\nCopyright 2019 The Skaffold 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 validation\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/testutil\"\n)\n\nvar (\n\tcfgWithErrors = &latest.SkaffoldConfig{\n\t\tPipeline: latest.Pipeline{\n\t\t\tBuild: latest.BuildConfig{\n\t\t\t\tArtifacts: []*latest.Artifact{\n\t\t\t\t\t{\n\t\t\t\t\t\tArtifactType: latest.ArtifactType{\n\t\t\t\t\t\t\tDockerArtifact: &latest.DockerArtifact{},\n\t\t\t\t\t\t\tBazelArtifact: &latest.BazelArtifact{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tArtifactType: latest.ArtifactType{\n\t\t\t\t\t\t\tBazelArtifact: &latest.BazelArtifact{},\n\t\t\t\t\t\t\tKanikoArtifact: &latest.KanikoArtifact{},\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\tDeploy: latest.DeployConfig{\n\t\t\t\tDeployType: latest.DeployType{\n\t\t\t\t\tHelmDeploy: &latest.HelmDeploy{},\n\t\t\t\t\tKubectlDeploy: &latest.KubectlDeploy{},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc TestValidateSchema(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tcfg *latest.SkaffoldConfig\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tname: \"config with errors\",\n\t\t\tcfg: cfgWithErrors,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"empty config\",\n\t\t\tcfg: &latest.SkaffoldConfig{},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"minimal config\",\n\t\t\tcfg: &latest.SkaffoldConfig{\n\t\t\t\tAPIVersion: \"foo\",\n\t\t\t\tKind: \"bar\",\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := Process(tt.cfg)\n\t\t\ttestutil.CheckError(t, tt.shouldErr, err)\n\t\t})\n\t}\n}\n\nfunc alwaysErr(_ interface{}) error {\n\treturn fmt.Errorf(\"always fail\")\n}\n\ntype emptyStruct struct{}\ntype nestedEmptyStruct struct {\n\tN emptyStruct\n}\n\nfunc TestVisitStructs(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput interface{}\n\t\texpectedErrs int\n\t}{\n\t\t{\n\t\t\tname: \"single struct to validate\",\n\t\t\tinput: emptyStruct{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into nested struct\",\n\t\t\tinput: nestedEmptyStruct{},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"check all slice items\",\n\t\t\tinput: struct {\n\t\t\t\tA []emptyStruct\n\t\t\t}{\n\t\t\t\tA: []emptyStruct{{}, {}},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []nestedEmptyStruct\n\t\t\t}{\n\t\t\t\tA: []nestedEmptyStruct{\n\t\t\t\t\t{\n\t\t\t\t\t\tN: emptyStruct{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into ptr slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []*nestedEmptyStruct\n\t\t\t}{\n\t\t\t\tA: []*nestedEmptyStruct{\n\t\t\t\t\t{\n\t\t\t\t\t\tN: emptyStruct{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore empty slices\",\n\t\t\tinput: struct {\n\t\t\t\tA []emptyStruct\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore nil pointers\",\n\t\t\tinput: struct {\n\t\t\t\tA *struct{}\n\t\t\t}{},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into members\",\n\t\t\tinput: struct {\n\t\t\t\tA, B emptyStruct\n\t\t\t}{\n\t\t\t\tA: emptyStruct{},\n\t\t\t\tB: emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"recurse into ptr members\",\n\t\t\tinput: struct {\n\t\t\t\tA, B *emptyStruct\n\t\t\t}{\n\t\t\t\tA: &emptyStruct{},\n\t\t\t\tB: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 3,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore other fields\",\n\t\t\tinput: struct {\n\t\t\t\tA emptyStruct\n\t\t\t\tC int\n\t\t\t}{\n\t\t\t\tA: emptyStruct{},\n\t\t\t\tC: 2,\n\t\t\t},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported fields\",\n\t\t\tinput: struct {\n\t\t\t\ta emptyStruct\n\t\t\t}{\n\t\t\t\ta: emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"exported and unexported fields\",\n\t\t\tinput: struct {\n\t\t\t\ta, A, b emptyStruct\n\t\t\t}{\n\t\t\t\ta: emptyStruct{},\n\t\t\t\tA: emptyStruct{},\n\t\t\t\tb: emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported nil ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta *emptyStruct\n\t\t\t}{\n\t\t\t\ta: nil,\n\t\t\t},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta *emptyStruct\n\t\t\t}{\n\t\t\t\ta: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"unexported and exported ptr fields\",\n\t\t\tinput: struct {\n\t\t\t\ta, A, b *emptyStruct\n\t\t\t}{\n\t\t\t\ta: &emptyStruct{},\n\t\t\t\tA: &emptyStruct{},\n\t\t\t\tb: &emptyStruct{},\n\t\t\t},\n\t\t\texpectedErrs: 2,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual := visitStructs(test.input, alwaysErr)\n\n\t\t\ttestutil.CheckDeepEqual(t, test.expectedErrs, len(actual))\n\t\t})\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\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\/\/go:generate binapi-generator --input-file=\/usr\/share\/vpp\/api\/session.api.json --output-dir=bin_api\n\npackage vpptcp\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"net\"\n\t\"strings\"\n\n\tgovpp \"git.fd.io\/govpp.git\/api\"\n\t\"github.com\/ligato\/cn-infra\/logging\"\n\n\t\"github.com\/contiv\/vpp\/plugins\/contiv\"\n\tpodmodel \"github.com\/contiv\/vpp\/plugins\/ksr\/model\/pod\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\/vpptcp\/bin_api\/session\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\/vpptcp\/cache\"\n)\n\n\/\/ SessionRuleTagPrefix is used to tag session rules created for the implementation\n\/\/ of K8s policies.\nconst SessionRuleTagPrefix = \"contiv\/vpp-policy-\"\n\n\/\/ Renderer renders Contiv Rules into VPP Session rules.\n\/\/ Session rules are configured into VPP directly via binary API using govpp.\ntype Renderer struct {\n\tDeps\n\n\tcache *cache.SessionRuleCache\n}\n\n\/\/ Deps lists dependencies of Renderer.\ntype Deps struct {\n\tLog logging.Logger\n\tLogFactory logging.LogFactory \/* optional *\/\n\tContiv contiv.API \/* for GetNsIndex() *\/\n\tGoVPPChan *govpp.Channel\n}\n\n\/\/ RendererTxn represents a single transaction of Renderer.\ntype RendererTxn struct {\n\tcacheTxn cache.Txn\n\trenderer *Renderer\n\tresync bool\n}\n\n\/\/ Init initializes the VPPTCP Renderer.\nfunc (r *Renderer) Init() error {\n\t\/\/ Init the cache\n\tr.cache = &cache.SessionRuleCache{}\n\tif r.LogFactory != nil {\n\t\tr.cache.Log = r.LogFactory.NewLogger(\"-vpptcpCache\")\n\t\tr.cache.Log.SetLevel(logging.DebugLevel)\n\t} else {\n\t\tr.cache.Log = r.Log\n\t}\n\tr.cache.Init(r.dumpRules, SessionRuleTagPrefix)\n\treturn nil\n}\n\n\/\/ NewTxn starts a new transaction. The rendering executes only after Commit()\n\/\/ is called. Rollback is not yet supported however.\n\/\/ If is enabled, the supplied configuration will completely\n\/\/ replace the existing one. Otherwise, the change is performed incrementally,\n\/\/ i.e. interfaces not mentioned in the transaction are left unaffected.\nfunc (r *Renderer) NewTxn(resync bool) renderer.Txn {\n\treturn &RendererTxn{cacheTxn: r.cache.NewTxn(resync), renderer: r, resync: resync}\n}\n\n\/\/ dumpRules queries VPP to get the currently installed set of rules.\nfunc (r *Renderer) dumpRules() ([]*cache.SessionRule, error) {\n\trules := []*cache.SessionRule{}\n\t\/\/ Send request to dump all installed rules.\n\treq := &session.SessionRulesDump{}\n\treqContext := r.GoVPPChan.SendMultiRequest(req)\n\t\/\/ Receive details about each installed rule.\n\tfor {\n\t\tmsg := &session.SessionRulesDetails{}\n\t\tstop, err := reqContext.ReceiveReply(msg)\n\t\tif err != nil {\n\t\t\tr.Log.WithField(\"err\", err).Error(\"Failed to get a session rule details\")\n\t\t\treturn rules, err\n\t\t}\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\ttagLen := bytes.IndexByte(msg.Tag, 0)\n\t\ttag := string(msg.Tag[:tagLen])\n\t\tif !strings.HasPrefix(tag, SessionRuleTagPrefix) {\n\t\t\t\/\/ Skip rules not installed by this renderer.\n\t\t\tcontinue\n\t\t}\n\t\tsessionRule := &cache.SessionRule{\n\t\t\tTransportProto: msg.TransportProto,\n\t\t\tIsIP4: msg.IsIP4,\n\t\t\tLclPlen: msg.LclPlen,\n\t\t\tRmtPlen: msg.RmtPlen,\n\t\t\tLclPort: msg.LclPort,\n\t\t\tRmtPort: msg.RmtPort,\n\t\t\tActionIndex: msg.ActionIndex,\n\t\t\tAppnsIndex: msg.AppnsIndex,\n\t\t\tScope: msg.Scope,\n\t\t}\n\t\tcopy(sessionRule.LclIP[:], msg.LclIP)\n\t\tcopy(sessionRule.RmtIP[:], msg.RmtIP)\n\t\tcopy(sessionRule.Tag[:], msg.Tag)\n\t\trules = append(rules, sessionRule)\n\t}\n\n\tr.Log.WithFields(logging.Fields{\n\t\t\"rules\": rules,\n\t}).Debug(\"VPPTCP Renderer dumpRules()\")\n\treturn rules, nil\n}\n\n\/\/ makeSessionRuleAddDelReq creates an instance of SessionRuleAddDel bin API\n\/\/ request.\nfunc (r *Renderer) makeSessionRuleAddDelReq(rule *cache.SessionRule, add bool) *govpp.VppRequest {\n\tisAdd := uint8(0)\n\tif add {\n\t\tisAdd = uint8(1)\n\t}\n\tmsg := &session.SessionRuleAddDel{\n\t\tTransportProto: rule.TransportProto,\n\t\tIsIP4: rule.IsIP4,\n\t\tLclIP: rule.LclIP[:],\n\t\tLclPlen: rule.LclPlen,\n\t\tRmtIP: rule.RmtIP[:],\n\t\tRmtPlen: rule.RmtPlen,\n\t\tLclPort: rule.LclPort,\n\t\tRmtPort: rule.RmtPort,\n\t\tActionIndex: rule.ActionIndex,\n\t\tIsAdd: isAdd,\n\t\tAppnsIndex: rule.AppnsIndex,\n\t\tScope: rule.Scope,\n\t\tTag: rule.Tag[:],\n\t}\n\tr.Log.WithField(\"msg:\", *msg).Debug(\"Sending BIN API Request to VPP.\")\n\treq := &govpp.VppRequest{\n\t\tMessage: msg,\n\t}\n\treturn req\n}\n\n\/\/ updateRules adds\/removes selected rules to\/from VPP Session rule tables.\nfunc (r *Renderer) updateRules(add, remove []*cache.SessionRule) error {\n\tconst errMsg = \"failed to update VPPTCP session rule\"\n\n\t\/\/ Prepare VPP requests.\n\trequests := []*govpp.VppRequest{}\n\tfor _, delRule := range remove {\n\t\trequests = append(requests, r.makeSessionRuleAddDelReq(delRule, false))\n\t}\n\tfor _, addRule := range add {\n\t\trequests = append(requests, r.makeSessionRuleAddDelReq(addRule, true))\n\t}\n\n\t\/\/ Send all VPP requests at once.\n\tfor _, req := range requests {\n\t\tr.GoVPPChan.ReqChan <- req\n\t}\n\n\t\/\/ Wait for all VPP responses.\n\tvar wasError error\n\tfor i := 0; i < len(requests); i++ {\n\t\treply := <-r.GoVPPChan.ReplyChan\n\t\tif reply.Error != nil {\n\t\t\tr.Log.WithField(\"err\", reply.Error).Error(errMsg)\n\t\t\twasError = reply.Error\n\t\t\tbreak\n\t\t}\n\t\tmsg := &session.SessionRuleAddDelReply{}\n\t\terr := r.GoVPPChan.MsgDecoder.DecodeMsg(reply.Data, msg)\n\t\tif err != nil {\n\t\t\tr.Log.WithField(\"err\", err).Error(errMsg)\n\t\t\twasError = err\n\t\t\tbreak\n\t\t}\n\t\tif msg.Retval != 0 {\n\t\t\tr.Log.WithField(\"retval\", msg.Retval).Error(errMsg)\n\t\t\twasError = errors.New(errMsg)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn wasError\n}\n\n\/\/ Render applies the set of ingress & egress rules for a given pod.\n\/\/ The existing rules are replaced.\n\/\/ Te actual change is performed only after the commit.\nfunc (art *RendererTxn) Render(pod podmodel.ID, podIP *net.IPNet, ingress []*renderer.ContivRule, egress []*renderer.ContivRule) renderer.Txn {\n\t\/\/ Get the target namespace index.\n\tnsIndex, found := art.renderer.Contiv.GetNsIndex(pod.Namespace, pod.Name)\n\tif !found {\n\t\tart.renderer.Log.WithField(\"pod\", pod).Warn(\"Unable to get the namespace index of the Pod\")\n\t\treturn art\n\t}\n\n\tart.renderer.Log.WithFields(logging.Fields{\n\t\t\"pod\": pod,\n\t\t\"nsIndex\": nsIndex,\n\t\t\"ingress\": ingress,\n\t\t\"egress\": egress,\n\t}).Debug(\"VPPTCP RendererTxn Render()\")\n\n\t\/\/ Add the rules into the transaction.\n\tart.cacheTxn.Update(nsIndex, podIP, ingress, egress)\n\treturn art\n}\n\n\/\/ Commit proceeds with the rendering. A minimalistic set of changes is\n\/\/ calculated using ContivRuleCache and applied via binary API using govpp.\nfunc (art *RendererTxn) Commit() error {\n\tadded, removed, err := art.cacheTxn.Changes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(added) == 0 && len(removed) == 0 {\n\t\tart.renderer.Log.Debug(\"No changes to be rendered in the transaction\")\n\t\treturn nil\n\t}\n\terr = art.renderer.updateRules(added, removed)\n\tif err != nil {\n\t\treturn err\n\t}\n\tart.cacheTxn.Commit()\n\treturn nil\n}SNK 292: Fix formatting.\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\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\/\/go:generate binapi-generator --input-file=\/usr\/share\/vpp\/api\/session.api.json --output-dir=bin_api\n\npackage vpptcp\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"net\"\n\t\"strings\"\n\n\tgovpp \"git.fd.io\/govpp.git\/api\"\n\t\"github.com\/ligato\/cn-infra\/logging\"\n\n\t\"github.com\/contiv\/vpp\/plugins\/contiv\"\n\tpodmodel \"github.com\/contiv\/vpp\/plugins\/ksr\/model\/pod\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\/vpptcp\/bin_api\/session\"\n\t\"github.com\/contiv\/vpp\/plugins\/policy\/renderer\/vpptcp\/cache\"\n)\n\n\/\/ SessionRuleTagPrefix is used to tag session rules created for the implementation\n\/\/ of K8s policies.\nconst SessionRuleTagPrefix = \"contiv\/vpp-policy-\"\n\n\/\/ Renderer renders Contiv Rules into VPP Session rules.\n\/\/ Session rules are configured into VPP directly via binary API using govpp.\ntype Renderer struct {\n\tDeps\n\n\tcache *cache.SessionRuleCache\n}\n\n\/\/ Deps lists dependencies of Renderer.\ntype Deps struct {\n\tLog logging.Logger\n\tLogFactory logging.LogFactory \/* optional *\/\n\tContiv contiv.API \/* for GetNsIndex() *\/\n\tGoVPPChan *govpp.Channel\n}\n\n\/\/ RendererTxn represents a single transaction of Renderer.\ntype RendererTxn struct {\n\tcacheTxn cache.Txn\n\trenderer *Renderer\n\tresync bool\n}\n\n\/\/ Init initializes the VPPTCP Renderer.\nfunc (r *Renderer) Init() error {\n\t\/\/ Init the cache\n\tr.cache = &cache.SessionRuleCache{}\n\tif r.LogFactory != nil {\n\t\tr.cache.Log = r.LogFactory.NewLogger(\"-vpptcpCache\")\n\t\tr.cache.Log.SetLevel(logging.DebugLevel)\n\t} else {\n\t\tr.cache.Log = r.Log\n\t}\n\tr.cache.Init(r.dumpRules, SessionRuleTagPrefix)\n\treturn nil\n}\n\n\/\/ NewTxn starts a new transaction. The rendering executes only after Commit()\n\/\/ is called. Rollback is not yet supported however.\n\/\/ If is enabled, the supplied configuration will completely\n\/\/ replace the existing one. Otherwise, the change is performed incrementally,\n\/\/ i.e. interfaces not mentioned in the transaction are left unaffected.\nfunc (r *Renderer) NewTxn(resync bool) renderer.Txn {\n\treturn &RendererTxn{cacheTxn: r.cache.NewTxn(resync), renderer: r, resync: resync}\n}\n\n\/\/ dumpRules queries VPP to get the currently installed set of rules.\nfunc (r *Renderer) dumpRules() ([]*cache.SessionRule, error) {\n\trules := []*cache.SessionRule{}\n\t\/\/ Send request to dump all installed rules.\n\treq := &session.SessionRulesDump{}\n\treqContext := r.GoVPPChan.SendMultiRequest(req)\n\t\/\/ Receive details about each installed rule.\n\tfor {\n\t\tmsg := &session.SessionRulesDetails{}\n\t\tstop, err := reqContext.ReceiveReply(msg)\n\t\tif err != nil {\n\t\t\tr.Log.WithField(\"err\", err).Error(\"Failed to get a session rule details\")\n\t\t\treturn rules, err\n\t\t}\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\ttagLen := bytes.IndexByte(msg.Tag, 0)\n\t\ttag := string(msg.Tag[:tagLen])\n\t\tif !strings.HasPrefix(tag, SessionRuleTagPrefix) {\n\t\t\t\/\/ Skip rules not installed by this renderer.\n\t\t\tcontinue\n\t\t}\n\t\tsessionRule := &cache.SessionRule{\n\t\t\tTransportProto: msg.TransportProto,\n\t\t\tIsIP4: msg.IsIP4,\n\t\t\tLclPlen: msg.LclPlen,\n\t\t\tRmtPlen: msg.RmtPlen,\n\t\t\tLclPort: msg.LclPort,\n\t\t\tRmtPort: msg.RmtPort,\n\t\t\tActionIndex: msg.ActionIndex,\n\t\t\tAppnsIndex: msg.AppnsIndex,\n\t\t\tScope: msg.Scope,\n\t\t}\n\t\tcopy(sessionRule.LclIP[:], msg.LclIP)\n\t\tcopy(sessionRule.RmtIP[:], msg.RmtIP)\n\t\tcopy(sessionRule.Tag[:], msg.Tag)\n\t\trules = append(rules, sessionRule)\n\t}\n\n\tr.Log.WithFields(logging.Fields{\n\t\t\"rules\": rules,\n\t}).Debug(\"VPPTCP Renderer dumpRules()\")\n\treturn rules, nil\n}\n\n\/\/ makeSessionRuleAddDelReq creates an instance of SessionRuleAddDel bin API\n\/\/ request.\nfunc (r *Renderer) makeSessionRuleAddDelReq(rule *cache.SessionRule, add bool) *govpp.VppRequest {\n\tisAdd := uint8(0)\n\tif add {\n\t\tisAdd = uint8(1)\n\t}\n\tmsg := &session.SessionRuleAddDel{\n\t\tTransportProto: rule.TransportProto,\n\t\tIsIP4: rule.IsIP4,\n\t\tLclIP: rule.LclIP[:],\n\t\tLclPlen: rule.LclPlen,\n\t\tRmtIP: rule.RmtIP[:],\n\t\tRmtPlen: rule.RmtPlen,\n\t\tLclPort: rule.LclPort,\n\t\tRmtPort: rule.RmtPort,\n\t\tActionIndex: rule.ActionIndex,\n\t\tIsAdd: isAdd,\n\t\tAppnsIndex: rule.AppnsIndex,\n\t\tScope: rule.Scope,\n\t\tTag: rule.Tag[:],\n\t}\n\tr.Log.WithField(\"msg:\", *msg).Debug(\"Sending BIN API Request to VPP.\")\n\treq := &govpp.VppRequest{\n\t\tMessage: msg,\n\t}\n\treturn req\n}\n\n\/\/ updateRules adds\/removes selected rules to\/from VPP Session rule tables.\nfunc (r *Renderer) updateRules(add, remove []*cache.SessionRule) error {\n\tconst errMsg = \"failed to update VPPTCP session rule\"\n\n\t\/\/ Prepare VPP requests.\n\trequests := []*govpp.VppRequest{}\n\tfor _, delRule := range remove {\n\t\trequests = append(requests, r.makeSessionRuleAddDelReq(delRule, false))\n\t}\n\tfor _, addRule := range add {\n\t\trequests = append(requests, r.makeSessionRuleAddDelReq(addRule, true))\n\t}\n\n\t\/\/ Send all VPP requests at once.\n\tfor _, req := range requests {\n\t\tr.GoVPPChan.ReqChan <- req\n\t}\n\n\t\/\/ Wait for all VPP responses.\n\tvar wasError error\n\tfor i := 0; i < len(requests); i++ {\n\t\treply := <-r.GoVPPChan.ReplyChan\n\t\tif reply.Error != nil {\n\t\t\tr.Log.WithField(\"err\", reply.Error).Error(errMsg)\n\t\t\twasError = reply.Error\n\t\t\tbreak\n\t\t}\n\t\tmsg := &session.SessionRuleAddDelReply{}\n\t\terr := r.GoVPPChan.MsgDecoder.DecodeMsg(reply.Data, msg)\n\t\tif err != nil {\n\t\t\tr.Log.WithField(\"err\", err).Error(errMsg)\n\t\t\twasError = err\n\t\t\tbreak\n\t\t}\n\t\tif msg.Retval != 0 {\n\t\t\tr.Log.WithField(\"retval\", msg.Retval).Error(errMsg)\n\t\t\twasError = errors.New(errMsg)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn wasError\n}\n\n\/\/ Render applies the set of ingress & egress rules for a given pod.\n\/\/ The existing rules are replaced.\n\/\/ Te actual change is performed only after the commit.\nfunc (art *RendererTxn) Render(pod podmodel.ID, podIP *net.IPNet, ingress []*renderer.ContivRule, egress []*renderer.ContivRule) renderer.Txn {\n\t\/\/ Get the target namespace index.\n\tnsIndex, found := art.renderer.Contiv.GetNsIndex(pod.Namespace, pod.Name)\n\tif !found {\n\t\tart.renderer.Log.WithField(\"pod\", pod).Warn(\"Unable to get the namespace index of the Pod\")\n\t\treturn art\n\t}\n\n\tart.renderer.Log.WithFields(logging.Fields{\n\t\t\"pod\": pod,\n\t\t\"nsIndex\": nsIndex,\n\t\t\"ingress\": ingress,\n\t\t\"egress\": egress,\n\t}).Debug(\"VPPTCP RendererTxn Render()\")\n\n\t\/\/ Add the rules into the transaction.\n\tart.cacheTxn.Update(nsIndex, podIP, ingress, egress)\n\treturn art\n}\n\n\/\/ Commit proceeds with the rendering. A minimalistic set of changes is\n\/\/ calculated using ContivRuleCache and applied via binary API using govpp.\nfunc (art *RendererTxn) Commit() error {\n\tadded, removed, err := art.cacheTxn.Changes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(added) == 0 && len(removed) == 0 {\n\t\tart.renderer.Log.Debug(\"No changes to be rendered in the transaction\")\n\t\treturn nil\n\t}\n\terr = art.renderer.updateRules(added, removed)\n\tif err != nil {\n\t\treturn err\n\t}\n\tart.cacheTxn.Commit()\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Package google implements logging in through Google's OpenID Connect provider.\npackage google\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/coreos\/go-oidc\"\n\t\"golang.org\/x\/oauth2\"\n\n\t\"github.com\/dexidp\/dex\/connector\"\n\t\"github.com\/dexidp\/dex\/pkg\/log\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/admin\/directory\/v1\"\n)\n\nconst (\n\tissuerURL = \"https:\/\/accounts.google.com\"\n)\n\n\/\/ Config holds configuration options for OpenID Connect logins.\ntype Config struct {\n\tClientID string `json:\"clientID\"`\n\tClientSecret string `json:\"clientSecret\"`\n\tRedirectURI string `json:\"redirectURI\"`\n\n\tScopes []string `json:\"scopes\"` \/\/ defaults to \"profile\" and \"email\"\n\n\t\/\/ Optional list of whitelisted domains\n\t\/\/ If this field is nonempty, only users from a listed domain will be allowed to log in\n\tHostedDomains []string `json:\"hostedDomains\"`\n\n\t\/\/ Optional path to service account json\n\t\/\/ If nonempty, and groups claim is made, will use authentication from file to\n\t\/\/ check groups with the admin directory api\n\tServiceAccountFilePath string `json:\"serviceAccountFilePath\"`\n\n\t\/\/ Required if ServiceAccountFilePath\n\t\/\/ The email of a GSuite super user which the service account will impersonate\n\t\/\/ when listing groups\n\tAdminEmail string\n}\n\n\/\/ Open returns a connector which can be used to login users through an upstream\n\/\/ OpenID Connect provider.\nfunc (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, err error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tprovider, err := oidc.NewProvider(ctx, issuerURL)\n\tif err != nil {\n\t\tcancel()\n\t\treturn nil, fmt.Errorf(\"failed to get provider: %v\", err)\n\t}\n\n\tscopes := []string{oidc.ScopeOpenID}\n\tif len(c.Scopes) > 0 {\n\t\tscopes = append(scopes, c.Scopes...)\n\t} else {\n\t\tscopes = append(scopes, \"profile\", \"email\")\n\t}\n\n\tclientID := c.ClientID\n\treturn &googleConnector{\n\t\tredirectURI: c.RedirectURI,\n\t\toauth2Config: &oauth2.Config{\n\t\t\tClientID: clientID,\n\t\t\tClientSecret: c.ClientSecret,\n\t\t\tEndpoint: provider.Endpoint(),\n\t\t\tScopes: scopes,\n\t\t\tRedirectURL: c.RedirectURI,\n\t\t},\n\t\tverifier: provider.Verifier(\n\t\t\t&oidc.Config{ClientID: clientID},\n\t\t),\n\t\tlogger: logger,\n\t\tcancel: cancel,\n\t\thostedDomains: c.HostedDomains,\n\t\tserviceAccountFilePath: c.ServiceAccountFilePath,\n\t\tadminEmail: c.AdminEmail,\n\t}, nil\n}\n\nvar (\n\t_ connector.CallbackConnector = (*googleConnector)(nil)\n\t_ connector.RefreshConnector = (*googleConnector)(nil)\n)\n\ntype googleConnector struct {\n\tredirectURI string\n\toauth2Config *oauth2.Config\n\tverifier *oidc.IDTokenVerifier\n\tctx context.Context\n\tcancel context.CancelFunc\n\tlogger log.Logger\n\thostedDomains []string\n\tserviceAccountFilePath string\n\tadminEmail string\n}\n\nfunc (c *googleConnector) Close() error {\n\tc.cancel()\n\treturn nil\n}\n\nfunc (c *googleConnector) LoginURL(s connector.Scopes, callbackURL, state string) (string, error) {\n\tif c.redirectURI != callbackURL {\n\t\treturn \"\", fmt.Errorf(\"expected callback URL %q did not match the URL in the config %q\", callbackURL, c.redirectURI)\n\t}\n\n\tvar opts []oauth2.AuthCodeOption\n\tif len(c.hostedDomains) > 0 {\n\t\tpreferredDomain := c.hostedDomains[0]\n\t\tif len(c.hostedDomains) > 1 {\n\t\t\tpreferredDomain = \"*\"\n\t\t}\n\t\topts = append(opts, oauth2.SetAuthURLParam(\"hd\", preferredDomain))\n\t}\n\n\tif s.OfflineAccess {\n\t\topts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam(\"prompt\", \"consent\"))\n\t}\n\treturn c.oauth2Config.AuthCodeURL(state, opts...), nil\n}\n\ntype oauth2Error struct {\n\terror string\n\terrorDescription string\n}\n\nfunc (e *oauth2Error) Error() string {\n\tif e.errorDescription == \"\" {\n\t\treturn e.error\n\t}\n\treturn e.error + \": \" + e.errorDescription\n}\n\nfunc (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) {\n\tq := r.URL.Query()\n\tif errType := q.Get(\"error\"); errType != \"\" {\n\t\treturn identity, &oauth2Error{errType, q.Get(\"error_description\")}\n\t}\n\ttoken, err := c.oauth2Config.Exchange(r.Context(), q.Get(\"code\"))\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to get token: %v\", err)\n\t}\n\n\treturn c.createIdentity(r.Context(), identity, s, token)\n}\n\n\/\/ Refresh is implemented for backwards compatibility, even though it's a no-op.\nfunc (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) {\n\tt := &oauth2.Token{\n\t\tRefreshToken: string(identity.ConnectorData),\n\t\tExpiry: time.Now().Add(-time.Hour),\n\t}\n\ttoken, err := c.oauth2Config.TokenSource(ctx, t).Token()\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to get token: %v\", err)\n\t}\n\n\treturn c.createIdentity(ctx, identity, s, token)\n}\n\nfunc (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, s connector.Scopes, token *oauth2.Token) (connector.Identity, error) {\n\trawIDToken, ok := token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn identity, errors.New(\"google: no id_token in token response\")\n\t}\n\tidToken, err := c.verifier.Verify(ctx, rawIDToken)\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to verify ID Token: %v\", err)\n\t}\n\n\tvar claims struct {\n\t\tUsername string `json:\"name\"`\n\t\tEmail string `json:\"email\"`\n\t\tEmailVerified bool `json:\"email_verified\"`\n\t\tHostedDomain string `json:\"hd\"`\n\t}\n\tif err := idToken.Claims(&claims); err != nil {\n\t\treturn identity, fmt.Errorf(\"oidc: failed to decode claims: %v\", err)\n\t}\n\n\tif len(c.hostedDomains) > 0 {\n\t\tfound := false\n\t\tfor _, domain := range c.hostedDomains {\n\t\t\tif claims.HostedDomain == domain {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn identity, fmt.Errorf(\"oidc: unexpected hd claim %v\", claims.HostedDomain)\n\t\t}\n\t}\n\n\tvar groups []string\n\tif s.Groups {\n\t\tgroups, err = c.getGroups(claims.Email)\n\t\tif err != nil {\n\t\t\treturn identity, fmt.Errorf(\"google: could not retrieve groups: %v\", err)\n\t\t}\n\t}\n\n\tidentity = connector.Identity{\n\t\tUserID: idToken.Subject,\n\t\tUsername: claims.Username,\n\t\tEmail: claims.Email,\n\t\tEmailVerified: claims.EmailVerified,\n\t\tConnectorData: []byte(token.RefreshToken),\n\t\tGroups: groups,\n\t}\n\treturn identity, nil\n}\n\nfunc (c *googleConnector) getGroups(email string) ([]string, error) {\n\tsrv, err := createDirectoryService(c.serviceAccountFilePath, c.adminEmail)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create directory service: %v\", err)\n\t}\n\n\tgroupsList, err := srv.Groups.List().UserKey(email).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not list groups: %v\", err)\n\t}\n\n\tvar userGroups []string\n\tfor _, group := range groupsList.Groups {\n\t\tuserGroups = append(userGroups, group.Email)\n\t}\n\n\treturn userGroups, nil\n}\n\nfunc createDirectoryService(serviceAccountFilePath string, email string) (*admin.Service, error) {\n\tjsonCredentials, err := ioutil.ReadFile(serviceAccountFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading credentials from file: %v\", err)\n\t}\n\n\tconfig, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryGroupReadonlyScope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse client secret file to config: %v\", err)\n\t}\n\n\tconfig.Subject = email\n\n\tctx := context.Background()\n\tclient := config.Client(ctx)\n\n\tsrv, err := admin.New(client)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create directory service %v\", err)\n\t}\n\treturn srv, nil\n}\nCheck config before getting groups\/\/ Package google implements logging in through Google's OpenID Connect provider.\npackage google\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/coreos\/go-oidc\"\n\t\"golang.org\/x\/oauth2\"\n\n\t\"github.com\/dexidp\/dex\/connector\"\n\t\"github.com\/dexidp\/dex\/pkg\/log\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/admin\/directory\/v1\"\n)\n\nconst (\n\tissuerURL = \"https:\/\/accounts.google.com\"\n)\n\n\/\/ Config holds configuration options for OpenID Connect logins.\ntype Config struct {\n\tClientID string `json:\"clientID\"`\n\tClientSecret string `json:\"clientSecret\"`\n\tRedirectURI string `json:\"redirectURI\"`\n\n\tScopes []string `json:\"scopes\"` \/\/ defaults to \"profile\" and \"email\"\n\n\t\/\/ Optional list of whitelisted domains\n\t\/\/ If this field is nonempty, only users from a listed domain will be allowed to log in\n\tHostedDomains []string `json:\"hostedDomains\"`\n\n\t\/\/ Optional path to service account json\n\t\/\/ If nonempty, and groups claim is made, will use authentication from file to\n\t\/\/ check groups with the admin directory api\n\tServiceAccountFilePath string `json:\"serviceAccountFilePath\"`\n\n\t\/\/ Required if ServiceAccountFilePath\n\t\/\/ The email of a GSuite super user which the service account will impersonate\n\t\/\/ when listing groups\n\tAdminEmail string\n}\n\n\/\/ Open returns a connector which can be used to login users through an upstream\n\/\/ OpenID Connect provider.\nfunc (c *Config) Open(id string, logger log.Logger) (conn connector.Connector, err error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tprovider, err := oidc.NewProvider(ctx, issuerURL)\n\tif err != nil {\n\t\tcancel()\n\t\treturn nil, fmt.Errorf(\"failed to get provider: %v\", err)\n\t}\n\n\tscopes := []string{oidc.ScopeOpenID}\n\tif len(c.Scopes) > 0 {\n\t\tscopes = append(scopes, c.Scopes...)\n\t} else {\n\t\tscopes = append(scopes, \"profile\", \"email\")\n\t}\n\n\tclientID := c.ClientID\n\treturn &googleConnector{\n\t\tredirectURI: c.RedirectURI,\n\t\toauth2Config: &oauth2.Config{\n\t\t\tClientID: clientID,\n\t\t\tClientSecret: c.ClientSecret,\n\t\t\tEndpoint: provider.Endpoint(),\n\t\t\tScopes: scopes,\n\t\t\tRedirectURL: c.RedirectURI,\n\t\t},\n\t\tverifier: provider.Verifier(\n\t\t\t&oidc.Config{ClientID: clientID},\n\t\t),\n\t\tlogger: logger,\n\t\tcancel: cancel,\n\t\thostedDomains: c.HostedDomains,\n\t\tserviceAccountFilePath: c.ServiceAccountFilePath,\n\t\tadminEmail: c.AdminEmail,\n\t}, nil\n}\n\nvar (\n\t_ connector.CallbackConnector = (*googleConnector)(nil)\n\t_ connector.RefreshConnector = (*googleConnector)(nil)\n)\n\ntype googleConnector struct {\n\tredirectURI string\n\toauth2Config *oauth2.Config\n\tverifier *oidc.IDTokenVerifier\n\tctx context.Context\n\tcancel context.CancelFunc\n\tlogger log.Logger\n\thostedDomains []string\n\tserviceAccountFilePath string\n\tadminEmail string\n}\n\nfunc (c *googleConnector) Close() error {\n\tc.cancel()\n\treturn nil\n}\n\nfunc (c *googleConnector) LoginURL(s connector.Scopes, callbackURL, state string) (string, error) {\n\tif c.redirectURI != callbackURL {\n\t\treturn \"\", fmt.Errorf(\"expected callback URL %q did not match the URL in the config %q\", callbackURL, c.redirectURI)\n\t}\n\n\tvar opts []oauth2.AuthCodeOption\n\tif len(c.hostedDomains) > 0 {\n\t\tpreferredDomain := c.hostedDomains[0]\n\t\tif len(c.hostedDomains) > 1 {\n\t\t\tpreferredDomain = \"*\"\n\t\t}\n\t\topts = append(opts, oauth2.SetAuthURLParam(\"hd\", preferredDomain))\n\t}\n\n\tif s.OfflineAccess {\n\t\topts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam(\"prompt\", \"consent\"))\n\t}\n\treturn c.oauth2Config.AuthCodeURL(state, opts...), nil\n}\n\ntype oauth2Error struct {\n\terror string\n\terrorDescription string\n}\n\nfunc (e *oauth2Error) Error() string {\n\tif e.errorDescription == \"\" {\n\t\treturn e.error\n\t}\n\treturn e.error + \": \" + e.errorDescription\n}\n\nfunc (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) {\n\tq := r.URL.Query()\n\tif errType := q.Get(\"error\"); errType != \"\" {\n\t\treturn identity, &oauth2Error{errType, q.Get(\"error_description\")}\n\t}\n\ttoken, err := c.oauth2Config.Exchange(r.Context(), q.Get(\"code\"))\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to get token: %v\", err)\n\t}\n\n\treturn c.createIdentity(r.Context(), identity, s, token)\n}\n\n\/\/ Refresh is implemented for backwards compatibility, even though it's a no-op.\nfunc (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) {\n\tt := &oauth2.Token{\n\t\tRefreshToken: string(identity.ConnectorData),\n\t\tExpiry: time.Now().Add(-time.Hour),\n\t}\n\ttoken, err := c.oauth2Config.TokenSource(ctx, t).Token()\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to get token: %v\", err)\n\t}\n\n\treturn c.createIdentity(ctx, identity, s, token)\n}\n\nfunc (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, s connector.Scopes, token *oauth2.Token) (connector.Identity, error) {\n\trawIDToken, ok := token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn identity, errors.New(\"google: no id_token in token response\")\n\t}\n\tidToken, err := c.verifier.Verify(ctx, rawIDToken)\n\tif err != nil {\n\t\treturn identity, fmt.Errorf(\"google: failed to verify ID Token: %v\", err)\n\t}\n\n\tvar claims struct {\n\t\tUsername string `json:\"name\"`\n\t\tEmail string `json:\"email\"`\n\t\tEmailVerified bool `json:\"email_verified\"`\n\t\tHostedDomain string `json:\"hd\"`\n\t}\n\tif err := idToken.Claims(&claims); err != nil {\n\t\treturn identity, fmt.Errorf(\"oidc: failed to decode claims: %v\", err)\n\t}\n\n\tif len(c.hostedDomains) > 0 {\n\t\tfound := false\n\t\tfor _, domain := range c.hostedDomains {\n\t\t\tif claims.HostedDomain == domain {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn identity, fmt.Errorf(\"oidc: unexpected hd claim %v\", claims.HostedDomain)\n\t\t}\n\t}\n\n\tvar groups []string\n\tif s.Groups && c.adminEmail != \"\" && c.serviceAccountFilePath != \"\" {\n\t\tgroups, err = c.getGroups(claims.Email)\n\t\tif err != nil {\n\t\t\treturn identity, fmt.Errorf(\"google: could not retrieve groups: %v\", err)\n\t\t}\n\t}\n\n\tidentity = connector.Identity{\n\t\tUserID: idToken.Subject,\n\t\tUsername: claims.Username,\n\t\tEmail: claims.Email,\n\t\tEmailVerified: claims.EmailVerified,\n\t\tConnectorData: []byte(token.RefreshToken),\n\t\tGroups: groups,\n\t}\n\treturn identity, nil\n}\n\nfunc (c *googleConnector) getGroups(email string) ([]string, error) {\n\tsrv, err := createDirectoryService(c.serviceAccountFilePath, c.adminEmail)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create directory service: %v\", err)\n\t}\n\n\tgroupsList, err := srv.Groups.List().UserKey(email).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not list groups: %v\", err)\n\t}\n\n\tvar userGroups []string\n\tfor _, group := range groupsList.Groups {\n\t\tuserGroups = append(userGroups, group.Email)\n\t}\n\n\treturn userGroups, nil\n}\n\nfunc createDirectoryService(serviceAccountFilePath string, email string) (*admin.Service, error) {\n\tjsonCredentials, err := ioutil.ReadFile(serviceAccountFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading credentials from file: %v\", err)\n\t}\n\n\tconfig, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryGroupReadonlyScope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse client secret file to config: %v\", err)\n\t}\n\n\tconfig.Subject = email\n\n\tctx := context.Background()\n\tclient := config.Client(ctx)\n\n\tsrv, err := admin.New(client)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create directory service %v\", err)\n\t}\n\treturn srv, nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 Uber Technologies, Inc.\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 zanzibar\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"go.uber.org\/zap\"\n)\n\n\/\/ ClientHTTPRequest is the struct for making a single client request using an outbound http client.\ntype ClientHTTPRequest struct {\n\tClientID string\n\tMethodName string\n\tclient *HTTPClient\n\thttpReq *http.Request\n\tres *ClientHTTPResponse\n\tstarted bool\n\tstartTime time.Time\n\tLogger *zap.Logger\n\tContextLogger ContextLogger\n\trawBody []byte\n\tdefaultHeaders map[string]string\n\tctx context.Context\n\tmetrics ContextMetrics\n}\n\n\/\/ NewClientHTTPRequest allocates a ClientHTTPRequest. The ctx parameter is the context associated with the outbound requests.\nfunc NewClientHTTPRequest(\n\tctx context.Context,\n\tclientID, methodName string,\n\tclient *HTTPClient,\n) *ClientHTTPRequest {\n\tscopeTags := map[string]string{scopeTagClientMethod: methodName, scopeTagClient: clientID}\n\tctx = WithScopeTags(ctx, scopeTags)\n\treq := &ClientHTTPRequest{\n\t\tClientID: clientID,\n\t\tMethodName: methodName,\n\t\tclient: client,\n\t\tLogger: client.loggers[methodName],\n\t\tContextLogger: NewContextLogger(client.loggers[methodName]),\n\t\tdefaultHeaders: client.DefaultHeaders,\n\t\tctx: ctx,\n\t\tmetrics: client.contextMetrics,\n\t}\n\treq.res = NewClientHTTPResponse(req)\n\treq.start()\n\treturn req\n}\n\n\/\/ Start the request, do some metrics book keeping\nfunc (req *ClientHTTPRequest) start() {\n\tif req.started {\n\t\t\/* coverage ignore next line *\/\n\t\treq.Logger.Error(\"Cannot start ClientHTTPRequest twice\")\n\t\t\/* coverage ignore next line *\/\n\t\treturn\n\t}\n\treq.started = true\n\treq.startTime = time.Now()\n}\n\n\/\/ CheckHeaders verifies that the outbound request contains required headers\nfunc (req *ClientHTTPRequest) CheckHeaders(expected []string) error {\n\tif req.httpReq == nil {\n\t\t\/* coverage ignore next line *\/\n\t\tpanic(\"must call `req.WriteJSON()` before `req.CheckHeaders()`\")\n\t}\n\n\tactualHeaders := req.httpReq.Header\n\n\tfor _, headerName := range expected {\n\t\t\/\/ headerName is case insensitive, http.Header Get canonicalize the key\n\t\theaderValue := actualHeaders.Get(headerName)\n\t\tif headerValue == \"\" {\n\t\t\treq.Logger.Warn(\"Got outbound request without mandatory header\",\n\t\t\t\tzap.String(\"headerName\", headerName),\n\t\t\t)\n\n\t\t\treturn errors.New(\"Missing mandatory header: \" + headerName)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ WriteJSON will send a json http request out.\nfunc (req *ClientHTTPRequest) WriteJSON(\n\tmethod, url string,\n\theaders map[string]string,\n\tbody json.Marshaler,\n) error {\n\tvar httpReq *http.Request\n\tvar httpErr error\n\tif body != nil {\n\t\trawBody, err := body.MarshalJSON()\n\t\tif err != nil {\n\t\t\treq.Logger.Error(\"Could not serialize request json\", zap.Error(err))\n\t\t\treturn errors.Wrapf(\n\t\t\t\terr, \"Could not serialize %s.%s request json\",\n\t\t\t\treq.ClientID, req.MethodName,\n\t\t\t)\n\t\t}\n\t\treq.rawBody = rawBody\n\t\thttpReq, httpErr = http.NewRequest(method, url, bytes.NewReader(rawBody))\n\t} else {\n\t\thttpReq, httpErr = http.NewRequest(method, url, nil)\n\t}\n\n\tif httpErr != nil {\n\t\treq.Logger.Error(\"Could not create outbound request\", zap.Error(httpErr))\n\t\treturn errors.Wrapf(\n\t\t\thttpErr, \"Could not create outbound %s.%s request\",\n\t\t\treq.ClientID, req.MethodName,\n\t\t)\n\t}\n\n\t\/\/ Using `Add` over `Set` intentionally, allowing us to create a list\n\t\/\/ of headerValues for a given key.\n\tfor headerKey, headerValue := range req.defaultHeaders {\n\t\thttpReq.Header.Add(headerKey, headerValue)\n\t}\n\n\tfor k := range headers {\n\t\thttpReq.Header.Add(k, headers[k])\n\t}\n\n\tif body != nil {\n\t\thttpReq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\treq.httpReq = httpReq\n\treq.ctx = WithLogFields(req.ctx,\n\t\tzap.String(logFieldRequestMethod, method),\n\t\tzap.String(logFieldRequestURL, url),\n\t\tzap.Time(logFieldRequestStartTime, req.startTime),\n\t)\n\n\treturn nil\n}\n\n\/\/ Do will send the request out.\nfunc (req *ClientHTTPRequest) Do() (*ClientHTTPResponse, error) {\n\topName := fmt.Sprintf(\"%s.%s\", req.ClientID, req.MethodName)\n\turlTag := opentracing.Tag{Key: \"URL\", Value: req.httpReq.URL}\n\tmethodTag := opentracing.Tag{Key: \"Method\", Value: req.httpReq.Method}\n\tspan, ctx := opentracing.StartSpanFromContext(req.ctx, opName, urlTag, methodTag)\n\terr := req.InjectSpanToHeader(span, opentracing.HTTPHeaders)\n\tif err != nil {\n\t\t\/* coverage ignore next line *\/\n\t\treq.Logger.Error(\"Fail to inject span to headers\", zap.Error(err))\n\t\t\/* coverage ignore next line *\/\n\t\treturn nil, err\n\t}\n\n\tlogFields := make([]zap.Field, 0, len(req.httpReq.Header))\n\tfor k, v := range req.httpReq.Header {\n\t\tlogFields = append(logFields, zap.String(fmt.Sprintf(\"%s-%s\", logFieldRequestHeaderPrefix, k), v[0]))\n\t}\n\tctx = WithLogFields(ctx, logFields...)\n\treq.ctx = ctx\n\n\tres, err := req.client.Client.Do(req.httpReq.WithContext(ctx))\n\tspan.Finish()\n\tif err != nil {\n\t\treq.Logger.Error(\"Could not make outbound request\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\t\/\/ emit metrics\n\treq.metrics.IncCounter(req.ctx, clientRequest, 1)\n\n\treq.res.setRawHTTPResponse(res)\n\treturn req.res, nil\n}\n\n\/\/ InjectSpanToHeader will inject span to request header\n\/\/ This method is current used for unit tests\n\/\/ TODO: we need to set source and test code as same pkg name which would makes UTs easier\nfunc (req *ClientHTTPRequest) InjectSpanToHeader(span opentracing.Span, format interface{}) error {\n\tcarrier := opentracing.HTTPHeadersCarrier(req.httpReq.Header)\n\tif err := span.Tracer().Inject(span.Context(), format, carrier); err != nil {\n\t\treq.Logger.Error(\"Failed to inject tracing span.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\nRemoved adding multiple uber source request headers\/\/ Copyright (c) 2019 Uber Technologies, Inc.\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 zanzibar\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"go.uber.org\/zap\"\n)\n\n\/\/ ClientHTTPRequest is the struct for making a single client request using an outbound http client.\ntype ClientHTTPRequest struct {\n\tClientID string\n\tMethodName string\n\tclient *HTTPClient\n\thttpReq *http.Request\n\tres *ClientHTTPResponse\n\tstarted bool\n\tstartTime time.Time\n\tLogger *zap.Logger\n\tContextLogger ContextLogger\n\trawBody []byte\n\tdefaultHeaders map[string]string\n\tctx context.Context\n\tmetrics ContextMetrics\n}\n\n\/\/ NewClientHTTPRequest allocates a ClientHTTPRequest. The ctx parameter is the context associated with the outbound requests.\nfunc NewClientHTTPRequest(\n\tctx context.Context,\n\tclientID, methodName string,\n\tclient *HTTPClient,\n) *ClientHTTPRequest {\n\tscopeTags := map[string]string{scopeTagClientMethod: methodName, scopeTagClient: clientID}\n\tctx = WithScopeTags(ctx, scopeTags)\n\treq := &ClientHTTPRequest{\n\t\tClientID: clientID,\n\t\tMethodName: methodName,\n\t\tclient: client,\n\t\tLogger: client.loggers[methodName],\n\t\tContextLogger: NewContextLogger(client.loggers[methodName]),\n\t\tdefaultHeaders: client.DefaultHeaders,\n\t\tctx: ctx,\n\t\tmetrics: client.contextMetrics,\n\t}\n\treq.res = NewClientHTTPResponse(req)\n\treq.start()\n\treturn req\n}\n\n\/\/ Start the request, do some metrics book keeping\nfunc (req *ClientHTTPRequest) start() {\n\tif req.started {\n\t\t\/* coverage ignore next line *\/\n\t\treq.Logger.Error(\"Cannot start ClientHTTPRequest twice\")\n\t\t\/* coverage ignore next line *\/\n\t\treturn\n\t}\n\treq.started = true\n\treq.startTime = time.Now()\n}\n\n\/\/ CheckHeaders verifies that the outbound request contains required headers\nfunc (req *ClientHTTPRequest) CheckHeaders(expected []string) error {\n\tif req.httpReq == nil {\n\t\t\/* coverage ignore next line *\/\n\t\tpanic(\"must call `req.WriteJSON()` before `req.CheckHeaders()`\")\n\t}\n\n\tactualHeaders := req.httpReq.Header\n\n\tfor _, headerName := range expected {\n\t\t\/\/ headerName is case insensitive, http.Header Get canonicalize the key\n\t\theaderValue := actualHeaders.Get(headerName)\n\t\tif headerValue == \"\" {\n\t\t\treq.Logger.Warn(\"Got outbound request without mandatory header\",\n\t\t\t\tzap.String(\"headerName\", headerName),\n\t\t\t)\n\n\t\t\treturn errors.New(\"Missing mandatory header: \" + headerName)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ WriteJSON will send a json http request out.\nfunc (req *ClientHTTPRequest) WriteJSON(\n\tmethod, url string,\n\theaders map[string]string,\n\tbody json.Marshaler,\n) error {\n\tvar httpReq *http.Request\n\tvar httpErr error\n\tif body != nil {\n\t\trawBody, err := body.MarshalJSON()\n\t\tif err != nil {\n\t\t\treq.Logger.Error(\"Could not serialize request json\", zap.Error(err))\n\t\t\treturn errors.Wrapf(\n\t\t\t\terr, \"Could not serialize %s.%s request json\",\n\t\t\t\treq.ClientID, req.MethodName,\n\t\t\t)\n\t\t}\n\t\treq.rawBody = rawBody\n\t\thttpReq, httpErr = http.NewRequest(method, url, bytes.NewReader(rawBody))\n\t} else {\n\t\thttpReq, httpErr = http.NewRequest(method, url, nil)\n\t}\n\n\tif httpErr != nil {\n\t\treq.Logger.Error(\"Could not create outbound request\", zap.Error(httpErr))\n\t\treturn errors.Wrapf(\n\t\t\thttpErr, \"Could not create outbound %s.%s request\",\n\t\t\treq.ClientID, req.MethodName,\n\t\t)\n\t}\n\n\t\/\/ Using `Add` over `Set` intentionally, allowing us to create a list\n\t\/\/ of headerValues for a given key.\n\tfor headerKey, headerValue := range req.filteredDefaultHeaders(req.defaultHeaders, headers) {\n\t\thttpReq.Header.Add(headerKey, headerValue)\n\t}\n\n\tfor k := range headers {\n\t\thttpReq.Header.Add(k, headers[k])\n\t}\n\n\tif body != nil {\n\t\thttpReq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\treq.httpReq = httpReq\n\treq.ctx = WithLogFields(req.ctx,\n\t\tzap.String(logFieldRequestMethod, method),\n\t\tzap.String(logFieldRequestURL, url),\n\t\tzap.Time(logFieldRequestStartTime, req.startTime),\n\t)\n\n\treturn nil\n}\n\n\/\/ Do will send the request out.\nfunc (req *ClientHTTPRequest) Do() (*ClientHTTPResponse, error) {\n\topName := fmt.Sprintf(\"%s.%s\", req.ClientID, req.MethodName)\n\turlTag := opentracing.Tag{Key: \"URL\", Value: req.httpReq.URL}\n\tmethodTag := opentracing.Tag{Key: \"Method\", Value: req.httpReq.Method}\n\tspan, ctx := opentracing.StartSpanFromContext(req.ctx, opName, urlTag, methodTag)\n\terr := req.InjectSpanToHeader(span, opentracing.HTTPHeaders)\n\tif err != nil {\n\t\t\/* coverage ignore next line *\/\n\t\treq.Logger.Error(\"Fail to inject span to headers\", zap.Error(err))\n\t\t\/* coverage ignore next line *\/\n\t\treturn nil, err\n\t}\n\n\tlogFields := make([]zap.Field, 0, len(req.httpReq.Header))\n\tfor k, v := range req.httpReq.Header {\n\t\tlogFields = append(logFields, zap.String(fmt.Sprintf(\"%s-%s\", logFieldRequestHeaderPrefix, k), v[0]))\n\t}\n\tctx = WithLogFields(ctx, logFields...)\n\treq.ctx = ctx\n\n\tres, err := req.client.Client.Do(req.httpReq.WithContext(ctx))\n\tspan.Finish()\n\tif err != nil {\n\t\treq.Logger.Error(\"Could not make outbound request\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\t\/\/ emit metrics\n\treq.metrics.IncCounter(req.ctx, clientRequest, 1)\n\n\treq.res.setRawHTTPResponse(res)\n\treturn req.res, nil\n}\n\n\/\/ InjectSpanToHeader will inject span to request header\n\/\/ This method is current used for unit tests\n\/\/ TODO: we need to set source and test code as same pkg name which would makes UTs easier\nfunc (req *ClientHTTPRequest) InjectSpanToHeader(span opentracing.Span, format interface{}) error {\n\tcarrier := opentracing.HTTPHeadersCarrier(req.httpReq.Header)\n\tif err := span.Tracer().Inject(span.Context(), format, carrier); err != nil {\n\t\treq.Logger.Error(\"Failed to inject tracing span.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (req *ClientHTTPRequest) filteredDefaultHeaders(defaultHeaders map[string]string, headers map[string]string) map[string]string {\n\tfilteredDefaultHeaders := make(map[string]string)\n\t\/\/ Copy from the original map to the filtered map\n\tfor key, value := range defaultHeaders {\n\t\tfilteredDefaultHeaders[key] = value\n\t}\n\n\tsourceHeader := \"x-uber-source\"\n\tif filteredDefaultHeaders[sourceHeader] != \"\" && headers[sourceHeader] != \"\" {\n\t\tdelete(filteredDefaultHeaders, sourceHeader)\n\t}\n\treturn filteredDefaultHeaders\n}\n<|endoftext|>"} {"text":"package sync\n\nimport (\n \"ghighlighter\/models\"\n \"ghighlighter\/readmill\/readmillreadings\"\n \"ghighlighter\/readmill\/readmillhighlights\"\n)\n\nfunc Sync() {\n config := models.Config()\n\n syncHighlights(config.AccessToken)\n syncReadings(config.UserId, config.AccessToken)\n}\n\nfunc syncHighlights(accessToken string) {\n highlights := models.Highlights()\n\n tmpItems := make([]models.GhHighlight, len(highlights.Items))\n copy(tmpItems, highlights.Items)\n\n for _, highlight := range tmpItems {\n readmillHighlight := readmillhighlights.Highlight{highlight.Content,\n highlight.Position, highlight.Timestamp, readmillhighlights.HighlightLocators{}}\n\n success := readmillhighlights.PostHighlight(readmillHighlight, highlight.ReadingReadmillId, accessToken)\n\n if success {\n highlights.Delete(highlight)\n }\n }\n}\n\nfunc syncReadings(userId int, accessToken string) {\n readings := models.Readings()\n readmillReadings := readmillreadings.GetReadings(userId, accessToken)\n\n for _, readmillReading := range readmillReadings {\n title := readmillReading.Book.Title + \" - \" + readmillReading.Book.Author\n reading := models.GhReading{title, readmillReading.Id, 0}\n readings.Add(reading)\n }\n}\n\nUse 1 as default value for total pages of a readingpackage sync\n\nimport (\n \"ghighlighter\/models\"\n \"ghighlighter\/readmill\/readmillreadings\"\n \"ghighlighter\/readmill\/readmillhighlights\"\n)\n\nfunc Sync() {\n config := models.Config()\n\n syncHighlights(config.AccessToken)\n syncReadings(config.UserId, config.AccessToken)\n}\n\nfunc syncHighlights(accessToken string) {\n highlights := models.Highlights()\n\n tmpItems := make([]models.GhHighlight, len(highlights.Items))\n copy(tmpItems, highlights.Items)\n\n for _, highlight := range tmpItems {\n readmillHighlight := readmillhighlights.Highlight{highlight.Content,\n highlight.Position, highlight.Timestamp, readmillhighlights.HighlightLocators{}}\n\n success := readmillhighlights.PostHighlight(readmillHighlight, highlight.ReadingReadmillId, accessToken)\n\n if success {\n highlights.Delete(highlight)\n }\n }\n}\n\nfunc syncReadings(userId int, accessToken string) {\n readings := models.Readings()\n readmillReadings := readmillreadings.GetReadings(userId, accessToken)\n\n for _, readmillReading := range readmillReadings {\n title := readmillReading.Book.Title + \" - \" + readmillReading.Book.Author\n reading := models.GhReading{title, readmillReading.Id, 1}\n readings.Add(reading)\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Bobby Powers. 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\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/nlopes\/slack\"\n\n\t\"bazil.org\/fuse\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype IdNamer interface {\n\tId() string\n\tName() string\n}\n\ntype FSConn struct {\n\t\/\/\n\tsuper *Super\n\n\tapi *slack.Slack\n\tws *slack.SlackWS\n\n\tin chan slack.SlackEvent\n\n\tinfo *slack.Info\n\n\tusers *DirSet\n\tchannels *DirSet\n\tgroups *DirSet\n}\n\n\/\/ shared by offline\/offline public New functions\nfunc newFSConn(token, infoPath string) (conn *FSConn, err error) {\n\tvar info slack.Info\n\tconn = new(FSConn)\n\n\tif infoPath != \"\" {\n\t\tbuf, err := ioutil.ReadFile(infoPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadFile(%s): %s\", infoPath, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &info)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unmarshal: %s\", err)\n\t\t}\n\t} else {\n\t\tconn.api = slack.New(token)\n\t\tconn.ws, err = conn.api.StartRTM(\"\", \"https:\/\/slack.com\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"StartRTM(): %s\\n\", err)\n\t\t}\n\t\tinfo = conn.api.GetInfo()\n\t}\n\n\t\/\/conn.api.SetDebug(true)\n\n\tconn.info = &info\n\tconn.in = make(chan slack.SlackEvent)\n\tconn.super = NewSuper()\n\n\troot := conn.super.GetRoot()\n\n\terr = conn.initUsers(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initUsers: %s\", err)\n\t}\n\terr = conn.initChannels(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initChannels: %s\", err)\n\t}\n\terr = conn.initGroups(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initChannels: %s\", err)\n\t}\n\n\tgo conn.ws.HandleIncomingEvents(conn.in)\n\tgo conn.ws.Keepalive(10 * time.Second)\n\tgo conn.routeIncomingEvents()\n\n\treturn conn, nil\n}\n\nfunc NewFSConn(token string) (*FSConn, error) {\n\treturn newFSConn(token, \"\")\n}\n\nfunc NewOfflineFSConn(infoPath string) (*FSConn, error) {\n\treturn newFSConn(\"\", infoPath)\n}\n\nfunc (fs *FSConn) initUsers(parent *DirNode) (err error) {\n\tfs.users, err = NewDirSet(fs.super.root, \"users\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('users'): %s\", err)\n\t}\n\n\tuserParent := fs.users.Container()\n\tfor _, u := range fs.info.Users {\n\t\tup := new(slack.User)\n\t\t*up = u\n\t\tud, err := NewUserDir(userParent, up)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewUserDir(%s): %s\", up.Id, err)\n\t\t}\n\t\terr = fs.users.Add(u.Id, u.Name, ud)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", up.Id, err)\n\t\t}\n\t}\n\n\tfs.users.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) initChannels(parent *DirNode) (err error) {\n\tfs.channels, err = NewDirSet(fs.super.root, \"channels\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('channels'): %s\", err)\n\t}\n\n\tchanParent := fs.users.Container()\n\tfor _, c := range fs.info.Channels {\n\t\tcp := new(Channel)\n\t\tcp.Channel = c\n\t\tcd, err := NewChannelDir(chanParent, cp)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewChanDir(%s): %s\", cp.Id, err)\n\t\t}\n\t\terr = fs.channels.Add(c.Id, c.Name, cd)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", cp.Id, err)\n\t\t}\n\t}\n\n\tfs.channels.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) initGroups(parent *DirNode) (err error) {\n\tfs.groups, err = NewDirSet(fs.super.root, \"groups\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('groups'): %s\", err)\n\t}\n\n\tgroupParent := fs.users.Container()\n\tfor _, g := range fs.info.Groups {\n\t\tgp := new(Group)\n\t\tgp.Group = g\n\t\tgd, err := NewGroupDir(groupParent, gp)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewChanDir(%s): %s\", gp.Id, err)\n\t\t}\n\t\terr = fs.groups.Add(g.Id, g.Name, gd)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", gp.Id, err)\n\t\t}\n\t}\n\n\tfs.groups.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) GetUser(id string) (*slack.User, bool) {\n\tuserDir := fs.users.LookupId(id)\n\tif userDir == nil {\n\t\treturn nil, false\n\t}\n\tu, ok := userDir.priv.(*slack.User)\n\treturn u, ok\n}\n\nfunc (fs *FSConn) routeIncomingEvents() {\n\tfor {\n\t\tmsg := <-fs.in\n\n\t\tswitch ev := msg.Data.(type) {\n\t\tcase *slack.MessageEvent:\n\t\t\tfmt.Printf(\"msg\\t%s\\t%s\\t%s\\t(%#v)\\n\", ev.Timestamp, ev.UserId, ev.Text, ev)\n\t\tcase *slack.PresenceChangeEvent:\n\t\t\tname := \"\"\n\t\t\tif u, ok := fs.GetUser(ev.UserId); ok {\n\t\t\t\tname = u.Name\n\t\t\t}\n\t\t\tfmt.Printf(\"presence\\t%s\\t%s\\n\", name, ev.Presence)\n\t\tcase *slack.SlackWSError:\n\t\t\tfmt.Printf(\"err: %s\\n\", ev)\n\t\t}\n\t}\n}\n\nfunc (fs *FSConn) Send(txtBytes []byte, id string) error {\n\ttxt := strings.TrimSpace(string(txtBytes))\n\n\tout := fs.ws.NewOutgoingMessage(txt, id)\n\terr := fs.ws.SendMessage(out)\n\tif err != nil {\n\t\tlog.Printf(\"SendMessage: %s\", err)\n\t}\n\t\/\/ TODO(bp) add this message to the session buffer, after we\n\t\/\/ get an ok\n\treturn err\n}\nfsconn: small cleanups to logging and a missing comment\/\/ Copyright 2015 Bobby Powers. 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\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/nlopes\/slack\"\n\n\t\"bazil.org\/fuse\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype IdNamer interface {\n\tId() string\n\tName() string\n}\n\ntype FSConn struct {\n\tsuper *Super\n\n\tapi *slack.Slack\n\tws *slack.SlackWS\n\tin chan slack.SlackEvent\n\tinfo *slack.Info\n\n\tusers *DirSet\n\tchannels *DirSet\n\tgroups *DirSet\n}\n\n\/\/ shared by offline\/offline public New functions\nfunc newFSConn(token, infoPath string) (conn *FSConn, err error) {\n\tvar info slack.Info\n\tconn = new(FSConn)\n\n\tif infoPath != \"\" {\n\t\tbuf, err := ioutil.ReadFile(infoPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadFile(%s): %s\", infoPath, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &info)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unmarshal: %s\", err)\n\t\t}\n\t} else {\n\t\tconn.api = slack.New(token)\n\t\tconn.ws, err = conn.api.StartRTM(\"\", \"https:\/\/slack.com\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"StartRTM(): %s\\n\", err)\n\t\t}\n\t\tinfo = conn.api.GetInfo()\n\t}\n\n\t\/\/conn.api.SetDebug(true)\n\n\tconn.info = &info\n\tconn.in = make(chan slack.SlackEvent)\n\tconn.super = NewSuper()\n\n\troot := conn.super.GetRoot()\n\n\terr = conn.initUsers(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initUsers: %s\", err)\n\t}\n\terr = conn.initChannels(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initChannels: %s\", err)\n\t}\n\terr = conn.initGroups(root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initChannels: %s\", err)\n\t}\n\n\tgo conn.ws.HandleIncomingEvents(conn.in)\n\tgo conn.ws.Keepalive(10 * time.Second)\n\tgo conn.routeIncomingEvents()\n\n\treturn conn, nil\n}\n\nfunc NewFSConn(token string) (*FSConn, error) {\n\treturn newFSConn(token, \"\")\n}\n\nfunc NewOfflineFSConn(infoPath string) (*FSConn, error) {\n\treturn newFSConn(\"\", infoPath)\n}\n\nfunc (fs *FSConn) initUsers(parent *DirNode) (err error) {\n\tfs.users, err = NewDirSet(fs.super.root, \"users\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('users'): %s\", err)\n\t}\n\n\tuserParent := fs.users.Container()\n\tfor _, u := range fs.info.Users {\n\t\tup := new(slack.User)\n\t\t*up = u\n\t\tud, err := NewUserDir(userParent, up)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewUserDir(%s): %s\", up.Id, err)\n\t\t}\n\t\terr = fs.users.Add(u.Id, u.Name, ud)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", up.Id, err)\n\t\t}\n\t}\n\n\tfs.users.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) initChannels(parent *DirNode) (err error) {\n\tfs.channels, err = NewDirSet(fs.super.root, \"channels\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('channels'): %s\", err)\n\t}\n\n\tchanParent := fs.users.Container()\n\tfor _, c := range fs.info.Channels {\n\t\tcp := new(Channel)\n\t\tcp.Channel = c\n\t\tcd, err := NewChannelDir(chanParent, cp)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewChanDir(%s): %s\", cp.Id, err)\n\t\t}\n\t\terr = fs.channels.Add(c.Id, c.Name, cd)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", cp.Id, err)\n\t\t}\n\t}\n\n\tfs.channels.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) initGroups(parent *DirNode) (err error) {\n\tfs.groups, err = NewDirSet(fs.super.root, \"groups\", fs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewDirSet('groups'): %s\", err)\n\t}\n\n\tgroupParent := fs.users.Container()\n\tfor _, g := range fs.info.Groups {\n\t\tgp := new(Group)\n\t\tgp.Group = g\n\t\tgd, err := NewGroupDir(groupParent, gp)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"NewChanDir(%s): %s\", gp.Id, err)\n\t\t}\n\t\terr = fs.groups.Add(g.Id, g.Name, gd)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Add(%s): %s\", gp.Id, err)\n\t\t}\n\t}\n\n\tfs.groups.Activate()\n\treturn nil\n}\n\nfunc (fs *FSConn) GetUser(id string) (*slack.User, bool) {\n\tuserDir := fs.users.LookupId(id)\n\tif userDir == nil {\n\t\treturn nil, false\n\t}\n\tu, ok := userDir.priv.(*slack.User)\n\treturn u, ok\n}\n\nfunc (fs *FSConn) routeIncomingEvents() {\n\tfor {\n\t\tmsg := <-fs.in\n\n\t\tswitch ev := msg.Data.(type) {\n\t\tcase *slack.MessageEvent:\n\t\t\tfmt.Printf(\"msg\\t%s\\t%s\\t%s\\n\", ev.Timestamp, ev.UserId, ev.Text)\n\t\tcase *slack.PresenceChangeEvent:\n\t\t\tname := \"\"\n\t\t\tif u, ok := fs.GetUser(ev.UserId); ok {\n\t\t\t\tname = u.Name\n\t\t\t}\n\t\t\tfmt.Printf(\"presence\\t%s\\t%s\\n\", name, ev.Presence)\n\t\tcase *slack.SlackWSError:\n\t\t\tfmt.Printf(\"err: %s\\n\", ev)\n\t\t}\n\t}\n}\n\nfunc (fs *FSConn) Send(txtBytes []byte, id string) error {\n\ttxt := strings.TrimSpace(string(txtBytes))\n\n\tout := fs.ws.NewOutgoingMessage(txt, id)\n\terr := fs.ws.SendMessage(out)\n\tif err != nil {\n\t\tlog.Printf(\"SendMessage: %s\", err)\n\t}\n\t\/\/ TODO(bp) add this message to the session buffer, after we\n\t\/\/ get an ok\n\treturn err\n}\n<|endoftext|>"} {"text":"package tcpreuse\n\nimport (\n\t\"testing\"\n\n\tma \"github.com\/multiformats\/go-multiaddr\"\n)\n\nfunc TestAll(t *testing.T) {\n\tvar trA Transport\n\tvar trB Transport\n\tladdr, _ := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/tcp\/0\")\n\tlistenerA, err := trA.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerA.Close()\n\tlistenerB, err := trB.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerB.Close()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tc, err := listenerA.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tc.Close()\n\t}()\n\n\tc, err := trB.Dial(listenerA.Multiaddr())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t<-done\n\tc.Close()\n}\nadd another test casepackage tcpreuse\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\tma \"github.com\/multiformats\/go-multiaddr\"\n)\n\nfunc TestSingle(t *testing.T) {\n\tvar trA Transport\n\tvar trB Transport\n\tladdr, _ := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/tcp\/0\")\n\tlistenerA, err := trA.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerA.Close()\n\tlistenerB, err := trB.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerB.Close()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tc, err := listenerA.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tc.Close()\n\t}()\n\n\tc, err := trB.Dial(listenerA.Multiaddr())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t<-done\n\tc.Close()\n}\n\nfunc TestTwoLocal(t *testing.T) {\n\tvar trA Transport\n\tvar trB Transport\n\tladdr, _ := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/tcp\/0\")\n\tlistenerA, err := trA.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerA.Close()\n\n\tlistenerB1, err := trB.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerB1.Close()\n\n\tlistenerB2, err := trB.Listen(laddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listenerB2.Close()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tc, err := listenerA.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tc.Close()\n\t}()\n\n\tc, err := trB.Dial(listenerA.Multiaddr())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlocalPort := c.LocalAddr().(*net.TCPAddr).Port\n\tif localPort != listenerB1.Addr().(*net.TCPAddr).Port &&\n\t\tlocalPort != listenerB2.Addr().(*net.TCPAddr).Port {\n\t\tt.Fatal(\"didn't dial from one of our listener ports\")\n\t}\n\t<-done\n\tc.Close()\n}\n<|endoftext|>"} {"text":"package controllers\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"gopkg.in\/DATA-DOG\/go-sqlmock.v1\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/eirka\/eirka-libs\/audit\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\te \"github.com\/eirka\/eirka-libs\/errors\"\n\t\"github.com\/eirka\/eirka-libs\/redis\"\n\t\"github.com\/eirka\/eirka-libs\/user\"\n)\n\n\/\/ gin router for tests\nvar router *gin.Engine\n\nfunc init() {\n\tuser.Secret = \"secret\"\n\n\t\/\/ Set up fake Redis connection\n\tredis.NewRedisMock()\n\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter = gin.New()\n\n\trouter.Use(user.Auth(false))\n\n\trouter.POST(\"\/tag\/add\", AddTagController)\n}\n\nfunc performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, path, nil)\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc performJsonRequest(r http.Handler, method, path string, body []byte) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(body))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc errorMessage(err error) string {\n\treturn fmt.Sprintf(`{\"error_message\":\"%s\"}`, err)\n}\n\nfunc successMessage(message string) string {\n\treturn fmt.Sprintf(`{\"success_message\":\"%s\"}`, message)\n}\n\nfunc TestAddTagController(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\tmock.ExpectExec(\"INSERT into tagmap\").\n\t\tWithArgs(1, 1).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\tmock.ExpectExec(`INSERT INTO audit \\(user_id,ib_id,audit_type,audit_ip,audit_time,audit_action,audit_info\\)`).\n\t\tWithArgs(1, 1, audit.BoardLog, \"127.0.0.1\", audit.AuditAddTag, \"1\").\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\tredis.RedisCache.Mock.Command(\"DEL\", \"tags:1\", \"tag:1:1\", \"image:1\")\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 200, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), successMessage(audit.AuditAddTag), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n\n}\n\nfunc TestAddTagControllerBadInput(t *testing.T) {\n\n\tvar reuesttests = []struct {\n\t\tname string\n\t\tin []byte\n\t}{\n\t\t{\"nofield\", []byte(`{}`)},\n\t\t{\"badfield\", []byte(`{\"derp\": 1}`)},\n\t\t{\"badmissing\", []byte(`{\"ib\": 0}`)},\n\t\t{\"badmissing\", []byte(`{\"ib\": 0, \"tag\": 1}`)},\n\t\t{\"badmissing\", []byte(`{\"image\": 1}`)},\n\t\t{\"badib\", []byte(`{\"ib\": 0, \"tag\": 1, \"image\": 1}`)},\n\t\t{\"badib\", []byte(`{\"ib\": dur, \"tag\": 1, \"image\": 1}`)},\n\t\t{\"badtag\", []byte(`{\"ib\": 1, \"tag\": 0, \"image\": 1}`)},\n\t\t{\"badtag\", []byte(`{\"ib\": 1, \"tag\": dur, \"image\": 1}`)},\n\t\t{\"badimage\", []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 0}`)},\n\t\t{\"badimage\", []byte(`{\"ib\": 1, \"tag\": 1, \"image\": dur}`)},\n\t\t{\"badall\", []byte(`{\"ib\": 0, \"tag\": 0, \"image\": 0}`)},\n\t}\n\n\tfor _, test := range reuesttests {\n\t\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", test.in)\n\t\tassert.Equal(t, first.Code, 400, fmt.Sprintf(\"HTTP request code should match for request %s\", test.name))\n\t}\n\n}\n\nfunc TestAddTagControllerImageNotFound(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 400, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), errorMessage(e.ErrNotFound), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n}\n\nfunc TestAddTagControllerDuplicate(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 400, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), errorMessage(e.ErrDuplicateTag), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n}\nadd controller testspackage controllers\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"gopkg.in\/DATA-DOG\/go-sqlmock.v1\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/eirka\/eirka-libs\/audit\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\te \"github.com\/eirka\/eirka-libs\/errors\"\n\t\"github.com\/eirka\/eirka-libs\/redis\"\n\t\"github.com\/eirka\/eirka-libs\/user\"\n)\n\n\/\/ gin router for tests\nvar router *gin.Engine\n\nfunc init() {\n\tuser.Secret = \"secret\"\n\n\t\/\/ Set up fake Redis connection\n\tredis.NewRedisMock()\n\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter = gin.New()\n\n\trouter.Use(user.Auth(false))\n\n\trouter.POST(\"\/tag\/add\", AddTagController)\n}\n\nfunc performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, path, nil)\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc performJsonRequest(r http.Handler, method, path string, body []byte) *httptest.ResponseRecorder {\n\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(body))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc errorMessage(err error) string {\n\treturn fmt.Sprintf(`{\"error_message\":\"%s\"}`, err)\n}\n\nfunc successMessage(message string) string {\n\treturn fmt.Sprintf(`{\"success_message\":\"%s\"}`, message)\n}\n\nfunc TestAddTagController(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\tmock.ExpectExec(\"INSERT into tagmap\").\n\t\tWithArgs(1, 1).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\tmock.ExpectExec(`INSERT INTO audit \\(user_id,ib_id,audit_type,audit_ip,audit_time,audit_action,audit_info\\)`).\n\t\tWithArgs(1, 1, audit.BoardLog, \"127.0.0.1\", audit.AuditAddTag).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\tredis.RedisCache.Mock.Command(\"DEL\", \"tags:1\", \"tag:1:1\", \"image:1\")\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 200, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), successMessage(audit.AuditAddTag), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n\n}\n\nfunc TestAddTagControllerBadInput(t *testing.T) {\n\n\tvar reuesttests = []struct {\n\t\tname string\n\t\tin []byte\n\t}{\n\t\t{\"nofield\", []byte(`{}`)},\n\t\t{\"badfield\", []byte(`{\"derp\": 1}`)},\n\t\t{\"badmissing\", []byte(`{\"ib\": 0}`)},\n\t\t{\"badmissing\", []byte(`{\"ib\": 0, \"tag\": 1}`)},\n\t\t{\"badmissing\", []byte(`{\"image\": 1}`)},\n\t\t{\"badib\", []byte(`{\"ib\": 0, \"tag\": 1, \"image\": 1}`)},\n\t\t{\"badib\", []byte(`{\"ib\": dur, \"tag\": 1, \"image\": 1}`)},\n\t\t{\"badtag\", []byte(`{\"ib\": 1, \"tag\": 0, \"image\": 1}`)},\n\t\t{\"badtag\", []byte(`{\"ib\": 1, \"tag\": dur, \"image\": 1}`)},\n\t\t{\"badimage\", []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 0}`)},\n\t\t{\"badimage\", []byte(`{\"ib\": 1, \"tag\": 1, \"image\": dur}`)},\n\t\t{\"badall\", []byte(`{\"ib\": 0, \"tag\": 0, \"image\": 0}`)},\n\t}\n\n\tfor _, test := range reuesttests {\n\t\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", test.in)\n\t\tassert.Equal(t, first.Code, 400, fmt.Sprintf(\"HTTP request code should match for request %s\", test.name))\n\t}\n\n}\n\nfunc TestAddTagControllerImageNotFound(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 400, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), errorMessage(e.ErrNotFound), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n}\n\nfunc TestAddTagControllerDuplicate(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\trequest := []byte(`{\"ib\": 1, \"tag\": 1, \"image\": 1}`)\n\n\tfirst := performJsonRequest(router, \"POST\", \"\/tag\/add\", request)\n\n\tassert.Equal(t, first.Code, 400, \"HTTP request code should match\")\n\tassert.JSONEq(t, first.Body.String(), errorMessage(e.ErrDuplicateTag), \"HTTP response should match\")\n\n\tassert.NoError(t, mock.ExpectationsWereMet(), \"An error was not expected\")\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\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 condition\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/node-problem-detector\/pkg\/exporters\/k8sexporter\/problemclient\"\n\t\"k8s.io\/node-problem-detector\/pkg\/types\"\n\tproblemutil \"k8s.io\/node-problem-detector\/pkg\/util\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/clock\"\n\n\t\"github.com\/golang\/glog\"\n)\n\nconst (\n\t\/\/ updatePeriod is the period at which condition manager checks update.\n\tupdatePeriod = 1 * time.Second\n\t\/\/ resyncPeriod is the period at which condition manager does resync, only updates when needed.\n\tresyncPeriod = 10 * time.Second\n\t\/\/ heartbeatPeriod is the period at which condition manager does forcibly sync with apiserver.\n\theartbeatPeriod = 1 * time.Minute\n)\n\n\/\/ ConditionManager synchronizes node conditions with the apiserver with problem client.\n\/\/ It makes sure that:\n\/\/ 1) Node conditions are updated to apiserver as soon as possible.\n\/\/ 2) Node problem detector won't flood apiserver.\n\/\/ 3) No one else could change the node conditions maintained by node problem detector.\n\/\/ ConditionManager checks every updatePeriod to see whether there is node condition update. If there are any,\n\/\/ it will synchronize with the apiserver. This addresses 1) and 2).\n\/\/ ConditionManager synchronizes with apiserver every resyncPeriod no matter there is node condition update or\n\/\/ not. This addresses 3).\ntype ConditionManager interface {\n\t\/\/ Start starts the condition manager.\n\tStart()\n\t\/\/ UpdateCondition updates a specific condition.\n\tUpdateCondition(types.Condition)\n\t\/\/ GetConditions returns all current conditions.\n\tGetConditions() []types.Condition\n}\n\ntype conditionManager struct {\n\t\/\/ Only 2 fields will be accessed by more than one goroutines at the same time:\n\t\/\/ * `updates`: updates will be written by random caller and the sync routine,\n\t\/\/ so it needs to be protected by write lock in both `UpdateCondition` and\n\t\/\/ `needUpdates`.\n\t\/\/ * `conditions`: conditions will only be written in the sync routine, but\n\t\/\/ it will be read by random caller and the sync routine. So it needs to be\n\t\/\/ protected by write lock in `needUpdates` and read lock in `GetConditions`.\n\t\/\/ No lock is needed in `sync`, because it is in the same goroutine with the\n\t\/\/ write operation.\n\tsync.RWMutex\n\tclock clock.Clock\n\tlatestTry time.Time\n\tresyncNeeded bool\n\tclient problemclient.Client\n\tupdates map[string]types.Condition\n\tconditions map[string]types.Condition\n}\n\n\/\/ NewConditionManager creates a condition manager.\nfunc NewConditionManager(client problemclient.Client, clock clock.Clock) ConditionManager {\n\treturn &conditionManager{\n\t\tclient: client,\n\t\tclock: clock,\n\t\tupdates: make(map[string]types.Condition),\n\t\tconditions: make(map[string]types.Condition),\n\t}\n}\n\nfunc (c *conditionManager) Start() {\n\tgo c.syncLoop()\n}\n\nfunc (c *conditionManager) UpdateCondition(condition types.Condition) {\n\tc.Lock()\n\tdefer c.Unlock()\n\t\/\/ New node condition will override the old condition, because we only need the newest\n\t\/\/ condition for each condition type.\n\tc.updates[condition.Type] = condition\n}\n\nfunc (c *conditionManager) GetConditions() []types.Condition {\n\tc.RLock()\n\tdefer c.RUnlock()\n\tvar conditions []types.Condition\n\tfor _, condition := range c.conditions {\n\t\tconditions = append(conditions, condition)\n\t}\n\treturn conditions\n}\n\nfunc (c *conditionManager) syncLoop() {\n\tupdateCh := c.clock.Tick(updatePeriod)\n\tfor {\n\t\tselect {\n\t\tcase <-updateCh:\n\t\t\tif c.needUpdates() || c.needResync() || c.needHeartbeat() {\n\t\t\t\tc.sync()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ needUpdates checks whether there are recent updates.\nfunc (c *conditionManager) needUpdates() bool {\n\tc.Lock()\n\tdefer c.Unlock()\n\tneedUpdate := false\n\tfor t, update := range c.updates {\n\t\tif !reflect.DeepEqual(c.conditions[t], update) {\n\t\t\tneedUpdate = true\n\t\t\tc.conditions[t] = update\n\t\t}\n\t\tdelete(c.updates, t)\n\t}\n\treturn needUpdate\n}\n\n\/\/ needResync checks whether a resync is needed.\nfunc (c *conditionManager) needResync() bool {\n\t\/\/ Only update when resync is needed.\n\treturn c.clock.Now().Sub(c.latestTry) >= resyncPeriod && c.resyncNeeded\n}\n\n\/\/ needHeartbeat checks whether a forcible heartbeat is needed.\nfunc (c *conditionManager) needHeartbeat() bool {\n\treturn c.clock.Now().Sub(c.latestTry) >= heartbeatPeriod\n}\n\n\/\/ sync synchronizes node conditions with the apiserver.\nfunc (c *conditionManager) sync() {\n\tc.latestTry = c.clock.Now()\n\tc.resyncNeeded = false\n\tconditions := []v1.NodeCondition{}\n\tfor i := range c.conditions {\n\t\tconditions = append(conditions, problemutil.ConvertToAPICondition(c.conditions[i]))\n\t}\n\tif err := c.client.SetConditions(conditions); err != nil {\n\t\t\/\/ The conditions will be updated again in future sync\n\t\tglog.Errorf(\"failed to update node conditions: %v\", err)\n\t\tc.resyncNeeded = true\n\t\treturn\n\t}\n}\nHandle vendor change in k8s.io\/apimachinery\/pkg\/util\/clock\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\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 condition\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/node-problem-detector\/pkg\/exporters\/k8sexporter\/problemclient\"\n\t\"k8s.io\/node-problem-detector\/pkg\/types\"\n\tproblemutil \"k8s.io\/node-problem-detector\/pkg\/util\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/clock\"\n\n\t\"github.com\/golang\/glog\"\n)\n\nconst (\n\t\/\/ updatePeriod is the period at which condition manager checks update.\n\tupdatePeriod = 1 * time.Second\n\t\/\/ resyncPeriod is the period at which condition manager does resync, only updates when needed.\n\tresyncPeriod = 10 * time.Second\n\t\/\/ heartbeatPeriod is the period at which condition manager does forcibly sync with apiserver.\n\theartbeatPeriod = 1 * time.Minute\n)\n\n\/\/ ConditionManager synchronizes node conditions with the apiserver with problem client.\n\/\/ It makes sure that:\n\/\/ 1) Node conditions are updated to apiserver as soon as possible.\n\/\/ 2) Node problem detector won't flood apiserver.\n\/\/ 3) No one else could change the node conditions maintained by node problem detector.\n\/\/ ConditionManager checks every updatePeriod to see whether there is node condition update. If there are any,\n\/\/ it will synchronize with the apiserver. This addresses 1) and 2).\n\/\/ ConditionManager synchronizes with apiserver every resyncPeriod no matter there is node condition update or\n\/\/ not. This addresses 3).\ntype ConditionManager interface {\n\t\/\/ Start starts the condition manager.\n\tStart()\n\t\/\/ UpdateCondition updates a specific condition.\n\tUpdateCondition(types.Condition)\n\t\/\/ GetConditions returns all current conditions.\n\tGetConditions() []types.Condition\n}\n\ntype conditionManager struct {\n\t\/\/ Only 2 fields will be accessed by more than one goroutines at the same time:\n\t\/\/ * `updates`: updates will be written by random caller and the sync routine,\n\t\/\/ so it needs to be protected by write lock in both `UpdateCondition` and\n\t\/\/ `needUpdates`.\n\t\/\/ * `conditions`: conditions will only be written in the sync routine, but\n\t\/\/ it will be read by random caller and the sync routine. So it needs to be\n\t\/\/ protected by write lock in `needUpdates` and read lock in `GetConditions`.\n\t\/\/ No lock is needed in `sync`, because it is in the same goroutine with the\n\t\/\/ write operation.\n\tsync.RWMutex\n\tclock clock.Clock\n\tlatestTry time.Time\n\tresyncNeeded bool\n\tclient problemclient.Client\n\tupdates map[string]types.Condition\n\tconditions map[string]types.Condition\n}\n\n\/\/ NewConditionManager creates a condition manager.\nfunc NewConditionManager(client problemclient.Client, clock clock.Clock) ConditionManager {\n\treturn &conditionManager{\n\t\tclient: client,\n\t\tclock: clock,\n\t\tupdates: make(map[string]types.Condition),\n\t\tconditions: make(map[string]types.Condition),\n\t}\n}\n\nfunc (c *conditionManager) Start() {\n\tgo c.syncLoop()\n}\n\nfunc (c *conditionManager) UpdateCondition(condition types.Condition) {\n\tc.Lock()\n\tdefer c.Unlock()\n\t\/\/ New node condition will override the old condition, because we only need the newest\n\t\/\/ condition for each condition type.\n\tc.updates[condition.Type] = condition\n}\n\nfunc (c *conditionManager) GetConditions() []types.Condition {\n\tc.RLock()\n\tdefer c.RUnlock()\n\tvar conditions []types.Condition\n\tfor _, condition := range c.conditions {\n\t\tconditions = append(conditions, condition)\n\t}\n\treturn conditions\n}\n\nfunc (c *conditionManager) syncLoop() {\n\tticker := c.clock.NewTicker(updatePeriod)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C():\n\t\t\tif c.needUpdates() || c.needResync() || c.needHeartbeat() {\n\t\t\t\tc.sync()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ needUpdates checks whether there are recent updates.\nfunc (c *conditionManager) needUpdates() bool {\n\tc.Lock()\n\tdefer c.Unlock()\n\tneedUpdate := false\n\tfor t, update := range c.updates {\n\t\tif !reflect.DeepEqual(c.conditions[t], update) {\n\t\t\tneedUpdate = true\n\t\t\tc.conditions[t] = update\n\t\t}\n\t\tdelete(c.updates, t)\n\t}\n\treturn needUpdate\n}\n\n\/\/ needResync checks whether a resync is needed.\nfunc (c *conditionManager) needResync() bool {\n\t\/\/ Only update when resync is needed.\n\treturn c.clock.Now().Sub(c.latestTry) >= resyncPeriod && c.resyncNeeded\n}\n\n\/\/ needHeartbeat checks whether a forcible heartbeat is needed.\nfunc (c *conditionManager) needHeartbeat() bool {\n\treturn c.clock.Now().Sub(c.latestTry) >= heartbeatPeriod\n}\n\n\/\/ sync synchronizes node conditions with the apiserver.\nfunc (c *conditionManager) sync() {\n\tc.latestTry = c.clock.Now()\n\tc.resyncNeeded = false\n\tconditions := []v1.NodeCondition{}\n\tfor i := range c.conditions {\n\t\tconditions = append(conditions, problemutil.ConvertToAPICondition(c.conditions[i]))\n\t}\n\tif err := c.client.SetConditions(conditions); err != nil {\n\t\t\/\/ The conditions will be updated again in future sync\n\t\tglog.Errorf(\"failed to update node conditions: %v\", err)\n\t\tc.resyncNeeded = true\n\t\treturn\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 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\"errors\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Fetcher interface {\n\t\/\/ Fetch returns the body of URL and\n\t\/\/ a slice of URLs found on that page.\n\tFetch(url string) (body string, urls []string, err error)\n}\n\n\/\/ fetched tracks URLs that have been (or are being) fetched.\n\/\/ The lock must be held while reading from or writing to the map.\n\/\/ See http:\/\/golang.org\/ref\/spec#Struct_types section on embedded types.\nvar fetched = struct {\n\tm map[string]error\n\tsync.Mutex\n}{m: make(map[string]error)}\n\nvar loading = errors.New(\"url load in progress\") \/\/ sentinel value \n\n\/\/ Crawl uses fetcher to recursively crawl\n\/\/ pages starting with url, to a maximum of depth.\nfunc Crawl(url string, depth int, fetcher Fetcher) {\n\tif depth <= 0 {\n\t\tfmt.Printf(\"<- Done with %v, depth 0.\\n\", url)\n\t\treturn\n\t}\n\n\tfetched.Lock()\n\tif _, ok := fetched.m[url]; ok {\n\t\tfetched.Unlock()\n\t\tfmt.Printf(\"<- Done with %v, already fetched.\\n\", url)\n\t\treturn\n\t}\n\t\/\/ We mark the url to be loading to avoid others reloading it at the same time.\n\tfetched.m[url] = loading\n\tfetched.Unlock()\n\n\t\/\/ We load it concurrently.\n\tbody, urls, err := fetcher.Fetch(url)\n\n\t\/\/ And update the status in a synced zone.\n\tfetched.Lock()\n\tfetched.m[url] = err\n\tfetched.Unlock()\n\n\tif err != nil {\n\t\tfmt.Printf(\"<- Error on %v: %v\\n\", url, err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Found: %s %q\\n\", url, body)\n\tdone := make(chan bool)\n\tfor i, u := range urls {\n\t\tfmt.Printf(\"-> Crawling child %v\/%v of %v : %v.\\n\", i, len(urls), url, u)\n\t\tgo func(url string) {\n\t\t\tCrawl(url, depth, fetcher)\n\t\t\tdone <- true\n\t\t}(u)\n\t}\n\tfor i := range urls {\n\t\tfmt.Printf(\"<- [%v] %v\/%v Waiting for child %v.\\n\", url, i, len(urls))\n\t\t<-done\n\t}\n\tfmt.Printf(\"<- Done with %v\\n\", url)\n}\n\nfunc main() {\n\tCrawl(\"http:\/\/golang.org\/\", 4, fetcher)\n\n\tfmt.Println(\"Fetching stats\\n--------------\")\n\tfor url, err := range fetched.m {\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%v failed: %v\\n\", url, err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%v was fetched\\n\", url)\n\t\t}\n\t}\n}\n\n\/\/ fakeFetcher is Fetcher that returns canned results.\ntype fakeFetcher map[string]*fakeResult\n\ntype fakeResult struct {\n\tbody string\n\turls []string\n}\n\nfunc (f *fakeFetcher) Fetch(url string) (string, []string, error) {\n\tif res, ok := (*f)[url]; ok {\n\t\treturn res.body, res.urls, nil\n\t}\n\treturn \"\", nil, fmt.Errorf(\"not found: %s\", url)\n}\n\n\/\/ fetcher is a populated fakeFetcher.\nvar fetcher = &fakeFetcher{\n\t\"http:\/\/golang.org\/\": &fakeResult{\n\t\t\"The Go Programming Language\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t\t\"http:\/\/golang.org\/cmd\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/\": &fakeResult{\n\t\t\"Packages\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/cmd\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/fmt\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/os\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/fmt\/\": &fakeResult{\n\t\t\"Package fmt\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/os\/\": &fakeResult{\n\t\t\"Package os\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t},\n\t},\n}\n[x\/tour] go-tour: Fixing webcrawler solution. Fixes #45\/\/ Copyright 2012 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\"errors\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Fetcher interface {\n\t\/\/ Fetch returns the body of URL and\n\t\/\/ a slice of URLs found on that page.\n\tFetch(url string) (body string, urls []string, err error)\n}\n\n\/\/ fetched tracks URLs that have been (or are being) fetched.\n\/\/ The lock must be held while reading from or writing to the map.\n\/\/ See http:\/\/golang.org\/ref\/spec#Struct_types section on embedded types.\nvar fetched = struct {\n\tm map[string]error\n\tsync.Mutex\n}{m: make(map[string]error)}\n\nvar loading = errors.New(\"url load in progress\") \/\/ sentinel value \n\n\/\/ Crawl uses fetcher to recursively crawl\n\/\/ pages starting with url, to a maximum of depth.\nfunc Crawl(url string, depth int, fetcher Fetcher) {\n\tif depth <= 0 {\n\t\tfmt.Printf(\"<- Done with %v, depth 0.\\n\", url)\n\t\treturn\n\t}\n\n\tfetched.Lock()\n\tif _, ok := fetched.m[url]; ok {\n\t\tfetched.Unlock()\n\t\tfmt.Printf(\"<- Done with %v, already fetched.\\n\", url)\n\t\treturn\n\t}\n\t\/\/ We mark the url to be loading to avoid others reloading it at the same time.\n\tfetched.m[url] = loading\n\tfetched.Unlock()\n\n\t\/\/ We load it concurrently.\n\tbody, urls, err := fetcher.Fetch(url)\n\n\t\/\/ And update the status in a synced zone.\n\tfetched.Lock()\n\tfetched.m[url] = err\n\tfetched.Unlock()\n\n\tif err != nil {\n\t\tfmt.Printf(\"<- Error on %v: %v\\n\", url, err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Found: %s %q\\n\", url, body)\n\tdone := make(chan bool)\n\tfor i, u := range urls {\n\t\tfmt.Printf(\"-> Crawling child %v\/%v of %v : %v.\\n\", i, len(urls), url, u)\n\t\tgo func(url string) {\n\t\t\tCrawl(url, depth-1, fetcher)\n\t\t\tdone <- true\n\t\t}(u)\n\t}\n\tfor i := range urls {\n\t\tfmt.Printf(\"<- [%v] %v\/%v Waiting for child %v.\\n\", url, i, len(urls))\n\t\t<-done\n\t}\n\tfmt.Printf(\"<- Done with %v\\n\", url)\n}\n\nfunc main() {\n\tCrawl(\"http:\/\/golang.org\/\", 4, fetcher)\n\n\tfmt.Println(\"Fetching stats\\n--------------\")\n\tfor url, err := range fetched.m {\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%v failed: %v\\n\", url, err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%v was fetched\\n\", url)\n\t\t}\n\t}\n}\n\n\/\/ fakeFetcher is Fetcher that returns canned results.\ntype fakeFetcher map[string]*fakeResult\n\ntype fakeResult struct {\n\tbody string\n\turls []string\n}\n\nfunc (f *fakeFetcher) Fetch(url string) (string, []string, error) {\n\tif res, ok := (*f)[url]; ok {\n\t\treturn res.body, res.urls, nil\n\t}\n\treturn \"\", nil, fmt.Errorf(\"not found: %s\", url)\n}\n\n\/\/ fetcher is a populated fakeFetcher.\nvar fetcher = &fakeFetcher{\n\t\"http:\/\/golang.org\/\": &fakeResult{\n\t\t\"The Go Programming Language\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t\t\"http:\/\/golang.org\/cmd\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/\": &fakeResult{\n\t\t\"Packages\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/cmd\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/fmt\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/os\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/fmt\/\": &fakeResult{\n\t\t\"Package fmt\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t},\n\t},\n\t\"http:\/\/golang.org\/pkg\/os\/\": &fakeResult{\n\t\t\"Package os\",\n\t\t[]string{\n\t\t\t\"http:\/\/golang.org\/\",\n\t\t\t\"http:\/\/golang.org\/pkg\/\",\n\t\t},\n\t},\n}\n<|endoftext|>"} {"text":"package builder\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/dev-cloverlab\/carpenter\/dialect\/mysql\"\n)\n\nfunc Build(db *sql.DB, old, new *mysql.Table, withDrop bool) (queries []string, err error) {\n\tif old == nil && new == nil {\n\t\treturn queries, fmt.Errorf(\"err: Both pointer of the specified new and old is nil.\")\n\t}\n\tif old != nil && new != nil && old.TableName != new.TableName {\n\t\treturn queries, fmt.Errorf(\"err: Table name of the specified new and old is a difference\")\n\t}\n\tif reflect.DeepEqual(old, new) {\n\t\treturn queries, nil\n\t}\n\tif q := willCreate(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q)\n\t}\n\tif withDrop {\n\t\tif q := willDrop(old, new); len(q) > 0 {\n\t\t\tqueries = append(queries, q)\n\t\t}\n\t}\n\tif q := willAlterTableCharacterSet(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q)\n\t}\n\tif q := willAlterColumnCharacterSet(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q...)\n\t}\n\tif q := willAlter(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q)\n\t}\n\treturn queries, nil\n}\n\nfunc willCreate(old, new *mysql.Table) string {\n\tif old == nil && new != nil {\n\t\treturn new.ToCreateSQL()\n\t}\n\treturn \"\"\n}\n\nfunc willDrop(old, new *mysql.Table) string {\n\tif old != nil && new == nil {\n\t\treturn old.ToDropSQL()\n\t}\n\treturn \"\"\n}\n\nfunc willAlterTableCharacterSet(old, new *mysql.Table) string {\n\tif old == nil || new == nil {\n\t\treturn \"\"\n\t}\n\n\talter := []string{}\n\tif old.GetCharset() != new.GetCharset() {\n\t\talter = append(alter, new.ToConvertCharsetSQL())\n\t\told.TableCollation = new.TableCollation\n\t}\n\treturn new.ToAlterSQL(alter, \"\")\n}\n\nfunc willAlterColumnCharacterSet(old, new *mysql.Table) []string {\n\tif old == nil || new == nil {\n\t\treturn []string{}\n\t}\n\n\tnewCols := new.Columns.GroupByColumnName()\n\toldCols := old.Columns.GroupByColumnName()\n\tsqls := []string{}\n\tfor _, colName := range new.Columns.GetSortedColumnNames() {\n\t\tif _, ok := oldCols[colName]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\tnewCol := newCols[colName]\n\t\toldCol := oldCols[colName]\n\t\tif !newCol.CharacterSetName.Valid || (oldCol.CompareCharacterSet(newCol) && oldCol.CompareCollation(newCol)) {\n\t\t\tcontinue\n\t\t}\n\t\toldCols[colName].CollationName = newCol.CollationName\n\t\tsqls = append(sqls, new.ToAlterSQL([]string{newCol.ToModifyCharsetSQL()}, \"\"))\n\t}\n\treturn sqls\n}\n\nfunc willAlter(old, new *mysql.Table) string {\n\tif old == nil || new == nil {\n\t\treturn \"\"\n\t}\n\tif reflect.DeepEqual(old, new) {\n\t\treturn \"\"\n\t}\n\n\talter := []string{}\n\talter = append(alter, willDropIndex(old, new)...)\n\talter = append(alter, willDropColumn(old, new)...)\n\talter = append(alter, willAddColumn(old, new)...)\n\talter = append(alter, willAddIndex(old, new)...)\n\talter = append(alter, willModifyColumn(old, new)...)\n\treturn new.ToAlterSQL(alter, willModifyPartition(old, new))\n}\n\nfunc willAddColumn(old, new *mysql.Table) []string {\n\tcols := mysql.Columns{}\n\tfor _, column := range new.Columns {\n\t\tif old.Columns.Contains(column) {\n\t\t\tcontinue\n\t\t}\n\t\tcols = append(cols, column)\n\t}\n\treturn cols.ToAddSQL(new.Columns)\n}\n\nfunc willDropColumn(old, new *mysql.Table) []string {\n\tcols := mysql.Columns{}\n\tfor _, column := range old.Columns {\n\t\tif new.Columns.Contains(column) {\n\t\t\tcontinue\n\t\t}\n\t\tcols = append(cols, column)\n\t}\n\treturn cols.ToDropSQL()\n}\n\nfunc willModifyColumn(old, new *mysql.Table) []string {\n\tnewCols := new.Columns.GroupByColumnName()\n\toldCols := old.Columns.GroupByColumnName()\n\tsqls := []string{}\n\tfor _, colName := range new.Columns.GetSortedColumnNames() {\n\t\tif _, ok := oldCols[colName]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\tnewCol := newCols[colName]\n\t\toldCol := oldCols[colName]\n\t\toldTableSchema := oldCol.TableSchema\n\t\toldColumnKey := oldCol.ColumnKey\n\t\toldPrivileges := oldCol.Privileges\n\t\toldOrdinalPosition := oldCol.OrdinalPosition\n\t\toldCol.TableSchema = newCol.TableSchema\n\t\toldCol.ColumnKey = newCol.ColumnKey\n\t\toldCol.Privileges = newCol.Privileges\n\t\toldCol.OrdinalPosition = newCol.OrdinalPosition\n\t\tif !reflect.DeepEqual(oldCol, newCol) {\n\t\t\tsqls = append(sqls, newCol.ToModifySQL())\n\t\t}\n\t\toldCol.TableSchema = oldTableSchema\n\t\toldCol.ColumnKey = oldColumnKey\n\t\toldCol.Privileges = oldPrivileges\n\t\toldCol.OrdinalPosition = oldOrdinalPosition\n\t}\n\treturn sqls\n}\n\nfunc willModifyPartition(old, new *mysql.Table) string {\n\tif reflect.DeepEqual(old.Partitions, new.Partitions) {\n\t\treturn \"\"\n\t}\n\tif len(new.Partitions) <= 0 {\n\t\treturn \"\"\n\t}\n\treturn new.Partitions.ToSQL()\n}\n\nfunc willAddIndex(old, new *mysql.Table) []string {\n\tnewIndicesMap := new.Indices.GroupByKeyName()\n\toldIndicesMap := old.Indices.GroupByKeyName()\n\tsqls := []string{}\n\tfor _, keyName := range new.Indices.GetSortedKeys() {\n\t\tif _, ok := oldIndicesMap[keyName]; !ok {\n\t\t\tsqls = append(sqls, newIndicesMap[keyName].ToAddSQL()...)\n\t\t\tcontinue\n\t\t}\n\t\tnewIndices := newIndicesMap[keyName]\n\t\toldIndices := oldIndicesMap[keyName]\n\t\tif reflect.DeepEqual(oldIndices, newIndices) {\n\t\t\tcontinue\n\t\t}\n\t\tsqls = append(sqls, oldIndices.ToDropSQL()...)\n\t\tsqls = append(sqls, newIndices.ToAddSQL()...)\n\t}\n\treturn sqls\n}\n\nfunc willDropIndex(old, new *mysql.Table) []string {\n\tnewIndicesMap := new.Indices.GroupByKeyName()\n\toldIndicesMap := old.Indices.GroupByKeyName()\n\tsqls := []string{}\n\tfor _, keyName := range old.Indices.GetSortedKeys() {\n\t\tif _, ok := newIndicesMap[keyName]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tsqls = append(sqls, oldIndicesMap[keyName].ToDropSQL()...)\n\t}\n\treturn sqls\n}\nchange willAlter calling function willAlter call willAlterTableCharacterSet and willAlterColumnCharacterSetpackage builder\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/dev-cloverlab\/carpenter\/dialect\/mysql\"\n)\n\nfunc Build(db *sql.DB, old, new *mysql.Table, withDrop bool) (queries []string, err error) {\n\tif old == nil && new == nil {\n\t\treturn queries, fmt.Errorf(\"err: Both pointer of the specified new and old is nil.\")\n\t}\n\tif old != nil && new != nil && old.TableName != new.TableName {\n\t\treturn queries, fmt.Errorf(\"err: Table name of the specified new and old is a difference\")\n\t}\n\tif reflect.DeepEqual(old, new) {\n\t\treturn queries, nil\n\t}\n\tif q := willCreate(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q)\n\t}\n\tif withDrop {\n\t\tif q := willDrop(old, new); len(q) > 0 {\n\t\t\tqueries = append(queries, q)\n\t\t}\n\t}\n\tif q := willAlter(old, new); len(q) > 0 {\n\t\tqueries = append(queries, q)\n\t}\n\treturn queries, nil\n}\n\nfunc willCreate(old, new *mysql.Table) string {\n\tif old == nil && new != nil {\n\t\treturn new.ToCreateSQL()\n\t}\n\treturn \"\"\n}\n\nfunc willDrop(old, new *mysql.Table) string {\n\tif old != nil && new == nil {\n\t\treturn old.ToDropSQL()\n\t}\n\treturn \"\"\n}\n\nfunc willAlterTableCharacterSet(old, new *mysql.Table) []string {\n\tif old == nil || new == nil {\n\t\treturn []string{}\n\t}\n\n\talter := []string{}\n\tif old.GetCharset() != new.GetCharset() {\n\t\talter = append(alter, new.ToConvertCharsetSQL())\n\t\told.TableCollation = new.TableCollation\n\t}\n\treturn alter\n}\n\nfunc willAlterColumnCharacterSet(old, new *mysql.Table) []string {\n\tif old == nil || new == nil {\n\t\treturn []string{}\n\t}\n\n\tnewCols := new.Columns.GroupByColumnName()\n\toldCols := old.Columns.GroupByColumnName()\n\tsqls := []string{}\n\tfor _, colName := range new.Columns.GetSortedColumnNames() {\n\t\tif _, ok := oldCols[colName]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\tnewCol := newCols[colName]\n\t\toldCol := oldCols[colName]\n\t\tif !newCol.CharacterSetName.Valid || (oldCol.CompareCharacterSet(newCol) && oldCol.CompareCollation(newCol)) {\n\t\t\tcontinue\n\t\t}\n\t\toldCols[colName].CollationName = newCol.CollationName\n\t\tsqls = append(sqls, newCol.ToModifyCharsetSQL())\n\t}\n\treturn sqls\n}\n\nfunc willAlter(old, new *mysql.Table) string {\n\tif old == nil || new == nil {\n\t\treturn \"\"\n\t}\n\tif reflect.DeepEqual(old, new) {\n\t\treturn \"\"\n\t}\n\n\talter := []string{}\n\talter = append(alter, willAlterTableCharacterSet(old, new)...)\n\talter = append(alter, willAlterColumnCharacterSet(old, new)...)\n\talter = append(alter, willDropIndex(old, new)...)\n\talter = append(alter, willDropColumn(old, new)...)\n\talter = append(alter, willAddColumn(old, new)...)\n\talter = append(alter, willAddIndex(old, new)...)\n\talter = append(alter, willModifyColumn(old, new)...)\n\treturn new.ToAlterSQL(alter, willModifyPartition(old, new))\n}\n\nfunc willAddColumn(old, new *mysql.Table) []string {\n\tcols := mysql.Columns{}\n\tfor _, column := range new.Columns {\n\t\tif old.Columns.Contains(column) {\n\t\t\tcontinue\n\t\t}\n\t\tcols = append(cols, column)\n\t}\n\treturn cols.ToAddSQL(new.Columns)\n}\n\nfunc willDropColumn(old, new *mysql.Table) []string {\n\tcols := mysql.Columns{}\n\tfor _, column := range old.Columns {\n\t\tif new.Columns.Contains(column) {\n\t\t\tcontinue\n\t\t}\n\t\tcols = append(cols, column)\n\t}\n\treturn cols.ToDropSQL()\n}\n\nfunc willModifyColumn(old, new *mysql.Table) []string {\n\tnewCols := new.Columns.GroupByColumnName()\n\toldCols := old.Columns.GroupByColumnName()\n\tsqls := []string{}\n\tfor _, colName := range new.Columns.GetSortedColumnNames() {\n\t\tif _, ok := oldCols[colName]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\tnewCol := newCols[colName]\n\t\toldCol := oldCols[colName]\n\t\toldTableSchema := oldCol.TableSchema\n\t\toldColumnKey := oldCol.ColumnKey\n\t\toldPrivileges := oldCol.Privileges\n\t\toldOrdinalPosition := oldCol.OrdinalPosition\n\t\toldCol.TableSchema = newCol.TableSchema\n\t\toldCol.ColumnKey = newCol.ColumnKey\n\t\toldCol.Privileges = newCol.Privileges\n\t\toldCol.OrdinalPosition = newCol.OrdinalPosition\n\t\tif !reflect.DeepEqual(oldCol, newCol) {\n\t\t\tsqls = append(sqls, newCol.ToModifySQL())\n\t\t}\n\t\toldCol.TableSchema = oldTableSchema\n\t\toldCol.ColumnKey = oldColumnKey\n\t\toldCol.Privileges = oldPrivileges\n\t\toldCol.OrdinalPosition = oldOrdinalPosition\n\t}\n\treturn sqls\n}\n\nfunc willModifyPartition(old, new *mysql.Table) string {\n\tif reflect.DeepEqual(old.Partitions, new.Partitions) {\n\t\treturn \"\"\n\t}\n\tif len(new.Partitions) <= 0 {\n\t\treturn \"\"\n\t}\n\treturn new.Partitions.ToSQL()\n}\n\nfunc willAddIndex(old, new *mysql.Table) []string {\n\tnewIndicesMap := new.Indices.GroupByKeyName()\n\toldIndicesMap := old.Indices.GroupByKeyName()\n\tsqls := []string{}\n\tfor _, keyName := range new.Indices.GetSortedKeys() {\n\t\tif _, ok := oldIndicesMap[keyName]; !ok {\n\t\t\tsqls = append(sqls, newIndicesMap[keyName].ToAddSQL()...)\n\t\t\tcontinue\n\t\t}\n\t\tnewIndices := newIndicesMap[keyName]\n\t\toldIndices := oldIndicesMap[keyName]\n\t\tif reflect.DeepEqual(oldIndices, newIndices) {\n\t\t\tcontinue\n\t\t}\n\t\tsqls = append(sqls, oldIndices.ToDropSQL()...)\n\t\tsqls = append(sqls, newIndices.ToAddSQL()...)\n\t}\n\treturn sqls\n}\n\nfunc willDropIndex(old, new *mysql.Table) []string {\n\tnewIndicesMap := new.Indices.GroupByKeyName()\n\toldIndicesMap := old.Indices.GroupByKeyName()\n\tsqls := []string{}\n\tfor _, keyName := range old.Indices.GetSortedKeys() {\n\t\tif _, ok := newIndicesMap[keyName]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tsqls = append(sqls, oldIndicesMap[keyName].ToDropSQL()...)\n\t}\n\treturn sqls\n}\n<|endoftext|>"} {"text":"\/\/ Built-in functions\npackage builtin\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ncw\/gpython\/py\"\n\t\"github.com\/ncw\/gpython\/vm\"\n)\n\nconst builtin_doc = `Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the 'nil' object; Ellipsis represents '...' in slices.`\n\n\/\/ Initialise the module\nfunc init() {\n\tmethods := []*py.Method{\n\t\tpy.NewMethod(\"__build_class__\", builtin___build_class__, 0, build_class_doc),\n\t\t\/\/ py.NewMethod(\"__import__\", builtin___import__, 0, import_doc),\n\t\tpy.NewMethod(\"abs\", builtin_abs, 0, abs_doc),\n\t\t\/\/ py.NewMethod(\"all\", builtin_all, 0, all_doc),\n\t\t\/\/ py.NewMethod(\"any\", builtin_any, 0, any_doc),\n\t\t\/\/ py.NewMethod(\"ascii\", builtin_ascii, 0, ascii_doc),\n\t\t\/\/ py.NewMethod(\"bin\", builtin_bin, 0, bin_doc),\n\t\t\/\/ py.NewMethod(\"callable\", builtin_callable, 0, callable_doc),\n\t\t\/\/ py.NewMethod(\"chr\", builtin_chr, 0, chr_doc),\n\t\t\/\/ py.NewMethod(\"compile\", builtin_compile, 0, compile_doc),\n\t\t\/\/ py.NewMethod(\"delattr\", builtin_delattr, 0, delattr_doc),\n\t\t\/\/ py.NewMethod(\"dir\", builtin_dir, 0, dir_doc),\n\t\t\/\/ py.NewMethod(\"divmod\", builtin_divmod, 0, divmod_doc),\n\t\t\/\/ py.NewMethod(\"eval\", builtin_eval, 0, eval_doc),\n\t\t\/\/ py.NewMethod(\"exec\", builtin_exec, 0, exec_doc),\n\t\t\/\/ py.NewMethod(\"format\", builtin_format, 0, format_doc),\n\t\t\/\/ py.NewMethod(\"getattr\", builtin_getattr, 0, getattr_doc),\n\t\t\/\/ py.NewMethod(\"globals\", builtin_globals, py.METH_NOARGS, globals_doc),\n\t\t\/\/ py.NewMethod(\"hasattr\", builtin_hasattr, 0, hasattr_doc),\n\t\t\/\/ py.NewMethod(\"hash\", builtin_hash, 0, hash_doc),\n\t\t\/\/ py.NewMethod(\"hex\", builtin_hex, 0, hex_doc),\n\t\t\/\/ py.NewMethod(\"id\", builtin_id, 0, id_doc),\n\t\t\/\/ py.NewMethod(\"input\", builtin_input, 0, input_doc),\n\t\t\/\/ py.NewMethod(\"isinstance\", builtin_isinstance, 0, isinstance_doc),\n\t\t\/\/ py.NewMethod(\"issubclass\", builtin_issubclass, 0, issubclass_doc),\n\t\t\/\/ py.NewMethod(\"iter\", builtin_iter, 0, iter_doc),\n\t\t\/\/ py.NewMethod(\"len\", builtin_len, 0, len_doc),\n\t\t\/\/ py.NewMethod(\"locals\", builtin_locals, py.METH_NOARGS, locals_doc),\n\t\t\/\/ py.NewMethod(\"max\", builtin_max, 0, max_doc),\n\t\t\/\/ py.NewMethod(\"min\", builtin_min, 0, min_doc),\n\t\t\/\/ py.NewMethod(\"next\", builtin_next, 0, next_doc),\n\t\t\/\/ py.NewMethod(\"oct\", builtin_oct, 0, oct_doc),\n\t\t\/\/ py.NewMethod(\"ord\", builtin_ord, 0, ord_doc),\n\t\tpy.NewMethod(\"pow\", builtin_pow, 0, pow_doc),\n\t\tpy.NewMethod(\"print\", builtin_print, 0, print_doc),\n\t\t\/\/ py.NewMethod(\"repr\", builtin_repr, 0, repr_doc),\n\t\tpy.NewMethod(\"round\", builtin_round, 0, round_doc),\n\t\t\/\/ py.NewMethod(\"setattr\", builtin_setattr, 0, setattr_doc),\n\t\t\/\/ py.NewMethod(\"sorted\", builtin_sorted, 0, sorted_doc),\n\t\t\/\/ py.NewMethod(\"sum\", builtin_sum, 0, sum_doc),\n\t\t\/\/ py.NewMethod(\"vars\", builtin_vars, 0, vars_doc),\n\t}\n\tglobals := py.StringDict{\n\t\t\"None\": py.None,\n\t\t\"Ellipsis\": py.Ellipsis,\n\t\t\"NotImplemented\": py.NotImplemented,\n\t\t\"False\": py.False,\n\t\t\"True\": py.True,\n\t\t\"bool\": py.BoolType,\n\t\t\/\/ \"memoryview\": py.MemoryViewType,\n\t\t\/\/ \"bytearray\": py.ByteArrayType,\n\t\t\"bytes\": py.BytesType,\n\t\t\/\/ \"classmethod\": py.ClassMethodType,\n\t\t\"complex\": py.ComplexType,\n\t\t\"dict\": py.StringDictType, \/\/ FIXME\n\t\t\/\/ \"enumerate\": py.EnumType,\n\t\t\/\/ \"filter\": py.FilterType,\n\t\t\"float\": py.FloatType,\n\t\t\"frozenset\": py.FrozenSetType,\n\t\t\/\/ \"property\": py.PropertyType,\n\t\t\"int\": py.IntType, \/\/ FIXME LongType?\n\t\t\"list\": py.ListType,\n\t\t\/\/ \"map\": py.MapType,\n\t\t\/\/ \"object\": py.BaseObjectType,\n\t\t\/\/ \"range\": py.RangeType,\n\t\t\/\/ \"reversed\": py.ReversedType,\n\t\t\"set\": py.SetType,\n\t\t\/\/ \"slice\": py.SliceType,\n\t\t\/\/ \"staticmethod\": py.StaticMethodType,\n\t\t\"str\": py.StringType,\n\t\t\/\/ \"super\": py.SuperType,\n\t\t\"tuple\": py.TupleType,\n\t\t\"type\": py.TypeType,\n\t\t\/\/ \"zip\": py.ZipType,\n\t}\n\tpy.NewModule(\"builtins\", builtin_doc, methods, globals)\n}\n\nconst print_doc = `print(value, ..., sep=' ', end='\\\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream.`\n\nfunc builtin_print(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tfmt.Printf(\"print %v, %v, %v\\n\", self, args, kwargs)\n\treturn py.None\n}\n\nconst pow_doc = `pow(x, y[, z]) -> number\n\nWith two arguments, equivalent to x**y. With three arguments,\nequivalent to (x**y) % z, but may be more efficient (e.g. for ints).`\n\nfunc builtin_pow(self py.Object, args py.Tuple) py.Object {\n\tvar v, w, z py.Object\n\tz = py.None\n\tpy.UnpackTuple(args, \"pow\", 2, 3, &v, &w, &z)\n\treturn py.Pow(v, w, z)\n}\n\nconst abs_doc = `\"abs(number) -> number\n\nReturn the absolute value of the argument.`\n\nfunc builtin_abs(self, v py.Object) py.Object {\n\treturn py.Abs(v)\n}\n\nconst round_doc = `round(number[, ndigits]) -> number\n\nRound a number to a given precision in decimal digits (default 0 digits).\nThis returns an int when called with one argument, otherwise the\nsame type as the number. ndigits may be negative.`\n\nfunc builtin_round(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tvar number, ndigits py.Object\n\tndigits = py.Int(0)\n\t\/\/ var kwlist = []string{\"number\", \"ndigits\"}\n\t\/\/ FIXME py.ParseTupleAndKeywords(args, kwargs, \"O|O:round\", kwlist, &number, &ndigits)\n\tpy.UnpackTuple(args, \"round\", 1, 2, &number, &ndigits)\n\n\tnumberRounder, ok := number.(py.I__round__)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: type %s doesn't define __round__ method\", number.Type().Name))\n\t}\n\n\treturn numberRounder.M__round__(ndigits)\n}\n\nconst build_class_doc = `__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\nInternal helper function used by the class statement.`\n\nfunc builtin___build_class__(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tfmt.Printf(\"__build_class__(self=%#v, args=%#v, kwargs=%#v\\n\", self, args, kwargs)\n\tvar prep, cell, cls py.Object\n\tvar mkw, ns py.StringDict\n\tvar meta, winner *py.Type\n\tvar isclass bool\n\n\tif len(args) < 2 {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build_class__: not enough arguments\"))\n\t}\n\n\t\/\/ Better be callable\n\tfn, ok := args[0].(*py.Function)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build__class__: func must be a function\"))\n\t}\n\n\tname := args[1].(py.String)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build_class__: name is not a string\"))\n\t}\n\tbases := args[2:]\n\n\tif kwargs != nil {\n\t\tmkw = kwargs.Copy() \/\/ Don't modify kwds passed in!\n\t\tmeta := mkw[\"metaclass\"] \/\/ _PyDict_GetItemId(mkw, &PyId_metaclass)\n\t\tif meta != nil {\n\t\t\tdelete(mkw, \"metaclass\")\n\t\t\t\/\/ metaclass is explicitly given, check if it's indeed a class\n\t\t\t_, isclass = meta.(*py.Type)\n\t\t}\n\t}\n\tif meta == nil {\n\t\t\/\/ if there are no bases, use type:\n\t\tif len(bases) == 0 {\n\t\t\tmeta = py.TypeType\n\t\t} else {\n\t\t\t\/\/ else get the type of the first base\n\t\t\tmeta = bases[0].Type()\n\t\t}\n\t\tisclass = true \/\/ meta is really a class\n\t}\n\n\tif isclass {\n\t\t\/\/ meta is really a class, so check for a more derived\n\t\t\/\/ metaclass, or possible metaclass conflicts:\n\t\twinner = meta.CalculateMetaclass(bases)\n\t\tif winner != meta {\n\t\t\tmeta = winner\n\t\t}\n\t}\n\t\/\/ else: meta is not a class, so we cannot do the metaclass\n\t\/\/ calculation, so we will use the explicitly given object as it is\n\tprep = meta.Type().Dict[\"___prepare__\"] \/\/ FIXME should be using _PyObject_GetAttr\n\tif prep == nil {\n\t\tns = py.NewStringDict()\n\t} else {\n\t\tns = py.Call(prep, py.Tuple{name, bases}, mkw).(py.StringDict)\n\t}\n\tfmt.Printf(\"Calling %v with %#v and %#v\\n\", fn.Name, fn.Globals, ns)\n\tcell, err := vm.Run(fn.Globals, ns, fn.Code) \/\/ FIXME PyFunction_GET_CLOSURE(fn))\n\tfmt.Printf(\"result %v %s\\n\", cell, err)\n\tif err != nil {\n\t\t\/\/ FIXME\n\t\tpanic(err)\n\t}\n\tif cell != nil {\n\t\tfmt.Printf(\"Calling %v\\n\", meta)\n\t\tcls = py.Call(meta, py.Tuple{name, bases, ns}, mkw)\n\t\tif c, ok := cell.(*py.Cell); ok {\n\t\t\tc.Set(cls)\n\t\t}\n\t}\n\tfmt.Printf(\"Globals = %v, Locals = %v\\n\", fn.Globals, ns)\n\treturn cls\n}\nFix locals for class constructor call\/\/ Built-in functions\npackage builtin\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ncw\/gpython\/py\"\n\t\"github.com\/ncw\/gpython\/vm\"\n)\n\nconst builtin_doc = `Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the 'nil' object; Ellipsis represents '...' in slices.`\n\n\/\/ Initialise the module\nfunc init() {\n\tmethods := []*py.Method{\n\t\tpy.NewMethod(\"__build_class__\", builtin___build_class__, 0, build_class_doc),\n\t\t\/\/ py.NewMethod(\"__import__\", builtin___import__, 0, import_doc),\n\t\tpy.NewMethod(\"abs\", builtin_abs, 0, abs_doc),\n\t\t\/\/ py.NewMethod(\"all\", builtin_all, 0, all_doc),\n\t\t\/\/ py.NewMethod(\"any\", builtin_any, 0, any_doc),\n\t\t\/\/ py.NewMethod(\"ascii\", builtin_ascii, 0, ascii_doc),\n\t\t\/\/ py.NewMethod(\"bin\", builtin_bin, 0, bin_doc),\n\t\t\/\/ py.NewMethod(\"callable\", builtin_callable, 0, callable_doc),\n\t\t\/\/ py.NewMethod(\"chr\", builtin_chr, 0, chr_doc),\n\t\t\/\/ py.NewMethod(\"compile\", builtin_compile, 0, compile_doc),\n\t\t\/\/ py.NewMethod(\"delattr\", builtin_delattr, 0, delattr_doc),\n\t\t\/\/ py.NewMethod(\"dir\", builtin_dir, 0, dir_doc),\n\t\t\/\/ py.NewMethod(\"divmod\", builtin_divmod, 0, divmod_doc),\n\t\t\/\/ py.NewMethod(\"eval\", builtin_eval, 0, eval_doc),\n\t\t\/\/ py.NewMethod(\"exec\", builtin_exec, 0, exec_doc),\n\t\t\/\/ py.NewMethod(\"format\", builtin_format, 0, format_doc),\n\t\t\/\/ py.NewMethod(\"getattr\", builtin_getattr, 0, getattr_doc),\n\t\t\/\/ py.NewMethod(\"globals\", builtin_globals, py.METH_NOARGS, globals_doc),\n\t\t\/\/ py.NewMethod(\"hasattr\", builtin_hasattr, 0, hasattr_doc),\n\t\t\/\/ py.NewMethod(\"hash\", builtin_hash, 0, hash_doc),\n\t\t\/\/ py.NewMethod(\"hex\", builtin_hex, 0, hex_doc),\n\t\t\/\/ py.NewMethod(\"id\", builtin_id, 0, id_doc),\n\t\t\/\/ py.NewMethod(\"input\", builtin_input, 0, input_doc),\n\t\t\/\/ py.NewMethod(\"isinstance\", builtin_isinstance, 0, isinstance_doc),\n\t\t\/\/ py.NewMethod(\"issubclass\", builtin_issubclass, 0, issubclass_doc),\n\t\t\/\/ py.NewMethod(\"iter\", builtin_iter, 0, iter_doc),\n\t\t\/\/ py.NewMethod(\"len\", builtin_len, 0, len_doc),\n\t\t\/\/ py.NewMethod(\"locals\", builtin_locals, py.METH_NOARGS, locals_doc),\n\t\t\/\/ py.NewMethod(\"max\", builtin_max, 0, max_doc),\n\t\t\/\/ py.NewMethod(\"min\", builtin_min, 0, min_doc),\n\t\t\/\/ py.NewMethod(\"next\", builtin_next, 0, next_doc),\n\t\t\/\/ py.NewMethod(\"oct\", builtin_oct, 0, oct_doc),\n\t\t\/\/ py.NewMethod(\"ord\", builtin_ord, 0, ord_doc),\n\t\tpy.NewMethod(\"pow\", builtin_pow, 0, pow_doc),\n\t\tpy.NewMethod(\"print\", builtin_print, 0, print_doc),\n\t\t\/\/ py.NewMethod(\"repr\", builtin_repr, 0, repr_doc),\n\t\tpy.NewMethod(\"round\", builtin_round, 0, round_doc),\n\t\t\/\/ py.NewMethod(\"setattr\", builtin_setattr, 0, setattr_doc),\n\t\t\/\/ py.NewMethod(\"sorted\", builtin_sorted, 0, sorted_doc),\n\t\t\/\/ py.NewMethod(\"sum\", builtin_sum, 0, sum_doc),\n\t\t\/\/ py.NewMethod(\"vars\", builtin_vars, 0, vars_doc),\n\t}\n\tglobals := py.StringDict{\n\t\t\"None\": py.None,\n\t\t\"Ellipsis\": py.Ellipsis,\n\t\t\"NotImplemented\": py.NotImplemented,\n\t\t\"False\": py.False,\n\t\t\"True\": py.True,\n\t\t\"bool\": py.BoolType,\n\t\t\/\/ \"memoryview\": py.MemoryViewType,\n\t\t\/\/ \"bytearray\": py.ByteArrayType,\n\t\t\"bytes\": py.BytesType,\n\t\t\/\/ \"classmethod\": py.ClassMethodType,\n\t\t\"complex\": py.ComplexType,\n\t\t\"dict\": py.StringDictType, \/\/ FIXME\n\t\t\/\/ \"enumerate\": py.EnumType,\n\t\t\/\/ \"filter\": py.FilterType,\n\t\t\"float\": py.FloatType,\n\t\t\"frozenset\": py.FrozenSetType,\n\t\t\/\/ \"property\": py.PropertyType,\n\t\t\"int\": py.IntType, \/\/ FIXME LongType?\n\t\t\"list\": py.ListType,\n\t\t\/\/ \"map\": py.MapType,\n\t\t\/\/ \"object\": py.BaseObjectType,\n\t\t\/\/ \"range\": py.RangeType,\n\t\t\/\/ \"reversed\": py.ReversedType,\n\t\t\"set\": py.SetType,\n\t\t\/\/ \"slice\": py.SliceType,\n\t\t\/\/ \"staticmethod\": py.StaticMethodType,\n\t\t\"str\": py.StringType,\n\t\t\/\/ \"super\": py.SuperType,\n\t\t\"tuple\": py.TupleType,\n\t\t\"type\": py.TypeType,\n\t\t\/\/ \"zip\": py.ZipType,\n\t}\n\tpy.NewModule(\"builtins\", builtin_doc, methods, globals)\n}\n\nconst print_doc = `print(value, ..., sep=' ', end='\\\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream.`\n\nfunc builtin_print(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tfmt.Printf(\"print %v, %v, %v\\n\", self, args, kwargs)\n\treturn py.None\n}\n\nconst pow_doc = `pow(x, y[, z]) -> number\n\nWith two arguments, equivalent to x**y. With three arguments,\nequivalent to (x**y) % z, but may be more efficient (e.g. for ints).`\n\nfunc builtin_pow(self py.Object, args py.Tuple) py.Object {\n\tvar v, w, z py.Object\n\tz = py.None\n\tpy.UnpackTuple(args, \"pow\", 2, 3, &v, &w, &z)\n\treturn py.Pow(v, w, z)\n}\n\nconst abs_doc = `\"abs(number) -> number\n\nReturn the absolute value of the argument.`\n\nfunc builtin_abs(self, v py.Object) py.Object {\n\treturn py.Abs(v)\n}\n\nconst round_doc = `round(number[, ndigits]) -> number\n\nRound a number to a given precision in decimal digits (default 0 digits).\nThis returns an int when called with one argument, otherwise the\nsame type as the number. ndigits may be negative.`\n\nfunc builtin_round(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tvar number, ndigits py.Object\n\tndigits = py.Int(0)\n\t\/\/ var kwlist = []string{\"number\", \"ndigits\"}\n\t\/\/ FIXME py.ParseTupleAndKeywords(args, kwargs, \"O|O:round\", kwlist, &number, &ndigits)\n\tpy.UnpackTuple(args, \"round\", 1, 2, &number, &ndigits)\n\n\tnumberRounder, ok := number.(py.I__round__)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: type %s doesn't define __round__ method\", number.Type().Name))\n\t}\n\n\treturn numberRounder.M__round__(ndigits)\n}\n\nconst build_class_doc = `__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\nInternal helper function used by the class statement.`\n\nfunc builtin___build_class__(self py.Object, args py.Tuple, kwargs py.StringDict) py.Object {\n\tfmt.Printf(\"__build_class__(self=%#v, args=%#v, kwargs=%#v\\n\", self, args, kwargs)\n\tvar prep, cell, cls py.Object\n\tvar mkw, ns py.StringDict\n\tvar meta, winner *py.Type\n\tvar isclass bool\n\n\tif len(args) < 2 {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build_class__: not enough arguments\"))\n\t}\n\n\t\/\/ Better be callable\n\tfn, ok := args[0].(*py.Function)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build__class__: func must be a function\"))\n\t}\n\n\tname := args[1].(py.String)\n\tif !ok {\n\t\t\/\/ FIXME TypeError\n\t\tpanic(fmt.Sprintf(\"TypeError: __build_class__: name is not a string\"))\n\t}\n\tbases := args[2:]\n\n\tif kwargs != nil {\n\t\tmkw = kwargs.Copy() \/\/ Don't modify kwds passed in!\n\t\tmeta := mkw[\"metaclass\"] \/\/ _PyDict_GetItemId(mkw, &PyId_metaclass)\n\t\tif meta != nil {\n\t\t\tdelete(mkw, \"metaclass\")\n\t\t\t\/\/ metaclass is explicitly given, check if it's indeed a class\n\t\t\t_, isclass = meta.(*py.Type)\n\t\t}\n\t}\n\tif meta == nil {\n\t\t\/\/ if there are no bases, use type:\n\t\tif len(bases) == 0 {\n\t\t\tmeta = py.TypeType\n\t\t} else {\n\t\t\t\/\/ else get the type of the first base\n\t\t\tmeta = bases[0].Type()\n\t\t}\n\t\tisclass = true \/\/ meta is really a class\n\t}\n\n\tif isclass {\n\t\t\/\/ meta is really a class, so check for a more derived\n\t\t\/\/ metaclass, or possible metaclass conflicts:\n\t\twinner = meta.CalculateMetaclass(bases)\n\t\tif winner != meta {\n\t\t\tmeta = winner\n\t\t}\n\t}\n\t\/\/ else: meta is not a class, so we cannot do the metaclass\n\t\/\/ calculation, so we will use the explicitly given object as it is\n\tprep = meta.Type().Dict[\"___prepare__\"] \/\/ FIXME should be using _PyObject_GetAttr\n\tif prep == nil {\n\t\tns = py.NewStringDict()\n\t} else {\n\t\tns = py.Call(prep, py.Tuple{name, bases}, mkw).(py.StringDict)\n\t}\n\t\/\/ fmt.Printf(\"Calling %v with %p and %p\\n\", fn.Name, fn.Globals, ns)\n\t\/\/ fmt.Printf(\"Code = %#v\\n\", fn.Code)\n\tlocals := fn.LocalsForCall(py.Tuple{ns})\n\tcell, err := vm.Run(fn.Globals, locals, fn.Code) \/\/ FIXME PyFunction_GET_CLOSURE(fn))\n\n\t\/\/ fmt.Printf(\"result = %#v err = %s\\n\", cell, err)\n\t\/\/ fmt.Printf(\"locals = %#v\\n\", locals)\n\t\/\/ fmt.Printf(\"ns = %#v\\n\", ns)\n\tif err != nil {\n\t\t\/\/ FIXME\n\t\tpanic(err)\n\t}\n\tif cell != nil {\n\t\tfmt.Printf(\"Calling %v\\n\", meta)\n\t\tcls = py.Call(meta, py.Tuple{name, bases, ns}, mkw)\n\t\tif c, ok := cell.(*py.Cell); ok {\n\t\t\tc.Set(cls)\n\t\t}\n\t}\n\tfmt.Printf(\"Globals = %v, Locals = %v\\n\", fn.Globals, ns)\n\treturn cls\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"path\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/gogo\/protobuf\/types\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pfs\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pps\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/backoff\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/hashtree\"\n\tworkerpkg \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/worker\"\n\n\tetcd \"github.com\/coreos\/etcd\/clientv3\"\n\t\"github.com\/coreos\/etcd\/clientv3\/mirror\"\n\t\"go.pedge.io\/lion\/proto\"\n\t\"google.golang.org\/grpc\"\n)\n\nconst (\n\tworkerEtcdPrefix = \"workers\"\n)\n\n\/\/ An input\/output pair for a single datum. When a worker has finished\n\/\/ processing 'data', it writes the resulting hashtree to 'resp' (each job has\n\/\/ its own response channel)\ntype datumAndResp struct {\n\tjobID string \/\/ This is passed to workers, so they can annotate their logs\n\tdatum []*pfs.FileInfo\n\trespCh chan hashtree.HashTree\n\terrCh chan struct{}\n\tretCh chan *datumAndResp\n\tretries int\n}\n\n\/\/ WorkerPool represents a pool of workers that can be used to process datums.\ntype WorkerPool interface {\n\tDataCh() chan *datumAndResp\n}\n\ntype worker struct {\n\tctx context.Context\n\tcancel func()\n\taddr string\n\tworkerClient workerpkg.WorkerClient\n\tpachClient *client.APIClient\n\tretries int\n}\n\nfunc (w *worker) run(dataCh chan *datumAndResp) {\n\tdefer func() {\n\t\tprotolion.Infof(\"goro for worker %s is exiting\", w.addr)\n\t}()\n\treturnDatum := func(dr *datumAndResp) {\n\t\tdr.retries++\n\t\tselect {\n\t\tcase dr.retCh <- dr:\n\t\tcase <-w.ctx.Done():\n\t\t}\n\t}\n\tfor {\n\t\tvar dr *datumAndResp\n\t\tselect {\n\t\tcase dr = <-dataCh:\n\t\tcase <-w.ctx.Done():\n\t\t\treturn\n\t\t}\n\t\tif dr.retries > w.retries {\n\t\t\tclose(dr.errCh)\n\t\t\tcontinue\n\t\t}\n\t\tresp, err := w.workerClient.Process(w.ctx, &workerpkg.ProcessRequest{\n\t\t\tJobID: dr.jobID,\n\t\t\tData: dr.datum,\n\t\t})\n\t\tif err != nil || resp.Failed {\n\t\t\tprotolion.Errorf(\"worker %s failed to process datum %v with error %s\", w.addr, dr.datum, err)\n\t\t\treturnDatum(dr)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.Tag != nil {\n\t\t\tvar buffer bytes.Buffer\n\t\t\tif err := w.pachClient.GetTag(resp.Tag.Name, &buffer); err != nil {\n\t\t\t\tprotolion.Errorf(\"failed to retrieve hashtree after worker %s has ostensibly processed the datum %v: %v\", w.addr, dr.datum, err)\n\t\t\t\treturnDatum(dr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttree, err := hashtree.Deserialize(buffer.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tprotolion.Errorf(\"failed to serialize hashtree after worker %s has ostensibly processed the datum %v; this is likely a bug: %v\", w.addr, dr.datum, err)\n\t\t\t\treturnDatum(dr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdr.respCh <- tree\n\t\t} else {\n\t\t\tprotolion.Errorf(\"unrecognized response from worker %s when processing datum %v; this is likely a bug\", w.addr, dr.datum)\n\t\t\treturnDatum(dr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\ntype workerPool struct {\n\t\/\/ Worker pool recieves work via this channel\n\tdataCh chan *datumAndResp\n\t\/\/ Parent of all worker contexts (see workersMap)\n\tctx context.Context\n\t\/\/ The prefix in etcd where new workers can be discovered\n\tworkerDir string\n\t\/\/ Map of worker address to workers\n\tworkersMap map[string]*worker\n\t\/\/ RWMutex to protect workersMap\n\tworkersMapMu sync.RWMutex\n\t\/\/ Used to check for workers added\/deleted in etcd\n\tetcdClient *etcd.Client\n\t\/\/ The number of times to retry failures\n\tretries int\n}\n\nfunc (w *workerPool) discoverWorkers(ctx context.Context) {\n\tb := backoff.NewInfiniteBackOff()\n\tif err := backoff.RetryNotify(func() error {\n\t\tsyncer := mirror.NewSyncer(w.etcdClient, w.workerDir, 0)\n\t\trespCh, errCh := syncer.SyncBase(ctx)\n\tgetBaseWorkers:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase resp, ok := <-respCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tif err := <-errCh; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tbreak getBaseWorkers\n\t\t\t\t}\n\t\t\t\tfor _, kv := range resp.Kvs {\n\t\t\t\t\taddr := path.Base(string(kv.Key))\n\t\t\t\t\tif err := w.addWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err := <-errCh:\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twatchCh := syncer.SyncUpdates(ctx)\n\t\tprotolion.Infof(\"watching `%s` for workers\", w.workerDir)\n\t\tfor {\n\t\t\tresp, ok := <-watchCh\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"watcher for prefix %s closed for unknown reasons\", w.workerDir)\n\t\t\t}\n\t\t\tif err := resp.Err(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, event := range resp.Events {\n\t\t\t\taddr := path.Base(string(event.Kv.Key))\n\t\t\t\tswitch event.Type {\n\t\t\t\tcase etcd.EventTypePut:\n\t\t\t\t\tif err := w.addWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase etcd.EventTypeDelete:\n\t\t\t\t\tif err := w.delWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpanic(\"unreachable\")\n\t}, b, func(err error, d time.Duration) error {\n\t\tif err == context.Canceled {\n\t\t\treturn err\n\t\t}\n\t\tprotolion.Errorf(\"error discovering workers: %v; retrying in %v\", err, d)\n\t\treturn nil\n\t}); err != context.Canceled {\n\t\tpanic(fmt.Sprintf(\"the retry loop should not exit with a non-context-cancelled error: %v\", err))\n\t}\n}\n\nfunc (w *workerPool) addWorker(addr string) error {\n\tw.workersMapMu.RLock()\n\tif worker, ok := w.workersMap[addr]; ok {\n\t\tworker.cancel()\n\t}\n\tw.workersMapMu.RUnlock()\n\n\tconn, err := grpc.Dial(fmt.Sprintf(\"%s:%d\", addr, client.PPSWorkerPort), grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))\n\tif err != nil {\n\t\treturn err\n\t}\n\tchildCtx, cancelFn := context.WithCancel(w.ctx)\n\n\tpachClient, err := client.NewInCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twr := &worker{\n\t\tctx: childCtx,\n\t\tcancel: cancelFn,\n\t\taddr: addr,\n\t\tworkerClient: workerpkg.NewWorkerClient(conn),\n\t\tpachClient: pachClient,\n\t\tretries: w.retries,\n\t}\n\tw.workersMapMu.Lock()\n\tw.workersMap[addr] = wr\n\tw.workersMapMu.Unlock()\n\tprotolion.Infof(\"launching new worker at %v\", addr)\n\tgo wr.run(w.dataCh)\n\treturn nil\n}\n\nfunc (w *workerPool) delWorker(addr string) error {\n\tw.workersMapMu.RLock()\n\tdefer w.workersMapMu.RUnlock()\n\tworker, ok := w.workersMap[addr]\n\tif !ok {\n\t\treturn fmt.Errorf(\"deleting worker %s which is not in worker pool\", addr)\n\t}\n\tworker.cancel()\n\treturn nil\n}\n\nfunc (w *workerPool) DataCh() chan *datumAndResp {\n\treturn w.dataCh\n}\n\nfunc status(ctx context.Context, id string, etcdClient *etcd.Client, etcdPrefix string) ([]*pps.WorkerStatus, error) {\n\tworkerClients, err := workerClients(ctx, id, etcdClient, etcdPrefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result []*pps.WorkerStatus\n\tfor _, workerClient := range workerClients {\n\t\tstatus, err := workerClient.Status(ctx, &types.Empty{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, status)\n\t}\n\treturn result, nil\n}\n\nfunc cancel(ctx context.Context, id string, etcdClient *etcd.Client,\n\tetcdPrefix string, jobID string, dataFilter []string) error {\n\tworkerClients, err := workerClients(ctx, id, etcdClient, etcdPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, workerClient := range workerClients {\n\t\tstatus, err := workerClient.Status(ctx, &types.Empty{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif jobID == status.JobID && workerpkg.MatchDatum(dataFilter, status.Data) {\n\t\t\t_, err := workerClient.Cancel(ctx, &workerpkg.CancelRequest{\n\t\t\t\tDataFilters: dataFilter,\n\t\t\t})\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ workerPool fetches the worker pool associated with 'id', or creates one if\n\/\/ none exists.\nfunc (a *apiServer) workerPool(ctx context.Context, id string, retries int) WorkerPool {\n\ta.workerPoolsLock.Lock()\n\tdefer a.workerPoolsLock.Unlock()\n\tworkerPool, ok := a.workerPools[id]\n\tif !ok {\n\t\tworkerPool = a.newWorkerPool(ctx, id, retries)\n\t\ta.workerPools[id] = workerPool\n\t}\n\treturn workerPool\n}\n\n\/\/ newWorkerPool generates a new worker pool for the job or pipeline identified\n\/\/ with 'id'. Each 'id' used to create a new worker pool must correspond to\n\/\/ a unique binary (in other words, all workers in the worker pool for 'id'\n\/\/ will be running the same user binary)\nfunc (a *apiServer) newWorkerPool(ctx context.Context, id string, retries int) WorkerPool {\n\twp := &workerPool{\n\t\tctx: ctx,\n\t\tdataCh: make(chan *datumAndResp),\n\t\tworkerDir: path.Join(a.etcdPrefix, workerEtcdPrefix, id),\n\t\tworkersMap: make(map[string]*worker),\n\t\tetcdClient: a.etcdClient,\n\t\tretries: retries,\n\t}\n\t\/\/ We need to make sure that the prefix ends with the trailing slash,\n\t\/\/ because\n\tif wp.workerDir[len(wp.workerDir)-1] != '\/' {\n\t\twp.workerDir += \"\/\"\n\t}\n\n\tgo wp.discoverWorkers(ctx)\n\treturn wp\n}\n\nfunc (a *apiServer) delWorkerPool(id string) {\n\ta.workerPoolsLock.Lock()\n\tdefer a.workerPoolsLock.Unlock()\n\tdelete(a.workerPools, id)\n}\n\nfunc workerClients(ctx context.Context, id string, etcdClient *etcd.Client, etcdPrefix string) ([]workerpkg.WorkerClient, error) {\n\tresp, err := etcdClient.Get(ctx, path.Join(etcdPrefix, workerEtcdPrefix, id), etcd.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []workerpkg.WorkerClient\n\tfor _, kv := range resp.Kvs {\n\t\tconn, err := grpc.Dial(fmt.Sprintf(\"%s:%d\", string(kv.Key), client.PPSWorkerPort), grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, workerpkg.NewWorkerClient(conn))\n\t}\n\treturn result, nil\n}\nRemove unneeded mutex.package server\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/gogo\/protobuf\/types\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pfs\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pps\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/backoff\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/hashtree\"\n\tworkerpkg \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/worker\"\n\n\tetcd \"github.com\/coreos\/etcd\/clientv3\"\n\t\"github.com\/coreos\/etcd\/clientv3\/mirror\"\n\t\"go.pedge.io\/lion\/proto\"\n\t\"google.golang.org\/grpc\"\n)\n\nconst (\n\tworkerEtcdPrefix = \"workers\"\n)\n\n\/\/ An input\/output pair for a single datum. When a worker has finished\n\/\/ processing 'data', it writes the resulting hashtree to 'resp' (each job has\n\/\/ its own response channel)\ntype datumAndResp struct {\n\tjobID string \/\/ This is passed to workers, so they can annotate their logs\n\tdatum []*pfs.FileInfo\n\trespCh chan hashtree.HashTree\n\terrCh chan struct{}\n\tretCh chan *datumAndResp\n\tretries int\n}\n\n\/\/ WorkerPool represents a pool of workers that can be used to process datums.\ntype WorkerPool interface {\n\tDataCh() chan *datumAndResp\n}\n\ntype worker struct {\n\tctx context.Context\n\tcancel func()\n\taddr string\n\tworkerClient workerpkg.WorkerClient\n\tpachClient *client.APIClient\n\tretries int\n}\n\nfunc (w *worker) run(dataCh chan *datumAndResp) {\n\tdefer func() {\n\t\tprotolion.Infof(\"goro for worker %s is exiting\", w.addr)\n\t}()\n\treturnDatum := func(dr *datumAndResp) {\n\t\tdr.retries++\n\t\tselect {\n\t\tcase dr.retCh <- dr:\n\t\tcase <-w.ctx.Done():\n\t\t}\n\t}\n\tfor {\n\t\tvar dr *datumAndResp\n\t\tselect {\n\t\tcase dr = <-dataCh:\n\t\tcase <-w.ctx.Done():\n\t\t\treturn\n\t\t}\n\t\tif dr.retries > w.retries {\n\t\t\tclose(dr.errCh)\n\t\t\tcontinue\n\t\t}\n\t\tresp, err := w.workerClient.Process(w.ctx, &workerpkg.ProcessRequest{\n\t\t\tJobID: dr.jobID,\n\t\t\tData: dr.datum,\n\t\t})\n\t\tif err != nil || resp.Failed {\n\t\t\tprotolion.Errorf(\"worker %s failed to process datum %v with error %s\", w.addr, dr.datum, err)\n\t\t\treturnDatum(dr)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.Tag != nil {\n\t\t\tvar buffer bytes.Buffer\n\t\t\tif err := w.pachClient.GetTag(resp.Tag.Name, &buffer); err != nil {\n\t\t\t\tprotolion.Errorf(\"failed to retrieve hashtree after worker %s has ostensibly processed the datum %v: %v\", w.addr, dr.datum, err)\n\t\t\t\treturnDatum(dr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttree, err := hashtree.Deserialize(buffer.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tprotolion.Errorf(\"failed to serialize hashtree after worker %s has ostensibly processed the datum %v; this is likely a bug: %v\", w.addr, dr.datum, err)\n\t\t\t\treturnDatum(dr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdr.respCh <- tree\n\t\t} else {\n\t\t\tprotolion.Errorf(\"unrecognized response from worker %s when processing datum %v; this is likely a bug\", w.addr, dr.datum)\n\t\t\treturnDatum(dr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\ntype workerPool struct {\n\t\/\/ Worker pool recieves work via this channel\n\tdataCh chan *datumAndResp\n\t\/\/ Parent of all worker contexts (see workersMap)\n\tctx context.Context\n\t\/\/ The prefix in etcd where new workers can be discovered\n\tworkerDir string\n\t\/\/ Map of worker address to workers\n\tworkersMap map[string]*worker\n\t\/\/ Used to check for workers added\/deleted in etcd\n\tetcdClient *etcd.Client\n\t\/\/ The number of times to retry failures\n\tretries int\n}\n\nfunc (w *workerPool) discoverWorkers(ctx context.Context) {\n\tb := backoff.NewInfiniteBackOff()\n\tif err := backoff.RetryNotify(func() error {\n\t\tsyncer := mirror.NewSyncer(w.etcdClient, w.workerDir, 0)\n\t\trespCh, errCh := syncer.SyncBase(ctx)\n\tgetBaseWorkers:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase resp, ok := <-respCh:\n\t\t\t\tif !ok {\n\t\t\t\t\tif err := <-errCh; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tbreak getBaseWorkers\n\t\t\t\t}\n\t\t\t\tfor _, kv := range resp.Kvs {\n\t\t\t\t\taddr := path.Base(string(kv.Key))\n\t\t\t\t\tif err := w.addWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err := <-errCh:\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twatchCh := syncer.SyncUpdates(ctx)\n\t\tprotolion.Infof(\"watching `%s` for workers\", w.workerDir)\n\t\tfor {\n\t\t\tresp, ok := <-watchCh\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"watcher for prefix %s closed for unknown reasons\", w.workerDir)\n\t\t\t}\n\t\t\tif err := resp.Err(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, event := range resp.Events {\n\t\t\t\taddr := path.Base(string(event.Kv.Key))\n\t\t\t\tswitch event.Type {\n\t\t\t\tcase etcd.EventTypePut:\n\t\t\t\t\tif err := w.addWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase etcd.EventTypeDelete:\n\t\t\t\t\tif err := w.delWorker(addr); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpanic(\"unreachable\")\n\t}, b, func(err error, d time.Duration) error {\n\t\tif err == context.Canceled {\n\t\t\treturn err\n\t\t}\n\t\tprotolion.Errorf(\"error discovering workers: %v; retrying in %v\", err, d)\n\t\treturn nil\n\t}); err != context.Canceled {\n\t\tpanic(fmt.Sprintf(\"the retry loop should not exit with a non-context-cancelled error: %v\", err))\n\t}\n}\n\nfunc (w *workerPool) addWorker(addr string) error {\n\tif worker, ok := w.workersMap[addr]; ok {\n\t\tworker.cancel()\n\t}\n\n\tconn, err := grpc.Dial(fmt.Sprintf(\"%s:%d\", addr, client.PPSWorkerPort), grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))\n\tif err != nil {\n\t\treturn err\n\t}\n\tchildCtx, cancelFn := context.WithCancel(w.ctx)\n\n\tpachClient, err := client.NewInCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twr := &worker{\n\t\tctx: childCtx,\n\t\tcancel: cancelFn,\n\t\taddr: addr,\n\t\tworkerClient: workerpkg.NewWorkerClient(conn),\n\t\tpachClient: pachClient,\n\t\tretries: w.retries,\n\t}\n\tw.workersMap[addr] = wr\n\tprotolion.Infof(\"launching new worker at %v\", addr)\n\tgo wr.run(w.dataCh)\n\treturn nil\n}\n\nfunc (w *workerPool) delWorker(addr string) error {\n\tworker, ok := w.workersMap[addr]\n\tif !ok {\n\t\treturn fmt.Errorf(\"deleting worker %s which is not in worker pool\", addr)\n\t}\n\tworker.cancel()\n\treturn nil\n}\n\nfunc (w *workerPool) DataCh() chan *datumAndResp {\n\treturn w.dataCh\n}\n\nfunc status(ctx context.Context, id string, etcdClient *etcd.Client, etcdPrefix string) ([]*pps.WorkerStatus, error) {\n\tworkerClients, err := workerClients(ctx, id, etcdClient, etcdPrefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result []*pps.WorkerStatus\n\tfor _, workerClient := range workerClients {\n\t\tstatus, err := workerClient.Status(ctx, &types.Empty{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, status)\n\t}\n\treturn result, nil\n}\n\nfunc cancel(ctx context.Context, id string, etcdClient *etcd.Client,\n\tetcdPrefix string, jobID string, dataFilter []string) error {\n\tworkerClients, err := workerClients(ctx, id, etcdClient, etcdPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, workerClient := range workerClients {\n\t\tstatus, err := workerClient.Status(ctx, &types.Empty{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif jobID == status.JobID && workerpkg.MatchDatum(dataFilter, status.Data) {\n\t\t\t_, err := workerClient.Cancel(ctx, &workerpkg.CancelRequest{\n\t\t\t\tDataFilters: dataFilter,\n\t\t\t})\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ workerPool fetches the worker pool associated with 'id', or creates one if\n\/\/ none exists.\nfunc (a *apiServer) workerPool(ctx context.Context, id string, retries int) WorkerPool {\n\ta.workerPoolsLock.Lock()\n\tdefer a.workerPoolsLock.Unlock()\n\tworkerPool, ok := a.workerPools[id]\n\tif !ok {\n\t\tworkerPool = a.newWorkerPool(ctx, id, retries)\n\t\ta.workerPools[id] = workerPool\n\t}\n\treturn workerPool\n}\n\n\/\/ newWorkerPool generates a new worker pool for the job or pipeline identified\n\/\/ with 'id'. Each 'id' used to create a new worker pool must correspond to\n\/\/ a unique binary (in other words, all workers in the worker pool for 'id'\n\/\/ will be running the same user binary)\nfunc (a *apiServer) newWorkerPool(ctx context.Context, id string, retries int) WorkerPool {\n\twp := &workerPool{\n\t\tctx: ctx,\n\t\tdataCh: make(chan *datumAndResp),\n\t\tworkerDir: path.Join(a.etcdPrefix, workerEtcdPrefix, id),\n\t\tworkersMap: make(map[string]*worker),\n\t\tetcdClient: a.etcdClient,\n\t\tretries: retries,\n\t}\n\t\/\/ We need to make sure that the prefix ends with the trailing slash,\n\t\/\/ because\n\tif wp.workerDir[len(wp.workerDir)-1] != '\/' {\n\t\twp.workerDir += \"\/\"\n\t}\n\n\tgo wp.discoverWorkers(ctx)\n\treturn wp\n}\n\nfunc (a *apiServer) delWorkerPool(id string) {\n\ta.workerPoolsLock.Lock()\n\tdefer a.workerPoolsLock.Unlock()\n\tdelete(a.workerPools, id)\n}\n\nfunc workerClients(ctx context.Context, id string, etcdClient *etcd.Client, etcdPrefix string) ([]workerpkg.WorkerClient, error) {\n\tresp, err := etcdClient.Get(ctx, path.Join(etcdPrefix, workerEtcdPrefix, id), etcd.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []workerpkg.WorkerClient\n\tfor _, kv := range resp.Kvs {\n\t\tconn, err := grpc.Dial(fmt.Sprintf(\"%s:%d\", string(kv.Key), client.PPSWorkerPort), grpc.WithInsecure(), grpc.WithTimeout(5*time.Second))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, workerpkg.NewWorkerClient(conn))\n\t}\n\treturn result, nil\n}\n<|endoftext|>"} {"text":"package gannoy\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com\/gansidui\/priority_queue\"\n)\n\ntype GannoyIndex struct {\n\tmeta meta\n\tmaps Maps\n\ttree int\n\tdim int\n\tdistance Distance\n\trandom Random\n\tnodes Nodes\n\tK int\n\tbuildChan chan buildArgs\n}\n\nfunc NewGannoyIndex(metaFile string, distance Distance, random Random) (GannoyIndex, error) {\n\n\tmeta, err := loadMeta(metaFile)\n\tif err != nil {\n\t\treturn GannoyIndex{}, err\n\t}\n\ttree := meta.tree\n\tdim := meta.dim\n\n\tann := meta.treePath()\n\tmaps := meta.mapPath()\n\n\t\/\/ K := 3\n\tK := 50\n\tgannoy := GannoyIndex{\n\t\tmeta: meta,\n\t\tmaps: newMaps(maps),\n\t\ttree: tree,\n\t\tdim: dim,\n\t\tdistance: distance,\n\t\trandom: random,\n\t\tK: K,\n\t\tnodes: newNodes(ann, tree, dim, K),\n\t\tbuildChan: make(chan buildArgs, 1),\n\t}\n\tgo gannoy.builder()\n\treturn gannoy, nil\n}\n\nfunc (g GannoyIndex) Tree() {\n\tfor i, root := range g.meta.roots() {\n\t\tg.walk(i, g.nodes.getNode(root), root, 0)\n\t}\n}\n\nfunc (g *GannoyIndex) AddItem(id int, w []float64) error {\n\targs := buildArgs{action: ADD, id: id, w: w, result: make(chan error)}\n\tg.buildChan <- args\n\treturn <-args.result\n}\n\nfunc (g *GannoyIndex) RemoveItem(id int) error {\n\targs := buildArgs{action: DELETE, id: id, result: make(chan error)}\n\tg.buildChan <- args\n\treturn <-args.result\n}\n\nfunc (g GannoyIndex) GetNnsByItem(id, n, searchK int) []int {\n\tm := g.nodes.getNode(g.maps.getIndex(id))\n\tif !m.isLeaf() {\n\t\treturn []int{}\n\t}\n\tindices := g.getAllNns(m.v, n, searchK)\n\tids := make([]int, len(indices))\n\tfor i, index := range indices {\n\t\tids[i] = g.maps.getId(index)\n\t}\n\treturn ids\n}\n\nfunc (g GannoyIndex) getAllNns(v []float64, n, searchK int) []int {\n\tif searchK == -1 {\n\t\tsearchK = n * g.tree\n\t}\n\n\tq := priority_queue.New()\n\tfor _, root := range g.meta.roots() {\n\t\tq.Push(&Queue{priority: math.Inf(1), value: root})\n\t}\n\n\tnns := []int{}\n\tfor len(nns) < searchK && q.Len() > 0 {\n\t\ttop := q.Top().(*Queue)\n\t\td := top.priority\n\t\ti := top.value\n\n\t\tnd := g.nodes.getNode(i)\n\t\tq.Pop()\n\t\tif nd.isLeaf() {\n\t\t\tnns = append(nns, i)\n\t\t} else if nd.nDescendants <= g.K {\n\t\t\tdst := nd.children\n\t\t\tnns = append(nns, dst...)\n\t\t} else {\n\t\t\tmargin := g.distance.margin(nd, v, g.dim)\n\t\t\tq.Push(&Queue{priority: math.Min(d, +margin), value: nd.children[1]})\n\t\t\tq.Push(&Queue{priority: math.Min(d, -margin), value: nd.children[0]})\n\t\t}\n\t}\n\n\tsort.Ints(nns)\n\tnnsDist := []Dist{}\n\tlast := -1\n\tfor _, j := range nns {\n\t\tif j == last {\n\t\t\tcontinue\n\t\t}\n\t\tlast = j\n\t\tnnsDist = append(nnsDist, Dist{distance: g.distance.distance(v, g.nodes.getNode(j).v, g.dim), item: j})\n\t}\n\n\tm := len(nnsDist)\n\tp := m\n\tif n < m {\n\t\tp = n\n\t}\n\n\tresult := []int{}\n\tsort.Slice(nnsDist, func(i, j int) bool {\n\t\treturn nnsDist[i].distance < nnsDist[j].distance\n\t})\n\tfor i := 0; i < p; i++ {\n\t\tresult = append(result, nnsDist[i].item)\n\t}\n\n\treturn result\n}\n\nfunc (g *GannoyIndex) addItem(id int, w []float64) error {\n\tn := g.nodes.newNode()\n\tn.v = w\n\tn.parents = make([]int, g.tree)\n\terr := n.save()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ fmt.Printf(\"id %d\\n\", n.id)\n\n\tvar wg sync.WaitGroup\n\twg.Add(g.tree)\n\tbuildChan := make(chan int, g.tree)\n\tworker := func(n Node) {\n\t\tfor index := range buildChan {\n\t\t\t\/\/ fmt.Printf(\"root: %d\\n\", g.meta.roots()[index])\n\t\t\tg.build(index, g.meta.roots()[index], n)\n\t\t\twg.Done()\n\t\t}\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\tgo worker(n)\n\t}\n\n\tfor index, _ := range g.meta.roots() {\n\t\tbuildChan <- index\n\t}\n\n\twg.Wait()\n\tclose(buildChan)\n\tg.maps.add(n.id, id)\n\n\treturn nil\n}\n\nfunc (g *GannoyIndex) build(index, root int, n Node) {\n\tif root == -1 {\n\t\t\/\/ 最初のノード\n\t\tn.parents[index] = -1\n\t\tn.save()\n\t\tg.meta.updateRoot(index, n.id)\n\t\treturn\n\t}\n\titem := g.findBranchByVector(root, n.v)\n\tfound := g.nodes.getNode(item)\n\t\/\/ fmt.Printf(\"Found %d\\n\", item)\n\n\torg_parent := found.parents[index]\n\tif found.isBucket() && len(found.children) < g.K {\n\t\t\/\/ ノードに余裕があれば追加\n\t\t\/\/ fmt.Printf(\"pattern bucket\\n\")\n\t\tn.updateParents(index, item)\n\t\tfound.nDescendants++\n\t\tfound.children = append(found.children, n.id)\n\t\tfound.save()\n\t} else {\n\t\t\/\/ ノードが上限またはリーフノードであれば新しいノードを追加\n\t\twillDelete := false\n\t\tvar indices []int\n\t\tif found.isLeaf() {\n\t\t\t\/\/ fmt.Printf(\"pattern leaf node\\n\")\n\t\t\tindices = []int{item, n.id}\n\t\t} else {\n\t\t\t\/\/ fmt.Printf(\"pattern full backet\\n\")\n\t\t\tindices = append(found.children, n.id)\n\t\t\twillDelete = true\n\t\t}\n\n\t\tm := g.makeTree(index, org_parent, indices)\n\t\t\/\/ fmt.Printf(\"m: %d, org_parent: %d\\n\", m, org_parent)\n\t\tif org_parent == -1 {\n\t\t\t\/\/ rootノードの入れ替え\n\t\t\tg.meta.updateRoot(index, m)\n\t\t} else {\n\t\t\tparent := g.nodes.getNode(org_parent)\n\t\t\tparent.nDescendants++\n\t\t\tchildren := make([]int, len(parent.children))\n\t\t\tfor i, child := range parent.children {\n\t\t\t\tif child == item {\n\t\t\t\t\t\/\/ 新しいノードに変更\n\t\t\t\t\tchildren[i] = m\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ 既存のノードのまま\n\t\t\t\t\tchildren[i] = child\n\t\t\t\t}\n\t\t\t}\n\t\t\tparent.children = children\n\t\t\tparent.save()\n\n\t\t}\n\t\tif willDelete {\n\t\t\tfound.destroy()\n\t\t}\n\t}\n}\n\nfunc (g *GannoyIndex) removeItem(id int) error {\n\tindex := g.maps.getIndex(id)\n\tn := g.nodes.getNode(index)\n\n\tvar wg sync.WaitGroup\n\twg.Add(g.tree)\n\tbuildChan := make(chan int, g.tree)\n\tworker := func(n Node) {\n\t\tfor root := range buildChan {\n\t\t\tg.remove(root, n)\n\t\t\twg.Done()\n\t\t}\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\tgo worker(n)\n\t}\n\tfor index, _ := range g.meta.roots() {\n\t\tbuildChan <- index\n\t}\n\n\twg.Wait()\n\tclose(buildChan)\n\n\tg.maps.remove(n.id, id)\n\tn.ref = false\n\tn.save()\n\n\treturn nil\n}\n\nfunc (g *GannoyIndex) remove(root int, node Node) {\n\tparent := g.nodes.getNode(node.parents[root])\n\tif parent.isBucket() && len(parent.children) > 2 {\n\t\t\/\/ fmt.Printf(\"pattern bucket\\n\")\n\t\ttarget := -1\n\t\tfor i, child := range parent.children {\n\t\t\tif child == node.id {\n\t\t\t\ttarget = i\n\t\t\t}\n\t\t}\n\t\tif target == -1 {\n\t\t\treturn\n\t\t}\n\t\tchildren := append(parent.children[:target], parent.children[(target+1):]...)\n\t\tparent.nDescendants--\n\t\tparent.children = children\n\t\tparent.save()\n\t} else {\n\t\t\/\/ fmt.Printf(\"pattern leaf node\\n\")\n\t\tvar other int\n\t\tfor _, child := range parent.children {\n\t\t\tif child != node.id {\n\t\t\t\tother = child\n\t\t\t}\n\t\t}\n\t\tgrandParent := g.nodes.getNode(parent.parents[root])\n\t\tchildren := []int{}\n\t\tfor _, child := range grandParent.children {\n\t\t\tif child == node.parents[root] {\n\t\t\t\tchildren = append(children, other)\n\t\t\t} else {\n\t\t\t\tchildren = append(children, child)\n\t\t\t}\n\t\t}\n\t\tgrandParent.nDescendants--\n\t\tgrandParent.children = children\n\t\tgrandParent.save()\n\n\t\totherNode := g.nodes.getNode(other)\n\t\totherNode.parents[root] = parent.parents[root]\n\t\totherNode.save()\n\n\t\tparent.ref = false\n\t\tparent.save()\n\t}\n}\n\nfunc (g GannoyIndex) findBranchByVector(index int, v []float64) int {\n\tnode := g.nodes.getNode(index)\n\tif node.isLeaf() || node.isBucket() {\n\t\treturn index\n\t}\n\tside := g.distance.side(node, v, g.dim, g.random)\n\treturn g.findBranchByVector(node.children[side], v)\n}\n\nfunc (g *GannoyIndex) makeTree(root, parent int, indices []int) int {\n\tif len(indices) == 1 {\n\t\tn := g.nodes.getNode(indices[0])\n\t\tif len(n.parents) == 0 {\n\t\t\tn.parents = make([]int, g.tree)\n\t\t}\n\t\tn.updateParents(root, parent)\n\t\treturn indices[0]\n\t}\n\n\tif len(indices) <= g.K {\n\t\tm := g.nodes.newNode()\n\t\tm.parents = make([]int, g.tree)\n\t\tm.nDescendants = len(indices)\n\t\tm.parents[root] = parent\n\t\tm.children = indices\n\t\tm.save()\n\t\tfor _, child := range indices {\n\t\t\tc := g.nodes.getNode(child)\n\t\t\tif len(c.parents) == 0 {\n\t\t\t\tc.parents = make([]int, g.tree)\n\t\t\t}\n\t\t\tc.updateParents(root, m.id)\n\t\t}\n\t\treturn m.id\n\t}\n\n\tchildren := make([]Node, len(indices))\n\tfor i, idx := range indices {\n\t\tchildren[i] = g.nodes.getNode(idx)\n\t}\n\n\tchildrenIndices := [2][]int{[]int{}, []int{}}\n\n\tm := g.nodes.newNode()\n\tm.parents = make([]int, g.tree)\n\tm.nDescendants = len(indices)\n\tm.parents[root] = parent\n\n\tm = g.distance.createSplit(children, g.dim, g.random, m)\n\tfor _, idx := range indices {\n\t\tn := g.nodes.getNode(idx)\n\t\tside := g.distance.side(m, n.v, g.dim, g.random)\n\t\tchildrenIndices[side] = append(childrenIndices[side], idx)\n\t}\n\n\tfor len(childrenIndices[0]) == 0 || len(childrenIndices[1]) == 0 {\n\t\tchildrenIndices[0] = []int{}\n\t\tchildrenIndices[1] = []int{}\n\t\tfor z := 0; z < g.dim; z++ {\n\t\t\tm.v[z] = 0.0\n\t\t}\n\t\tfor _, idx := range indices {\n\t\t\tside := g.random.flip()\n\t\t\tchildrenIndices[side] = append(childrenIndices[side], idx)\n\t\t}\n\t}\n\n\tvar flip int\n\tif len(childrenIndices[0]) > len(childrenIndices[1]) {\n\t\tflip = 1\n\t}\n\n\tm.save()\n\tfor side := 0; side < 2; side++ {\n\t\tm.children[side^flip] = g.makeTree(root, m.id, childrenIndices[side^flip])\n\t}\n\tm.save()\n\n\treturn m.id\n}\n\ntype buildArgs struct {\n\taction int\n\tid int\n\tw []float64\n\tresult chan error\n}\n\nfunc (g *GannoyIndex) builder() {\n\tfor args := range g.buildChan {\n\t\tswitch args.action {\n\t\tcase ADD:\n\t\t\targs.result <- g.addItem(args.id, args.w)\n\t\tcase DELETE:\n\t\t\targs.result <- g.removeItem(args.id)\n\t\t}\n\t}\n}\n\nfunc (g GannoyIndex) walk(root int, node Node, id, tab int) {\n\tfor i := 0; i < tab*2; i++ {\n\t\tfmt.Print(\" \")\n\t}\n\tfmt.Printf(\"%d [%d] (%d) [nDescendants: %d, v: %v]\\n\", id, g.maps.getId(id), node.parents[root], node.nDescendants, node.v)\n\tif !node.isLeaf() {\n\t\tfor _, child := range node.children {\n\t\t\tg.walk(root, g.nodes.getNode(child), child, tab+1)\n\t\t}\n\t}\n}\nImplemented a feature for updating node from trees.package gannoy\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com\/gansidui\/priority_queue\"\n)\n\ntype GannoyIndex struct {\n\tmeta meta\n\tmaps Maps\n\ttree int\n\tdim int\n\tdistance Distance\n\trandom Random\n\tnodes Nodes\n\tK int\n\tbuildChan chan buildArgs\n}\n\nfunc NewGannoyIndex(metaFile string, distance Distance, random Random) (GannoyIndex, error) {\n\n\tmeta, err := loadMeta(metaFile)\n\tif err != nil {\n\t\treturn GannoyIndex{}, err\n\t}\n\ttree := meta.tree\n\tdim := meta.dim\n\n\tann := meta.treePath()\n\tmaps := meta.mapPath()\n\n\t\/\/ K := 3\n\tK := 50\n\tgannoy := GannoyIndex{\n\t\tmeta: meta,\n\t\tmaps: newMaps(maps),\n\t\ttree: tree,\n\t\tdim: dim,\n\t\tdistance: distance,\n\t\trandom: random,\n\t\tK: K,\n\t\tnodes: newNodes(ann, tree, dim, K),\n\t\tbuildChan: make(chan buildArgs, 1),\n\t}\n\tgo gannoy.builder()\n\treturn gannoy, nil\n}\n\nfunc (g GannoyIndex) Tree() {\n\tfor i, root := range g.meta.roots() {\n\t\tg.walk(i, g.nodes.getNode(root), root, 0)\n\t}\n}\n\nfunc (g *GannoyIndex) AddItem(id int, w []float64) error {\n\targs := buildArgs{action: ADD, id: id, w: w, result: make(chan error)}\n\tg.buildChan <- args\n\treturn <-args.result\n}\n\nfunc (g *GannoyIndex) RemoveItem(id int) error {\n\targs := buildArgs{action: DELETE, id: id, result: make(chan error)}\n\tg.buildChan <- args\n\treturn <-args.result\n}\n\nfunc (g *GannoyIndex) UpdateItem(id int, w []float64) error {\n\targs := buildArgs{action: UPDATE, id: id, w: w, result: make(chan error)}\n\tg.buildChan <- args\n\treturn <-args.result\n}\n\nfunc (g GannoyIndex) GetNnsByItem(id, n, searchK int) []int {\n\tm := g.nodes.getNode(g.maps.getIndex(id))\n\tif !m.isLeaf() {\n\t\treturn []int{}\n\t}\n\tindices := g.getAllNns(m.v, n, searchK)\n\tids := make([]int, len(indices))\n\tfor i, index := range indices {\n\t\tids[i] = g.maps.getId(index)\n\t}\n\treturn ids\n}\n\nfunc (g GannoyIndex) getAllNns(v []float64, n, searchK int) []int {\n\tif searchK == -1 {\n\t\tsearchK = n * g.tree\n\t}\n\n\tq := priority_queue.New()\n\tfor _, root := range g.meta.roots() {\n\t\tq.Push(&Queue{priority: math.Inf(1), value: root})\n\t}\n\n\tnns := []int{}\n\tfor len(nns) < searchK && q.Len() > 0 {\n\t\ttop := q.Top().(*Queue)\n\t\td := top.priority\n\t\ti := top.value\n\n\t\tnd := g.nodes.getNode(i)\n\t\tq.Pop()\n\t\tif nd.isLeaf() {\n\t\t\tnns = append(nns, i)\n\t\t} else if nd.nDescendants <= g.K {\n\t\t\tdst := nd.children\n\t\t\tnns = append(nns, dst...)\n\t\t} else {\n\t\t\tmargin := g.distance.margin(nd, v, g.dim)\n\t\t\tq.Push(&Queue{priority: math.Min(d, +margin), value: nd.children[1]})\n\t\t\tq.Push(&Queue{priority: math.Min(d, -margin), value: nd.children[0]})\n\t\t}\n\t}\n\n\tsort.Ints(nns)\n\tnnsDist := []Dist{}\n\tlast := -1\n\tfor _, j := range nns {\n\t\tif j == last {\n\t\t\tcontinue\n\t\t}\n\t\tlast = j\n\t\tnnsDist = append(nnsDist, Dist{distance: g.distance.distance(v, g.nodes.getNode(j).v, g.dim), item: j})\n\t}\n\n\tm := len(nnsDist)\n\tp := m\n\tif n < m {\n\t\tp = n\n\t}\n\n\tresult := []int{}\n\tsort.Slice(nnsDist, func(i, j int) bool {\n\t\treturn nnsDist[i].distance < nnsDist[j].distance\n\t})\n\tfor i := 0; i < p; i++ {\n\t\tresult = append(result, nnsDist[i].item)\n\t}\n\n\treturn result\n}\n\nfunc (g *GannoyIndex) addItem(id int, w []float64) error {\n\tn := g.nodes.newNode()\n\tn.v = w\n\tn.parents = make([]int, g.tree)\n\terr := n.save()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ fmt.Printf(\"id %d\\n\", n.id)\n\n\tvar wg sync.WaitGroup\n\twg.Add(g.tree)\n\tbuildChan := make(chan int, g.tree)\n\tworker := func(n Node) {\n\t\tfor index := range buildChan {\n\t\t\t\/\/ fmt.Printf(\"root: %d\\n\", g.meta.roots()[index])\n\t\t\tg.build(index, g.meta.roots()[index], n)\n\t\t\twg.Done()\n\t\t}\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\tgo worker(n)\n\t}\n\n\tfor index, _ := range g.meta.roots() {\n\t\tbuildChan <- index\n\t}\n\n\twg.Wait()\n\tclose(buildChan)\n\tg.maps.add(n.id, id)\n\n\treturn nil\n}\n\nfunc (g *GannoyIndex) build(index, root int, n Node) {\n\tif root == -1 {\n\t\t\/\/ 最初のノード\n\t\tn.parents[index] = -1\n\t\tn.save()\n\t\tg.meta.updateRoot(index, n.id)\n\t\treturn\n\t}\n\titem := g.findBranchByVector(root, n.v)\n\tfound := g.nodes.getNode(item)\n\t\/\/ fmt.Printf(\"Found %d\\n\", item)\n\n\torg_parent := found.parents[index]\n\tif found.isBucket() && len(found.children) < g.K {\n\t\t\/\/ ノードに余裕があれば追加\n\t\t\/\/ fmt.Printf(\"pattern bucket\\n\")\n\t\tn.updateParents(index, item)\n\t\tfound.nDescendants++\n\t\tfound.children = append(found.children, n.id)\n\t\tfound.save()\n\t} else {\n\t\t\/\/ ノードが上限またはリーフノードであれば新しいノードを追加\n\t\twillDelete := false\n\t\tvar indices []int\n\t\tif found.isLeaf() {\n\t\t\t\/\/ fmt.Printf(\"pattern leaf node\\n\")\n\t\t\tindices = []int{item, n.id}\n\t\t} else {\n\t\t\t\/\/ fmt.Printf(\"pattern full backet\\n\")\n\t\t\tindices = append(found.children, n.id)\n\t\t\twillDelete = true\n\t\t}\n\n\t\tm := g.makeTree(index, org_parent, indices)\n\t\t\/\/ fmt.Printf(\"m: %d, org_parent: %d\\n\", m, org_parent)\n\t\tif org_parent == -1 {\n\t\t\t\/\/ rootノードの入れ替え\n\t\t\tg.meta.updateRoot(index, m)\n\t\t} else {\n\t\t\tparent := g.nodes.getNode(org_parent)\n\t\t\tparent.nDescendants++\n\t\t\tchildren := make([]int, len(parent.children))\n\t\t\tfor i, child := range parent.children {\n\t\t\t\tif child == item {\n\t\t\t\t\t\/\/ 新しいノードに変更\n\t\t\t\t\tchildren[i] = m\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ 既存のノードのまま\n\t\t\t\t\tchildren[i] = child\n\t\t\t\t}\n\t\t\t}\n\t\t\tparent.children = children\n\t\t\tparent.save()\n\n\t\t}\n\t\tif willDelete {\n\t\t\tfound.destroy()\n\t\t}\n\t}\n}\n\nfunc (g *GannoyIndex) removeItem(id int) error {\n\tindex := g.maps.getIndex(id)\n\tn := g.nodes.getNode(index)\n\n\tvar wg sync.WaitGroup\n\twg.Add(g.tree)\n\tbuildChan := make(chan int, g.tree)\n\tworker := func(n Node) {\n\t\tfor root := range buildChan {\n\t\t\tg.remove(root, n)\n\t\t\twg.Done()\n\t\t}\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\tgo worker(n)\n\t}\n\tfor index, _ := range g.meta.roots() {\n\t\tbuildChan <- index\n\t}\n\n\twg.Wait()\n\tclose(buildChan)\n\n\tg.maps.remove(n.id, id)\n\tn.ref = false\n\tn.save()\n\n\treturn nil\n}\n\nfunc (g *GannoyIndex) remove(root int, node Node) {\n\tparent := g.nodes.getNode(node.parents[root])\n\tif parent.isBucket() && len(parent.children) > 2 {\n\t\t\/\/ fmt.Printf(\"pattern bucket\\n\")\n\t\ttarget := -1\n\t\tfor i, child := range parent.children {\n\t\t\tif child == node.id {\n\t\t\t\ttarget = i\n\t\t\t}\n\t\t}\n\t\tif target == -1 {\n\t\t\treturn\n\t\t}\n\t\tchildren := append(parent.children[:target], parent.children[(target+1):]...)\n\t\tparent.nDescendants--\n\t\tparent.children = children\n\t\tparent.save()\n\t} else {\n\t\t\/\/ fmt.Printf(\"pattern leaf node\\n\")\n\t\tvar other int\n\t\tfor _, child := range parent.children {\n\t\t\tif child != node.id {\n\t\t\t\tother = child\n\t\t\t}\n\t\t}\n\t\tgrandParent := g.nodes.getNode(parent.parents[root])\n\t\tchildren := []int{}\n\t\tfor _, child := range grandParent.children {\n\t\t\tif child == node.parents[root] {\n\t\t\t\tchildren = append(children, other)\n\t\t\t} else {\n\t\t\t\tchildren = append(children, child)\n\t\t\t}\n\t\t}\n\t\tgrandParent.nDescendants--\n\t\tgrandParent.children = children\n\t\tgrandParent.save()\n\n\t\totherNode := g.nodes.getNode(other)\n\t\totherNode.parents[root] = parent.parents[root]\n\t\totherNode.save()\n\n\t\tparent.ref = false\n\t\tparent.save()\n\t}\n}\n\nfunc (g GannoyIndex) findBranchByVector(index int, v []float64) int {\n\tnode := g.nodes.getNode(index)\n\tif node.isLeaf() || node.isBucket() {\n\t\treturn index\n\t}\n\tside := g.distance.side(node, v, g.dim, g.random)\n\treturn g.findBranchByVector(node.children[side], v)\n}\n\nfunc (g *GannoyIndex) makeTree(root, parent int, indices []int) int {\n\tif len(indices) == 1 {\n\t\tn := g.nodes.getNode(indices[0])\n\t\tif len(n.parents) == 0 {\n\t\t\tn.parents = make([]int, g.tree)\n\t\t}\n\t\tn.updateParents(root, parent)\n\t\treturn indices[0]\n\t}\n\n\tif len(indices) <= g.K {\n\t\tm := g.nodes.newNode()\n\t\tm.parents = make([]int, g.tree)\n\t\tm.nDescendants = len(indices)\n\t\tm.parents[root] = parent\n\t\tm.children = indices\n\t\tm.save()\n\t\tfor _, child := range indices {\n\t\t\tc := g.nodes.getNode(child)\n\t\t\tif len(c.parents) == 0 {\n\t\t\t\tc.parents = make([]int, g.tree)\n\t\t\t}\n\t\t\tc.updateParents(root, m.id)\n\t\t}\n\t\treturn m.id\n\t}\n\n\tchildren := make([]Node, len(indices))\n\tfor i, idx := range indices {\n\t\tchildren[i] = g.nodes.getNode(idx)\n\t}\n\n\tchildrenIndices := [2][]int{[]int{}, []int{}}\n\n\tm := g.nodes.newNode()\n\tm.parents = make([]int, g.tree)\n\tm.nDescendants = len(indices)\n\tm.parents[root] = parent\n\n\tm = g.distance.createSplit(children, g.dim, g.random, m)\n\tfor _, idx := range indices {\n\t\tn := g.nodes.getNode(idx)\n\t\tside := g.distance.side(m, n.v, g.dim, g.random)\n\t\tchildrenIndices[side] = append(childrenIndices[side], idx)\n\t}\n\n\tfor len(childrenIndices[0]) == 0 || len(childrenIndices[1]) == 0 {\n\t\tchildrenIndices[0] = []int{}\n\t\tchildrenIndices[1] = []int{}\n\t\tfor z := 0; z < g.dim; z++ {\n\t\t\tm.v[z] = 0.0\n\t\t}\n\t\tfor _, idx := range indices {\n\t\t\tside := g.random.flip()\n\t\t\tchildrenIndices[side] = append(childrenIndices[side], idx)\n\t\t}\n\t}\n\n\tvar flip int\n\tif len(childrenIndices[0]) > len(childrenIndices[1]) {\n\t\tflip = 1\n\t}\n\n\tm.save()\n\tfor side := 0; side < 2; side++ {\n\t\tm.children[side^flip] = g.makeTree(root, m.id, childrenIndices[side^flip])\n\t}\n\tm.save()\n\n\treturn m.id\n}\n\ntype buildArgs struct {\n\taction int\n\tid int\n\tw []float64\n\tresult chan error\n}\n\nfunc (g *GannoyIndex) builder() {\n\tfor args := range g.buildChan {\n\t\tswitch args.action {\n\t\tcase ADD:\n\t\t\targs.result <- g.addItem(args.id, args.w)\n\t\tcase DELETE:\n\t\t\targs.result <- g.removeItem(args.id)\n\t\tcase UPDATE:\n\t\t\terr := g.removeItem(args.id)\n\t\t\tif err != nil {\n\t\t\t\targs.result <- err\n\t\t\t} else {\n\t\t\t\targs.result <- g.addItem(args.id, args.w)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (g GannoyIndex) walk(root int, node Node, id, tab int) {\n\tfor i := 0; i < tab*2; i++ {\n\t\tfmt.Print(\" \")\n\t}\n\tfmt.Printf(\"%d [%d] (%d) [nDescendants: %d, v: %v]\\n\", id, g.maps.getId(id), node.parents[root], node.nDescendants, node.v)\n\tif !node.isLeaf() {\n\t\tfor _, child := range node.children {\n\t\t\tg.walk(root, g.nodes.getNode(child), child, tab+1)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package ice\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pion\/stun\"\n\t\"github.com\/pion\/transport\/vnet\"\n\t\"github.com\/pion\/turn\"\n)\n\nconst (\n\tstunGatherTimeout = time.Second * 5\n)\n\nfunc (a *Agent) localInterfaces(networkTypes []NetworkType) ([]net.IP, error) {\n\tips := []net.IP{}\n\tifaces, err := a.net.Interfaces()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\n\tvar IPv4Requested, IPv6Requested bool\n\tfor _, typ := range networkTypes {\n\t\tif typ.IsIPv4() {\n\t\t\tIPv4Requested = true\n\t\t}\n\n\t\tif typ.IsIPv6() {\n\t\t\tIPv6Requested = true\n\t\t}\n\t}\n\n\tfor _, iface := range ifaces {\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue \/\/ interface down\n\t\t}\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue \/\/ loopback interface\n\t\t}\n\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch addr := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = addr.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = addr.IP\n\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ipv4 := ip.To4(); ipv4 == nil {\n\t\t\t\tif !IPv6Requested {\n\t\t\t\t\tcontinue\n\t\t\t\t} else if !isSupportedIPv6(ip) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if !IPv4Requested {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tips = append(ips, ip)\n\t\t}\n\t}\n\treturn ips, nil\n}\n\nfunc (a *Agent) listenUDP(portMax, portMin int, network string, laddr *net.UDPAddr) (vnet.UDPPacketConn, error) {\n\tif (laddr.Port != 0) || ((portMin == 0) && (portMax == 0)) {\n\t\treturn a.net.ListenUDP(network, laddr)\n\t}\n\tvar i, j int\n\ti = portMin\n\tif i == 0 {\n\t\ti = 1\n\t}\n\tj = portMax\n\tif j == 0 {\n\t\tj = 0xFFFF\n\t}\n\tfor i <= j {\n\t\tladdr = &net.UDPAddr{IP: laddr.IP, Port: i}\n\t\tc, e := a.net.ListenUDP(network, laddr)\n\t\tif e == nil {\n\t\t\treturn c, e\n\t\t}\n\t\ta.log.Debugf(\"failed to listen %s: %v\", laddr.String(), e)\n\t\ti++\n\t}\n\treturn nil, ErrPort\n}\n\n\/\/ GatherCandidates initiates the trickle based gathering process.\nfunc (a *Agent) GatherCandidates() error {\n\tgatherErrChan := make(chan error, 1)\n\n\trunErr := a.run(func(agent *Agent) {\n\t\tif a.gatheringState != GatheringStateNew {\n\t\t\tgatherErrChan <- ErrMultipleGatherAttempted\n\t\t\treturn\n\t\t} else if a.onCandidateHdlr == nil {\n\t\t\tgatherErrChan <- ErrNoOnCandidateHandler\n\t\t\treturn\n\t\t}\n\n\t\tgo a.gatherCandidates()\n\n\t\tgatherErrChan <- nil\n\t})\n\tif runErr != nil {\n\t\treturn runErr\n\t}\n\treturn <-gatherErrChan\n}\n\nfunc (a *Agent) gatherCandidates() {\n\tgatherStateUpdated := make(chan bool)\n\tif err := a.run(func(agent *Agent) {\n\t\ta.gatheringState = GatheringStateGathering\n\t\tclose(gatherStateUpdated)\n\t}); err != nil {\n\t\ta.log.Warnf(\"failed to set gatheringState to GatheringStateGathering for gatherCandidates: %v\", err)\n\t\treturn\n\t}\n\t<-gatherStateUpdated\n\n\tfor _, t := range a.candidateTypes {\n\t\tswitch t {\n\t\tcase CandidateTypeHost:\n\t\t\ta.gatherCandidatesLocal(a.networkTypes)\n\t\tcase CandidateTypeServerReflexive:\n\t\t\ta.gatherCandidatesSrflx(a.urls, a.networkTypes)\n\t\tcase CandidateTypeRelay:\n\t\t\tif err := a.gatherCandidatesRelay(a.urls); err != nil {\n\t\t\t\ta.log.Errorf(\"Failed to gather relay candidates: %v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := a.run(func(agent *Agent) {\n\t\tif a.onCandidateHdlr != nil {\n\t\t\tgo a.onCandidateHdlr(nil)\n\t\t}\n\t}); err != nil {\n\t\ta.log.Warnf(\"Failed to run onCandidateHdlr task: %v\\n\", err)\n\t\treturn\n\t}\n\n\tif err := a.run(func(agent *Agent) {\n\t\ta.gatheringState = GatheringStateComplete\n\t}); err != nil {\n\t\ta.log.Warnf(\"Failed to update gatheringState: %v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc (a *Agent) gatherCandidatesLocal(networkTypes []NetworkType) {\n\tvar wg sync.WaitGroup\n\tdefer wg.Wait()\n\n\tlocalIPs, err := a.localInterfaces(networkTypes)\n\tif err != nil {\n\t\ta.log.Warnf(\"failed to iterate local interfaces, host candidates will not be gathered %s\", err)\n\t\treturn\n\t}\n\n\twg.Add(len(localIPs) * len(supportedNetworks))\n\tfor _, ip := range localIPs {\n\t\tfor _, network := range supportedNetworks {\n\t\t\tgo func(network string, ip net.IP) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn, err := a.listenUDP(int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: ip, Port: 0})\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"could not listen %s %s\\n\", network, ip)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\taddress := ip.String()\n\t\t\t\tif a.mDNSMode == MulticastDNSModeQueryAndGather {\n\t\t\t\t\taddress = a.mDNSName\n\t\t\t\t}\n\n\t\t\t\tport := conn.LocalAddr().(*net.UDPAddr).Port\n\n\t\t\t\thostConfig := CandidateHostConfig{\n\t\t\t\t\tNetwork: network,\n\t\t\t\t\tAddress: address,\n\t\t\t\t\tPort: port,\n\t\t\t\t\tComponent: ComponentRTP,\n\t\t\t\t}\n\n\t\t\t\tc, err := NewCandidateHost(&hostConfig)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"Failed to create host candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif a.mDNSMode == MulticastDNSModeQueryAndGather {\n\t\t\t\t\tif err = c.setIP(ip); err != nil {\n\t\t\t\t\t\ta.log.Warnf(\"Failed to create host candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := a.run(func(agent *Agent) {\n\t\t\t\t\tc.start(a, conn)\n\t\t\t\t\ta.addCandidate(c)\n\n\t\t\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\t\t\tgo a.onCandidateHdlr(c)\n\t\t\t\t\t}\n\t\t\t\t}); err != nil {\n\t\t\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t\t\t}\n\t\t\t}(network, ip)\n\t\t}\n\t}\n}\n\nfunc (a *Agent) gatherCandidatesSrflx(urls []*URL, networkTypes []NetworkType) {\n\tfor _, networkType := range networkTypes {\n\t\tnetwork := networkType.String()\n\t\tfor _, url := range urls {\n\t\t\tif url.Scheme != SchemeTypeSTUN {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", url.Host, url.Port)\n\t\t\tserverAddr, err := a.net.ResolveUDPAddr(network, hostPort)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"failed to resolve stun host: %s: %v\", hostPort, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconn, err := a.listenUDP(int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: nil, Port: 0})\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to listen on %s for %s: %v\\n\", conn.LocalAddr().String(), serverAddr.String(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\txoraddr, err := getXORMappedAddr(conn, serverAddr, stunGatherTimeout)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"could not get server reflexive address %s %s: %v\\n\", network, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tladdr := conn.LocalAddr().(*net.UDPAddr)\n\t\t\tip := xoraddr.IP\n\t\t\tport := xoraddr.Port\n\t\t\trelIP := laddr.IP.String()\n\t\t\trelPort := laddr.Port\n\n\t\t\tsrflxConfig := CandidateServerReflexiveConfig{\n\t\t\t\tNetwork: network,\n\t\t\t\tAddress: ip.String(),\n\t\t\t\tPort: port,\n\t\t\t\tComponent: ComponentRTP,\n\t\t\t\tRelAddr: relIP,\n\t\t\t\tRelPort: relPort,\n\t\t\t}\n\t\t\tc, err := NewCandidateServerReflexive(&srflxConfig)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to create server reflexive candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := a.run(func(agent *Agent) {\n\t\t\t\tc.start(a, conn)\n\t\t\t\ta.addCandidate(c)\n\n\t\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\t\tgo a.onCandidateHdlr(c)\n\t\t\t\t}\n\t\t\t}); err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc (a *Agent) gatherCandidatesRelay(urls []*URL) error {\n\tnetwork := NetworkTypeUDP4.String() \/\/ TODO IPv6\n\tfor _, url := range urls {\n\t\tswitch {\n\t\tcase url.Scheme != SchemeTypeTURN:\n\t\t\tcontinue\n\t\tcase url.Username == \"\":\n\t\t\treturn ErrUsernameEmpty\n\t\tcase url.Password == \"\":\n\t\t\treturn ErrPasswordEmpty\n\t\t}\n\n\t\tlocConn, err := a.net.ListenPacket(network, \"0.0.0.0:0\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err := turn.NewClient(&turn.ClientConfig{\n\t\t\tTURNServerAddr: fmt.Sprintf(\"%s:%d\", url.Host, url.Port),\n\t\t\tConn: locConn,\n\t\t\tUsername: url.Username,\n\t\t\tPassword: url.Password,\n\t\t\tLoggerFactory: a.loggerFactory,\n\t\t\tNet: a.net,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = client.Listen()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelayConn, err := client.Allocate()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tladdr := locConn.LocalAddr().(*net.UDPAddr)\n\t\traddr := relayConn.LocalAddr().(*net.UDPAddr)\n\n\t\trelayConfig := CandidateRelayConfig{\n\t\t\tNetwork: network,\n\t\t\tComponent: ComponentRTP,\n\t\t\tAddress: raddr.IP.String(),\n\t\t\tPort: raddr.Port,\n\t\t\tRelAddr: laddr.IP.String(),\n\t\t\tRelPort: laddr.Port,\n\t\t\tOnClose: func() error {\n\t\t\t\tclient.Close()\n\t\t\t\treturn locConn.Close()\n\t\t\t},\n\t\t}\n\t\tcandidate, err := NewCandidateRelay(&relayConfig)\n\t\tif err != nil {\n\t\t\ta.log.Warnf(\"Failed to create relay candidate: %s %s: %v\\n\",\n\t\t\t\tnetwork, raddr.String(), err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := a.run(func(agent *Agent) {\n\t\t\tcandidate.start(a, relayConn)\n\t\t\ta.addCandidate(candidate)\n\n\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\tgo a.onCandidateHdlr(candidate)\n\t\t\t}\n\t\t}); err != nil {\n\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ getXORMappedAddr initiates a stun requests to serverAddr using conn, reads the response and returns\n\/\/ the XORMappedAddress returned by the stun server.\n\/\/\n\/\/ Adapted from stun v0.2.\nfunc getXORMappedAddr(conn net.PacketConn, serverAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) {\n\tif deadline > 0 {\n\t\tif err := conn.SetReadDeadline(time.Now().Add(deadline)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdefer func() {\n\t\tif deadline > 0 {\n\t\t\t_ = conn.SetReadDeadline(time.Time{})\n\t\t}\n\t}()\n\tresp, err := stunRequest(\n\t\tfunc(p []byte) (int, error) {\n\t\t\tn, _, errr := conn.ReadFrom(p)\n\t\t\treturn n, errr\n\t\t},\n\t\tfunc(b []byte) (int, error) {\n\t\t\treturn conn.WriteTo(b, serverAddr)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar addr stun.XORMappedAddress\n\tif err = addr.GetFrom(resp); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get XOR-MAPPED-ADDRESS response: %v\", err)\n\t}\n\treturn &addr, nil\n}\n\nfunc stunRequest(read func([]byte) (int, error), write func([]byte) (int, error)) (*stun.Message, error) {\n\treq, err := stun.Build(stun.BindingRequest, stun.TransactionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = write(req.Raw); err != nil {\n\t\treturn nil, err\n\t}\n\tconst maxMessageSize = 1280\n\tbs := make([]byte, maxMessageSize)\n\tn, err := read(bs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := &stun.Message{Raw: bs[:n]}\n\tif err := res.Decode(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\nFix connection nil pointerpackage ice\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pion\/stun\"\n\t\"github.com\/pion\/transport\/vnet\"\n\t\"github.com\/pion\/turn\"\n)\n\nconst (\n\tstunGatherTimeout = time.Second * 5\n)\n\nfunc (a *Agent) localInterfaces(networkTypes []NetworkType) ([]net.IP, error) {\n\tips := []net.IP{}\n\tifaces, err := a.net.Interfaces()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\n\tvar IPv4Requested, IPv6Requested bool\n\tfor _, typ := range networkTypes {\n\t\tif typ.IsIPv4() {\n\t\t\tIPv4Requested = true\n\t\t}\n\n\t\tif typ.IsIPv6() {\n\t\t\tIPv6Requested = true\n\t\t}\n\t}\n\n\tfor _, iface := range ifaces {\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue \/\/ interface down\n\t\t}\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue \/\/ loopback interface\n\t\t}\n\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch addr := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = addr.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = addr.IP\n\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ipv4 := ip.To4(); ipv4 == nil {\n\t\t\t\tif !IPv6Requested {\n\t\t\t\t\tcontinue\n\t\t\t\t} else if !isSupportedIPv6(ip) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if !IPv4Requested {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tips = append(ips, ip)\n\t\t}\n\t}\n\treturn ips, nil\n}\n\nfunc (a *Agent) listenUDP(portMax, portMin int, network string, laddr *net.UDPAddr) (vnet.UDPPacketConn, error) {\n\tif (laddr.Port != 0) || ((portMin == 0) && (portMax == 0)) {\n\t\treturn a.net.ListenUDP(network, laddr)\n\t}\n\tvar i, j int\n\ti = portMin\n\tif i == 0 {\n\t\ti = 1\n\t}\n\tj = portMax\n\tif j == 0 {\n\t\tj = 0xFFFF\n\t}\n\tfor i <= j {\n\t\tladdr = &net.UDPAddr{IP: laddr.IP, Port: i}\n\t\tc, e := a.net.ListenUDP(network, laddr)\n\t\tif e == nil {\n\t\t\treturn c, e\n\t\t}\n\t\ta.log.Debugf(\"failed to listen %s: %v\", laddr.String(), e)\n\t\ti++\n\t}\n\treturn nil, ErrPort\n}\n\n\/\/ GatherCandidates initiates the trickle based gathering process.\nfunc (a *Agent) GatherCandidates() error {\n\tgatherErrChan := make(chan error, 1)\n\n\trunErr := a.run(func(agent *Agent) {\n\t\tif a.gatheringState != GatheringStateNew {\n\t\t\tgatherErrChan <- ErrMultipleGatherAttempted\n\t\t\treturn\n\t\t} else if a.onCandidateHdlr == nil {\n\t\t\tgatherErrChan <- ErrNoOnCandidateHandler\n\t\t\treturn\n\t\t}\n\n\t\tgo a.gatherCandidates()\n\n\t\tgatherErrChan <- nil\n\t})\n\tif runErr != nil {\n\t\treturn runErr\n\t}\n\treturn <-gatherErrChan\n}\n\nfunc (a *Agent) gatherCandidates() {\n\tgatherStateUpdated := make(chan bool)\n\tif err := a.run(func(agent *Agent) {\n\t\ta.gatheringState = GatheringStateGathering\n\t\tclose(gatherStateUpdated)\n\t}); err != nil {\n\t\ta.log.Warnf(\"failed to set gatheringState to GatheringStateGathering for gatherCandidates: %v\", err)\n\t\treturn\n\t}\n\t<-gatherStateUpdated\n\n\tfor _, t := range a.candidateTypes {\n\t\tswitch t {\n\t\tcase CandidateTypeHost:\n\t\t\ta.gatherCandidatesLocal(a.networkTypes)\n\t\tcase CandidateTypeServerReflexive:\n\t\t\ta.gatherCandidatesSrflx(a.urls, a.networkTypes)\n\t\tcase CandidateTypeRelay:\n\t\t\tif err := a.gatherCandidatesRelay(a.urls); err != nil {\n\t\t\t\ta.log.Errorf(\"Failed to gather relay candidates: %v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := a.run(func(agent *Agent) {\n\t\tif a.onCandidateHdlr != nil {\n\t\t\tgo a.onCandidateHdlr(nil)\n\t\t}\n\t}); err != nil {\n\t\ta.log.Warnf(\"Failed to run onCandidateHdlr task: %v\\n\", err)\n\t\treturn\n\t}\n\n\tif err := a.run(func(agent *Agent) {\n\t\ta.gatheringState = GatheringStateComplete\n\t}); err != nil {\n\t\ta.log.Warnf(\"Failed to update gatheringState: %v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc (a *Agent) gatherCandidatesLocal(networkTypes []NetworkType) {\n\tvar wg sync.WaitGroup\n\tdefer wg.Wait()\n\n\tlocalIPs, err := a.localInterfaces(networkTypes)\n\tif err != nil {\n\t\ta.log.Warnf(\"failed to iterate local interfaces, host candidates will not be gathered %s\", err)\n\t\treturn\n\t}\n\n\twg.Add(len(localIPs) * len(supportedNetworks))\n\tfor _, ip := range localIPs {\n\t\tfor _, network := range supportedNetworks {\n\t\t\tgo func(network string, ip net.IP) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn, err := a.listenUDP(int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: ip, Port: 0})\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"could not listen %s %s\\n\", network, ip)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\taddress := ip.String()\n\t\t\t\tif a.mDNSMode == MulticastDNSModeQueryAndGather {\n\t\t\t\t\taddress = a.mDNSName\n\t\t\t\t}\n\n\t\t\t\tport := conn.LocalAddr().(*net.UDPAddr).Port\n\n\t\t\t\thostConfig := CandidateHostConfig{\n\t\t\t\t\tNetwork: network,\n\t\t\t\t\tAddress: address,\n\t\t\t\t\tPort: port,\n\t\t\t\t\tComponent: ComponentRTP,\n\t\t\t\t}\n\n\t\t\t\tc, err := NewCandidateHost(&hostConfig)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"Failed to create host candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif a.mDNSMode == MulticastDNSModeQueryAndGather {\n\t\t\t\t\tif err = c.setIP(ip); err != nil {\n\t\t\t\t\t\ta.log.Warnf(\"Failed to create host candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := a.run(func(agent *Agent) {\n\t\t\t\t\tc.start(a, conn)\n\t\t\t\t\ta.addCandidate(c)\n\n\t\t\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\t\t\tgo a.onCandidateHdlr(c)\n\t\t\t\t\t}\n\t\t\t\t}); err != nil {\n\t\t\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t\t\t}\n\t\t\t}(network, ip)\n\t\t}\n\t}\n}\n\nfunc (a *Agent) gatherCandidatesSrflx(urls []*URL, networkTypes []NetworkType) {\n\tfor _, networkType := range networkTypes {\n\t\tnetwork := networkType.String()\n\t\tfor _, url := range urls {\n\t\t\tif url.Scheme != SchemeTypeSTUN {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", url.Host, url.Port)\n\t\t\tserverAddr, err := a.net.ResolveUDPAddr(network, hostPort)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"failed to resolve stun host: %s: %v\", hostPort, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconn, err := a.listenUDP(int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: nil, Port: 0})\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to listen for %s: %v\\n\", serverAddr.String(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\txoraddr, err := getXORMappedAddr(conn, serverAddr, stunGatherTimeout)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"could not get server reflexive address %s %s: %v\\n\", network, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tladdr := conn.LocalAddr().(*net.UDPAddr)\n\t\t\tip := xoraddr.IP\n\t\t\tport := xoraddr.Port\n\t\t\trelIP := laddr.IP.String()\n\t\t\trelPort := laddr.Port\n\n\t\t\tsrflxConfig := CandidateServerReflexiveConfig{\n\t\t\t\tNetwork: network,\n\t\t\t\tAddress: ip.String(),\n\t\t\t\tPort: port,\n\t\t\t\tComponent: ComponentRTP,\n\t\t\t\tRelAddr: relIP,\n\t\t\t\tRelPort: relPort,\n\t\t\t}\n\t\t\tc, err := NewCandidateServerReflexive(&srflxConfig)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to create server reflexive candidate: %s %s %d: %v\\n\", network, ip, port, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := a.run(func(agent *Agent) {\n\t\t\t\tc.start(a, conn)\n\t\t\t\ta.addCandidate(c)\n\n\t\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\t\tgo a.onCandidateHdlr(c)\n\t\t\t\t}\n\t\t\t}); err != nil {\n\t\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc (a *Agent) gatherCandidatesRelay(urls []*URL) error {\n\tnetwork := NetworkTypeUDP4.String() \/\/ TODO IPv6\n\tfor _, url := range urls {\n\t\tswitch {\n\t\tcase url.Scheme != SchemeTypeTURN:\n\t\t\tcontinue\n\t\tcase url.Username == \"\":\n\t\t\treturn ErrUsernameEmpty\n\t\tcase url.Password == \"\":\n\t\t\treturn ErrPasswordEmpty\n\t\t}\n\n\t\tlocConn, err := a.net.ListenPacket(network, \"0.0.0.0:0\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err := turn.NewClient(&turn.ClientConfig{\n\t\t\tTURNServerAddr: fmt.Sprintf(\"%s:%d\", url.Host, url.Port),\n\t\t\tConn: locConn,\n\t\t\tUsername: url.Username,\n\t\t\tPassword: url.Password,\n\t\t\tLoggerFactory: a.loggerFactory,\n\t\t\tNet: a.net,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = client.Listen()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelayConn, err := client.Allocate()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tladdr := locConn.LocalAddr().(*net.UDPAddr)\n\t\traddr := relayConn.LocalAddr().(*net.UDPAddr)\n\n\t\trelayConfig := CandidateRelayConfig{\n\t\t\tNetwork: network,\n\t\t\tComponent: ComponentRTP,\n\t\t\tAddress: raddr.IP.String(),\n\t\t\tPort: raddr.Port,\n\t\t\tRelAddr: laddr.IP.String(),\n\t\t\tRelPort: laddr.Port,\n\t\t\tOnClose: func() error {\n\t\t\t\tclient.Close()\n\t\t\t\treturn locConn.Close()\n\t\t\t},\n\t\t}\n\t\tcandidate, err := NewCandidateRelay(&relayConfig)\n\t\tif err != nil {\n\t\t\ta.log.Warnf(\"Failed to create relay candidate: %s %s: %v\\n\",\n\t\t\t\tnetwork, raddr.String(), err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := a.run(func(agent *Agent) {\n\t\t\tcandidate.start(a, relayConn)\n\t\t\ta.addCandidate(candidate)\n\n\t\t\tif a.onCandidateHdlr != nil {\n\t\t\t\tgo a.onCandidateHdlr(candidate)\n\t\t\t}\n\t\t}); err != nil {\n\t\t\ta.log.Warnf(\"Failed to append to localCandidates and run onCandidateHdlr: %v\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ getXORMappedAddr initiates a stun requests to serverAddr using conn, reads the response and returns\n\/\/ the XORMappedAddress returned by the stun server.\n\/\/\n\/\/ Adapted from stun v0.2.\nfunc getXORMappedAddr(conn net.PacketConn, serverAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) {\n\tif deadline > 0 {\n\t\tif err := conn.SetReadDeadline(time.Now().Add(deadline)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdefer func() {\n\t\tif deadline > 0 {\n\t\t\t_ = conn.SetReadDeadline(time.Time{})\n\t\t}\n\t}()\n\tresp, err := stunRequest(\n\t\tfunc(p []byte) (int, error) {\n\t\t\tn, _, errr := conn.ReadFrom(p)\n\t\t\treturn n, errr\n\t\t},\n\t\tfunc(b []byte) (int, error) {\n\t\t\treturn conn.WriteTo(b, serverAddr)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar addr stun.XORMappedAddress\n\tif err = addr.GetFrom(resp); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get XOR-MAPPED-ADDRESS response: %v\", err)\n\t}\n\treturn &addr, nil\n}\n\nfunc stunRequest(read func([]byte) (int, error), write func([]byte) (int, error)) (*stun.Message, error) {\n\treq, err := stun.Build(stun.BindingRequest, stun.TransactionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = write(req.Raw); err != nil {\n\t\treturn nil, err\n\t}\n\tconst maxMessageSize = 1280\n\tbs := make([]byte, maxMessageSize)\n\tn, err := read(bs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := &stun.Message{Raw: bs[:n]}\n\tif err := res.Decode(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright © 2016 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 http\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\"sync\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/stats\"\n\t\"github.com\/apex\/log\"\n)\n\n\/\/ Adapter type materializes an http adapter which implements the basic http protocol\ntype Adapter struct {\n\thttp.Client \/\/ Adapter is also an http client\n\tctx log.Interface \/\/ Just a logger, no one really cares about him.\n\tpackets chan PktReq \/\/ Channel used to \"transforms\" incoming request to something we can handle concurrently\n\trecipients []core.Recipient \/\/ Known recipient used for broadcast if any\n\tregistrations chan RegReq \/\/ Incoming registrations\n\tserveMux *http.ServeMux \/\/ Holds a references to the adapter servemux in order to dynamically define endpoints\n}\n\n\/\/ Handler defines endpoint-specific handler.\ntype Handler interface {\n\tURL() string\n\tHandle(w http.ResponseWriter, chpkt chan<- PktReq, chreg chan<- RegReq, req *http.Request)\n}\n\n\/\/ MsgRes are sent through the response channel of a pktReq or regReq\ntype MsgRes struct {\n\tStatusCode int \/\/ The http status code to set as an answer\n\tContent []byte \/\/ The response content.\n}\n\n\/\/ PktReq are sent through the packets channel when an incoming request arrives\ntype PktReq struct {\n\tPacket []byte \/\/ The actual packet that has been parsed\n\tChresp chan MsgRes \/\/ A response channel waiting for an success or reject confirmation\n}\n\n\/\/ RegReq are sent through the registration channel when an incoming registration arrives\ntype RegReq struct {\n\tRegistration core.Registration\n\tChresp chan MsgRes\n}\n\n\/\/ NewAdapter constructs and allocates a new http adapter\nfunc NewAdapter(net string, recipients []core.Recipient, ctx log.Interface) (*Adapter, error) {\n\ta := Adapter{\n\t\tClient: http.Client{Timeout: 6 * time.Second},\n\t\tctx: ctx,\n\t\tpackets: make(chan PktReq),\n\t\trecipients: recipients,\n\t\tregistrations: make(chan RegReq),\n\t\tserveMux: http.NewServeMux(),\n\t}\n\n\tgo a.listenRequests(net)\n\n\treturn &a, nil\n}\n\n\/\/ Register implements the core.Subscriber interface\nfunc (a *Adapter) Subscribe(r core.Registration) error {\n\tjsonMarshaler, ok := r.(json.Marshaler)\n\tif !ok {\n\t\treturn errors.New(errors.Structural, \"Unable to marshal registration\")\n\t}\n\thttpRecipient, ok := r.Recipient().(Recipient)\n\tif !ok {\n\t\treturn errors.New(errors.Structural, \"Invalid recipient\")\n\t}\n\n\tdata, err := jsonMarshaler.MarshalJSON()\n\tif err != nil {\n\t\treturn errors.New(errors.Structural, err)\n\t}\n\tbuf := new(bytes.Buffer)\n\tbuf.Write(data)\n\tresp, err := a.Post(fmt.Sprintf(\"http:\/\/%s\/end-devices\", httpRecipient.URL()), \"application\/json\", buf)\n\tif err != nil {\n\t\treturn errors.New(errors.Operational, err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {\n\t\treturn errors.New(errors.Operational, \"Unable to subscribe\")\n\t}\n\treturn nil\n}\n\n\/\/ Send implements the core.Adapter interface\nfunc (a *Adapter) Send(p core.Packet, recipients ...core.Recipient) ([]byte, error) {\n\tstats.MarkMeter(\"http_adapter.send\")\n\tstats.UpdateHistogram(\"http_adapter.send_recipients\", int64(len(recipients)))\n\n\t\/\/ Marshal the packet to raw binary data\n\tdata, err := p.MarshalBinary()\n\tif err != nil {\n\t\ta.ctx.WithError(err).Warn(\"Invalid Packet\")\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\n\t\/\/ Try to define a more helpful context\n\tctx := a.ctx.WithField(\"devEUI\", p.DevEUI())\n\tctx.Debug(\"Sending Packet\")\n\n\t\/\/ Determine whether it's a broadcast or a direct send\n\tnb := len(recipients)\n\tisBroadcast := false\n\tif nb == 0 {\n\t\t\/\/ If no recipient was supplied, try with the known one, otherwise quit.\n\t\trecipients = a.recipients\n\t\tnb = len(recipients)\n\t\tisBroadcast = true\n\t\tif nb == 0 {\n\t\t\treturn nil, errors.New(errors.Structural, \"No recipient found\")\n\t\t}\n\t}\n\n\t\/\/ Prepare ground for parrallel http request\n\tcherr := make(chan error, nb)\n\tchresp := make(chan []byte, nb)\n\twg := sync.WaitGroup{}\n\twg.Add(nb)\n\n\t\/\/ Run each request\n\tfor _, recipient := range recipients {\n\t\tgo func(rawRecipient core.Recipient) {\n\t\t\tdefer wg.Done()\n\n\t\t\t\/\/ Get the actual recipient\n\t\t\trecipient, ok := rawRecipient.(Recipient)\n\t\t\tif !ok {\n\t\t\t\tctx.WithField(\"recipient\", rawRecipient).Warn(\"Unable to interpret recipient as Recipient\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx := ctx.WithField(\"recipient\", recipient.URL())\n\n\t\t\t\/\/ Send request\n\t\t\tctx.Debugf(\"%s Request\", recipient.Method())\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tbuf.Write(data)\n\t\t\tresp, err := a.Post(fmt.Sprintf(\"http:\/\/%s\/packets\", recipient.URL()), \"application\/octet-stream\", buf)\n\t\t\tif err != nil {\n\t\t\t\tcherr <- errors.New(errors.Operational, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\t\/\/ This is needed because the default HTTP client's Transport does not\n\t\t\t\t\/\/ attempt to reuse HTTP\/1.0 or HTTP\/1.1 TCP connections unless the Body\n\t\t\t\t\/\/ is read to completion and is closed.\n\t\t\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\t\t\tresp.Body.Close()\n\t\t\t}()\n\n\t\t\t\/\/ Check response code\n\t\t\tswitch resp.StatusCode {\n\t\t\tcase http.StatusOK:\n\t\t\t\tctx.Debug(\"Recipient registered for packet\")\n\t\t\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tif err != nil && err != io.EOF {\n\t\t\t\t\tcherr <- errors.New(errors.Operational, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchresp <- data\n\t\t\t\tif isBroadcast { \/\/ Generate registration on broadcast\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\ta.registrations <- RegReq{\n\t\t\t\t\t\t\tRegistration: httpRegistration{\n\t\t\t\t\t\t\t\trecipient: rawRecipient,\n\t\t\t\t\t\t\t\tdevEUI: p.DevEUI(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tChresp: nil,\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\tcase http.StatusNotFound:\n\t\t\t\tctx.Debug(\"Recipient not interested in packet\")\n\t\t\t\tcherr <- errors.New(errors.Behavioural, \"Recipient not interested\")\n\t\t\tdefault:\n\t\t\t\tcherr <- errors.New(errors.Operational, fmt.Sprintf(\"Unexpected response from server: %s (%d)\", resp.Status, resp.StatusCode))\n\t\t\t}\n\t\t}(recipient)\n\t}\n\n\t\/\/ Wait for each request to be done\n\tstats.IncCounter(\"http_adapter.waiting_for_send\")\n\twg.Wait()\n\tstats.DecCounter(\"http_adapter.waiting_for_send\")\n\tclose(cherr)\n\tclose(chresp)\n\n\t\/\/ Collect errors and see if everything went well\n\tvar errored uint8\n\tfor i := 0; i < len(cherr); i++ {\n\t\terr := <-cherr\n\t\tif err.(errors.Failure).Nature != errors.Behavioural {\n\t\t\terrored++\n\t\t\tctx.WithError(err).Warn(\"POST Failed\")\n\t\t}\n\t}\n\n\t\/\/ Collect response\n\tif len(chresp) > 1 {\n\t\treturn nil, errors.New(errors.Behavioural, \"Received too many positive answers\")\n\t}\n\n\tif len(chresp) == 0 && errored != 0 {\n\t\treturn nil, errors.New(errors.Operational, \"No positive response from recipients but got unexpected answer\")\n\t}\n\n\tif len(chresp) == 0 && errored == 0 {\n\t\treturn nil, errors.New(errors.Behavioural, \"No recipient gave a positive answer\")\n\t}\n\n\treturn <-chresp, nil\n}\n\n\/\/ GetRecipient implements the core.Adapter interface\nfunc (a *Adapter) GetRecipient(raw []byte) (core.Recipient, error) {\n\trecipient := new(recipient)\n\tif err := recipient.UnmarshalBinary(raw); err != nil {\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\treturn *recipient, nil\n}\n\n\/\/ Next implements the core.Adapter interface\nfunc (a *Adapter) Next() ([]byte, core.AckNacker, error) {\n\tp := <-a.packets\n\treturn p.Packet, httpAckNacker{Chresp: p.Chresp}, nil\n}\n\n\/\/ NextRegistration implements the core.Adapter interface. Not implemented for this adapter.\n\/\/\n\/\/ See broadcast and pubsub adapters for mechanisms to handle registrations.\nfunc (a *Adapter) NextRegistration() (core.Registration, core.AckNacker, error) {\n\tr := <-a.registrations\n\treturn r.Registration, regAckNacker{Chresp: r.Chresp}, nil\n}\n\n\/\/ Bind registers a handler to a specific endpoint\nfunc (a *Adapter) Bind(h Handler) {\n\ta.ctx.WithField(\"url\", h.URL()).Info(\"Register new endpoint\")\n\ta.serveMux.HandleFunc(h.URL(), func(w http.ResponseWriter, req *http.Request) {\n\t\ta.ctx.WithField(\"url\", h.URL()).Debug(\"Handle new request\")\n\t\th.Handle(w, a.packets, a.registrations, req)\n\t})\n}\n\n\/\/ listenRequests handles incoming registration request sent through http to the adapter\nfunc (a *Adapter) listenRequests(net string) {\n\tserver := http.Server{\n\t\tAddr: net,\n\t\tHandler: a.serveMux,\n\t}\n\ta.ctx.WithField(\"bind\", net).Info(\"Starting Server\")\n\terr := server.ListenAndServe()\n\ta.ctx.WithError(err).Warn(\"HTTP connection lost\")\n}\n[test\/http-adapter] Use of correct http verbs in http adapters\/\/ Copyright © 2016 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 http\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\"sync\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/stats\"\n\t\"github.com\/apex\/log\"\n)\n\n\/\/ Adapter type materializes an http adapter which implements the basic http protocol\ntype Adapter struct {\n\thttp.Client \/\/ Adapter is also an http client\n\tctx log.Interface \/\/ Just a logger, no one really cares about him.\n\tpackets chan PktReq \/\/ Channel used to \"transforms\" incoming request to something we can handle concurrently\n\trecipients []core.Recipient \/\/ Known recipient used for broadcast if any\n\tregistrations chan RegReq \/\/ Incoming registrations\n\tserveMux *http.ServeMux \/\/ Holds a references to the adapter servemux in order to dynamically define endpoints\n}\n\n\/\/ Handler defines endpoint-specific handler.\ntype Handler interface {\n\tURL() string\n\tHandle(w http.ResponseWriter, chpkt chan<- PktReq, chreg chan<- RegReq, req *http.Request)\n}\n\n\/\/ MsgRes are sent through the response channel of a pktReq or regReq\ntype MsgRes struct {\n\tStatusCode int \/\/ The http status code to set as an answer\n\tContent []byte \/\/ The response content.\n}\n\n\/\/ PktReq are sent through the packets channel when an incoming request arrives\ntype PktReq struct {\n\tPacket []byte \/\/ The actual packet that has been parsed\n\tChresp chan MsgRes \/\/ A response channel waiting for an success or reject confirmation\n}\n\n\/\/ RegReq are sent through the registration channel when an incoming registration arrives\ntype RegReq struct {\n\tRegistration core.Registration\n\tChresp chan MsgRes\n}\n\n\/\/ NewAdapter constructs and allocates a new http adapter\nfunc NewAdapter(net string, recipients []core.Recipient, ctx log.Interface) (*Adapter, error) {\n\ta := Adapter{\n\t\tClient: http.Client{Timeout: 6 * time.Second},\n\t\tctx: ctx,\n\t\tpackets: make(chan PktReq),\n\t\trecipients: recipients,\n\t\tregistrations: make(chan RegReq),\n\t\tserveMux: http.NewServeMux(),\n\t}\n\n\tgo a.listenRequests(net)\n\n\treturn &a, nil\n}\n\n\/\/ Register implements the core.Subscriber interface\nfunc (a *Adapter) Subscribe(r core.Registration) error {\n\tjsonMarshaler, ok := r.(json.Marshaler)\n\tif !ok {\n\t\treturn errors.New(errors.Structural, \"Unable to marshal registration\")\n\t}\n\thttpRecipient, ok := r.Recipient().(Recipient)\n\tif !ok {\n\t\treturn errors.New(errors.Structural, \"Invalid recipient\")\n\t}\n\n\tdata, err := jsonMarshaler.MarshalJSON()\n\tif err != nil {\n\t\treturn errors.New(errors.Structural, err)\n\t}\n\tbuf := new(bytes.Buffer)\n\tbuf.Write(data)\n\treq, err := http.NewRequest(httpRecipient.Method(), fmt.Sprintf(\"http:\/\/%s\/end-devices\", httpRecipient.URL()), buf)\n\tif err != nil {\n\t\treturn errors.New(errors.Operational, err)\n\t}\n\treq.Header.Add(\"content-type\", \"application\/json\")\n\tresp, err := a.Do(req)\n\tif err != nil {\n\t\treturn errors.New(errors.Operational, err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {\n\t\treturn errors.New(errors.Operational, \"Unable to subscribe\")\n\t}\n\treturn nil\n}\n\n\/\/ Send implements the core.Adapter interface\nfunc (a *Adapter) Send(p core.Packet, recipients ...core.Recipient) ([]byte, error) {\n\tstats.MarkMeter(\"http_adapter.send\")\n\tstats.UpdateHistogram(\"http_adapter.send_recipients\", int64(len(recipients)))\n\n\t\/\/ Marshal the packet to raw binary data\n\tdata, err := p.MarshalBinary()\n\tif err != nil {\n\t\ta.ctx.WithError(err).Warn(\"Invalid Packet\")\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\n\t\/\/ Try to define a more helpful context\n\tctx := a.ctx.WithField(\"devEUI\", p.DevEUI())\n\tctx.Debug(\"Sending Packet\")\n\n\t\/\/ Determine whether it's a broadcast or a direct send\n\tnb := len(recipients)\n\tisBroadcast := false\n\tif nb == 0 {\n\t\t\/\/ If no recipient was supplied, try with the known one, otherwise quit.\n\t\trecipients = a.recipients\n\t\tnb = len(recipients)\n\t\tisBroadcast = true\n\t\tif nb == 0 {\n\t\t\treturn nil, errors.New(errors.Structural, \"No recipient found\")\n\t\t}\n\t}\n\n\t\/\/ Prepare ground for parrallel http request\n\tcherr := make(chan error, nb)\n\tchresp := make(chan []byte, nb)\n\twg := sync.WaitGroup{}\n\twg.Add(nb)\n\n\t\/\/ Run each request\n\tfor _, recipient := range recipients {\n\t\tgo func(rawRecipient core.Recipient) {\n\t\t\tdefer wg.Done()\n\n\t\t\t\/\/ Get the actual recipient\n\t\t\trecipient, ok := rawRecipient.(Recipient)\n\t\t\tif !ok {\n\t\t\t\tctx.WithField(\"recipient\", rawRecipient).Warn(\"Unable to interpret recipient as Recipient\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tctx := ctx.WithField(\"recipient\", recipient.URL())\n\n\t\t\t\/\/ Send request\n\t\t\tctx.Debugf(\"%s Request\", recipient.Method())\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tbuf.Write(data)\n\t\t\treq, err := http.NewRequest(recipient.Method(), fmt.Sprintf(\"http:\/\/%s\/packets\", recipient.URL()), buf)\n\t\t\tif err != nil {\n\t\t\t\tcherr <- errors.New(errors.Operational, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\treq.Header.Add(\"content-type\", \"application\/octet-stream\")\n\t\t\tresp, err := a.Do(req)\n\n\t\t\tif err != nil {\n\t\t\t\tcherr <- errors.New(errors.Operational, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\t\/\/ This is needed because the default HTTP client's Transport does not\n\t\t\t\t\/\/ attempt to reuse HTTP\/1.0 or HTTP\/1.1 TCP connections unless the Body\n\t\t\t\t\/\/ is read to completion and is closed.\n\t\t\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\t\t\tresp.Body.Close()\n\t\t\t}()\n\n\t\t\t\/\/ Check response code\n\t\t\tswitch resp.StatusCode {\n\t\t\tcase http.StatusOK:\n\t\t\t\tctx.Debug(\"Recipient registered for packet\")\n\t\t\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tif err != nil && err != io.EOF {\n\t\t\t\t\tcherr <- errors.New(errors.Operational, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchresp <- data\n\t\t\t\tif isBroadcast { \/\/ Generate registration on broadcast\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\ta.registrations <- RegReq{\n\t\t\t\t\t\t\tRegistration: httpRegistration{\n\t\t\t\t\t\t\t\trecipient: rawRecipient,\n\t\t\t\t\t\t\t\tdevEUI: p.DevEUI(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tChresp: nil,\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\tcase http.StatusNotFound:\n\t\t\t\tctx.Debug(\"Recipient not interested in packet\")\n\t\t\t\tcherr <- errors.New(errors.Behavioural, \"Recipient not interested\")\n\t\t\tdefault:\n\t\t\t\tcherr <- errors.New(errors.Operational, fmt.Sprintf(\"Unexpected response from server: %s (%d)\", resp.Status, resp.StatusCode))\n\t\t\t}\n\t\t}(recipient)\n\t}\n\n\t\/\/ Wait for each request to be done\n\tstats.IncCounter(\"http_adapter.waiting_for_send\")\n\twg.Wait()\n\tstats.DecCounter(\"http_adapter.waiting_for_send\")\n\tclose(cherr)\n\tclose(chresp)\n\n\t\/\/ Collect errors and see if everything went well\n\tvar errored uint8\n\tfor i := 0; i < len(cherr); i++ {\n\t\terr := <-cherr\n\t\tif err.(errors.Failure).Nature != errors.Behavioural {\n\t\t\terrored++\n\t\t\tctx.WithError(err).Warn(\"POST Failed\")\n\t\t}\n\t}\n\n\t\/\/ Collect response\n\tif len(chresp) > 1 {\n\t\treturn nil, errors.New(errors.Behavioural, \"Received too many positive answers\")\n\t}\n\n\tif len(chresp) == 0 && errored != 0 {\n\t\treturn nil, errors.New(errors.Operational, \"No positive response from recipients but got unexpected answer\")\n\t}\n\n\tif len(chresp) == 0 && errored == 0 {\n\t\treturn nil, errors.New(errors.Behavioural, \"No recipient gave a positive answer\")\n\t}\n\n\treturn <-chresp, nil\n}\n\n\/\/ GetRecipient implements the core.Adapter interface\nfunc (a *Adapter) GetRecipient(raw []byte) (core.Recipient, error) {\n\trecipient := new(recipient)\n\tif err := recipient.UnmarshalBinary(raw); err != nil {\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\treturn *recipient, nil\n}\n\n\/\/ Next implements the core.Adapter interface\nfunc (a *Adapter) Next() ([]byte, core.AckNacker, error) {\n\tp := <-a.packets\n\treturn p.Packet, httpAckNacker{Chresp: p.Chresp}, nil\n}\n\n\/\/ NextRegistration implements the core.Adapter interface. Not implemented for this adapter.\n\/\/\n\/\/ See broadcast and pubsub adapters for mechanisms to handle registrations.\nfunc (a *Adapter) NextRegistration() (core.Registration, core.AckNacker, error) {\n\tr := <-a.registrations\n\treturn r.Registration, regAckNacker{Chresp: r.Chresp}, nil\n}\n\n\/\/ Bind registers a handler to a specific endpoint\nfunc (a *Adapter) Bind(h Handler) {\n\ta.ctx.WithField(\"url\", h.URL()).Info(\"Register new endpoint\")\n\ta.serveMux.HandleFunc(h.URL(), func(w http.ResponseWriter, req *http.Request) {\n\t\ta.ctx.WithField(\"url\", h.URL()).Debug(\"Handle new request\")\n\t\th.Handle(w, a.packets, a.registrations, req)\n\t})\n}\n\n\/\/ listenRequests handles incoming registration request sent through http to the adapter\nfunc (a *Adapter) listenRequests(net string) {\n\tserver := http.Server{\n\t\tAddr: net,\n\t\tHandler: a.serveMux,\n\t}\n\ta.ctx.WithField(\"bind\", net).Info(\"Starting Server\")\n\terr := server.ListenAndServe()\n\ta.ctx.WithError(err).Warn(\"HTTP connection lost\")\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/oschwald\/maxminddb-golang\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar reader *maxminddb.Reader\nvar verbose bool\nvar format string\n\ntype geoIPResult struct {\n\tLocation struct {\n\t\tLongitude float64 `maxminddb:\"longitude\"`\n\t\tLatitude float64 `maxminddb:\"latitude\"`\n\t} `maxminddb:\"location\"`\n\tCity struct {\n\t\tNames map[string]string `maxminddb:\"names\"`\n\t} `maxminddb:\"city\"`\n\tCountry struct {\n\t\tIsoCode string `maxminddb:\"iso_code\"`\n\t\tNames map[string]string `maxminddb:\"names\"`\n\t} `maxminddb:\"country\"`\n}\n\nfunc init() {\n\t\/\/ download database\n\tpath := \"\/tmp\/GeoLite2-City.mmdb\"\n\n\t_, err := os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\tfmt.Println(\"Downloading database\")\n\n\t\tclient := &http.Client{}\n\n\t\treq, err := http.NewRequest(\"GET\", geoLiteURL, nil)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tvar resp *http.Response\n\t\tif resp, err = client.Do(req); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\n\t\tgzf, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer gzf.Close()\n\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tdefer f.Close()\n\n\t\t_, err = io.Copy(f, gzf)\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 verbose {\n\t\tfmt.Printf(\"Using database %s.\\n\", path)\n\t}\n\n\treader, err = maxminddb.Open(path)\n}\n\nfunc help() {\n\tfmt.Println(\"No ip addresses\")\n}\n\nfunc update() error {\n\treturn nil\n}\n\nconst geoLiteURL = \"http:\/\/geolite.maxmind.com\/download\/geoip\/database\/GeoLite2-City.mmdb.gz\"\n\nfunc main() {\n\t\/\/ initial download\n\t\/\/ update\n\t\/\/ open from cache\n\t\/\/ resolve\n\n\tflag.StringVar(&format, \"format\", \"(country) ((city))\", \"format\")\n\tflag.BoolVar(&verbose, \"verbose\", false, \"verbose\")\n\tflag.Parse()\n\n\tfi, err := os.Stdin.Stat()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar args = flag.Args()\n\n\tif fi.Mode()&os.ModeNamedPipe > 0 {\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\n\t\tfor scanner.Scan() {\n\t\t\targs = append(args, scanner.Text())\n\t\t}\n\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif len(args) == 0 {\n\t\thelp()\n\t\tos.Exit(1)\n\t}\n\n\tfor _, arg := range args {\n\t\tvar addr net.IP\n\t\taddr = net.ParseIP(arg)\n\t\tif addr == nil {\n\t\t\tfmt.Printf(\"%s is not a valid ip address\", addr)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result geoIPResult\n\n\t\tvar err error\n\t\tif err = reader.Lookup(addr, &result); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tvar p string\n\t\tp = format\n\t\tp = strings.Replace(p, \"(ip)\", addr.String(), -1)\n\t\tp = strings.Replace(p, \"(country)\", result.Country.Names[\"en\"], -1)\n\t\tp = strings.Replace(p, \"(city)\", result.City.Names[\"en\"], -1)\n\t\tp = strings.Replace(p, \"(lat)\", fmt.Sprintf(\"%f\", result.Location.Latitude), -1)\n\t\tp = strings.Replace(p, \"(long)\", fmt.Sprintf(\"%f\", result.Location.Longitude), -1)\n\n\t\tfmt.Print(p)\n\t}\n}\nadded newline support in formatpackage main\n\nimport (\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/oschwald\/maxminddb-golang\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar reader *maxminddb.Reader\nvar verbose bool\nvar format string\n\ntype geoIPResult struct {\n\tLocation struct {\n\t\tLongitude float64 `maxminddb:\"longitude\"`\n\t\tLatitude float64 `maxminddb:\"latitude\"`\n\t} `maxminddb:\"location\"`\n\tCity struct {\n\t\tNames map[string]string `maxminddb:\"names\"`\n\t} `maxminddb:\"city\"`\n\tCountry struct {\n\t\tIsoCode string `maxminddb:\"iso_code\"`\n\t\tNames map[string]string `maxminddb:\"names\"`\n\t} `maxminddb:\"country\"`\n}\n\nfunc init() {\n\t\/\/ download database\n\tpath := \"\/tmp\/GeoLite2-City.mmdb\"\n\n\t_, err := os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\tfmt.Println(\"Downloading database\")\n\n\t\tclient := &http.Client{}\n\n\t\treq, err := http.NewRequest(\"GET\", geoLiteURL, nil)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tvar resp *http.Response\n\t\tif resp, err = client.Do(req); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\n\t\tgzf, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer gzf.Close()\n\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tdefer f.Close()\n\n\t\t_, err = io.Copy(f, gzf)\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 verbose {\n\t\tfmt.Printf(\"Using database %s.\\n\", path)\n\t}\n\n\treader, err = maxminddb.Open(path)\n}\n\nfunc help() {\n\tfmt.Println(\"No ip addresses\")\n}\n\nfunc update() error {\n\treturn nil\n}\n\nconst geoLiteURL = \"http:\/\/geolite.maxmind.com\/download\/geoip\/database\/GeoLite2-City.mmdb.gz\"\n\nfunc main() {\n\t\/\/ initial download\n\t\/\/ update\n\t\/\/ open from cache\n\t\/\/ resolve\n\n\tflag.StringVar(&format, \"format\", \"(country) ((city))\", \"format\")\n\tflag.BoolVar(&verbose, \"verbose\", false, \"verbose\")\n\tflag.Parse()\n\n\tformat = strings.Replace(format, \"\\\\n\", \"\\n\", -1)\n\n\tfi, err := os.Stdin.Stat()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar args = flag.Args()\n\n\tif fi.Mode()&os.ModeNamedPipe > 0 {\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\n\t\tfor scanner.Scan() {\n\t\t\targs = append(args, scanner.Text())\n\t\t}\n\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif len(args) == 0 {\n\t\thelp()\n\t\tos.Exit(1)\n\t}\n\n\tfor _, arg := range args {\n\t\tvar addr net.IP\n\t\taddr = net.ParseIP(arg)\n\t\tif addr == nil {\n\t\t\tfmt.Printf(\"%s is not a valid ip address\", addr)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result geoIPResult\n\n\t\tvar err error\n\t\tif err = reader.Lookup(addr, &result); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tvar p string\n\t\tp = format\n\t\tp = strings.Replace(p, \"(ip)\", addr.String(), -1)\n\t\tp = strings.Replace(p, \"(country)\", result.Country.Names[\"en\"], -1)\n\t\tp = strings.Replace(p, \"(city)\", result.City.Names[\"en\"], -1)\n\t\tp = strings.Replace(p, \"(lat)\", fmt.Sprintf(\"%f\", result.Location.Latitude), -1)\n\t\tp = strings.Replace(p, \"(long)\", fmt.Sprintf(\"%f\", result.Location.Longitude), -1)\n\n\t\tfmt.Print(p)\n\t}\n}\n<|endoftext|>"} {"text":"package meetup\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tfakeTimeMu sync.Mutex\n\tfakeTime = time.Now()\n)\n\nfunc init() {\n\tnow = func() time.Time {\n\t\tfakeTimeMu.Lock()\n\t\tt := fakeTime\n\t\tfakeTimeMu.Unlock()\n\t\treturn t\n\t}\n}\n\nfunc advanceTime(d time.Duration) {\n\tfakeTimeMu.Lock()\n\tfakeTime = fakeTime.Add(d)\n\tfakeTimeMu.Unlock()\n}\n\nfunc mustGet(t *testing.T, c *Cache, key string, want interface{}) {\n\tv, err := c.Get(key)\n\tif err != nil {\n\t\tt.Errorf(\"Get(%#v) returned unexpected error %v\", key, err)\n\t}\n\tif !reflect.DeepEqual(v, want) {\n\t\tt.Errorf(\"Get(%#v) = %#v, but wanted %#v\", key, v, want)\n\t}\n}\n\nfunc TestCache(t *testing.T) {\n\thits := 0\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\thits++\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tif hits != 0 {\n\t\tt.Fatalf(\"hits != 0 after init\")\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits != 1 after first use\")\n\t}\n\n\tmustGet(t, c, \"b\", \"b\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after second use\", hits)\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits != 2 after third use\")\n\t}\n}\n\nfunc TestExpiry(t *testing.T) {\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn key, nil\n\t\t},\n\t\tExpireAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits = %v after first use\", hits)\n\t}\n\tmu.Unlock()\n\n\tadvanceTime(2 * time.Second)\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits != 2 after second use\")\n\t}\n\tmu.Unlock()\n\n\tadvanceTime(time.Second \/ 2)\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after third use\", hits)\n\t}\n\tmu.Unlock()\n}\n\nfunc TestExpiryUsesStartTime(t *testing.T) {\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tadvanceTime(time.Second)\n\t\t\thits++\n\t\t\treturn key, nil\n\t\t},\n\t\tExpireAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits != 1 after first use\")\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after second use\", hits)\n\t}\n}\n\nfunc TestMeetup(t *testing.T) {\n\tpostGetCheckCh = make(chan struct{})\n\tdefer func() { postGetCheckCh = nil }()\n\n\tconst concurrency = 1000\n\n\tblockGets := newBoolWatcher(true)\n\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tblockGets.Wait(false)\n\n\t\t\tmu.Lock()\n\t\t\tc := hits\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn c, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tvals := make(chan interface{})\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tv, err := c.Get(\"a\")\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(`c.Get(\"a\") returned error %v`, err)\n\t\t\t}\n\t\t\tvals <- v\n\t\t}()\n\t}\n\n\tfor i := 0; i < concurrency; i++ {\n\t\t<-postGetCheckCh\n\t}\n\n\tblockGets.Set(false)\n\n\tfor i := 0; i < concurrency; i++ {\n\t\tv := <-vals\n\t\tif !reflect.DeepEqual(v, 0) {\n\t\t\tt.Errorf(\"Cache did not meet up. Wanted value %v, got %v\", 0, v)\n\t\t}\n\t}\n}\n\nfunc TestConcurrencyLimit(t *testing.T) {\n\tblockGets := newBoolWatcher(true)\n\n\tconst (\n\t\tworkers = 1000\n\t\tlimit = 3\n\t)\n\n\tvar mu sync.Mutex\n\tconc := 0\n\tmaxConc := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\tconc++\n\t\t\tif conc > maxConc {\n\t\t\t\tmaxConc = conc\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\tblockGets.Wait(false)\n\n\t\t\tmu.Lock()\n\t\t\tconc--\n\t\t\tmu.Unlock()\n\n\t\t\treturn key, nil\n\t\t},\n\t\tConcurrency: limit,\n\t})\n\tdefer c.Close()\n\n\tvals := make(chan interface{})\n\n\tfor i := 0; i < workers; i++ {\n\t\tgo func(i int) {\n\t\t\tk := strconv.FormatInt(int64(i), 10)\n\t\t\tv, _ := c.Get(k)\n\t\t\tvals <- v\n\t\t}(i)\n\t}\n\n\tblockGets.Set(false)\n\n\tfor i := 0; i < workers; i++ {\n\t\t<-vals\n\t}\n\n\tif conc != 0 {\n\t\tt.Errorf(\"Options.Get still running after Cache.Get returned\")\n\t}\n\n\tt.Logf(\"max concurrency seen was %v\", maxConc)\n\tif maxConc > limit {\n\t\tt.Errorf(\"max concurrency of %v is over limit %v\", maxConc, limit)\n\t}\n}\n\nfunc TestCacheDoesntKeepErrors(t *testing.T) {\n\tdeliberateErr := errors.New(\"deliberate failure\")\n\n\thits := 0\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\thits++\n\t\t\treturn nil, deliberateErr\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tv, err := c.Get(\"a\")\n\tif v != nil {\n\t\tt.Errorf(\"Got unexpected value %#v from c.Get\", v)\n\t}\n\tif err != deliberateErr {\n\t\tt.Errorf(\"Got unexpected error %v from c.Get\", err)\n\t}\n\n\tv, err = c.Get(\"a\")\n\tif v != nil {\n\t\tt.Errorf(\"Got unexpected value %#v from c.Get\", v)\n\t}\n\tif err != deliberateErr {\n\t\tt.Errorf(\"Got unexpected error %v from c.Get\", err)\n\t}\n\n\tif hits != 2 {\n\t\tt.Errorf(\"Hits was %v, not 2\", hits)\n\t}\n}\n\nfunc TestRevalidation(t *testing.T) {\n\tfillComplete = make(chan struct{})\n\tdefer func() { fillComplete = nil }()\n\n\tblockGets := newBoolWatcher(false)\n\tvar getReadyToBlock chan struct{}\n\n\tvar mu sync.Mutex\n\thits := 0\n\tfinished := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmyHits := hits\n\t\t\tmu.Unlock()\n\t\t\tif getReadyToBlock != nil {\n\t\t\t\tgetReadyToBlock <- struct{}{}\n\t\t\t}\n\t\t\tblockGets.Wait(false)\n\t\t\tmu.Lock()\n\t\t\tfinished++\n\t\t\tmu.Unlock()\n\t\t\treturn myHits, nil\n\t\t},\n\t\tRevalidateAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", 1)\n\t<-fillComplete\n\tif hits != 1 {\n\t\tt.Errorf(\"hits != 1\")\n\t}\n\n\tblockGets.Set(true)\n\tadvanceTime(time.Second)\n\n\tgetReadyToBlock = make(chan struct{}, 1)\n\tmustGet(t, c, \"a\", 1) \/\/ NB: does not block with background revalidation\n\t<-getReadyToBlock\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Errorf(\"hits = %v, wanted 2\", hits)\n\t}\n\tif finished != 1 {\n\t\tt.Errorf(\"finished != 1\")\n\t}\n\tmu.Unlock()\n\n\tblockGets.Set(false)\n\t<-fillComplete\n\n\tgetReadyToBlock = nil\n\tmustGet(t, c, \"a\", 2)\n}\n\nfunc TestErrorCaching(t *testing.T) {\n\tdeliberate := errors.New(\"deliberate failure\")\n\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn nil, deliberate\n\t\t},\n\t\tErrorAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\t_, err := c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\t_, err = c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\tif hits != 1 {\n\t\tt.Errorf(\"error was not cached\")\n\t}\n\n\tadvanceTime(time.Second)\n\n\tdeliberate = errors.New(\"other deliberate failure\")\n\t_, err = c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\tif hits != 2 {\n\t\tt.Errorf(\"hits = %v\", hits)\n\t}\n}\n\nfunc TestClosedGet(t *testing.T) {\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tc.Close()\n\n\t_, err := c.Get(\"a\")\n\tif err != ErrClosed {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n}\n\nfunc TestGetMeetupCreateRace(t *testing.T) {\n\t\/\/ This test tries to maximize the likelihood of the read lock to write lock\n\t\/\/ transition in Cache.Get noticing that the entry has already been created\n\t\/\/ even though it already transitioned to a write lock.\n\t\/\/\n\t\/\/ By having multiple workers requesting the same key, then changing that\n\t\/\/ key relatively slowly over time, we should see exactly as many hits as\n\t\/\/ keys, and we should never deadlock.\n\n\tvar hits uint64\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tatomic.AddUint64(&hits, 1)\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tvar keyInt uint64 = 1\n\n\tdone := make(chan struct{})\n\tfor worker := 0; worker < 5; worker++ {\n\t\tgo func() {\n\t\t\tfor i := 0; i < 1000; i++ {\n\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\tc.Get(strconv.FormatUint(atomic.LoadUint64(&keyInt), 10))\n\t\t\t\t}\n\n\t\t\t\tnewKeyInt := atomic.AddUint64(&keyInt, 1)\n\t\t\t\tc.Get(strconv.FormatUint(newKeyInt, 10))\n\t\t\t}\n\t\t\tdone <- struct{}{}\n\t\t}()\n\t}\n\n\tfor worker := 0; worker < 5; worker++ {\n\t\t<-done\n\t}\n\n\tgotHits := atomic.LoadUint64(&hits)\n\tgotKeys := atomic.LoadUint64(&keyInt)\n\n\tif gotHits != gotKeys {\n\t\tt.Errorf(\"made %v keys, but got %v hits\", gotKeys, gotHits)\n\t}\n\n\tt.Logf(\"key at end was %s\", gotKeys)\n}\nmake TestGetMeetupCreateRace more customizable and slightly stricterpackage meetup\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tfakeTimeMu sync.Mutex\n\tfakeTime = time.Now()\n)\n\nfunc init() {\n\tnow = func() time.Time {\n\t\tfakeTimeMu.Lock()\n\t\tt := fakeTime\n\t\tfakeTimeMu.Unlock()\n\t\treturn t\n\t}\n}\n\nfunc advanceTime(d time.Duration) {\n\tfakeTimeMu.Lock()\n\tfakeTime = fakeTime.Add(d)\n\tfakeTimeMu.Unlock()\n}\n\nfunc mustGet(t *testing.T, c *Cache, key string, want interface{}) {\n\tv, err := c.Get(key)\n\tif err != nil {\n\t\tt.Errorf(\"Get(%#v) returned unexpected error %v\", key, err)\n\t}\n\tif !reflect.DeepEqual(v, want) {\n\t\tt.Errorf(\"Get(%#v) = %#v, but wanted %#v\", key, v, want)\n\t}\n}\n\nfunc TestCache(t *testing.T) {\n\thits := 0\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\thits++\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tif hits != 0 {\n\t\tt.Fatalf(\"hits != 0 after init\")\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits != 1 after first use\")\n\t}\n\n\tmustGet(t, c, \"b\", \"b\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after second use\", hits)\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits != 2 after third use\")\n\t}\n}\n\nfunc TestExpiry(t *testing.T) {\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn key, nil\n\t\t},\n\t\tExpireAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits = %v after first use\", hits)\n\t}\n\tmu.Unlock()\n\n\tadvanceTime(2 * time.Second)\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits != 2 after second use\")\n\t}\n\tmu.Unlock()\n\n\tadvanceTime(time.Second \/ 2)\n\n\tmustGet(t, c, \"a\", \"a\")\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after third use\", hits)\n\t}\n\tmu.Unlock()\n}\n\nfunc TestExpiryUsesStartTime(t *testing.T) {\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tadvanceTime(time.Second)\n\t\t\thits++\n\t\t\treturn key, nil\n\t\t},\n\t\tExpireAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 1 {\n\t\tt.Fatalf(\"hits != 1 after first use\")\n\t}\n\n\tmustGet(t, c, \"a\", \"a\")\n\tif hits != 2 {\n\t\tt.Fatalf(\"hits = %v after second use\", hits)\n\t}\n}\n\nfunc TestMeetup(t *testing.T) {\n\tpostGetCheckCh = make(chan struct{})\n\tdefer func() { postGetCheckCh = nil }()\n\n\tconst concurrency = 1000\n\n\tblockGets := newBoolWatcher(true)\n\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tblockGets.Wait(false)\n\n\t\t\tmu.Lock()\n\t\t\tc := hits\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn c, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tvals := make(chan interface{})\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tv, err := c.Get(\"a\")\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(`c.Get(\"a\") returned error %v`, err)\n\t\t\t}\n\t\t\tvals <- v\n\t\t}()\n\t}\n\n\tfor i := 0; i < concurrency; i++ {\n\t\t<-postGetCheckCh\n\t}\n\n\tblockGets.Set(false)\n\n\tfor i := 0; i < concurrency; i++ {\n\t\tv := <-vals\n\t\tif !reflect.DeepEqual(v, 0) {\n\t\t\tt.Errorf(\"Cache did not meet up. Wanted value %v, got %v\", 0, v)\n\t\t}\n\t}\n}\n\nfunc TestConcurrencyLimit(t *testing.T) {\n\tblockGets := newBoolWatcher(true)\n\n\tconst (\n\t\tworkers = 1000\n\t\tlimit = 3\n\t)\n\n\tvar mu sync.Mutex\n\tconc := 0\n\tmaxConc := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\tconc++\n\t\t\tif conc > maxConc {\n\t\t\t\tmaxConc = conc\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\tblockGets.Wait(false)\n\n\t\t\tmu.Lock()\n\t\t\tconc--\n\t\t\tmu.Unlock()\n\n\t\t\treturn key, nil\n\t\t},\n\t\tConcurrency: limit,\n\t})\n\tdefer c.Close()\n\n\tvals := make(chan interface{})\n\n\tfor i := 0; i < workers; i++ {\n\t\tgo func(i int) {\n\t\t\tk := strconv.FormatInt(int64(i), 10)\n\t\t\tv, _ := c.Get(k)\n\t\t\tvals <- v\n\t\t}(i)\n\t}\n\n\tblockGets.Set(false)\n\n\tfor i := 0; i < workers; i++ {\n\t\t<-vals\n\t}\n\n\tif conc != 0 {\n\t\tt.Errorf(\"Options.Get still running after Cache.Get returned\")\n\t}\n\n\tt.Logf(\"max concurrency seen was %v\", maxConc)\n\tif maxConc > limit {\n\t\tt.Errorf(\"max concurrency of %v is over limit %v\", maxConc, limit)\n\t}\n}\n\nfunc TestCacheDoesntKeepErrors(t *testing.T) {\n\tdeliberateErr := errors.New(\"deliberate failure\")\n\n\thits := 0\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\thits++\n\t\t\treturn nil, deliberateErr\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tv, err := c.Get(\"a\")\n\tif v != nil {\n\t\tt.Errorf(\"Got unexpected value %#v from c.Get\", v)\n\t}\n\tif err != deliberateErr {\n\t\tt.Errorf(\"Got unexpected error %v from c.Get\", err)\n\t}\n\n\tv, err = c.Get(\"a\")\n\tif v != nil {\n\t\tt.Errorf(\"Got unexpected value %#v from c.Get\", v)\n\t}\n\tif err != deliberateErr {\n\t\tt.Errorf(\"Got unexpected error %v from c.Get\", err)\n\t}\n\n\tif hits != 2 {\n\t\tt.Errorf(\"Hits was %v, not 2\", hits)\n\t}\n}\n\nfunc TestRevalidation(t *testing.T) {\n\tfillComplete = make(chan struct{})\n\tdefer func() { fillComplete = nil }()\n\n\tblockGets := newBoolWatcher(false)\n\tvar getReadyToBlock chan struct{}\n\n\tvar mu sync.Mutex\n\thits := 0\n\tfinished := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmyHits := hits\n\t\t\tmu.Unlock()\n\t\t\tif getReadyToBlock != nil {\n\t\t\t\tgetReadyToBlock <- struct{}{}\n\t\t\t}\n\t\t\tblockGets.Wait(false)\n\t\t\tmu.Lock()\n\t\t\tfinished++\n\t\t\tmu.Unlock()\n\t\t\treturn myHits, nil\n\t\t},\n\t\tRevalidateAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\tmustGet(t, c, \"a\", 1)\n\t<-fillComplete\n\tif hits != 1 {\n\t\tt.Errorf(\"hits != 1\")\n\t}\n\n\tblockGets.Set(true)\n\tadvanceTime(time.Second)\n\n\tgetReadyToBlock = make(chan struct{}, 1)\n\tmustGet(t, c, \"a\", 1) \/\/ NB: does not block with background revalidation\n\t<-getReadyToBlock\n\tmu.Lock()\n\tif hits != 2 {\n\t\tt.Errorf(\"hits = %v, wanted 2\", hits)\n\t}\n\tif finished != 1 {\n\t\tt.Errorf(\"finished != 1\")\n\t}\n\tmu.Unlock()\n\n\tblockGets.Set(false)\n\t<-fillComplete\n\n\tgetReadyToBlock = nil\n\tmustGet(t, c, \"a\", 2)\n}\n\nfunc TestErrorCaching(t *testing.T) {\n\tdeliberate := errors.New(\"deliberate failure\")\n\n\tvar mu sync.Mutex\n\thits := 0\n\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tmu.Lock()\n\t\t\thits++\n\t\t\tmu.Unlock()\n\t\t\treturn nil, deliberate\n\t\t},\n\t\tErrorAge: time.Second,\n\t})\n\tdefer c.Close()\n\n\t_, err := c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\t_, err = c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\tif hits != 1 {\n\t\tt.Errorf(\"error was not cached\")\n\t}\n\n\tadvanceTime(time.Second)\n\n\tdeliberate = errors.New(\"other deliberate failure\")\n\t_, err = c.Get(\"a\")\n\tif err != deliberate {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n\n\tif hits != 2 {\n\t\tt.Errorf(\"hits = %v\", hits)\n\t}\n}\n\nfunc TestClosedGet(t *testing.T) {\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tc.Close()\n\n\t_, err := c.Get(\"a\")\n\tif err != ErrClosed {\n\t\tt.Errorf(\"Got unexpected error %v from Get\", err)\n\t}\n}\n\nfunc TestGetMeetupCreateRace(t *testing.T) {\n\t\/\/ This test tries to maximize the likelihood of the read lock to write lock\n\t\/\/ transition in Cache.Get noticing that the entry has already been created\n\t\/\/ even though it already transitioned to a write lock.\n\t\/\/\n\t\/\/ By having multiple workers requesting the same key, then changing that\n\t\/\/ key relatively slowly over time, we should see exactly as many hits as\n\t\/\/ keys, and we should never deadlock.\n\n\tconst (\n\t\tworkers = 5\n\t\titerations = 1000\n\t\textraGetsPerKey = 2 * workers\n\t)\n\n\tvar hits uint64\n\tc := NewCache(Options{\n\t\tGet: func(key string) (interface{}, error) {\n\t\t\tatomic.AddUint64(&hits, 1)\n\t\t\treturn key, nil\n\t\t},\n\t})\n\tdefer c.Close()\n\n\tvar keyInt uint64 = 1\n\n\tdone := make(chan struct{})\n\tfor worker := 0; worker < workers; worker++ {\n\t\tgo func() {\n\t\t\tfor i := 0; i < iterations; i++ {\n\t\t\t\tfor i := 0; i < extraGetsPerKey; i++ {\n\t\t\t\t\tc.Get(strconv.FormatUint(atomic.LoadUint64(&keyInt), 10))\n\t\t\t\t}\n\n\t\t\t\tnewKeyInt := atomic.AddUint64(&keyInt, 1)\n\t\t\t\tc.Get(strconv.FormatUint(newKeyInt, 10))\n\t\t\t}\n\t\t\tdone <- struct{}{}\n\t\t}()\n\t}\n\n\tfor worker := 0; worker < workers; worker++ {\n\t\t<-done\n\t}\n\n\tgotHits := atomic.LoadUint64(&hits)\n\tgotKeys := atomic.LoadUint64(&keyInt)\n\n\tif gotHits != gotKeys {\n\t\tt.Errorf(\"made %v keys, but got %v hits\", gotKeys, gotHits)\n\t}\n\n\tif gotKeys != iterations*workers+1 {\n\t\tt.Errorf(\"created %v keys but wanted %v\", gotKeys, iterations*workers+1)\n\t}\n\n\tt.Logf(\"key at end was %v\", gotKeys)\n}\n<|endoftext|>"} {"text":"package obj\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\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\/aws\/credentials\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/storagegateway\"\n\t\"github.com\/cenkalti\/backoff\"\n\t\"go.pedge.io\/lion\"\n)\n\ntype amazonClient struct {\n\tbucket string\n\tdistribution string\n\ts3 *s3.S3\n\tuploader *s3manager.Uploader\n}\n\nfunc newAmazonClient(bucket string, distribution string, id string, secret string, token string, region string) (*amazonClient, error) {\n\tsession := session.New(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, token),\n\t\tRegion: aws.String(region),\n\t})\n\treturn &amazonClient{\n\t\tbucket: bucket,\n\t\tdistribution: strings.TrimSpace(distribution),\n\t\ts3: s3.New(session),\n\t\tuploader: s3manager.NewUploader(session),\n\t}, nil\n}\n\nfunc (c *amazonClient) Writer(name string) (io.WriteCloser, error) {\n\treturn newBackoffWriteCloser(c, newWriter(c, name)), nil\n}\n\nfunc (c *amazonClient) Walk(name string, fn func(name string) error) error {\n\tvar fnErr error\n\tif err := c.s3.ListObjectsPages(\n\t\t&s3.ListObjectsInput{\n\t\t\tBucket: aws.String(c.bucket),\n\t\t\tPrefix: aws.String(name),\n\t\t},\n\t\tfunc(listObjectsOutput *s3.ListObjectsOutput, lastPage bool) bool {\n\t\t\tfor _, object := range listObjectsOutput.Contents {\n\t\t\t\tif err := fn(*object.Key); err != nil {\n\t\t\t\t\tfnErr = err\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t); err != nil {\n\t\treturn err\n\t}\n\treturn fnErr\n}\n\nfunc (c *amazonClient) Reader(name string, offset uint64, size uint64) (io.ReadCloser, error) {\n\tbyteRange := byteRange(offset, size)\n\tif byteRange != \"\" {\n\t\tbyteRange = fmt.Sprintf(\"bytes=%s\", byteRange)\n\t}\n\n\tvar reader io.ReadCloser\n\tif c.distribution != \"\" {\n\t\tvar resp *http.Response\n\t\tvar connErr error\n\t\turl := fmt.Sprintf(\"http:\/\/%v.cloudfront.net\/%v\", c.distribution, name)\n\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Header.Add(\"Range\", byteRange)\n\n\t\tbackoff.RetryNotify(func() error {\n\t\t\tresp, connErr = http.DefaultClient.Do(req)\n\t\t\tif connErr != nil && isNetRetryable(connErr) {\n\t\t\t\treturn connErr\n\t\t\t}\n\t\t\treturn nil\n\t\t}, backoff.NewExponentialBackOff(), func(err error, d time.Duration) {\n\t\t\tlion.Infof(\"Error connecting to (%v); retrying in %s: %#v\", url, d, err)\n\t\t})\n\t\tif connErr != nil {\n\t\t\treturn nil, connErr\n\t\t}\n\t\tif resp.StatusCode >= 300 {\n\t\t\t\/\/ Cloudfront returns 200s, and 206s as success codes\n\t\t\treturn nil, fmt.Errorf(\"cloudfront returned HTTP error code %v\", resp.StatusCode)\n\t\t}\n\t\treader = resp.Body\n\t} else {\n\t\tgetObjectOutput, err := c.s3.GetObject(&s3.GetObjectInput{\n\t\t\tBucket: aws.String(c.bucket),\n\t\t\tKey: aws.String(name),\n\t\t\tRange: aws.String(byteRange),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treader = getObjectOutput.Body\n\t}\n\treturn newBackoffReadCloser(c, reader), nil\n}\n\nfunc (c *amazonClient) Delete(name string) error {\n\t_, err := c.s3.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t})\n\treturn err\n}\n\nfunc (c *amazonClient) Exists(name string) bool {\n\t_, err := c.s3.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t})\n\treturn err == nil\n}\n\nfunc (c *amazonClient) isRetryable(err error) (retVal bool) {\n\tif strings.Contains(err.Error(), \"unexpected EOF\") {\n\t\treturn true\n\t}\n\n\tawsErr, ok := err.(awserr.Error)\n\tif !ok {\n\t\treturn false\n\t}\n\tfor _, c := range []string{\n\t\tstoragegateway.ErrorCodeServiceUnavailable,\n\t\tstoragegateway.ErrorCodeInternalError,\n\t\tstoragegateway.ErrorCodeGatewayInternalError,\n\t} {\n\t\tif c == awsErr.Code() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (c *amazonClient) IsIgnorable(err error) bool {\n\treturn false\n}\n\nfunc (c *amazonClient) IsNotExist(err error) bool {\n\tif c.distribution != \"\" {\n\t\t\/\/ cloudfront returns forbidden error for nonexisting data\n\t\tif strings.Contains(err.Error(), \"error code 403\") {\n\t\t\treturn true\n\t\t}\n\t}\n\tawsErr, ok := err.(awserr.Error)\n\tif !ok {\n\t\treturn false\n\t}\n\tif awsErr.Code() == \"NoSuchKey\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype amazonWriter struct {\n\terrChan chan error\n\tpipe *io.PipeWriter\n}\n\nfunc newWriter(client *amazonClient, name string) *amazonWriter {\n\treader, writer := io.Pipe()\n\tw := &amazonWriter{\n\t\terrChan: make(chan error),\n\t\tpipe: writer,\n\t}\n\tgo func() {\n\t\t_, err := client.uploader.Upload(&s3manager.UploadInput{\n\t\t\tBody: reader,\n\t\t\tBucket: aws.String(client.bucket),\n\t\t\tKey: aws.String(name),\n\t\t\tContentEncoding: aws.String(\"application\/octet-stream\"),\n\t\t})\n\t\tw.errChan <- err\n\t}()\n\treturn w\n}\n\nfunc (w *amazonWriter) Write(p []byte) (int, error) {\n\treturn w.pipe.Write(p)\n}\n\nfunc (w *amazonWriter) Close() error {\n\tif err := w.pipe.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn <-w.errChan\n}\nReport more info when cloudfront errspackage obj\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\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\/aws\/credentials\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/storagegateway\"\n\t\"github.com\/cenkalti\/backoff\"\n\t\"go.pedge.io\/lion\"\n)\n\ntype amazonClient struct {\n\tbucket string\n\tdistribution string\n\ts3 *s3.S3\n\tuploader *s3manager.Uploader\n}\n\nfunc newAmazonClient(bucket string, distribution string, id string, secret string, token string, region string) (*amazonClient, error) {\n\tsession := session.New(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(id, secret, token),\n\t\tRegion: aws.String(region),\n\t})\n\treturn &amazonClient{\n\t\tbucket: bucket,\n\t\tdistribution: strings.TrimSpace(distribution),\n\t\ts3: s3.New(session),\n\t\tuploader: s3manager.NewUploader(session),\n\t}, nil\n}\n\nfunc (c *amazonClient) Writer(name string) (io.WriteCloser, error) {\n\treturn newBackoffWriteCloser(c, newWriter(c, name)), nil\n}\n\nfunc (c *amazonClient) Walk(name string, fn func(name string) error) error {\n\tvar fnErr error\n\tif err := c.s3.ListObjectsPages(\n\t\t&s3.ListObjectsInput{\n\t\t\tBucket: aws.String(c.bucket),\n\t\t\tPrefix: aws.String(name),\n\t\t},\n\t\tfunc(listObjectsOutput *s3.ListObjectsOutput, lastPage bool) bool {\n\t\t\tfor _, object := range listObjectsOutput.Contents {\n\t\t\t\tif err := fn(*object.Key); err != nil {\n\t\t\t\t\tfnErr = err\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t); err != nil {\n\t\treturn err\n\t}\n\treturn fnErr\n}\n\nfunc (c *amazonClient) Reader(name string, offset uint64, size uint64) (io.ReadCloser, error) {\n\tbyteRange := byteRange(offset, size)\n\tif byteRange != \"\" {\n\t\tbyteRange = fmt.Sprintf(\"bytes=%s\", byteRange)\n\t}\n\n\tvar reader io.ReadCloser\n\tif c.distribution != \"\" {\n\t\tvar resp *http.Response\n\t\tvar connErr error\n\t\turl := fmt.Sprintf(\"http:\/\/%v.cloudfront.net\/%v\", c.distribution, name)\n\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Header.Add(\"Range\", byteRange)\n\n\t\tbackoff.RetryNotify(func() error {\n\t\t\tresp, connErr = http.DefaultClient.Do(req)\n\t\t\tif connErr != nil && isNetRetryable(connErr) {\n\t\t\t\treturn connErr\n\t\t\t}\n\t\t\treturn nil\n\t\t}, backoff.NewExponentialBackOff(), func(err error, d time.Duration) {\n\t\t\tlion.Infof(\"Error connecting to (%v); retrying in %s: %#v\", url, d, err)\n\t\t})\n\t\tif connErr != nil {\n\t\t\treturn nil, connErr\n\t\t}\n\t\tif resp.StatusCode >= 300 {\n\t\t\t\/\/ Cloudfront returns 200s, and 206s as success codes\n\t\t\treturn nil, fmt.Errorf(\"cloudfront returned HTTP error code %v for url %v\", resp.Status, url)\n\t\t}\n\t\treader = resp.Body\n\t} else {\n\t\tgetObjectOutput, err := c.s3.GetObject(&s3.GetObjectInput{\n\t\t\tBucket: aws.String(c.bucket),\n\t\t\tKey: aws.String(name),\n\t\t\tRange: aws.String(byteRange),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treader = getObjectOutput.Body\n\t}\n\treturn newBackoffReadCloser(c, reader), nil\n}\n\nfunc (c *amazonClient) Delete(name string) error {\n\t_, err := c.s3.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t})\n\treturn err\n}\n\nfunc (c *amazonClient) Exists(name string) bool {\n\t_, err := c.s3.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t})\n\treturn err == nil\n}\n\nfunc (c *amazonClient) isRetryable(err error) (retVal bool) {\n\tif strings.Contains(err.Error(), \"unexpected EOF\") {\n\t\treturn true\n\t}\n\n\tawsErr, ok := err.(awserr.Error)\n\tif !ok {\n\t\treturn false\n\t}\n\tfor _, c := range []string{\n\t\tstoragegateway.ErrorCodeServiceUnavailable,\n\t\tstoragegateway.ErrorCodeInternalError,\n\t\tstoragegateway.ErrorCodeGatewayInternalError,\n\t} {\n\t\tif c == awsErr.Code() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (c *amazonClient) IsIgnorable(err error) bool {\n\treturn false\n}\n\nfunc (c *amazonClient) IsNotExist(err error) bool {\n\tif c.distribution != \"\" {\n\t\t\/\/ cloudfront returns forbidden error for nonexisting data\n\t\tif strings.Contains(err.Error(), \"error code 403\") {\n\t\t\treturn true\n\t\t}\n\t}\n\tawsErr, ok := err.(awserr.Error)\n\tif !ok {\n\t\treturn false\n\t}\n\tif awsErr.Code() == \"NoSuchKey\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype amazonWriter struct {\n\terrChan chan error\n\tpipe *io.PipeWriter\n}\n\nfunc newWriter(client *amazonClient, name string) *amazonWriter {\n\treader, writer := io.Pipe()\n\tw := &amazonWriter{\n\t\terrChan: make(chan error),\n\t\tpipe: writer,\n\t}\n\tgo func() {\n\t\t_, err := client.uploader.Upload(&s3manager.UploadInput{\n\t\t\tBody: reader,\n\t\t\tBucket: aws.String(client.bucket),\n\t\t\tKey: aws.String(name),\n\t\t\tContentEncoding: aws.String(\"application\/octet-stream\"),\n\t\t})\n\t\tw.errChan <- err\n\t}()\n\treturn w\n}\n\nfunc (w *amazonWriter) Write(p []byte) (int, error) {\n\treturn w.pipe.Write(p)\n}\n\nfunc (w *amazonWriter) Close() error {\n\tif err := w.pipe.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn <-w.errChan\n}\n<|endoftext|>"} {"text":"package quantity\n\nimport (\n\t\"errors\"\n\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/config\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/system\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/uncertainty\"\n\n\tinterpolation \"github.com\/ready-steady\/adapt\/algorithm\"\n)\n\ntype Quantity interface {\n\tDimensions() (uint, uint)\n\tCompute([]float64, []float64)\n\n\tEvaluate([]float64) float64\n\tForward([]float64) []float64\n\tBackward([]float64) []float64\n}\n\nfunc New(system *system.System, uncertainty uncertainty.Uncertainty,\n\tconfig *config.Quantity) (Quantity, error) {\n\n\tswitch config.Name {\n\tcase \"end-to-end-delay\":\n\t\treturn newDelay(system, uncertainty, config)\n\tcase \"total-energy\":\n\t\treturn newEnergy(system, uncertainty, config)\n\tcase \"maximum-temperature\":\n\t\treturn newTemperature(system, uncertainty, config)\n\tdefault:\n\t\treturn nil, errors.New(\"the quantity is unknown\")\n\t}\n}\n\nfunc Invoke(quantity Quantity, points []float64) []float64 {\n\tni, no := quantity.Dimensions()\n\treturn interpolation.Invoke(quantity.Compute, points, ni, no)\n}\nDisable multithreading in the lapack packagepackage quantity\n\nimport (\n\t\"errors\"\n\n\t\"github.com\/ready-steady\/lapack\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/config\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/system\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/uncertainty\"\n\n\tinterpolation \"github.com\/ready-steady\/adapt\/algorithm\"\n)\n\nfunc init() {\n\t\/\/ The quantities of interest involve linear algebra, which is powered by\n\t\/\/ OpenBLAS via the lapack package. They are evaluated in multiple threads;\n\t\/\/ however, OpenBLAS is multithreaded by itself. The two multithreading\n\t\/\/ implementations might collide. Hence, the OpenBLAS one must be disabled.\n\tlapack.SetNumberOfThreads(1)\n}\n\ntype Quantity interface {\n\tDimensions() (uint, uint)\n\tCompute([]float64, []float64)\n\n\tEvaluate([]float64) float64\n\tForward([]float64) []float64\n\tBackward([]float64) []float64\n}\n\nfunc New(system *system.System, uncertainty uncertainty.Uncertainty,\n\tconfig *config.Quantity) (Quantity, error) {\n\n\tswitch config.Name {\n\tcase \"end-to-end-delay\":\n\t\treturn newDelay(system, uncertainty, config)\n\tcase \"total-energy\":\n\t\treturn newEnergy(system, uncertainty, config)\n\tcase \"maximum-temperature\":\n\t\treturn newTemperature(system, uncertainty, config)\n\tdefault:\n\t\treturn nil, errors.New(\"the quantity is unknown\")\n\t}\n}\n\nfunc Invoke(quantity Quantity, points []float64) []float64 {\n\tni, no := quantity.Dimensions()\n\treturn interpolation.Invoke(quantity.Compute, points, ni, no)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 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\/\/ +build ignore\n\n\/\/ The clanghost binary is like clangwrap.sh but for self-hosted iOS.\n\/\/\n\/\/ Use -ldflags=\"-X main.sdkpath=\" when building\n\/\/ the wrapper.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\nvar sdkpath = \"\"\n\nfunc main() {\n\tif sdkpath == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"no SDK is set; use -ldflags=\\\"-X main.sdkpath=\\\" when building this wrapper.\\n\")\n\t\tos.Exit(1)\n\t}\n\targs := os.Args[1:]\n\tcmd := exec.Command(\"clang\", \"-isysroot\", sdkpath, \"-mios-version-min=6.0\")\n\tcmd.Args = append(cmd.Args, args...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tif err, ok := err.(*exec.ExitError); ok {\n\t\t\tos.Exit(err.ExitCode())\n\t\t}\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}\nenv\/corellium: bump minimum ios version\/\/ Copyright 2019 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\/\/ +build ignore\n\n\/\/ The clanghost binary is like clangwrap.sh but for self-hosted iOS.\n\/\/\n\/\/ Use -ldflags=\"-X main.sdkpath=\" when building\n\/\/ the wrapper.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\nvar sdkpath = \"\"\n\nfunc main() {\n\tif sdkpath == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"no SDK is set; use -ldflags=\\\"-X main.sdkpath=\\\" when building this wrapper.\\n\")\n\t\tos.Exit(1)\n\t}\n\targs := os.Args[1:]\n\tcmd := exec.Command(\"clang\", \"-isysroot\", sdkpath, \"-mios-version-min=12.0\")\n\tcmd.Args = append(cmd.Args, args...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tif err, ok := err.(*exec.ExitError); ok {\n\t\t\tos.Exit(err.ExitCode())\n\t\t}\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}\n<|endoftext|>"} {"text":"package request_handler\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/twitchscience\/aws_utils\/environment\"\n\n\t\"github.com\/cactus\/go-statsd-client\/statsd\"\n\t\"github.com\/twitchscience\/gologging\/gologging\"\n\t\"github.com\/twitchscience\/spade_edge\/uuid\"\n)\n\nvar (\n\tAssigner uuid.UUIDAssigner = uuid.StartUUIDAssigner(\n\t\tos.Getenv(\"HOST\"),\n\t\tos.Getenv(\"CLOUD_CLUSTER\"),\n\t)\n\txDomainContents []byte = func() []byte {\n\t\tfilename := os.Getenv(\"CROSS_DOMAIN_LOCATION\")\n\t\tif filename == \"\" {\n\t\t\tfilename = \"..\/build\/config\/crossdomain.xml\"\n\t\t}\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Cross domain file not found: \", err)\n\t\t}\n\t\treturn b\n\t}()\n\txarth []byte = []byte(\"XARTH\")\n\txmlApplicationType = mime.TypeByExtension(\".xml\")\n\tDataFlag []byte = []byte(\"data=\")\n\tisProd = environment.IsProd()\n)\n\ntype SpadeEdgeLogger interface {\n\tLog(EventRecord)\n\tClose()\n}\n\ntype SpadeHandler struct {\n\tStatLogger statsd.Statter\n\tEdgeLogger SpadeEdgeLogger\n\tAssigner uuid.UUIDAssigner\n}\n\ntype FileAuditLogger struct {\n\tAuditLogger *gologging.UploadLogger\n\tSpadeLogger *gologging.UploadLogger\n}\n\nfunc (a *FileAuditLogger) Close() {\n\ta.AuditLogger.Close()\n\ta.SpadeLogger.Close()\n}\n\nfunc (a *FileAuditLogger) Log(log EventRecord) {\n\ta.AuditLogger.Log(\"%s\", log.AuditTrail())\n\ta.SpadeLogger.Log(\"%s\", log.HttpRequest())\n}\n\nfunc getIpFromHeader(headerKey string, header http.Header) string {\n\tclientIp := header.Get(headerKey)\n\tif clientIp == \"\" {\n\t\treturn clientIp\n\t}\n\tcomma := strings.Index(clientIp, \",\")\n\tif comma > -1 {\n\t\tclientIp = clientIp[:comma]\n\t}\n\n\treturn clientIp\n}\n\nfunc (s *SpadeHandler) HandleSpadeRequests(r *http.Request, context *requestContext) int {\n\tstatTimer := newTimerInstance()\n\n\tclientIp := getIpFromHeader(context.IpHeader, r.Header)\n\tif clientIp == \"\" {\n\t\treturn http.StatusBadRequest\n\t}\n\tcontext.Timers[\"ip\"] = statTimer.stopTiming()\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn http.StatusBadRequest\n\t}\n\n\tdata := r.Form.Get(\"data\")\n\tif data == \"\" && r.Method == \"POST\" {\n\t\t\/\/ if we're here then our clients have POSTed us something weird,\n\t\t\/\/ for example, something that maybe\n\t\t\/\/ application\/x-www-form-urlencoded but with the Content-Type\n\t\t\/\/ header set incorrectly... best effort here on out\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn http.StatusBadRequest\n\t\t}\n\t\tif bytes.Equal(b[:5], DataFlag) {\n\t\t\tcontext.BadClient = true\n\t\t\tb = b[5:]\n\t\t}\n\t\tdata = string(b)\n\n\t}\n\tif data == \"\" {\n\t\treturn http.StatusBadRequest\n\t}\n\n\tcontext.Timers[\"data\"] = statTimer.stopTiming()\n\n\t\/\/ \/\/ get event\n\tuuid := s.Assigner.Assign()\n\tcontext.Timers[\"uuid\"] = statTimer.stopTiming()\n\n\trecord := &Event{\n\t\tReceivedAt: context.Now,\n\t\tClientIp: clientIp,\n\t\tUUID: uuid,\n\t\tData: data,\n\t\tVersion: EVENT_VERSION,\n\t}\n\n\ts.EdgeLogger.Log(record)\n\tcontext.Timers[\"write\"] = statTimer.stopTiming()\n\n\treturn http.StatusNoContent\n}\n\nconst (\n\tipOverrideHeader = \"X-Original-Ip\"\n\tipForwardHeader = \"X-Forwarded-For\"\n\tbadEndpoint = \"FourOhFour\"\n\tnTimers = 5\n)\n\nfunc getTimeStampFromHeader(r *http.Request) (time.Time, error) {\n\ttimeStamp := r.Header.Get(\"X-ORIGINAL-MSEC\")\n\tif timeStamp != \"\" {\n\t\tsplitIdx := strings.Index(timeStamp, \".\")\n\t\tif splitIdx > -1 {\n\t\t\tsecs, err := strconv.ParseInt(timeStamp[:splitIdx], 10, 64)\n\t\t\tif err == nil {\n\t\t\t\treturn time.Unix(secs, 0), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn time.Time{}, errors.New(\"could not process timestamp from header\")\n}\n\nvar allowedMethods = map[string]bool{\n\t\"GET\": true,\n\t\"POST\": true,\n}\n\nfunc (s *SpadeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !allowedMethods[r.Method] {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tnow := time.Now()\n\tvar ts time.Time\n\tvar err error\n\tts = now\n\t\/\/ For integration time correction\n\tif !isProd {\n\t\tts, err = getTimeStampFromHeader(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\t\/\/\n\tcontext := &requestContext{\n\t\tNow: ts,\n\t\tMethod: r.Method,\n\t\tEndpoint: r.URL.Path,\n\t\tIpHeader: ipForwardHeader,\n\t\tTimers: make(map[string]time.Duration, nTimers),\n\t\tBadClient: false,\n\t}\n\ttimer := newTimerInstance()\n\tcontext.setStatus(s.serve(w, r, context))\n\tcontext.Timers[\"http\"] = timer.stopTiming()\n\n\tcontext.recordStats(s.StatLogger)\n}\n\nfunc (s *SpadeHandler) serve(w http.ResponseWriter, r *http.Request, context *requestContext) int {\n\tvar status int\n\tswitch r.URL.Path {\n\tcase \"\/crossdomain.xml\":\n\t\tw.Header().Add(\"Content-Type\", xmlApplicationType)\n\t\tw.Write(xDomainContents)\n\t\tstatus = http.StatusOK\n\tcase \"\/healthcheck\":\n\t\tstatus = http.StatusOK\n\tcase \"\/xarth\":\n\t\tw.Write(xarth)\n\t\tstatus = http.StatusOK\n\t\/\/ Accepted tracking endpoints.\n\tcase \"\/\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\tcase \"\/track\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\tcase \"\/track\/\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\t\/\/ dont track everything else\n\tdefault:\n\t\tcontext.Endpoint = badEndpoint\n\t\tstatus = http.StatusNotFound\n\t}\n\tw.WriteHeader(status)\n\treturn status\n}\nfixed multiple request header callspackage request_handler\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/twitchscience\/aws_utils\/environment\"\n\n\t\"github.com\/cactus\/go-statsd-client\/statsd\"\n\t\"github.com\/twitchscience\/gologging\/gologging\"\n\t\"github.com\/twitchscience\/spade_edge\/uuid\"\n)\n\nvar (\n\tAssigner uuid.UUIDAssigner = uuid.StartUUIDAssigner(\n\t\tos.Getenv(\"HOST\"),\n\t\tos.Getenv(\"CLOUD_CLUSTER\"),\n\t)\n\txDomainContents []byte = func() []byte {\n\t\tfilename := os.Getenv(\"CROSS_DOMAIN_LOCATION\")\n\t\tif filename == \"\" {\n\t\t\tfilename = \"..\/build\/config\/crossdomain.xml\"\n\t\t}\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Cross domain file not found: \", err)\n\t\t}\n\t\treturn b\n\t}()\n\txarth []byte = []byte(\"XARTH\")\n\txmlApplicationType = mime.TypeByExtension(\".xml\")\n\tDataFlag []byte = []byte(\"data=\")\n\tisProd = environment.IsProd()\n)\n\ntype SpadeEdgeLogger interface {\n\tLog(EventRecord)\n\tClose()\n}\n\ntype SpadeHandler struct {\n\tStatLogger statsd.Statter\n\tEdgeLogger SpadeEdgeLogger\n\tAssigner uuid.UUIDAssigner\n}\n\ntype FileAuditLogger struct {\n\tAuditLogger *gologging.UploadLogger\n\tSpadeLogger *gologging.UploadLogger\n}\n\nfunc (a *FileAuditLogger) Close() {\n\ta.AuditLogger.Close()\n\ta.SpadeLogger.Close()\n}\n\nfunc (a *FileAuditLogger) Log(log EventRecord) {\n\ta.AuditLogger.Log(\"%s\", log.AuditTrail())\n\ta.SpadeLogger.Log(\"%s\", log.HttpRequest())\n}\n\nfunc getIpFromHeader(headerKey string, header http.Header) string {\n\tclientIp := header.Get(headerKey)\n\tif clientIp == \"\" {\n\t\treturn clientIp\n\t}\n\tcomma := strings.Index(clientIp, \",\")\n\tif comma > -1 {\n\t\tclientIp = clientIp[:comma]\n\t}\n\n\treturn clientIp\n}\n\nfunc (s *SpadeHandler) HandleSpadeRequests(r *http.Request, context *requestContext) int {\n\tstatTimer := newTimerInstance()\n\n\tclientIp := getIpFromHeader(context.IpHeader, r.Header)\n\tif clientIp == \"\" {\n\t\treturn http.StatusBadRequest\n\t}\n\tcontext.Timers[\"ip\"] = statTimer.stopTiming()\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn http.StatusBadRequest\n\t}\n\n\tdata := r.Form.Get(\"data\")\n\tif data == \"\" && r.Method == \"POST\" {\n\t\t\/\/ if we're here then our clients have POSTed us something weird,\n\t\t\/\/ for example, something that maybe\n\t\t\/\/ application\/x-www-form-urlencoded but with the Content-Type\n\t\t\/\/ header set incorrectly... best effort here on out\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn http.StatusBadRequest\n\t\t}\n\t\tif bytes.Equal(b[:5], DataFlag) {\n\t\t\tcontext.BadClient = true\n\t\t\tb = b[5:]\n\t\t}\n\t\tdata = string(b)\n\n\t}\n\tif data == \"\" {\n\t\treturn http.StatusBadRequest\n\t}\n\n\tcontext.Timers[\"data\"] = statTimer.stopTiming()\n\n\t\/\/ \/\/ get event\n\tuuid := s.Assigner.Assign()\n\tcontext.Timers[\"uuid\"] = statTimer.stopTiming()\n\n\trecord := &Event{\n\t\tReceivedAt: context.Now,\n\t\tClientIp: clientIp,\n\t\tUUID: uuid,\n\t\tData: data,\n\t\tVersion: EVENT_VERSION,\n\t}\n\n\ts.EdgeLogger.Log(record)\n\tcontext.Timers[\"write\"] = statTimer.stopTiming()\n\n\treturn http.StatusNoContent\n}\n\nconst (\n\tipOverrideHeader = \"X-Original-Ip\"\n\tipForwardHeader = \"X-Forwarded-For\"\n\tbadEndpoint = \"FourOhFour\"\n\tnTimers = 5\n)\n\nfunc getTimeStampFromHeader(r *http.Request) (time.Time, error) {\n\ttimeStamp := r.Header.Get(\"X-ORIGINAL-MSEC\")\n\tif timeStamp != \"\" {\n\t\tsplitIdx := strings.Index(timeStamp, \".\")\n\t\tif splitIdx > -1 {\n\t\t\tsecs, err := strconv.ParseInt(timeStamp[:splitIdx], 10, 64)\n\t\t\tif err == nil {\n\t\t\t\treturn time.Unix(secs, 0), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn time.Time{}, errors.New(\"could not process timestamp from header\")\n}\n\nvar allowedMethods = map[string]bool{\n\t\"GET\": true,\n\t\"POST\": true,\n}\n\nfunc (s *SpadeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif !allowedMethods[r.Method] {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tnow := time.Now()\n\tvar ts time.Time\n\tvar err error\n\tts = now\n\t\/\/ For integration time correction\n\tif !isProd {\n\t\tts, err = getTimeStampFromHeader(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\t\/\/\n\tcontext := &requestContext{\n\t\tNow: ts,\n\t\tMethod: r.Method,\n\t\tEndpoint: r.URL.Path,\n\t\tIpHeader: ipForwardHeader,\n\t\tTimers: make(map[string]time.Duration, nTimers),\n\t\tBadClient: false,\n\t}\n\ttimer := newTimerInstance()\n\tcontext.setStatus(s.serve(w, r, context))\n\tcontext.Timers[\"http\"] = timer.stopTiming()\n\n\tcontext.recordStats(s.StatLogger)\n}\n\nfunc (s *SpadeHandler) serve(w http.ResponseWriter, r *http.Request, context *requestContext) int {\n\tvar status int\n\tswitch r.URL.Path {\n\tcase \"\/crossdomain.xml\":\n\t\tw.Header().Add(\"Content-Type\", xmlApplicationType)\n\t\tw.Write(xDomainContents)\n\t\treturn http.StatusOK\n\tcase \"\/healthcheck\":\n\t\tstatus = http.StatusOK\n\tcase \"\/xarth\":\n\t\tw.Write(xarth)\n\t\treturn http.StatusOK\n\t\/\/ Accepted tracking endpoints.\n\tcase \"\/\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\tcase \"\/track\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\tcase \"\/track\/\":\n\t\tstatus = s.HandleSpadeRequests(r, context)\n\t\/\/ dont track everything else\n\tdefault:\n\t\tcontext.Endpoint = badEndpoint\n\t\tstatus = http.StatusNotFound\n\t}\n\tw.WriteHeader(status)\n\treturn status\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/RomanSaveljev\/android-symbols\/transmitter\/src\/lib\"\n\t\"net\/rpc\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strings\"\n\t\"log\"\n)\n\nconst APP_VERSION = \"0.0.1\"\n\n\/\/ RECEIVER=cmd.. PREFIX=... transmitter files...\n\n\/\/ The flag package provides a default help printer via -h switch\nvar versionFlag *bool = flag.Bool(\"v\", false, \"Print the version number\")\n\nfunc main() {\n\tlog.Println(\"TX: starting\")\n\tflag.Parse() \/\/ Scan the arguments list\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Version:\", APP_VERSION)\n\t\tos.Exit(0)\n\t}\n\n\trest := flag.Args()\n\n\tcommand := os.Getenv(\"RECEIVER\")\n\tif len(command) == 0 {\n\t\tpanic(\"RECEIVER environment variable must tell receiver command\")\n\t}\n\n\tprefix := os.Getenv(\"PREFIX\")\n\n\tsplitCmd := strings.Split(command, \" \")\n\ttr, err := NewProcessTransport(exec.Command(splitCmd[0], splitCmd[1:]...))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to create a transport: %v\", err))\n\t}\n\tlog.Println(\"TX: transport created\")\n\tdefer tr.Close()\n\tclient := rpc.NewClient(tr)\n\tdefer client.Close()\n\tfor _, f := range rest {\n\t\tif file, err := os.Open(f); err == nil {\n\t\t\trcv, _ := transmitter.NewReceiver(path.Join(prefix, f), client)\n\t\t\ttransmitter.ProcessFileSync(file, rcv)\n\t\t\tfile.Close()\n\t\t}\n\t}\n}\nRecord CPU profilepackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/RomanSaveljev\/android-symbols\/transmitter\/src\/lib\"\n\t\"log\"\n\t\"net\/rpc\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n)\n\nconst APP_VERSION = \"0.0.1\"\n\n\/\/ RECEIVER=cmd.. PREFIX=... transmitter files...\n\n\/\/ The flag package provides a default help printer via -h switch\nvar versionFlag *bool = flag.Bool(\"v\", false, \"Print the version number\")\n\nfunc main() {\n\tprofile := os.Getenv(\"CPU_PROFILE\")\n\tif len(profile) > 0 {\n\t\tprof, _ := os.Create(profile)\n\t\tpprof.StartCPUProfile(prof)\n\t}\n\n\tlog.Println(\"TX: starting\")\n\tflag.Parse() \/\/ Scan the arguments list\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Version:\", APP_VERSION)\n\t\tos.Exit(0)\n\t}\n\n\trest := flag.Args()\n\n\tcommand := os.Getenv(\"RECEIVER\")\n\tif len(command) == 0 {\n\t\tpanic(\"RECEIVER environment variable must tell receiver command\")\n\t}\n\n\tprefix := os.Getenv(\"PREFIX\")\n\n\tsplitCmd := strings.Split(command, \" \")\n\ttr, err := NewProcessTransport(exec.Command(splitCmd[0], splitCmd[1:]...))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to create a transport: %v\", err))\n\t}\n\tlog.Println(\"TX: transport created\")\n\tdefer tr.Close()\n\tclient := rpc.NewClient(tr)\n\tdefer client.Close()\n\tfor _, f := range rest {\n\t\tif file, err := os.Open(f); err == nil {\n\t\t\trcv, _ := transmitter.NewReceiver(path.Join(prefix, f), client)\n\t\t\ttransmitter.ProcessFileSync(file, rcv)\n\t\t\tfile.Close()\n\t\t}\n\t}\n\n\tif len(profile) > 0 {\n\t\tpprof.StopCPUProfile()\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Package sender manages actually sending the emails for the postmaster\npackage sender\n\nimport (\n\t\"fmt\"\n\t\"github.com\/levenlabs\/go-llog\"\n\t\"github.com\/levenlabs\/golib\/genapi\"\n\t\"github.com\/levenlabs\/golib\/rpcutil\"\n\t\"github.com\/levenlabs\/postmaster\/ga\"\n\t\"github.com\/sendgrid\/sendgrid-go\"\n\t\"gopkg.in\/validator.v2\"\n\t\"reflect\"\n)\n\nvar (\n\tclient *sendgrid.SGClient\n)\n\n\/\/ Mail encompasses an email that is intended to be sent\ntype Mail struct {\n\t\/\/ To is the email address of the recipient\n\tTo string `json:\"to\" validate:\"email,nonzero,max=256\"`\n\n\t\/\/ ToName is optional and represents the recipeient's name\n\tToName string `json:\"toName,omitempty\" validate:\"max=256\"`\n\n\t\/\/ From is the email address of the sender\n\tFrom string `json:\"from\" validate:\"email,nonzero,max=256\"`\n\n\t\/\/ FromName is optional and represents the name of the sender\n\tFromName string `json:\"fromName,omitempty\" validate:\"max=256\"`\n\n\t\/\/ Subject is the subject of the email\n\tSubject string `json:\"subject\" validate:\"nonzero,max=998\"` \/\/ RFC 5322 says not longer than 998\n\n\t\/\/ HTML is the HTML body of the email and is required unless Text is sent\n\tHTML string `json:\"html,omitempty\" validate:\"max=2097152\"` \/\/2MB\n\n\t\/\/ Text is the plain-text body and is required unless HTML is sent\n\tText string `json:\"text,omitempty\" validate:\"max=2097152\"` \/\/2MB\n\n\t\/\/ ReplyTo is the Reply-To email address for the email\n\tReplyTo string `json:\"replyTo,omitempty\" validate:\"max=256\"`\n\n\t\/\/ UniqueArgs are the SMTP unique arguments passed onto sendgrid\n\t\/\/ Note: pmStatsID is a reserved key and is used for stats recording\n\tUniqueArgs map[string]string `json:\"uniqueArgs,omitempty\" validate:\"argsMap=max=256\"`\n\n\t\/\/ Flags represent the category flags for this email and are used to\n\t\/\/ determine if the recipient has blocked this category of email\n\tFlags int64 `json:\"flags\"`\n\n\t\/\/ UniqueID is an optional uniqueID for this email that will be stored with\n\t\/\/ the email stats and can be used to later query when the last email with\n\t\/\/ this ID was sent\n\tUniqueID string `json:\"uniqueID,omitempty\" validate:\"max=256\"`\n}\n\nfunc init() {\n\tga.GA.AppendInit(func(g *genapi.GenAPI) {\n\t\tkey, _ := g.ParamStr(\"--sendgrid-key\")\n\t\tif key == \"\" {\n\t\t\tllog.Fatal(\"--sendgrid-key not set\")\n\t\t}\n\t\tclient = sendgrid.NewSendGridClientWithApiKey(key)\n\n\t\trpcutil.InstallCustomValidators()\n\t\tvalidator.SetValidationFunc(\"argsMap\", validateArgsMap)\n\t})\n}\n\n\/\/ Send takes a Mail struct and sends it to sendgrid\nfunc Send(job *Mail) error {\n\tmsg := sendgrid.NewMail()\n\tmsg.AddTo(job.To)\n\tif job.ToName != \"\" {\n\t\tmsg.AddToName(job.ToName)\n\t}\n\tmsg.SetFrom(job.From)\n\tif job.FromName != \"\" {\n\t\tmsg.SetFromName(job.FromName)\n\t}\n\tmsg.SetSubject(job.Subject)\n\tif job.HTML != \"\" {\n\t\tmsg.SetHTML(job.HTML)\n\t}\n\tif job.Text != \"\" {\n\t\tmsg.SetText(job.Text)\n\t}\n\tif job.ReplyTo != \"\" {\n\t\tmsg.SetReplyTo(job.ReplyTo)\n\t}\n\tif job.UniqueArgs != nil && len(job.UniqueArgs) > 0 {\n\t\tmsg.SMTPAPIHeader.SetUniqueArgs(job.UniqueArgs)\n\t}\n\treturn client.Send(msg)\n}\n\n\/\/ validateArgsMap maps over the args map and validates each key and value in\n\/\/ it using the passed in tag\nfunc validateArgsMap(v interface{}, param string) error {\n\tvv := reflect.ValueOf(v)\n\tif vv.Kind() == reflect.Ptr {\n\t\tvv = vv.Elem()\n\t}\n\n\tif k := vv.Kind(); k != reflect.Map {\n\t\treturn fmt.Errorf(\"non-array type: %s\", k)\n\t}\n\n\tks := vv.MapKeys()\n\tfor _, k := range ks {\n\t\t\/\/first check the key\n\t\tif err := validator.Valid(k.Interface(), param); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid key %s: %s\", k.String(), err)\n\t\t}\n\t\t\/\/now check the value\n\t\tkv := vv.MapIndex(k).Interface()\n\t\tif err := validator.Valid(kv, param); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid value at key %s: %s\", k.String(), err)\n\t\t}\n\t}\n\treturn nil\n}\nUpdated to v3 of SendGrid api\/\/ Package sender manages actually sending the emails for the postmaster\npackage sender\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n\n\t\"github.com\/levenlabs\/go-llog\"\n\t\"github.com\/levenlabs\/golib\/genapi\"\n\t\"github.com\/levenlabs\/golib\/rpcutil\"\n\t\"github.com\/levenlabs\/postmaster\/ga\"\n\t\"github.com\/sendgrid\/sendgrid-go\"\n\t\"github.com\/sendgrid\/sendgrid-go\/helpers\/mail\"\n\t\"gopkg.in\/validator.v2\"\n)\n\nvar (\n\tsgKey string\n)\n\n\/\/ Mail encompasses an email that is intended to be sent\ntype Mail struct {\n\t\/\/ To is the email address of the recipient\n\tTo string `json:\"to\" validate:\"email,nonzero,max=256\"`\n\n\t\/\/ ToName is optional and represents the recipeient's name\n\tToName string `json:\"toName,omitempty\" validate:\"max=256\"`\n\n\t\/\/ From is the email address of the sender\n\tFrom string `json:\"from\" validate:\"email,nonzero,max=256\"`\n\n\t\/\/ FromName is optional and represents the name of the sender\n\tFromName string `json:\"fromName,omitempty\" validate:\"max=256\"`\n\n\t\/\/ Subject is the subject of the email\n\tSubject string `json:\"subject\" validate:\"nonzero,max=998\"` \/\/ RFC 5322 says not longer than 998\n\n\t\/\/ HTML is the HTML body of the email and is required unless Text is sent\n\tHTML string `json:\"html,omitempty\" validate:\"max=2097152\"` \/\/2MB\n\n\t\/\/ Text is the plain-text body and is required unless HTML is sent\n\tText string `json:\"text,omitempty\" validate:\"max=2097152\"` \/\/2MB\n\n\t\/\/ ReplyTo is the Reply-To email address for the email\n\tReplyTo string `json:\"replyTo,omitempty\" validate:\"email,max=256\"`\n\n\t\/\/ UniqueArgs are the SMTP unique arguments passed onto sendgrid\n\t\/\/ Note: pmStatsID is a reserved key and is used for stats recording\n\tUniqueArgs map[string]string `json:\"uniqueArgs,omitempty\" validate:\"argsMap=max=256\"`\n\n\t\/\/ Flags represent the category flags for this email and are used to\n\t\/\/ determine if the recipient has blocked this category of email\n\tFlags int64 `json:\"flags\"`\n\n\t\/\/ UniqueID is an optional uniqueID for this email that will be stored with\n\t\/\/ the email stats and can be used to later query when the last email with\n\t\/\/ this ID was sent\n\tUniqueID string `json:\"uniqueID,omitempty\" validate:\"max=256\"`\n}\n\nfunc init() {\n\tga.GA.AppendInit(func(g *genapi.GenAPI) {\n\t\tkey, _ := g.ParamStr(\"--sendgrid-key\")\n\t\tif key == \"\" {\n\t\t\tllog.Fatal(\"--sendgrid-key not set\")\n\t\t}\n\t\tsgKey = key\n\n\t\trpcutil.InstallCustomValidators()\n\t\tvalidator.SetValidationFunc(\"argsMap\", validateArgsMap)\n\t})\n}\n\n\/\/ Send takes a Mail struct and sends it to sendgrid\nfunc Send(job *Mail) error {\n\tmsg := mail.NewV3Mail()\n\tmsg.SetFrom(mail.NewEmail(job.FromName, job.From))\n\tif job.ReplyTo != \"\" {\n\t\tmsg.SetReplyTo(mail.NewEmail(\"\", job.ReplyTo))\n\t}\n\n\tp := mail.NewPersonalization()\n\tp.AddTos(mail.NewEmail(job.ToName, job.To))\n\tmsg.AddPersonalizations(p)\n\n\tmsg.Subject = job.Subject\n\tcontents := []*mail.Content{}\n\tif job.HTML != \"\" {\n\t\tcontents = append(contents, mail.NewContent(\"text\/html\", job.HTML))\n\t}\n\tif job.Text != \"\" {\n\t\tcontents = append(contents, mail.NewContent(\"text\/plain\", job.Text))\n\t}\n\tmsg.AddContent(contents...)\n\n\tif job.UniqueArgs != nil && len(job.UniqueArgs) > 0 {\n\t\tfor k, v := range job.UniqueArgs {\n\t\t\tmsg.SetCustomArg(k, v)\n\t\t}\n\t}\n\treq := sendgrid.GetRequest(sgKey, \"\/v3\/mail\/send\", \"https:\/\/api.sendgrid.com\")\n\treq.Method = \"POST\"\n\treq.Body = mail.GetRequestBody(msg)\n\tresp, err := sendgrid.API(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusAccepted {\n\t\treturn errors.New(resp.Body)\n\t}\n\treturn nil\n}\n\n\/\/ validateArgsMap maps over the args map and validates each key and value in\n\/\/ it using the passed in tag\nfunc validateArgsMap(v interface{}, param string) error {\n\tvv := reflect.ValueOf(v)\n\tif vv.Kind() == reflect.Ptr {\n\t\tvv = vv.Elem()\n\t}\n\n\tif k := vv.Kind(); k != reflect.Map {\n\t\treturn fmt.Errorf(\"non-array type: %s\", k)\n\t}\n\n\tks := vv.MapKeys()\n\tfor _, k := range ks {\n\t\t\/\/first check the key\n\t\tif err := validator.Valid(k.Interface(), param); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid key %s: %s\", k.String(), err)\n\t\t}\n\t\t\/\/now check the value\n\t\tkv := vv.MapIndex(k).Interface()\n\t\tif err := validator.Valid(kv, param); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid value at key %s: %s\", k.String(), err)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"github.com\/hashicorp\/serf\/serf\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc clear() {\n\t\/\/ Use ANSI codes to clear the line and move the cursor to the left.\n\tfmt.Printf(\"\\033[2K\\033[100D\")\n}\n\nfunc main() {\n\t\/\/ Command-line options used to configure our chat client.\n\tusername := flag.String(\"username\", \"peon\", \"Username to use for chatting.\")\n\thostname := flag.String(\"host\", \"localhost:4444\", \"Host and port to bind to\")\n\totherhostname := flag.String(\"existing\", \"localhost:4445\", \"Host and port used for cluster discovery.\")\n\tflag.Parse()\n\n\t\/\/ Create a channel to handle incoming messages.\n\tevents := make(chan serf.Event, 1)\n\n\t\/\/ Set up a handler for events. This handler will run each time we receive an event from Serf.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-events:\n\t\t\t\tswitch event.(type) {\n\t\t\t\tcase serf.UserEvent:\n\t\t\t\t\tue, ok := event.(serf.UserEvent)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlog.Panic(\"Unable to convert to user event.\")\n\t\t\t\t\t}\n\t\t\t\t\tclear()\n\t\t\t\t\tfmt.Printf(\"<%v> %sMessage> \", ue.Name, ue.Payload)\n\t\t\t\tcase serf.MemberEvent:\n\t\t\t\t\tme, ok := event.(serf.MemberEvent)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlog.Panic(\"Unable to convert to member event.\")\n\t\t\t\t\t}\n\t\t\t\t\tclear()\n\t\t\t\t\tfor member := range me.Members {\n\t\t\t\t\t\tfmt.Printf(\"Member event: %v %v\\n\", me.Members[member].Name, me.Type.String())\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\"Message> \")\n\t\t\t\t}\n\t\t\t\t\/\/ We're ignoring other events such as member join\/leave.\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Set up host and ports used throughout.\n\thost, port, err := net.SplitHostPort(*hostname)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Create a unique node name.\n\tnodename := fmt.Sprintf(\"chat-%v-%v\", host, port)\n\n\t\/\/ A file to log Serf and Memberlist information to.\n\t\/\/ This is so our screen isn't cluttered with information but the logs\n\t\/\/ can be useful in looking at what's going on under the hood.\n\tfile, err := os.Create(fmt.Sprintf(\"\/tmp\/%v\", nodename))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Configure the host and port in the underlying memberlist config.\n\tportnum, err := strconv.Atoi(port)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tmemberconfig := memberlist.DefaultLANConfig()\n\tmemberconfig.BindAddr = host\n\tmemberconfig.BindPort = portnum\n\tmemberconfig.LogOutput = file\n\n\t\/\/ Create a configuration based on the default.\n\tconfig := serf.DefaultConfig()\n\tconfig.Init()\n\tconfig.NodeName = nodename\n\tconfig.Tags[\"username\"] = *username\n\tconfig.MemberlistConfig = memberconfig\n\tconfig.EventCh = events\n\tconfig.LogOutput = file\n\n\t\/\/ Create a Serf client.\n\tserfclient, err := serf.Create(config)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Join the cluster using the other local port as our existing seed.\n\tfmt.Printf(\"Connecting to %v\", *otherhostname)\n\tclients, err := serfclient.Join([]string{*otherhostname}, false)\n\tif err != nil {\n\t\t\/\/ If we're the first user we'll get a connection refused on the other host\n\t\t\/\/ so log but don't panic.\n\t\tclear()\n\t\tfmt.Printf(\"Connection error: %v\\n\", err)\n\t}\n\tfmt.Printf(\"There are %v clients connected.\\n\", clients)\n\n\t\/\/ let's chat. This is our main loop that takes a line of user input,\n\t\/\/ sends it as a UserEvent, and waits for more input.\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tclear()\n\t\tfmt.Printf(\"Message> \")\n\t\tline, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\terr = serfclient.UserEvent(*username, []byte(line), true)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\nOne more clear.package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"github.com\/hashicorp\/serf\/serf\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc clear() {\n\t\/\/ Use ANSI codes to clear the line and move the cursor to the left.\n\tfmt.Printf(\"\\033[2K\\033[100D\")\n}\n\nfunc main() {\n\t\/\/ Command-line options used to configure our chat client.\n\tusername := flag.String(\"username\", \"peon\", \"Username to use for chatting.\")\n\thostname := flag.String(\"host\", \"localhost:4444\", \"Host and port to bind to\")\n\totherhostname := flag.String(\"existing\", \"localhost:4445\", \"Host and port used for cluster discovery.\")\n\tflag.Parse()\n\n\t\/\/ Create a channel to handle incoming messages.\n\tevents := make(chan serf.Event, 1)\n\n\t\/\/ Set up a handler for events. This handler will run each time we receive an event from Serf.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-events:\n\t\t\t\tswitch event.(type) {\n\t\t\t\tcase serf.UserEvent:\n\t\t\t\t\tue, ok := event.(serf.UserEvent)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlog.Panic(\"Unable to convert to user event.\")\n\t\t\t\t\t}\n\t\t\t\t\tclear()\n\t\t\t\t\tfmt.Printf(\"<%v> %sMessage> \", ue.Name, ue.Payload)\n\t\t\t\tcase serf.MemberEvent:\n\t\t\t\t\tme, ok := event.(serf.MemberEvent)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlog.Panic(\"Unable to convert to member event.\")\n\t\t\t\t\t}\n\t\t\t\t\tclear()\n\t\t\t\t\tfor member := range me.Members {\n\t\t\t\t\t\tfmt.Printf(\"Member event: %v %v\\n\", me.Members[member].Name, me.Type.String())\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\"Message> \")\n\t\t\t\t}\n\t\t\t\t\/\/ We're ignoring other events such as member join\/leave.\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Set up host and ports used throughout.\n\thost, port, err := net.SplitHostPort(*hostname)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Create a unique node name.\n\tnodename := fmt.Sprintf(\"chat-%v-%v\", host, port)\n\n\t\/\/ A file to log Serf and Memberlist information to.\n\t\/\/ This is so our screen isn't cluttered with information but the logs\n\t\/\/ can be useful in looking at what's going on under the hood.\n\tfile, err := os.Create(fmt.Sprintf(\"\/tmp\/%v\", nodename))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Configure the host and port in the underlying memberlist config.\n\tportnum, err := strconv.Atoi(port)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tmemberconfig := memberlist.DefaultLANConfig()\n\tmemberconfig.BindAddr = host\n\tmemberconfig.BindPort = portnum\n\tmemberconfig.LogOutput = file\n\n\t\/\/ Create a configuration based on the default.\n\tconfig := serf.DefaultConfig()\n\tconfig.Init()\n\tconfig.NodeName = nodename\n\tconfig.Tags[\"username\"] = *username\n\tconfig.MemberlistConfig = memberconfig\n\tconfig.EventCh = events\n\tconfig.LogOutput = file\n\n\t\/\/ Create a Serf client.\n\tserfclient, err := serf.Create(config)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t\/\/ Join the cluster using the other local port as our existing seed.\n\tfmt.Printf(\"Connecting to %v\", *otherhostname)\n\tclients, err := serfclient.Join([]string{*otherhostname}, false)\n\tif err != nil {\n\t\t\/\/ If we're the first user we'll get a connection refused on the other host\n\t\t\/\/ so log but don't panic.\n\t\tclear()\n\t\tfmt.Printf(\"Connection error: %v\\n\", err)\n\t}\n\tclear()\n\tfmt.Printf(\"There are %v clients connected.\\n\", clients)\n\n\t\/\/ let's chat. This is our main loop that takes a line of user input,\n\t\/\/ sends it as a UserEvent, and waits for more input.\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tclear()\n\t\tfmt.Printf(\"Message> \")\n\t\tline, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\terr = serfclient.UserEvent(*username, []byte(line), true)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package url2oembed\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\/\/ to fetch gif info from url\n\t_ \"image\/gif\"\n\t\/\/ to fetch jpeg info from url\n\t_ \"image\/jpeg\"\n\t\/\/ to fetch png info from url\n\t_ \"image\/png\"\n\n\t\"github.com\/dyatlov\/go-htmlinfo\/htmlinfo\"\n\t\"github.com\/dyatlov\/go-oembed\/oembed\"\n)\n\n\/\/ Parser implements an url parsing code\ntype Parser struct {\n\toe *oembed.Oembed\n\tclient *http.Client\n\tAcceptLanguage string\n\tMaxHTMLBodySize int64\n\tMaxBinaryBodySize int64\n\tWaitTimeout time.Duration\n\tfetchURLCalls int\n\n\t\/\/ list of IP addresses to blacklist\n\tBlacklistedIPNetworks []*net.IPNet\n\n\t\/\/ list of IP addresses to whitelist\n\tWhitelistedIPNetworks []*net.IPNet\n}\n\n\/\/ OembedRedirectGoodError is a hack to stop following redirects and get oembed resource\ntype OembedRedirectGoodError struct {\n\turl string\n\titem *oembed.Item\n}\n\nvar (\n\timageTypeRegex = regexp.MustCompile(`^image\/.*`)\n\thtmlTypeRegex = regexp.MustCompile(`^text\/html`)\n)\n\n\/\/ GetItem return embed item\nfunc (orge *OembedRedirectGoodError) GetItem() *oembed.Item {\n\treturn orge.item\n}\n\n\/\/ GetURL returns url of resource with embeding implemented\nfunc (orge *OembedRedirectGoodError) GetURL() string {\n\treturn orge.url\n}\n\nfunc (orge *OembedRedirectGoodError) Error() string {\n\treturn fmt.Sprintf(\"Found resource supporting oembed: %s\", orge.url)\n}\n\n\/\/ NewParser returns new Parser instance\n\/\/ Oembed pointer is optional, it just speeds up information gathering\nfunc NewParser(oe *oembed.Oembed) *Parser {\n\tparser := &Parser{oe: oe}\n\tparser.init()\n\treturn parser\n}\n\nfunc (p *Parser) skipRedirectIfFoundOembed(req *http.Request, via []*http.Request) error {\n\tif p.fetchURLCalls >= 10 {\n\t\treturn errors.New(\"stopped after 10 redirects\")\n\t}\n\n\tp.fetchURLCalls++\n\n\tif p.oe == nil {\n\t\treturn nil\n\t}\n\n\titem := p.oe.FindItem(req.URL.String())\n\n\tif item != nil {\n\t\treturn &OembedRedirectGoodError{url: req.URL.String(), item: item}\n\t}\n\n\treturn nil\n}\n\nfunc (p *Parser) init() {\n\tp.MaxHTMLBodySize = 50000\n\tp.MaxBinaryBodySize = 4096\n\tp.AcceptLanguage = \"en-us\"\n\tp.WaitTimeout = 10 * time.Second\n}\n\nfunc (p *Parser) isBlacklistedIP(addr net.IP) bool {\n\t\/\/ if whitelisted then return false\n\tfor _, w := range p.WhitelistedIPNetworks {\n\t\tif w.Contains(addr) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t\/\/ if blacklisted then return true\n\tfor _, b := range p.BlacklistedIPNetworks {\n\t\tif b.Contains(addr) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ by default we disable local addresses and bradcast ones\n\treturn !addr.IsGlobalUnicast()\n}\n\nfunc (p *Parser) filterBlacklistedIPs(addrs []net.IP) ([]net.IP, bool) {\n\tisBlacklisted := false\n\n\tvar whiteListed []net.IP\n\n\tfor _, a := range addrs {\n\t\tif p.isBlacklistedIP(a) {\n\t\t\tisBlacklisted = true\n\t\t} else {\n\t\t\twhiteListed = append(whiteListed, a)\n\t\t}\n\t}\n\n\treturn whiteListed, isBlacklisted\n}\n\n\/\/ Dial is used to disable access to blacklisted IP addresses\nfunc (p *Parser) Dial(network, addr string) (net.Conn, error) {\n\tvar (\n\t\thost, port string\n\t\terr error\n\t\taddrs []net.IP\n\t)\n\n\tif host, port, err = net.SplitHostPort(addr); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif addrs, err = net.LookupIP(host); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif whiteListed, isBlacklisted := p.filterBlacklistedIPs(addrs); isBlacklisted {\n\t\tif len(whiteListed) == 0 {\n\t\t\treturn nil, errors.New(\"Host is blacklisted\")\n\t\t}\n\t\t\/\/ select first good one\n\t\tfirstGood := whiteListed[0]\n\t\tif len(whiteListed) > 1 {\n\t\t\tfor _, candidate := range whiteListed[1:] {\n\t\t\t\tif candidate.To4() != nil { \/\/ we prefer IPv4\n\t\t\t\t\tfirstGood = candidate\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\taddr = net.JoinHostPort(firstGood.String(), port)\n\t}\n\n\treturn net.Dial(network, addr)\n}\n\n\/\/ Parse parses an url and returns structurized representation\nfunc (p *Parser) Parse(u string) *oembed.Info {\n\tif p.client == nil {\n\t\ttransport := &http.Transport{DisableKeepAlives: true, Dial: p.Dial}\n\t\tp.client = &http.Client{Timeout: p.WaitTimeout, Transport: transport, CheckRedirect: p.skipRedirectIfFoundOembed}\n\t}\n\n\tp.fetchURLCalls = 0\n\tinfo := p.parseOembed(u)\n\n\t\/\/ and now we try to set missing image sizes\n\tif info != nil {\n\t\t\/\/ TODO: need to optimize this block, thats too much for 0 checking\n\t\tvar width int64\n\t\tvar err error\n\t\twidth, err = info.ThumbnailWidth.Int64()\n\t\tif err != nil {\n\t\t\twidth = 0\n\t\t}\n\t\t\/\/\/\/\n\t\tif len(info.ThumbnailURL) > 0 && width == 0 {\n\t\t\tp.fetchURLCalls = 0\n\t\t\tdata, newURL, _, err := p.fetchURL(info.ThumbnailURL)\n\t\t\tif err == nil {\n\t\t\t\tinfo.ThumbnailURL = newURL\n\t\t\t\tconfig, _, err := image.DecodeConfig(bytes.NewReader(data))\n\t\t\t\tif err == nil {\n\t\t\t\t\tinfo.ThumbnailWidth = json.Number(strconv.FormatInt(int64(config.Width), 10))\n\t\t\t\t\tinfo.ThumbnailHeight = json.Number(strconv.FormatInt(int64(config.Height), 10))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn info\n}\n\nfunc (p *Parser) parseOembed(u string) *oembed.Info {\n\t\/\/ check if we have it oembeded\n\tvar item *oembed.Item\n\n\tvar srvContentType string\n\n\tif p.oe != nil {\n\t\titem := p.oe.FindItem(u)\n\t\tif item != nil {\n\t\t\t\/\/ try to extract information\n\t\t\tei, _ := item.FetchOembed(u, p.client)\n\t\t\tif ei != nil && ei.Status < 300 {\n\t\t\t\treturn ei\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ fetch url\n\tdata, newURL, srvContentType, err := p.fetchURL(u)\n\n\tif err != nil {\n\t\tfor {\n\t\t\tif e, ok := err.(*url.Error); ok {\n\t\t\t\tif e, ok := e.Err.(*OembedRedirectGoodError); ok {\n\t\t\t\t\titem = e.GetItem()\n\t\t\t\t\t\/\/ TODO: optimize this.. calling the same code 2 times\n\t\t\t\t\tei, _ := item.FetchOembed(e.GetURL(), p.client)\n\t\t\t\t\tif ei != nil && ei.Status < 300 {\n\t\t\t\t\t\treturn ei\n\t\t\t\t\t}\n\n\t\t\t\t\tdata, newURL, srvContentType, err = p.fetchURL(e.GetURL())\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif data != nil {\n\t\tu = newURL\n\n\t\tcontentType := http.DetectContentType(data)\n\n\t\tif imageTypeRegex.MatchString(contentType) {\n\t\t\treturn p.getImageInfo(u, data)\n\t\t}\n\n\t\tif htmlTypeRegex.MatchString(contentType) {\n\t\t\treturn p.FetchOembedFromHTML(u, data, srvContentType)\n\t\t}\n\n\t\treturn p.getLinkInfo(u)\n\t}\n\n\treturn nil\n}\n\nfunc (p *Parser) getImageInfo(u string, data []byte) *oembed.Info {\n\tpu, _ := url.Parse(u)\n\n\tif pu == nil {\n\t\treturn nil\n\t}\n\n\tconfig, _, err := image.DecodeConfig(bytes.NewReader(data))\n\n\tinfo := oembed.NewInfo()\n\tinfo.Type = \"photo\"\n\tinfo.URL = u\n\tinfo.ProviderURL = \"http:\/\/\" + pu.Host\n\tinfo.ProviderName = pu.Host\n\n\tif err == nil {\n\t\tinfo.Width = json.Number(strconv.FormatInt(int64(config.Width), 10))\n\t\tinfo.Height = json.Number(strconv.FormatInt(int64(config.Height), 10))\n\t}\n\n\treturn info\n}\n\nfunc (p *Parser) getLinkInfo(u string) *oembed.Info {\n\tpu, _ := url.Parse(u)\n\n\tif pu == nil {\n\t\treturn nil\n\t}\n\n\tinfo := oembed.NewInfo()\n\tinfo.Type = \"link\"\n\tinfo.URL = u\n\tinfo.ProviderURL = \"http:\/\/\" + pu.Host\n\tinfo.ProviderName = pu.Host\n\n\treturn info\n}\n\n\/\/ FetchOembedFromHTML returns information extracted from html page\nfunc (p *Parser) FetchOembedFromHTML(pageURL string, data []byte, contentType string) *oembed.Info {\n\tbuf := bytes.NewReader(data)\n\tinfo := htmlinfo.NewHTMLInfo()\n\tinfo.Client = p.client\n\tinfo.AcceptLanguage = p.AcceptLanguage\n\tinfo.AllowOembedFetching = true\n\n\tif info.Parse(buf, &pageURL, &contentType) != nil {\n\t\treturn nil\n\t}\n\n\treturn info.GenerateOembedFor(pageURL)\n}\n\nfunc (p *Parser) fetchURL(url string) (data []byte, u string, contentType string, err error) {\n\tp.fetchURLCalls++\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Add(\"Accept-Language\", p.AcceptLanguage)\n\n\tresp, err := p.client.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\n\tu = resp.Request.URL.String()\n\n\tcontentType = resp.Header.Get(\"Content-Type\")\n\n\tvar reader io.Reader\n\n\t\/\/ if we have some raw stream then we can't parse html, so need just mime\n\tif contentType == \"\" || htmlTypeRegex.MatchString(contentType) {\n\t\treader = io.LimitReader(resp.Body, p.MaxHTMLBodySize)\n\t} else {\n\t\treader = io.LimitReader(resp.Body, p.MaxBinaryBodySize)\n\t}\n\n\tdata, err = ioutil.ReadAll(reader)\n\n\treturn\n}\nadded user agent and added preserving headers between redirectspackage url2oembed\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\/\/ to fetch gif info from url\n\t_ \"image\/gif\"\n\t\/\/ to fetch jpeg info from url\n\t_ \"image\/jpeg\"\n\t\/\/ to fetch png info from url\n\t_ \"image\/png\"\n\n\t\"github.com\/dyatlov\/go-htmlinfo\/htmlinfo\"\n\t\"github.com\/dyatlov\/go-oembed\/oembed\"\n)\n\n\/\/ Parser implements an url parsing code\ntype Parser struct {\n\toe *oembed.Oembed\n\tclient *http.Client\n\tAcceptLanguage string\n\tUserAgent string\n\tMaxHTMLBodySize int64\n\tMaxBinaryBodySize int64\n\tWaitTimeout time.Duration\n\tfetchURLCalls int\n\n\t\/\/ list of IP addresses to blacklist\n\tBlacklistedIPNetworks []*net.IPNet\n\n\t\/\/ list of IP addresses to whitelist\n\tWhitelistedIPNetworks []*net.IPNet\n}\n\n\/\/ OembedRedirectGoodError is a hack to stop following redirects and get oembed resource\ntype OembedRedirectGoodError struct {\n\turl string\n\titem *oembed.Item\n}\n\nvar (\n\timageTypeRegex = regexp.MustCompile(`^image\/.*`)\n\thtmlTypeRegex = regexp.MustCompile(`^text\/html`)\n)\n\n\/\/ GetItem return embed item\nfunc (orge *OembedRedirectGoodError) GetItem() *oembed.Item {\n\treturn orge.item\n}\n\n\/\/ GetURL returns url of resource with embeding implemented\nfunc (orge *OembedRedirectGoodError) GetURL() string {\n\treturn orge.url\n}\n\nfunc (orge *OembedRedirectGoodError) Error() string {\n\treturn fmt.Sprintf(\"Found resource supporting oembed: %s\", orge.url)\n}\n\n\/\/ NewParser returns new Parser instance\n\/\/ Oembed pointer is optional, it just speeds up information gathering\nfunc NewParser(oe *oembed.Oembed) *Parser {\n\tparser := &Parser{oe: oe}\n\tparser.init()\n\treturn parser\n}\n\nfunc (p *Parser) skipRedirectIfFoundOembed(req *http.Request, via []*http.Request) error {\n\tif p.fetchURLCalls >= 10 {\n\t\treturn errors.New(\"stopped after 10 redirects\")\n\t}\n\n\tp.fetchURLCalls++\n\n\tif p.oe == nil {\n\t\treturn nil\n\t}\n\n\titem := p.oe.FindItem(req.URL.String())\n\n\tif item != nil {\n\t\treturn &OembedRedirectGoodError{url: req.URL.String(), item: item}\n\t}\n\n\t\/\/ mutate the subsequent redirect requests with the first Header\n\tfor key, val := range via[0].Header {\n\t\treq.Header[key] = val\n\t}\n\n\treturn nil\n}\n\nfunc (p *Parser) init() {\n\tp.MaxHTMLBodySize = 50000\n\tp.MaxBinaryBodySize = 4096\n\tp.AcceptLanguage = \"en-us\"\n\tp.UserAgent = \"ProcLink Bot http:\/\/proc.link\"\n\tp.WaitTimeout = 10 * time.Second\n}\n\nfunc (p *Parser) isBlacklistedIP(addr net.IP) bool {\n\t\/\/ if whitelisted then return false\n\tfor _, w := range p.WhitelistedIPNetworks {\n\t\tif w.Contains(addr) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t\/\/ if blacklisted then return true\n\tfor _, b := range p.BlacklistedIPNetworks {\n\t\tif b.Contains(addr) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ by default we disable local addresses and bradcast ones\n\treturn !addr.IsGlobalUnicast()\n}\n\nfunc (p *Parser) filterBlacklistedIPs(addrs []net.IP) ([]net.IP, bool) {\n\tisBlacklisted := false\n\n\tvar whiteListed []net.IP\n\n\tfor _, a := range addrs {\n\t\tif p.isBlacklistedIP(a) {\n\t\t\tisBlacklisted = true\n\t\t} else {\n\t\t\twhiteListed = append(whiteListed, a)\n\t\t}\n\t}\n\n\treturn whiteListed, isBlacklisted\n}\n\n\/\/ Dial is used to disable access to blacklisted IP addresses\nfunc (p *Parser) Dial(network, addr string) (net.Conn, error) {\n\tvar (\n\t\thost, port string\n\t\terr error\n\t\taddrs []net.IP\n\t)\n\n\tif host, port, err = net.SplitHostPort(addr); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif addrs, err = net.LookupIP(host); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif whiteListed, isBlacklisted := p.filterBlacklistedIPs(addrs); isBlacklisted {\n\t\tif len(whiteListed) == 0 {\n\t\t\treturn nil, errors.New(\"Host is blacklisted\")\n\t\t}\n\t\t\/\/ select first good one\n\t\tfirstGood := whiteListed[0]\n\t\tif len(whiteListed) > 1 {\n\t\t\tfor _, candidate := range whiteListed[1:] {\n\t\t\t\tif candidate.To4() != nil { \/\/ we prefer IPv4\n\t\t\t\t\tfirstGood = candidate\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\taddr = net.JoinHostPort(firstGood.String(), port)\n\t}\n\n\treturn net.Dial(network, addr)\n}\n\n\/\/ Parse parses an url and returns structurized representation\nfunc (p *Parser) Parse(u string) *oembed.Info {\n\tif p.client == nil {\n\t\ttransport := &http.Transport{DisableKeepAlives: true, Dial: p.Dial}\n\t\tp.client = &http.Client{Timeout: p.WaitTimeout, Transport: transport, CheckRedirect: p.skipRedirectIfFoundOembed}\n\t}\n\n\tp.fetchURLCalls = 0\n\tinfo := p.parseOembed(u)\n\n\t\/\/ and now we try to set missing image sizes\n\tif info != nil {\n\t\t\/\/ TODO: need to optimize this block, thats too much for 0 checking\n\t\tvar width int64\n\t\tvar err error\n\t\twidth, err = info.ThumbnailWidth.Int64()\n\t\tif err != nil {\n\t\t\twidth = 0\n\t\t}\n\t\t\/\/\/\/\n\t\tif len(info.ThumbnailURL) > 0 && width == 0 {\n\t\t\tp.fetchURLCalls = 0\n\t\t\tdata, newURL, _, err := p.fetchURL(info.ThumbnailURL)\n\t\t\tif err == nil {\n\t\t\t\tinfo.ThumbnailURL = newURL\n\t\t\t\tconfig, _, err := image.DecodeConfig(bytes.NewReader(data))\n\t\t\t\tif err == nil {\n\t\t\t\t\tinfo.ThumbnailWidth = json.Number(strconv.FormatInt(int64(config.Width), 10))\n\t\t\t\t\tinfo.ThumbnailHeight = json.Number(strconv.FormatInt(int64(config.Height), 10))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn info\n}\n\nfunc (p *Parser) parseOembed(u string) *oembed.Info {\n\t\/\/ check if we have it oembeded\n\tvar item *oembed.Item\n\n\tvar srvContentType string\n\n\tif p.oe != nil {\n\t\titem := p.oe.FindItem(u)\n\t\tif item != nil {\n\t\t\t\/\/ try to extract information\n\t\t\tei, _ := item.FetchOembed(u, p.client)\n\t\t\tif ei != nil && ei.Status < 300 {\n\t\t\t\treturn ei\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ fetch url\n\tdata, newURL, srvContentType, err := p.fetchURL(u)\n\n\tif err != nil {\n\t\tfor {\n\t\t\tif e, ok := err.(*url.Error); ok {\n\t\t\t\tif e, ok := e.Err.(*OembedRedirectGoodError); ok {\n\t\t\t\t\titem = e.GetItem()\n\t\t\t\t\t\/\/ TODO: optimize this.. calling the same code 2 times\n\t\t\t\t\tei, _ := item.FetchOembed(e.GetURL(), p.client)\n\t\t\t\t\tif ei != nil && ei.Status < 300 {\n\t\t\t\t\t\treturn ei\n\t\t\t\t\t}\n\n\t\t\t\t\tdata, newURL, srvContentType, err = p.fetchURL(e.GetURL())\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif data != nil {\n\t\tu = newURL\n\n\t\tcontentType := http.DetectContentType(data)\n\n\t\tif imageTypeRegex.MatchString(contentType) {\n\t\t\treturn p.getImageInfo(u, data)\n\t\t}\n\n\t\tif htmlTypeRegex.MatchString(contentType) {\n\t\t\treturn p.FetchOembedFromHTML(u, data, srvContentType)\n\t\t}\n\n\t\treturn p.getLinkInfo(u)\n\t}\n\n\treturn nil\n}\n\nfunc (p *Parser) getImageInfo(u string, data []byte) *oembed.Info {\n\tpu, _ := url.Parse(u)\n\n\tif pu == nil {\n\t\treturn nil\n\t}\n\n\tconfig, _, err := image.DecodeConfig(bytes.NewReader(data))\n\n\tinfo := oembed.NewInfo()\n\tinfo.Type = \"photo\"\n\tinfo.URL = u\n\tinfo.ProviderURL = \"http:\/\/\" + pu.Host\n\tinfo.ProviderName = pu.Host\n\n\tif err == nil {\n\t\tinfo.Width = json.Number(strconv.FormatInt(int64(config.Width), 10))\n\t\tinfo.Height = json.Number(strconv.FormatInt(int64(config.Height), 10))\n\t}\n\n\treturn info\n}\n\nfunc (p *Parser) getLinkInfo(u string) *oembed.Info {\n\tpu, _ := url.Parse(u)\n\n\tif pu == nil {\n\t\treturn nil\n\t}\n\n\tinfo := oembed.NewInfo()\n\tinfo.Type = \"link\"\n\tinfo.URL = u\n\tinfo.ProviderURL = \"http:\/\/\" + pu.Host\n\tinfo.ProviderName = pu.Host\n\n\treturn info\n}\n\n\/\/ FetchOembedFromHTML returns information extracted from html page\nfunc (p *Parser) FetchOembedFromHTML(pageURL string, data []byte, contentType string) *oembed.Info {\n\tbuf := bytes.NewReader(data)\n\tinfo := htmlinfo.NewHTMLInfo()\n\tinfo.Client = p.client\n\tinfo.AcceptLanguage = p.AcceptLanguage\n\tinfo.AllowOembedFetching = true\n\n\tif info.Parse(buf, &pageURL, &contentType) != nil {\n\t\treturn nil\n\t}\n\n\treturn info.GenerateOembedFor(pageURL)\n}\n\nfunc (p *Parser) fetchURL(url string) (data []byte, u string, contentType string, err error) {\n\tp.fetchURLCalls++\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Add(\"Accept-Language\", p.AcceptLanguage)\n\treq.Header.Set(\"User-Agent\", p.UserAgent)\n\n\tresp, err := p.client.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\n\tu = resp.Request.URL.String()\n\n\tcontentType = resp.Header.Get(\"Content-Type\")\n\n\tvar reader io.Reader\n\n\t\/\/ if we have some raw stream then we can't parse html, so need just mime\n\tif contentType == \"\" || htmlTypeRegex.MatchString(contentType) {\n\t\treader = io.LimitReader(resp.Body, p.MaxHTMLBodySize)\n\t} else {\n\t\treader = io.LimitReader(resp.Body, p.MaxBinaryBodySize)\n\t}\n\n\tdata, err = ioutil.ReadAll(reader)\n\n\treturn\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\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 siv\n\nimport (\n\t\"github.com\/jacobsa\/crypto\/common\"\n)\n\n\/\/ Given strings A and B with len(A) >= len(B), return a new slice consisting\n\/\/ of B xor'd onto the right end of A. This matches the xorend operator of RFC\n\/\/ 5297.\nfunc xorend(a, b []byte) []byte {\n\taLen := len(a)\n\tbLen := len(b)\n\n\tif aLen < bLen {\n\t\tpanic(\"Invalid lengths.\")\n\t}\n\n\tresult := make([]byte, aLen)\n\tcopy(result, a)\n\n\tdifference := aLen - bLen\n\tcopy(result[difference:], common.Xor(a[difference:], b))\n\n\treturn result\n}\nFixed siv\/xorend.go.\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\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 siv\n\nimport (\n\t\"github.com\/jacobsa\/crypto\/common\"\n)\n\n\/\/ Given strings A and B with len(A) >= len(B), return a new slice consisting\n\/\/ of B xor'd onto the right end of A. This matches the xorend operator of RFC\n\/\/ 5297.\nfunc xorend(a, b []byte) []byte {\n\taLen := len(a)\n\tbLen := len(b)\n\n\tif aLen < bLen {\n\t\tpanic(\"Invalid lengths.\")\n\t}\n\n\tresult := make([]byte, aLen)\n\tcopy(result, a)\n\n\tdifference := aLen - bLen\n\ttmp := make([]byte, bLen)\n\tcommon.Xor(tmp, a[difference:], b)\n\n\tcopy(result[difference:], tmp)\n\n\treturn result\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"sourcegraph.com\/sourcegraph\/appdash\"\n\t\"sourcegraph.com\/sourcegraph\/appdash\/httptrace\"\n\t\"sourcegraph.com\/sourcegraph\/appdash\/traceapp\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\n\tinfluxDBServer \"github.com\/influxdata\/influxdb\/cmd\/influxd\/run\"\n\t\"github.com\/influxdata\/influxdb\/toml\"\n)\n\nconst CtxSpanID = 0\n\nvar collector appdash.Collector\n\nfunc main() {\n\tconf, err := influxDBServer.NewDemoConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create influxdb config, error: %v\", err)\n\t}\n\n\t\/\/ Enables InfluxDB server authentication.\n\tconf.HTTPD.AuthEnabled = true\n\n\t\/\/ Enables retention policies which will be executed within an interval of 30 minutes.\n\tconf.Retention.Enabled = true\n\tconf.Retention.CheckInterval = toml.Duration(30 * time.Minute)\n\n\t\/\/ InfluxDB server auth credentials. If user does not exist yet it will\n\t\/\/ be created as admin user.\n\tuser := appdash.InfluxDBAdminUser{Username: \"demo\", Password: \"demo\"}\n\n\t\/\/ Retention policy named \"one_day_only\" with a duration of \"1d\" - meaning db data older than \"1d\" will be deleted\n\t\/\/ with an interval checking set by `conf.Retention.CheckInterval`.\n\t\/\/ Minimum duration time is 1 hour (\"1h\") - See: github.com\/influxdata\/influxdb\/issues\/5198\n\tdefaultRP := appdash.InfluxDBRetentionPolicy{Name: \"one_day_only\", Duration: \"1d\"}\n\n\tstore, err := appdash.NewInfluxDBStore(appdash.InfluxDBStoreConfig{\n\t\tAdminUser: user,\n\t\tBuildInfo: &influxDBServer.BuildInfo{},\n\t\tDefaultRP: defaultRP,\n\t\tServer: conf,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create influxdb store, error: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err := store.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\ttapp := traceapp.New(nil)\n\ttapp.Store = store\n\ttapp.Queryer = store\n\tlog.Println(\"Appdash web UI running on HTTP :8700\")\n\tgo func() {\n\t\tlog.Fatal(http.ListenAndServe(\":8700\", tapp))\n\t}()\n\tcollector = appdash.NewLocalCollector(store)\n\ttracemw := httptrace.Middleware(collector, &httptrace.MiddlewareConfig{\n\t\tRouteName: func(r *http.Request) string { return r.URL.Path },\n\t\tSetContextSpan: func(r *http.Request, spanID appdash.SpanID) {\n\t\t\tcontext.Set(r, CtxSpanID, spanID)\n\t\t},\n\t})\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\/\", Home)\n\trouter.HandleFunc(\"\/endpoint\", Endpoint)\n\tn := negroni.Classic()\n\tn.Use(negroni.HandlerFunc(tracemw))\n\tn.UseHandler(router)\n\tn.Run(\":8699\")\n}\n\nfunc Home(w http.ResponseWriter, r *http.Request) {\n\tspan := context.Get(r, CtxSpanID).(appdash.SpanID)\n\thttpClient := &http.Client{\n\t\tTransport: &httptrace.Transport{\n\t\t\tRecorder: appdash.NewRecorder(span, collector),\n\t\t\tSetName: true,\n\t\t},\n\t}\n\tfor i := 0; i < 3; i++ {\n\t\tresp, err := httpClient.Get(\"http:\/\/localhost:8699\/endpoint\")\n\t\tif err != nil {\n\t\t\tlog.Println(\"\/endpoint:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresp.Body.Close()\n\t}\n\tfmt.Fprintf(w, `

Three API requests have been made!<\/p>`)\n\tfmt.Fprintf(w, `

View the trace (ID:%s)<\/a><\/p>`, span.Trace, span.Trace)\n}\n\nfunc Endpoint(w http.ResponseWriter, r *http.Request) {\n\ttime.Sleep(200 * time.Millisecond)\n\tfmt.Fprintf(w, \"Slept for 200ms!\")\n}\ndisables reporting to m.influxdb.compackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"sourcegraph.com\/sourcegraph\/appdash\"\n\t\"sourcegraph.com\/sourcegraph\/appdash\/httptrace\"\n\t\"sourcegraph.com\/sourcegraph\/appdash\/traceapp\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\n\tinfluxDBServer \"github.com\/influxdata\/influxdb\/cmd\/influxd\/run\"\n\t\"github.com\/influxdata\/influxdb\/toml\"\n)\n\nconst CtxSpanID = 0\n\nvar collector appdash.Collector\n\nfunc main() {\n\tconf, err := influxDBServer.NewDemoConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create influxdb config, error: %v\", err)\n\t}\n\n\t\/\/ Enables InfluxDB server authentication.\n\tconf.HTTPD.AuthEnabled = true\n\n\t\/\/ Enables retention policies which will be executed within an interval of 30 minutes.\n\tconf.Retention.Enabled = true\n\tconf.Retention.CheckInterval = toml.Duration(30 * time.Minute)\n\n\t\/\/ Disables sending anonymous data to m.influxdb.com\n\t\/\/ See: https:\/\/docs.influxdata.com\/influxdb\/v0.10\/administration\/config\/#reporting-disabled-false\n\tconf.ReportingDisabled = true\n\n\t\/\/ InfluxDB server auth credentials. If user does not exist yet it will\n\t\/\/ be created as admin user.\n\tuser := appdash.InfluxDBAdminUser{Username: \"demo\", Password: \"demo\"}\n\n\t\/\/ Retention policy named \"one_day_only\" with a duration of \"1d\" - meaning db data older than \"1d\" will be deleted\n\t\/\/ with an interval checking set by `conf.Retention.CheckInterval`.\n\t\/\/ Minimum duration time is 1 hour (\"1h\") - See: github.com\/influxdata\/influxdb\/issues\/5198\n\tdefaultRP := appdash.InfluxDBRetentionPolicy{Name: \"one_day_only\", Duration: \"1d\"}\n\n\tstore, err := appdash.NewInfluxDBStore(appdash.InfluxDBStoreConfig{\n\t\tAdminUser: user,\n\t\tBuildInfo: &influxDBServer.BuildInfo{},\n\t\tDefaultRP: defaultRP,\n\t\tServer: conf,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create influxdb store, error: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err := store.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\ttapp := traceapp.New(nil)\n\ttapp.Store = store\n\ttapp.Queryer = store\n\tlog.Println(\"Appdash web UI running on HTTP :8700\")\n\tgo func() {\n\t\tlog.Fatal(http.ListenAndServe(\":8700\", tapp))\n\t}()\n\tcollector = appdash.NewLocalCollector(store)\n\ttracemw := httptrace.Middleware(collector, &httptrace.MiddlewareConfig{\n\t\tRouteName: func(r *http.Request) string { return r.URL.Path },\n\t\tSetContextSpan: func(r *http.Request, spanID appdash.SpanID) {\n\t\t\tcontext.Set(r, CtxSpanID, spanID)\n\t\t},\n\t})\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\/\", Home)\n\trouter.HandleFunc(\"\/endpoint\", Endpoint)\n\tn := negroni.Classic()\n\tn.Use(negroni.HandlerFunc(tracemw))\n\tn.UseHandler(router)\n\tn.Run(\":8699\")\n}\n\nfunc Home(w http.ResponseWriter, r *http.Request) {\n\tspan := context.Get(r, CtxSpanID).(appdash.SpanID)\n\thttpClient := &http.Client{\n\t\tTransport: &httptrace.Transport{\n\t\t\tRecorder: appdash.NewRecorder(span, collector),\n\t\t\tSetName: true,\n\t\t},\n\t}\n\tfor i := 0; i < 3; i++ {\n\t\tresp, err := httpClient.Get(\"http:\/\/localhost:8699\/endpoint\")\n\t\tif err != nil {\n\t\t\tlog.Println(\"\/endpoint:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresp.Body.Close()\n\t}\n\tfmt.Fprintf(w, `

Three API requests have been made!<\/p>`)\n\tfmt.Fprintf(w, `

View the trace (ID:%s)<\/a><\/p>`, span.Trace, span.Trace)\n}\n\nfunc Endpoint(w http.ResponseWriter, r *http.Request) {\n\ttime.Sleep(200 * time.Millisecond)\n\tfmt.Fprintf(w, \"Slept for 200ms!\")\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"math\/rand\"\n\n\t. \"github.com\/peterstace\/grayt\/examples\/cornellbox\"\n\t. \"github.com\/peterstace\/grayt\/grayt\"\n)\n\nfunc main() {\n\tRun(\"splitbox\", Scene{\n\t\tCamera: Cam(1.3),\n\t\tObjects: Group(\n\t\t\tFloor,\n\t\t\tCeiling,\n\t\t\tBackWall,\n\t\t\tLeftWall.With(ColourRGB(Red)),\n\t\t\tRightWall.With(ColourRGB(Green)),\n\t\t\tCeilingLight().With(Emittance(1)),\n\t\t\tsplitBox(),\n\t\t),\n\t})\n}\n\nconst (\n\tinitialBoxRadius = 0.2\n\tnumMovements = 30\n)\n\ntype box struct {\n\tmin, max Vector\n}\n\nfunc splitBox() ObjectList {\n\n\tv1 := Vect(0.5-initialBoxRadius, 0, -0.5+initialBoxRadius)\n\tv2 := Vect(0.5+initialBoxRadius, 2*initialBoxRadius, -0.5-initialBoxRadius)\n\tv1, v2 = v1.Min(v2), v1.Max(v2)\n\tboxes := []box{{v1, v2}}\n\n\trnd := rand.New(rand.NewSource(0))\n\tfor i := 0; i < numMovements; i++ {\n\t\tvar newBoxes []box\n\t\tfor _, box := range boxes {\n\n\t\t\tkind := rnd.Intn(6)\n\t\t\tfn := movements[kind]\n\n\t\t\tvar splitLocation float64\n\t\t\tswitch kind {\n\t\t\tcase 0, 4:\n\t\t\t\tsplitLocation = v1.X + (v2.X-v1.X)*rnd.Float64()\n\t\t\tcase 2, 3:\n\t\t\t\tsplitLocation = v1.Y + (v2.Y-v1.Y)*rnd.Float64()\n\t\t\tcase 1, 5:\n\t\t\t\tsplitLocation = v1.Z + (v2.Z-v1.Z)*rnd.Float64()\n\t\t\tdefault:\n\t\t\t\tpanic(false)\n\t\t\t}\n\n\t\t\tsplitAmount := (rnd.Float64() - 0.5) * 0.05\n\t\t\tsplitBoxes := fn(splitLocation, splitAmount, box)\n\t\t\tnewBoxes = append(newBoxes, splitBoxes...)\n\t\t}\n\t\tboxes = newBoxes\n\t}\n\n\tvar objList ObjectList\n\tfor _, box := range boxes {\n\t\tobjList = Group(objList, AlignedBox(box.min, box.max))\n\t}\n\treturn objList\n}\n\nfunc splitLeftRight(x float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(x, b.max.Y, b.max.Z)}\n\tb2 := box{Vect(x, b.min.Y, b.min.Z), b.max}\n\treturn b1, b2\n}\n\nfunc splitUpDown(y float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(b.max.X, y, b.max.Z)}\n\tb2 := box{Vect(b.min.X, y, b.min.Z), b.max}\n\treturn b1, b2\n}\n\nfunc splitFwdBack(z float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(b.max.X, b.max.Y, z)}\n\tb2 := box{Vect(b.min.X, b.min.Y, z), b.max}\n\treturn b1, b2\n}\n\nfunc heightMovementLeftRight(x float64, amount float64, input box) []box {\n\tif x < input.min.X || x > input.max.X {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitLeftRight(x, input)\n\tscale := amount \/ (2 * initialBoxRadius)\n\tb1.min.Y *= 1 + scale\n\tb1.max.Y *= 1 + scale\n\tb2.min.Y *= 1 - scale\n\tb2.max.Y *= 1 - scale\n\treturn []box{b1, b2}\n}\n\nfunc heightMovementFwdBack(z float64, amount float64, input box) []box {\n\tif z < input.min.Z || z > input.max.Z {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitFwdBack(z, input)\n\tscale := amount \/ (2 * initialBoxRadius)\n\tb1.min.Y *= 1 + scale\n\tb1.max.Y *= 1 + scale\n\tb2.min.Y *= 1 - scale\n\tb2.max.Y *= 1 - scale\n\treturn []box{b1, b2}\n}\n\nfunc layerMovementLeftRight(y float64, amount float64, input box) []box {\n\tif y < input.min.Y || y > input.max.Y {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitUpDown(y, input)\n\tb1.min.X += amount\n\tb1.max.X += amount\n\tb2.min.X -= amount\n\tb2.max.X -= amount\n\treturn []box{b1, b2}\n}\n\nfunc layerMovementFwdBack(y float64, amount float64, input box) []box {\n\tif y < input.min.Y || y > input.max.Y {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitUpDown(y, input)\n\tb1.min.Z += amount\n\tb1.max.Z += amount\n\tb2.min.Z -= amount\n\tb2.max.Z -= amount\n\treturn []box{b1, b2}\n}\n\nfunc shearFwdBack(x float64, amount float64, input box) []box {\n\tif x < input.min.X || x > input.max.X {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitLeftRight(x, input)\n\tb1.min.Z += amount\n\tb1.max.Z += amount\n\tb2.min.Z -= amount\n\tb2.max.Z -= amount\n\treturn []box{b1, b2}\n}\n\nfunc shearLeftRight(z float64, amount float64, input box) []box {\n\tif z < input.min.Z || z > input.max.Z {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitFwdBack(z, input)\n\tb1.min.X += amount\n\tb1.max.X += amount\n\tb2.min.X -= amount\n\tb2.max.X -= amount\n\treturn []box{b1, b2}\n}\n\nvar movements = [...]func(float64, float64, box) []box{\n\theightMovementLeftRight,\n\theightMovementFwdBack,\n\tlayerMovementLeftRight,\n\tlayerMovementFwdBack,\n\tshearFwdBack,\n\tshearLeftRight,\n}\nFocus camera on the interesting part of the scenepackage main\n\nimport (\n\t\"math\/rand\"\n\n\t. \"github.com\/peterstace\/grayt\/examples\/cornellbox\"\n\t. \"github.com\/peterstace\/grayt\/grayt\"\n)\n\nfunc main() {\n\tat := Vect(0.5, initialBoxRadius, -0.5)\n\tc := Cam(1.3)\n\tc.ViewDirection = at.Sub(c.Location)\n\tc.FieldOfViewInDegrees *= 0.5\n\tRun(\"splitbox\", Scene{\n\t\tCamera: c,\n\t\tObjects: Group(\n\t\t\tFloor,\n\t\t\tCeiling,\n\t\t\tBackWall,\n\t\t\tLeftWall.With(ColourRGB(Red)),\n\t\t\tRightWall.With(ColourRGB(Green)),\n\t\t\tCeilingLight().With(Emittance(1)),\n\t\t\tsplitBox(),\n\t\t),\n\t})\n}\n\nconst (\n\tinitialBoxRadius = 0.2\n\tnumMovements = 30\n)\n\ntype box struct {\n\tmin, max Vector\n}\n\nfunc splitBox() ObjectList {\n\n\tv1 := Vect(0.5-initialBoxRadius, 0, -0.5+initialBoxRadius)\n\tv2 := Vect(0.5+initialBoxRadius, 2*initialBoxRadius, -0.5-initialBoxRadius)\n\tv1, v2 = v1.Min(v2), v1.Max(v2)\n\tboxes := []box{{v1, v2}}\n\n\trnd := rand.New(rand.NewSource(0))\n\tfor i := 0; i < numMovements; i++ {\n\t\tvar newBoxes []box\n\t\tfor _, box := range boxes {\n\n\t\t\tkind := rnd.Intn(6)\n\t\t\tfn := movements[kind]\n\n\t\t\tvar splitLocation float64\n\t\t\tswitch kind {\n\t\t\tcase 0, 4:\n\t\t\t\tsplitLocation = v1.X + (v2.X-v1.X)*rnd.Float64()\n\t\t\tcase 2, 3:\n\t\t\t\tsplitLocation = v1.Y + (v2.Y-v1.Y)*rnd.Float64()\n\t\t\tcase 1, 5:\n\t\t\t\tsplitLocation = v1.Z + (v2.Z-v1.Z)*rnd.Float64()\n\t\t\tdefault:\n\t\t\t\tpanic(false)\n\t\t\t}\n\n\t\t\tsplitAmount := (rnd.Float64() - 0.5) * 0.05\n\t\t\tsplitBoxes := fn(splitLocation, splitAmount, box)\n\t\t\tnewBoxes = append(newBoxes, splitBoxes...)\n\t\t}\n\t\tboxes = newBoxes\n\t}\n\n\tvar objList ObjectList\n\tfor _, box := range boxes {\n\t\tobjList = Group(objList, AlignedBox(box.min, box.max))\n\t}\n\treturn objList\n}\n\nfunc splitLeftRight(x float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(x, b.max.Y, b.max.Z)}\n\tb2 := box{Vect(x, b.min.Y, b.min.Z), b.max}\n\treturn b1, b2\n}\n\nfunc splitUpDown(y float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(b.max.X, y, b.max.Z)}\n\tb2 := box{Vect(b.min.X, y, b.min.Z), b.max}\n\treturn b1, b2\n}\n\nfunc splitFwdBack(z float64, b box) (box, box) {\n\tb1 := box{b.min, Vect(b.max.X, b.max.Y, z)}\n\tb2 := box{Vect(b.min.X, b.min.Y, z), b.max}\n\treturn b1, b2\n}\n\nfunc heightMovementLeftRight(x float64, amount float64, input box) []box {\n\tif x < input.min.X || x > input.max.X {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitLeftRight(x, input)\n\tscale := amount \/ (2 * initialBoxRadius)\n\tb1.min.Y *= 1 + scale\n\tb1.max.Y *= 1 + scale\n\tb2.min.Y *= 1 - scale\n\tb2.max.Y *= 1 - scale\n\treturn []box{b1, b2}\n}\n\nfunc heightMovementFwdBack(z float64, amount float64, input box) []box {\n\tif z < input.min.Z || z > input.max.Z {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitFwdBack(z, input)\n\tscale := amount \/ (2 * initialBoxRadius)\n\tb1.min.Y *= 1 + scale\n\tb1.max.Y *= 1 + scale\n\tb2.min.Y *= 1 - scale\n\tb2.max.Y *= 1 - scale\n\treturn []box{b1, b2}\n}\n\nfunc layerMovementLeftRight(y float64, amount float64, input box) []box {\n\tif y < input.min.Y || y > input.max.Y {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitUpDown(y, input)\n\tb1.min.X += amount\n\tb1.max.X += amount\n\tb2.min.X -= amount\n\tb2.max.X -= amount\n\treturn []box{b1, b2}\n}\n\nfunc layerMovementFwdBack(y float64, amount float64, input box) []box {\n\tif y < input.min.Y || y > input.max.Y {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitUpDown(y, input)\n\tb1.min.Z += amount\n\tb1.max.Z += amount\n\tb2.min.Z -= amount\n\tb2.max.Z -= amount\n\treturn []box{b1, b2}\n}\n\nfunc shearFwdBack(x float64, amount float64, input box) []box {\n\tif x < input.min.X || x > input.max.X {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitLeftRight(x, input)\n\tb1.min.Z += amount\n\tb1.max.Z += amount\n\tb2.min.Z -= amount\n\tb2.max.Z -= amount\n\treturn []box{b1, b2}\n}\n\nfunc shearLeftRight(z float64, amount float64, input box) []box {\n\tif z < input.min.Z || z > input.max.Z {\n\t\treturn []box{input}\n\t}\n\tb1, b2 := splitFwdBack(z, input)\n\tb1.min.X += amount\n\tb1.max.X += amount\n\tb2.min.X -= amount\n\tb2.max.X -= amount\n\treturn []box{b1, b2}\n}\n\nvar movements = [...]func(float64, float64, box) []box{\n\theightMovementLeftRight,\n\theightMovementFwdBack,\n\tlayerMovementLeftRight,\n\tlayerMovementFwdBack,\n\tshearFwdBack,\n\tshearLeftRight,\n}\n<|endoftext|>"} {"text":"package carton\n\nimport (\n\t\"bytes\"\n\t\"strconv\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/megamsys\/libgo\/cmd\"\n\t\"github.com\/megamsys\/libgo\/api\"\n\t\"github.com\/megamsys\/libgo\/pairs\"\n\t\"github.com\/megamsys\/vertice\/provision\"\n\t\"github.com\/pivotal-golang\/bytefmt\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tSNAPSHOTBUCKET = \"snapshots\"\n\tDISKSBUCKET = \"disks\"\n\tACCOUNTID = \"account_id\"\n\tASSEMBLYID = \"asm_id\"\n)\n\ntype DiskOpts struct {\n\tB *provision.Box\n}\n\ntype ApiSnaps struct {\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tResults []Snaps `json:\"results\" cql:\"results\"`\n}\n\ntype ApiDisks struct {\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tResults []Disks `json:\"results\" cql:\"results\"`\n}\n\n\n\/\/The grand elephant for megam cloud platform.\ntype Snaps struct {\n\tId string `json:\"id\" cql:\"id\"`\n\tImageId string `json:\"image_id\" cql:\"image_id\"`\n\tOrgId string `json:\"org_id\" cql:\"org_id\"`\n\tAccountId string `json:\"account_id\" cql:\"account_id\"`\n\tName string `json:\"name\" cql:\"name\"`\n\tAssemblyId string `json:\"asm_id\" cql:\"asm_id\"`\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tCreatedAt string `json:\"created_at\" cql:\"created_at\"`\n\tStatus string `json:\"status\" cql:\"status\"`\n\tTosca string `json:\"tosca_type\" cql:\"tosca_type\"`\n\tInputs pairs.JsonPairs `json:\"inputs\" cql:\"inputs\"`\n\tOutputs pairs.JsonPairs `json:\"inputs\" cql:\"inputs\"`\n}\n\ntype Disks struct {\n\tId string `json:\"id\" cql:\"id\"`\n\tDiskId string `json:\"disk_id\" cql:\"disk_id\"`\n\tOrgId string `json:\"org_id\" cql:\"org_id\"`\n\tAccountId string `json:\"account_id\" cql:\"account_id\"`\n\tAssemblyId string `json:\"asm_id\" cql:\"asm_id\"`\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tCreatedAt string `json:\"created_at\" cql:\"created_at\"`\n\tSize string `json:\"size\" cql:\"size\"`\n\tStatus string `json:\"status\" cql:\"status\"`\n}\n\nfunc (a *Snaps) String() string {\n\tif d, err := yaml.Marshal(a); err != nil {\n\t\treturn err.Error()\n\t} else {\n\t\treturn string(d)\n\t}\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc SaveImage(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].SaveImage(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc DeleteImage(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].DeleteImage(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc AttachDisk(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].AttachDisk(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc DetachDisk(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].DetachDisk(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/** A public function which pulls the snapshot for disk save as image.\nand any others we do. **\/\nfunc GetSnap(id , email string) (*Snaps, error) {\n\tcl := api.NewClient(newArgs(email, \"\"), \"\/snapshots\/\" + id)\n\tresponse, err := cl.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thtmlData, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ApiSnaps{}\n\terr = json.Unmarshal(htmlData, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := &res.Results[0]\n\tlog.Debugf(\"Snaps %v\", a)\n\treturn a, nil\n}\n\nfunc (s *Snaps) UpdateSnap() error {\n\tcl := api.NewClient(newArgs(s.AccountId, s.OrgId),\"\/snapshots\/update\" )\n\tif _, err := cl.Post(s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\/** A public function which pulls the disks that attached to vm.\nand any others we do. **\/\nfunc GetDisks(id, email string) (*Disks, error) {\n\tcl := api.NewClient(newArgs(email,\"\"), \"\/disks\/\" + id)\n\tresponse, err := cl.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thtmlData, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ApiDisks{}\n\terr = json.Unmarshal(htmlData, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td := &res.Results[0]\n\tlog.Debugf(\"Disks %v\", d)\n\treturn d, nil\n}\n\nfunc (a *Disks) RemoveDisk() error {\n\tcl := api.NewClient(newArgs(a.AccountId, a.OrgId), \"\/disks\/\" + a.Id)\n\tif\t_, err := cl.Delete(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (a *Snaps) RemoveSnap() error {\n\tcl := api.NewClient(newArgs(a.AccountId, a.OrgId), \"\/snapshots\/\" + a.Id)\n\tif\t_, err := cl.Delete(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *Disks) UpdateDisk() error {\n\tcl := api.NewClient(newArgs(d.AccountId, d.OrgId), \"\/disks\/update\")\n\tif _, err := cl.Post(d); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\n\/\/make cartons from snaps.\nfunc (a *Snaps) MkCartons() (Cartons, error) {\n\tnewCs := make(Cartons, 0, 1)\n\tif len(strings.TrimSpace(a.AssemblyId)) > 1 {\n\t\tif ca, err := mkCarton(a.Id, a.AssemblyId, a.AccountId); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tca.toBox() \/\/on success, make a carton2box if BoxLevel is BoxZero\n\t\t\tnewCs = append(newCs, ca) \/\/on success append carton\n\t\t}\n\t}\n\tlog.Debugf(\"Cartons %v\", newCs)\n\treturn newCs, nil\n}\n\n\/\/make cartons from disks.\nfunc (d *Disks) MkCartons() (Cartons, error) {\n\tnewCs := make(Cartons, 0, 1)\n\tif len(strings.TrimSpace(d.AssemblyId)) > 1 {\n\t\tif ca, err := mkCarton(d.Id, d.AssemblyId, d.AccountId); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tca.toBox() \/\/on success, make a carton2box if BoxLevel is BoxZero\n\t\t\tnewCs = append(newCs, ca) \/\/on success append carton\n\t\t}\n\t}\n\tlog.Debugf(\"Cartons %v\", newCs)\n\treturn newCs, nil\n}\n\nfunc (bc *Disks) NumMemory() string {\n\tif cp, err := bytefmt.ToMegabytes(strings.Replace(bc.Size, \" \", \"\", -1)); err != nil {\n\t\treturn strconv.FormatUint(0, 10)\n\t} else {\n\t\treturn strconv.FormatUint(cp, 10)\n\t}\n}\nsnap and disk url changepackage carton\n\nimport (\n\t\"bytes\"\n\t\"strconv\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/megamsys\/libgo\/cmd\"\n\t\"github.com\/megamsys\/libgo\/api\"\n\t\"github.com\/megamsys\/libgo\/pairs\"\n\t\"github.com\/megamsys\/vertice\/provision\"\n\t\"github.com\/pivotal-golang\/bytefmt\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tSNAPSHOTBUCKET = \"snapshots\"\n\tDISKSBUCKET = \"disks\"\n\tACCOUNTID = \"account_id\"\n\tASSEMBLYID = \"asm_id\"\n)\n\ntype DiskOpts struct {\n\tB *provision.Box\n}\n\ntype ApiSnaps struct {\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tResults []Snaps `json:\"results\" cql:\"results\"`\n}\n\ntype ApiDisks struct {\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tResults []Disks `json:\"results\" cql:\"results\"`\n}\n\n\n\/\/The grand elephant for megam cloud platform.\ntype Snaps struct {\n\tId string `json:\"id\" cql:\"id\"`\n\tImageId string `json:\"image_id\" cql:\"image_id\"`\n\tOrgId string `json:\"org_id\" cql:\"org_id\"`\n\tAccountId string `json:\"account_id\" cql:\"account_id\"`\n\tName string `json:\"name\" cql:\"name\"`\n\tAssemblyId string `json:\"asm_id\" cql:\"asm_id\"`\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tCreatedAt string `json:\"created_at\" cql:\"created_at\"`\n\tStatus string `json:\"status\" cql:\"status\"`\n\tTosca string `json:\"tosca_type\" cql:\"tosca_type\"`\n\tInputs pairs.JsonPairs `json:\"inputs\" cql:\"inputs\"`\n\tOutputs pairs.JsonPairs `json:\"inputs\" cql:\"inputs\"`\n}\n\ntype Disks struct {\n\tId string `json:\"id\" cql:\"id\"`\n\tDiskId string `json:\"disk_id\" cql:\"disk_id\"`\n\tOrgId string `json:\"org_id\" cql:\"org_id\"`\n\tAccountId string `json:\"account_id\" cql:\"account_id\"`\n\tAssemblyId string `json:\"asm_id\" cql:\"asm_id\"`\n\tJsonClaz string `json:\"json_claz\" cql:\"json_claz\"`\n\tCreatedAt string `json:\"created_at\" cql:\"created_at\"`\n\tSize string `json:\"size\" cql:\"size\"`\n\tStatus string `json:\"status\" cql:\"status\"`\n}\n\nfunc (a *Snaps) String() string {\n\tif d, err := yaml.Marshal(a); err != nil {\n\t\treturn err.Error()\n\t} else {\n\t\treturn string(d)\n\t}\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc SaveImage(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].SaveImage(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc DeleteImage(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].DeleteImage(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc AttachDisk(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].AttachDisk(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/\/ ChangeState runs a state increment of a machine or a container.\nfunc DetachDisk(opts *DiskOpts) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{Box: opts.B}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&outBuffer, &logWriter)\n\terr := ProvisionerMap[opts.B.Provider].DetachDisk(opts.B, writer)\n\telapsed := time.Since(start)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tslog := outBuffer.String()\n\tlog.Debugf(\"%s in (%s)\\n%s\",\n\t\tcmd.Colorfy(opts.B.GetFullName(), \"cyan\", \"\", \"bold\"),\n\t\tcmd.Colorfy(elapsed.String(), \"green\", \"\", \"bold\"),\n\t\tcmd.Colorfy(slog, \"yellow\", \"\", \"\"))\n\treturn nil\n}\n\n\/** A public function which pulls the snapshot for disk save as image.\nand any others we do. **\/\nfunc GetSnap(id , email string) (*Snaps, error) {\n\tcl := api.NewClient(newArgs(email, \"\"), \"\/snapshots\/show\/\" + id)\n\tresponse, err := cl.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thtmlData, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ApiSnaps{}\n\terr = json.Unmarshal(htmlData, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := &res.Results[0]\n\tlog.Debugf(\"Snaps %v\", a)\n\treturn a, nil\n}\n\nfunc (s *Snaps) UpdateSnap() error {\n\tcl := api.NewClient(newArgs(s.AccountId, s.OrgId),\"\/snapshots\/update\" )\n\tif _, err := cl.Post(s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\/** A public function which pulls the disks that attached to vm.\nand any others we do. **\/\nfunc GetDisks(id, email string) (*Disks, error) {\n\tcl := api.NewClient(newArgs(email,\"\"), \"\/disks\/show\/\" + id)\n\tresponse, err := cl.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thtmlData, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &ApiDisks{}\n\terr = json.Unmarshal(htmlData, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td := &res.Results[0]\n\tlog.Debugf(\"Disks %v\", d)\n\treturn d, nil\n}\n\nfunc (a *Disks) RemoveDisk() error {\n\tcl := api.NewClient(newArgs(a.AccountId, a.OrgId), \"\/disks\/\" + a.Id)\n\tif\t_, err := cl.Delete(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (a *Snaps) RemoveSnap() error {\n\tcl := api.NewClient(newArgs(a.AccountId, a.OrgId), \"\/snapshots\/\" + a.Id)\n\tif\t_, err := cl.Delete(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (d *Disks) UpdateDisk() error {\n\tcl := api.NewClient(newArgs(d.AccountId, d.OrgId), \"\/disks\/update\")\n\tif _, err := cl.Post(d); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\n\/\/make cartons from snaps.\nfunc (a *Snaps) MkCartons() (Cartons, error) {\n\tnewCs := make(Cartons, 0, 1)\n\tif len(strings.TrimSpace(a.AssemblyId)) > 1 {\n\t\tif ca, err := mkCarton(a.Id, a.AssemblyId, a.AccountId); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tca.toBox() \/\/on success, make a carton2box if BoxLevel is BoxZero\n\t\t\tnewCs = append(newCs, ca) \/\/on success append carton\n\t\t}\n\t}\n\tlog.Debugf(\"Cartons %v\", newCs)\n\treturn newCs, nil\n}\n\n\/\/make cartons from disks.\nfunc (d *Disks) MkCartons() (Cartons, error) {\n\tnewCs := make(Cartons, 0, 1)\n\tif len(strings.TrimSpace(d.AssemblyId)) > 1 {\n\t\tif ca, err := mkCarton(d.Id, d.AssemblyId, d.AccountId); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tca.toBox() \/\/on success, make a carton2box if BoxLevel is BoxZero\n\t\t\tnewCs = append(newCs, ca) \/\/on success append carton\n\t\t}\n\t}\n\tlog.Debugf(\"Cartons %v\", newCs)\n\treturn newCs, nil\n}\n\nfunc (bc *Disks) NumMemory() string {\n\tif cp, err := bytefmt.ToMegabytes(strings.Replace(bc.Size, \" \", \"\", -1)); err != nil {\n\t\treturn strconv.FormatUint(0, 10)\n\t} else {\n\t\treturn strconv.FormatUint(cp, 10)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/davecheney\/mdns\"\n)\n\nfunc main() {\n\t\/\/ A simple example. Publish an A record for my router at 192.168.1.254.\n\tmdns.Publish(\"router.local. 3600 A 192, 168, 1, 254\")\n\n\t\/\/ A more compilcated example. Publish a SVR record for ssh running on port\n\t\/\/ 22 for my home NAS.\n\n\t\/\/ Publish an A record as before\n\tmdns.Publish(\"stora.local. 3600 A 192, 168, 1, 200\")\n\n\t\/\/ Publish a PTR record for the _ssh._tcp DNS-SD type\n\tmdns.Publish(\"_ssh._tcp.local. 3600 PTR stora._ssh._tcp.local.\")\n\n\t\/\/ Publish a SRV record tying the _ssh._tcp record to an A record and a port.\n\tmdns.Publish(\"stora._ssh._tcp.local. 3600 SRV stora.local. 22\")\n\n\t\/\/ Most mDNS browsing tools expect a TXT record for the service even if there\n\t\/\/ are not records defined by RFC 2782.\n\tmdns.Publish(`stora._ssh._tcp.local. 3600 \"\"`)\n\n\tselect {}\n}\nPublish records via Publishpackage main\n\nimport (\n\t\"log\"\n\t\"github.com\/davecheney\/mdns\"\n)\n\nfunc mustPublish(rr string){\n\tif err := mdns.Publish(rr) ; err != nil {\n\t\tlog.Fatalf(`Unable to publish record \"%s\": %v`, rr, err)\n\t}\n}\n\nfunc main() {\n\t\/\/ A simple example. Publish an A record for my router at 192.168.1.254.\n\tmustPublish(\"router.local. 60 IN A 192.168.1.254\")\n\n\t\/\/ A more compilcated example. Publish a SVR record for ssh running on port\n\t\/\/ 22 for my home NAS.\n\n\t\/\/ Publish an A record as before\n\tmustPublish(\"stora.local. 60 IN A 192.168.1.200\")\n\n\t\/\/ Publish a PTR record for the _ssh._tcp DNS-SD type\n\tmustPublish(\"_ssh._tcp.local. 60 IN PTR stora._ssh._tcp.local.\")\n\n\t\/\/ Publish a SRV record tying the _ssh._tcp record to an A record and a port.\n\tmustPublish(\"stora 60 IN SRV 0 0 22 stora.local.\")\n\n\t\/\/ Most mDNS browsing tools expect a TXT record for the service even if there\n\t\/\/ are not records defined by RFC 2782.\n\tmustPublish(`stora._ssh._tcp.local. 60 IN TXT \"\"`)\n\n\tselect {}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 Uber Technologies, Inc.\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\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/mailru\/easyjson\/parser\"\n\t\/\/ Reference the gen package to be friendly to vendoring tools,\n\t\/\/ as it is an indirect dependency.\n\t\/\/ (The temporary bootstrapping code uses it.)\n\t\"github.com\/mailru\/easyjson\/bootstrap\"\n\t_ \"github.com\/mailru\/easyjson\/gen\"\n\t\"io\/ioutil\"\n)\n\nvar allStructs = flag.Bool(\n\t\"all\",\n\tfalse,\n\t\"generate marshaler\/unmarshalers for all structs in a file\",\n)\n\nvar prefixBytes = []byte(\n\t\"\/\/ Code generated by zanzibar\\n\" +\n\t\t\"\/\/ @generated\\n\",\n)\n\nfunc generate(fname string) error {\n\tfInfo, err := os.Stat(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := parser.Parser{AllStructs: *allStructs}\n\tif err := p.Parse(fname, fInfo.IsDir()); err != nil {\n\t\treturn fmt.Errorf(\"Error parsing %v: %v\", fname, err)\n\t}\n\n\tvar outName string\n\tif fInfo.IsDir() {\n\t\toutName = filepath.Join(fname, p.PkgName+\"_easyjson.go\")\n\t} else {\n\t\ts := strings.TrimSuffix(fname, \".go\")\n\t\tif s == fname {\n\t\t\treturn errors.New(\"Filename must end in '.go'\")\n\t\t}\n\t\toutName = s + \"_easyjson.go\"\n\t}\n\n\tg := bootstrap.Generator{\n\t\tBuildTags: \"\",\n\t\tPkgPath: p.PkgPath,\n\t\tPkgName: p.PkgName,\n\t\tTypes: p.StructNames,\n\t\tSnakeCase: false,\n\t\tNoStdMarshalers: false,\n\t\tOmitEmpty: false,\n\t\tLeaveTemps: false,\n\t\tOutName: outName,\n\t\tStubsOnly: false,\n\t\tNoFormat: false,\n\t}\n\n\tif err := g.Run(); err != nil {\n\t\treturn fmt.Errorf(\"Bootstrap failed: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tfiles := flag.Args()\n\tif len(files) != 1 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\tfile := files[0]\n\n\tif err := generate(file); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\teasyJSONFile := file[0:len(file)-3] + \"_easyjson.go\"\n\tbytes, err := ioutil.ReadFile(easyJSONFile)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tnewBytes := make([]byte, len(bytes)+len(prefixBytes))\n\tcopy(newBytes, prefixBytes)\n\tcopy(newBytes[len(prefixBytes):], bytes)\n\n\terr = ioutil.WriteFile(easyJSONFile, newBytes, 0644)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\nscripts\/easy_json : add checksum to short circuit generation\/\/ Copyright (c) 2017 Uber Technologies, Inc.\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\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/mailru\/easyjson\/parser\"\n\t\/\/ Reference the gen package to be friendly to vendoring tools,\n\t\/\/ as it is an indirect dependency.\n\t\/\/ (The temporary bootstrapping code uses it.)\n\t\"github.com\/mailru\/easyjson\/bootstrap\"\n\t_ \"github.com\/mailru\/easyjson\/gen\"\n)\n\nvar allStructs = flag.Bool(\n\t\"all\",\n\tfalse,\n\t\"generate marshaler\/unmarshalers for all structs in a file\",\n)\n\nvar checksumPrefix = \"\/\/ Checksum : \"\nvar prefixBytes = []byte(\n\t\"\/\/ Code generated by zanzibar\\n\" +\n\t\t\"\/\/ @generated\\n\",\n)\n\nfunc generate(fname string) error {\n\tfInfo, err := os.Stat(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := parser.Parser{AllStructs: *allStructs}\n\tif err := p.Parse(fname, fInfo.IsDir()); err != nil {\n\t\treturn fmt.Errorf(\"Error parsing %v: %v\", fname, err)\n\t}\n\n\tvar outName string\n\tif fInfo.IsDir() {\n\t\toutName = filepath.Join(fname, p.PkgName+\"_easyjson.go\")\n\t} else {\n\t\ts := strings.TrimSuffix(fname, \".go\")\n\t\tif s == fname {\n\t\t\treturn errors.New(\"Filename must end in '.go'\")\n\t\t}\n\t\toutName = s + \"_easyjson.go\"\n\t}\n\n\tg := bootstrap.Generator{\n\t\tBuildTags: \"\",\n\t\tPkgPath: p.PkgPath,\n\t\tPkgName: p.PkgName,\n\t\tTypes: p.StructNames,\n\t\tSnakeCase: false,\n\t\tNoStdMarshalers: false,\n\t\tOmitEmpty: false,\n\t\tLeaveTemps: false,\n\t\tOutName: outName,\n\t\tStubsOnly: false,\n\t\tNoFormat: false,\n\t}\n\n\tif err := g.Run(); err != nil {\n\t\treturn fmt.Errorf(\"Bootstrap failed: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc getOldChecksum(easyJSONFile string) string {\n\toldEasyJSONBytes, err := ioutil.ReadFile(easyJSONFile)\n\tif err == nil {\n\t\tsliceStart := len(prefixBytes) + len(checksumPrefix)\n\t\tsliceEnd := len(prefixBytes) + len(checksumPrefix) + 24\n\t\treturn string(oldEasyJSONBytes[sliceStart:sliceEnd])\n\t}\n\n\treturn \"\"\n}\n\nfunc getNewChecksum(file string) string {\n\tfileBytes, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t\treturn \"\"\n\t}\n\n\tchecksum := md5.Sum(fileBytes)\n\treturn base64.StdEncoding.EncodeToString(checksum[:])\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tfiles := flag.Args()\n\tif len(files) != 1 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\n\tfor _, file := range files {\n\t\teasyJSONFile := file[0:len(file)-3] + \"_easyjson.go\"\n\t\toldChecksum := getOldChecksum(easyJSONFile)\n\t\tnewChecksum := getNewChecksum(file)\n\n\t\t\/\/ If we have an checksum in easyjson file check it.\n\t\tif oldChecksum != \"\" && oldChecksum == newChecksum {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := generate(file); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t\treturn\n\t\t}\n\n\t\tbytes, err := ioutil.ReadFile(easyJSONFile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t\treturn\n\t\t}\n\n\t\tchecksumLine := checksumPrefix + newChecksum + \"\\n\"\n\t\tnewLength := len(bytes) + len(prefixBytes) + len(checksumLine)\n\n\t\tnewBytes := make([]byte, newLength)\n\t\tcopy(newBytes, prefixBytes)\n\t\tcopy(newBytes[len(prefixBytes):], []byte(checksumLine))\n\t\tcopy(newBytes[len(prefixBytes)+len(checksumLine):], bytes)\n\n\t\terr = ioutil.WriteFile(easyJSONFile, newBytes, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package filer\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\/log_buffer\"\n)\n\ntype MetaAggregator struct {\n\tfilers []string\n\tgrpcDialOption grpc.DialOption\n\tMetaLogBuffer *log_buffer.LogBuffer\n\t\/\/ notifying clients\n\tListenersLock sync.Mutex\n\tListenersCond *sync.Cond\n}\n\n\/\/ MetaAggregator only aggregates data \"on the fly\". The logs are not re-persisted to disk.\n\/\/ The old data comes from what each LocalMetadata persisted on disk.\nfunc NewMetaAggregator(filers []string, grpcDialOption grpc.DialOption) *MetaAggregator {\n\tt := &MetaAggregator{\n\t\tfilers: filers,\n\t\tgrpcDialOption: grpcDialOption,\n\t}\n\tt.ListenersCond = sync.NewCond(&t.ListenersLock)\n\tt.MetaLogBuffer = log_buffer.NewLogBuffer(LogFlushInterval, nil, func() {\n\t\tt.ListenersCond.Broadcast()\n\t})\n\treturn t\n}\n\nfunc (ma *MetaAggregator) StartLoopSubscribe(f *Filer, self string) {\n\tfor _, filer := range ma.filers {\n\t\tgo ma.subscribeToOneFiler(f, self, filer)\n\t}\n}\n\nfunc (ma *MetaAggregator) subscribeToOneFiler(f *Filer, self string, peer string) {\n\n\t\/*\n\t\tEach filer reads the \"filer.store.id\", which is the store's signature when filer starts.\n\n\t\tWhen reading from other filers' local meta changes:\n\t\t* if the received change does not contain signature from self, apply the change to current filer store.\n\n\t\tUpon connecting to other filers, need to remember their signature and their offsets.\n\n\t*\/\n\n\tvar maybeReplicateMetadataChange func(*filer_pb.SubscribeMetadataResponse)\n\tlastPersistTime := time.Now()\n\tlastTsNs := time.Now().Add(-LogFlushInterval).UnixNano()\n\n\tpeerSignature, err := ma.readFilerStoreSignature(peer)\n\tfor err != nil {\n\t\tglog.V(0).Infof(\"connecting to peer filer %s: %v\", peer, err)\n\t\ttime.Sleep(1357 * time.Millisecond)\n\t\tpeerSignature, err = ma.readFilerStoreSignature(peer)\n\t}\n\n\tif peerSignature != f.Signature {\n\t\tif prevTsNs, err := ma.readOffset(f, peer, peerSignature); err == nil {\n\t\t\tlastTsNs = prevTsNs\n\t\t}\n\n\t\tglog.V(0).Infof(\"follow peer: %v, last %v (%d)\", peer, time.Unix(0, lastTsNs), lastTsNs)\n\t\tvar counter int64\n\t\tvar synced bool\n\t\tmaybeReplicateMetadataChange = func(event *filer_pb.SubscribeMetadataResponse) {\n\t\t\tif err := Replay(f.Store, event); err != nil {\n\t\t\t\tglog.Errorf(\"failed to reply metadata change from %v: %v\", peer, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcounter++\n\t\t\tif lastPersistTime.Add(time.Minute).Before(time.Now()) {\n\t\t\t\tif err := ma.updateOffset(f, peer, peerSignature, event.TsNs); err == nil {\n\t\t\t\t\tif event.TsNs < time.Now().Add(-2*time.Minute).UnixNano() {\n\t\t\t\t\t\tglog.V(0).Infof(\"sync with %s progressed to: %v %0.2f\/sec\", peer, time.Unix(0, event.TsNs), float64(counter)\/60.0)\n\t\t\t\t\t} else if !synced {\n\t\t\t\t\t\tsynced = true\n\t\t\t\t\t\tglog.V(0).Infof(\"synced with %s\", peer)\n\t\t\t\t\t}\n\t\t\t\t\tlastPersistTime = time.Now()\n\t\t\t\t\tcounter = 0\n\t\t\t\t} else {\n\t\t\t\t\tglog.V(0).Infof(\"failed to update offset for %v: %v\", peer, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprocessEventFn := func(event *filer_pb.SubscribeMetadataResponse) error {\n\t\tdata, err := proto.Marshal(event)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"failed to marshal subscribed filer_pb.SubscribeMetadataResponse %+v: %v\", event, err)\n\t\t\treturn err\n\t\t}\n\t\tdir := event.Directory\n\t\t\/\/ println(\"received meta change\", dir, \"size\", len(data))\n\t\tma.MetaLogBuffer.AddToBuffer([]byte(dir), data, 0)\n\t\tif maybeReplicateMetadataChange != nil {\n\t\t\tmaybeReplicateMetadataChange(event)\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor {\n\t\terr := pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tdefer cancel()\n\t\t\tstream, err := client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{\n\t\t\t\tClientName: \"filer:\" + self,\n\t\t\t\tPathPrefix: \"\/\",\n\t\t\t\tSinceNs: lastTsNs,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"subscribe: %v\", err)\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tresp, listenErr := stream.Recv()\n\t\t\t\tif listenErr == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tif listenErr != nil {\n\t\t\t\t\treturn listenErr\n\t\t\t\t}\n\n\t\t\t\tif err := processEventFn(resp); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"process %v: %v\", resp, err)\n\t\t\t\t}\n\t\t\t\tlastTsNs = resp.TsNs\n\n\t\t\t\tf.onMetadataChangeEvent(resp)\n\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"subscribing remote %s meta change: %v\", peer, err)\n\t\t\ttime.Sleep(1733 * time.Millisecond)\n\t\t}\n\t}\n}\n\nfunc (ma *MetaAggregator) readFilerStoreSignature(peer string) (sig int32, err error) {\n\terr = pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\tresp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsig = resp.Signature\n\t\treturn nil\n\t})\n\treturn\n}\n\nconst (\n\tMetaOffsetPrefix = \"Meta\"\n)\n\nfunc (ma *MetaAggregator) readOffset(f *Filer, peer string, peerSignature int32) (lastTsNs int64, err error) {\n\n\tkey := []byte(MetaOffsetPrefix + \"xxxx\")\n\tutil.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))\n\n\tvalue, err := f.Store.KvGet(context.Background(), key)\n\n\tif err == ErrKvNotFound {\n\t\tglog.Warningf(\"readOffset %s not found\", peer)\n\t\treturn 0, nil\n\t}\n\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"readOffset %s : %v\", peer, err)\n\t}\n\n\tlastTsNs = int64(util.BytesToUint64(value))\n\n\tglog.V(0).Infof(\"readOffset %s : %d\", peer, lastTsNs)\n\n\treturn\n}\n\nfunc (ma *MetaAggregator) updateOffset(f *Filer, peer string, peerSignature int32, lastTsNs int64) (err error) {\n\n\tkey := []byte(MetaOffsetPrefix + \"xxxx\")\n\tutil.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))\n\n\tvalue := make([]byte, 8)\n\tutil.Uint64toBytes(value, uint64(lastTsNs))\n\n\terr = f.Store.KvPut(context.Background(), key, value)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"updateOffset %s : %v\", peer, err)\n\t}\n\n\tglog.V(4).Infof(\"updateOffset %s : %d\", peer, lastTsNs)\n\n\treturn\n}\nadd commentspackage filer\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\/log_buffer\"\n)\n\ntype MetaAggregator struct {\n\tfilers []string\n\tgrpcDialOption grpc.DialOption\n\tMetaLogBuffer *log_buffer.LogBuffer\n\t\/\/ notifying clients\n\tListenersLock sync.Mutex\n\tListenersCond *sync.Cond\n}\n\n\/\/ MetaAggregator only aggregates data \"on the fly\". The logs are not re-persisted to disk.\n\/\/ The old data comes from what each LocalMetadata persisted on disk.\nfunc NewMetaAggregator(filers []string, grpcDialOption grpc.DialOption) *MetaAggregator {\n\tt := &MetaAggregator{\n\t\tfilers: filers,\n\t\tgrpcDialOption: grpcDialOption,\n\t}\n\tt.ListenersCond = sync.NewCond(&t.ListenersLock)\n\tt.MetaLogBuffer = log_buffer.NewLogBuffer(LogFlushInterval, nil, func() {\n\t\tt.ListenersCond.Broadcast()\n\t})\n\treturn t\n}\n\nfunc (ma *MetaAggregator) StartLoopSubscribe(f *Filer, self string) {\n\tfor _, filer := range ma.filers {\n\t\tgo ma.subscribeToOneFiler(f, self, filer)\n\t}\n}\n\nfunc (ma *MetaAggregator) subscribeToOneFiler(f *Filer, self string, peer string) {\n\n\t\/*\n\t\tEach filer reads the \"filer.store.id\", which is the store's signature when filer starts.\n\n\t\tWhen reading from other filers' local meta changes:\n\t\t* if the received change does not contain signature from self, apply the change to current filer store.\n\n\t\tUpon connecting to other filers, need to remember their signature and their offsets.\n\n\t*\/\n\n\tvar maybeReplicateMetadataChange func(*filer_pb.SubscribeMetadataResponse)\n\tlastPersistTime := time.Now()\n\tlastTsNs := time.Now().Add(-LogFlushInterval).UnixNano()\n\n\tpeerSignature, err := ma.readFilerStoreSignature(peer)\n\tfor err != nil {\n\t\tglog.V(0).Infof(\"connecting to peer filer %s: %v\", peer, err)\n\t\ttime.Sleep(1357 * time.Millisecond)\n\t\tpeerSignature, err = ma.readFilerStoreSignature(peer)\n\t}\n\n\t\/\/ when filer store is not shared by multiple filers\n\tif peerSignature != f.Signature {\n\t\tif prevTsNs, err := ma.readOffset(f, peer, peerSignature); err == nil {\n\t\t\tlastTsNs = prevTsNs\n\t\t}\n\n\t\tglog.V(0).Infof(\"follow peer: %v, last %v (%d)\", peer, time.Unix(0, lastTsNs), lastTsNs)\n\t\tvar counter int64\n\t\tvar synced bool\n\t\tmaybeReplicateMetadataChange = func(event *filer_pb.SubscribeMetadataResponse) {\n\t\t\tif err := Replay(f.Store, event); err != nil {\n\t\t\t\tglog.Errorf(\"failed to reply metadata change from %v: %v\", peer, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcounter++\n\t\t\tif lastPersistTime.Add(time.Minute).Before(time.Now()) {\n\t\t\t\tif err := ma.updateOffset(f, peer, peerSignature, event.TsNs); err == nil {\n\t\t\t\t\tif event.TsNs < time.Now().Add(-2*time.Minute).UnixNano() {\n\t\t\t\t\t\tglog.V(0).Infof(\"sync with %s progressed to: %v %0.2f\/sec\", peer, time.Unix(0, event.TsNs), float64(counter)\/60.0)\n\t\t\t\t\t} else if !synced {\n\t\t\t\t\t\tsynced = true\n\t\t\t\t\t\tglog.V(0).Infof(\"synced with %s\", peer)\n\t\t\t\t\t}\n\t\t\t\t\tlastPersistTime = time.Now()\n\t\t\t\t\tcounter = 0\n\t\t\t\t} else {\n\t\t\t\t\tglog.V(0).Infof(\"failed to update offset for %v: %v\", peer, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprocessEventFn := func(event *filer_pb.SubscribeMetadataResponse) error {\n\t\tdata, err := proto.Marshal(event)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"failed to marshal subscribed filer_pb.SubscribeMetadataResponse %+v: %v\", event, err)\n\t\t\treturn err\n\t\t}\n\t\tdir := event.Directory\n\t\t\/\/ println(\"received meta change\", dir, \"size\", len(data))\n\t\tma.MetaLogBuffer.AddToBuffer([]byte(dir), data, 0)\n\t\tif maybeReplicateMetadataChange != nil {\n\t\t\tmaybeReplicateMetadataChange(event)\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor {\n\t\terr := pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tdefer cancel()\n\t\t\tstream, err := client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{\n\t\t\t\tClientName: \"filer:\" + self,\n\t\t\t\tPathPrefix: \"\/\",\n\t\t\t\tSinceNs: lastTsNs,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"subscribe: %v\", err)\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tresp, listenErr := stream.Recv()\n\t\t\t\tif listenErr == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tif listenErr != nil {\n\t\t\t\t\treturn listenErr\n\t\t\t\t}\n\n\t\t\t\tif err := processEventFn(resp); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"process %v: %v\", resp, err)\n\t\t\t\t}\n\t\t\t\tlastTsNs = resp.TsNs\n\n\t\t\t\tf.onMetadataChangeEvent(resp)\n\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"subscribing remote %s meta change: %v\", peer, err)\n\t\t\ttime.Sleep(1733 * time.Millisecond)\n\t\t}\n\t}\n}\n\nfunc (ma *MetaAggregator) readFilerStoreSignature(peer string) (sig int32, err error) {\n\terr = pb.WithFilerClient(peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\tresp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsig = resp.Signature\n\t\treturn nil\n\t})\n\treturn\n}\n\nconst (\n\tMetaOffsetPrefix = \"Meta\"\n)\n\nfunc (ma *MetaAggregator) readOffset(f *Filer, peer string, peerSignature int32) (lastTsNs int64, err error) {\n\n\tkey := []byte(MetaOffsetPrefix + \"xxxx\")\n\tutil.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))\n\n\tvalue, err := f.Store.KvGet(context.Background(), key)\n\n\tif err == ErrKvNotFound {\n\t\tglog.Warningf(\"readOffset %s not found\", peer)\n\t\treturn 0, nil\n\t}\n\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"readOffset %s : %v\", peer, err)\n\t}\n\n\tlastTsNs = int64(util.BytesToUint64(value))\n\n\tglog.V(0).Infof(\"readOffset %s : %d\", peer, lastTsNs)\n\n\treturn\n}\n\nfunc (ma *MetaAggregator) updateOffset(f *Filer, peer string, peerSignature int32, lastTsNs int64) (err error) {\n\n\tkey := []byte(MetaOffsetPrefix + \"xxxx\")\n\tutil.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))\n\n\tvalue := make([]byte, 8)\n\tutil.Uint64toBytes(value, uint64(lastTsNs))\n\n\terr = f.Store.KvPut(context.Background(), key, value)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"updateOffset %s : %v\", peer, err)\n\t}\n\n\tglog.V(4).Infof(\"updateOffset %s : %d\", peer, lastTsNs)\n\n\treturn\n}\n<|endoftext|>"} {"text":"package countmin\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc Benchmark_New_1000(b *testing.B) { benchNew(b, 1000) }\nfunc Benchmark_New_10000(b *testing.B) { benchNew(b, 10000) }\n\nfunc benchNew(b *testing.B, total int) {\n\tfor i := 0; i < b.N; i++ {\n\t\tNew(total, total)\n\t}\n}\n\nfunc Benchmark_Add_1000(b *testing.B) { benchAdd(b, 1000) }\nfunc benchAdd(b *testing.B, total int) {\n\tcm := New(200, 200)\n\tb.ResetTimer()\n\tvar i int64\n\tfor i = 0; i < int64(b.N); i++ {\n\t\tcm.Add([]byte(fmt.Sprintf(\"http:\/\/domain%d.com\/page%d\", i, i)), i)\n\t}\n}\nBenchmark addpackage countmin\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc Benchmark_New_1000(b *testing.B) { benchNew(b, 1000) }\nfunc Benchmark_New_10000(b *testing.B) { benchNew(b, 10000) }\n\nfunc benchNew(b *testing.B, total int) {\n\tfor i := 0; i < b.N; i++ {\n\t\tNew(total, total)\n\t}\n}\n\nfunc Benchmark_Add_1000(b *testing.B) { benchAdd(b, 1000) }\nfunc Benchmark_Add_10000(b *testing.B) { benchAdd(b, 10000) }\nfunc Benchmark_Add_100000(b *testing.B) { benchAdd(b, 1000000) }\nfunc benchAdd(b *testing.B, total int) {\n\tcm := New(40, 200)\n\tb.ResetTimer()\n\tvar i int64\n\tfor i = 0; i < int64(b.N); i++ {\n\t\tcm.Add([]byte(fmt.Sprintf(\"http:\/\/domain%d.com\/page%d\", i, i)), i)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\tRelaseNotFound = errors.New(\"release is not found\")\n)\n\ntype GitHub interface {\n\tCreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error)\n\tGetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error)\n\tDeleteRelease(ctx context.Context, releaseID int) error\n\tDeleteTag(ctx context.Context, tag string) error\n\n\tUploadAsset(ctx context.Context, releaseID int, filename string) (*github.ReleaseAsset, error)\n\tDeleteAsset(ctx context.Context, assetID int) error\n\tListAssets(ctx context.Context, releaseID int) ([]*github.ReleaseAsset, error)\n\n\tSetUploadURL(urlStr string) error\n}\n\ntype GitHubClient struct {\n\tOwner, Repo string\n\t*github.Client\n}\n\nfunc NewGitHubClient(owner, repo, token string, urlStr string) (GitHub, error) {\n\tif len(owner) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub repository owner\")\n\t}\n\n\tif len(owner) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub repository name\")\n\t}\n\n\tif len(token) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub API token\")\n\t}\n\n\tif len(urlStr) == 0 {\n\t\treturn nil, errors.New(\"missgig GitHub API URL\")\n\t}\n\n\tbaseURL, err := url.ParseRequestURI(urlStr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to parse Github API URL\")\n\t}\n\n\tts := oauth2.StaticTokenSource(&oauth2.Token{\n\t\tAccessToken: token,\n\t})\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\n\tclient := github.NewClient(tc)\n\tclient.BaseURL = baseURL\n\n\treturn &GitHubClient{\n\t\tOwner: owner,\n\t\tRepo: repo,\n\t\tClient: client,\n\t}, nil\n}\n\nfunc (c *GitHubClient) SetUploadURL(urlStr string) error {\n\ti := strings.Index(urlStr, \"repos\/\")\n\tparsedURL, err := url.ParseRequestURI(urlStr[:i])\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faield to parse upload URL\")\n\t}\n\n\tc.UploadURL = parsedURL\n\treturn nil\n}\n\nfunc (c *GitHubClient) CreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {\n\n\trelease, res, err := c.Repositories.CreateRelease(c.Owner, c.Repo, req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create a release\")\n\t}\n\n\tif res.StatusCode != http.StatusCreated {\n\t\treturn nil, errors.Errorf(\"create release: invalid status: %s\", res.Status)\n\t}\n\n\treturn release, nil\n}\n\nfunc (c *GitHubClient) GetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error) {\n\t\/\/ Check Release is already exist or not\n\trelease, res, err := c.Repositories.GetReleaseByTag(c.Owner, c.Repo, tag)\n\tif err != nil {\n\t\tif res == nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get release tag: %s\", tag)\n\t\t}\n\n\t\t\/\/ TODO(tcnksm): Handle invalid token\n\t\tif res.StatusCode != http.StatusNotFound {\n\t\t\treturn nil, errors.Wrapf(err,\n\t\t\t\t\"get release tag: invalid status: %s\", res.Status)\n\t\t}\n\n\t\treturn nil, RelaseNotFound\n\t}\n\n\treturn release, nil\n}\n\nfunc (c *GitHubClient) DeleteRelease(ctx context.Context, releaseID int) error {\n\tres, err := c.Repositories.DeleteRelease(c.Owner, c.Repo, releaseID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to delete release\")\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete release: invalid status: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) DeleteTag(ctx context.Context, tag string) error {\n\tref := fmt.Sprintf(\"tags\/%s\", tag)\n\tres, err := c.Git.DeleteRef(c.Owner, c.Repo, ref)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete tag: %s\", ref)\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete tag: invalid status: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) UploadAsset(ctx context.Context, releaseID int, filename string) (*github.ReleaseAsset, error) {\n\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get abs path\")\n\t}\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open file\")\n\t}\n\n\topts := &github.UploadOptions{\n\t\t\/\/ Use base name by default\n\t\tName: filepath.Base(filename),\n\t}\n\n\tasset, res, err := c.Repositories.UploadReleaseAsset(c.Owner, c.Repo, releaseID, opts, f)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to upload release asset: %s\", filename)\n\t}\n\n\tswitch res.StatusCode {\n\tcase http.StatusCreated:\n\t\treturn asset, nil\n\tcase 422:\n\t\treturn nil, errors.Errorf(\n\t\t\t\"upload release asset: invalid status code: %s\",\n\t\t\t\"422 (this is probably because the asset already uploaded)\")\n\tdefault:\n\t\treturn nil, errors.Errorf(\n\t\t\t\"upload release asset: invalid status code: %s\", res.Status)\n\t}\n}\n\nfunc (c *GitHubClient) DeleteAsset(ctx context.Context, assetID int) error {\n\tres, err := c.Repositories.DeleteReleaseAsset(c.Owner, c.Repo, assetID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to delete release asset\")\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete release assets: invalid status code: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) ListAssets(ctx context.Context, releaseID int) ([]*github.ReleaseAsset, error) {\n\tresult := []*github.ReleaseAsset{}\n\tpage := 1\n\n\tfor {\n\t\tassets, res, err := c.Repositories.ListReleaseAssets(c.Owner, c.Repo, releaseID, &github.ListOptions{Page: page})\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to list assets\")\n\t\t}\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.Errorf(\"list release assets: invalid status code: %s\", res.Status)\n\t\t}\n\n\t\tresult = append(result, assets...)\n\n\t\tif res.NextPage <= page {\n\t\t\tbreak\n\t\t}\n\n\t\tpage = res.NextPage\n\t}\n\n\treturn result, nil\n}\nFix arguments check in NewGithubClientpackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\tRelaseNotFound = errors.New(\"release is not found\")\n)\n\ntype GitHub interface {\n\tCreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error)\n\tGetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error)\n\tDeleteRelease(ctx context.Context, releaseID int) error\n\tDeleteTag(ctx context.Context, tag string) error\n\n\tUploadAsset(ctx context.Context, releaseID int, filename string) (*github.ReleaseAsset, error)\n\tDeleteAsset(ctx context.Context, assetID int) error\n\tListAssets(ctx context.Context, releaseID int) ([]*github.ReleaseAsset, error)\n\n\tSetUploadURL(urlStr string) error\n}\n\ntype GitHubClient struct {\n\tOwner, Repo string\n\t*github.Client\n}\n\nfunc NewGitHubClient(owner, repo, token string, urlStr string) (GitHub, error) {\n\tif len(owner) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub repository owner\")\n\t}\n\n\tif len(repo) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub repository name\")\n\t}\n\n\tif len(token) == 0 {\n\t\treturn nil, errors.New(\"missing GitHub API token\")\n\t}\n\n\tif len(urlStr) == 0 {\n\t\treturn nil, errors.New(\"missgig GitHub API URL\")\n\t}\n\n\tbaseURL, err := url.ParseRequestURI(urlStr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to parse Github API URL\")\n\t}\n\n\tts := oauth2.StaticTokenSource(&oauth2.Token{\n\t\tAccessToken: token,\n\t})\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\n\tclient := github.NewClient(tc)\n\tclient.BaseURL = baseURL\n\n\treturn &GitHubClient{\n\t\tOwner: owner,\n\t\tRepo: repo,\n\t\tClient: client,\n\t}, nil\n}\n\nfunc (c *GitHubClient) SetUploadURL(urlStr string) error {\n\ti := strings.Index(urlStr, \"repos\/\")\n\tparsedURL, err := url.ParseRequestURI(urlStr[:i])\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faield to parse upload URL\")\n\t}\n\n\tc.UploadURL = parsedURL\n\treturn nil\n}\n\nfunc (c *GitHubClient) CreateRelease(ctx context.Context, req *github.RepositoryRelease) (*github.RepositoryRelease, error) {\n\n\trelease, res, err := c.Repositories.CreateRelease(c.Owner, c.Repo, req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create a release\")\n\t}\n\n\tif res.StatusCode != http.StatusCreated {\n\t\treturn nil, errors.Errorf(\"create release: invalid status: %s\", res.Status)\n\t}\n\n\treturn release, nil\n}\n\nfunc (c *GitHubClient) GetRelease(ctx context.Context, tag string) (*github.RepositoryRelease, error) {\n\t\/\/ Check Release is already exist or not\n\trelease, res, err := c.Repositories.GetReleaseByTag(c.Owner, c.Repo, tag)\n\tif err != nil {\n\t\tif res == nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get release tag: %s\", tag)\n\t\t}\n\n\t\t\/\/ TODO(tcnksm): Handle invalid token\n\t\tif res.StatusCode != http.StatusNotFound {\n\t\t\treturn nil, errors.Wrapf(err,\n\t\t\t\t\"get release tag: invalid status: %s\", res.Status)\n\t\t}\n\n\t\treturn nil, RelaseNotFound\n\t}\n\n\treturn release, nil\n}\n\nfunc (c *GitHubClient) DeleteRelease(ctx context.Context, releaseID int) error {\n\tres, err := c.Repositories.DeleteRelease(c.Owner, c.Repo, releaseID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to delete release\")\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete release: invalid status: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) DeleteTag(ctx context.Context, tag string) error {\n\tref := fmt.Sprintf(\"tags\/%s\", tag)\n\tres, err := c.Git.DeleteRef(c.Owner, c.Repo, ref)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete tag: %s\", ref)\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete tag: invalid status: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) UploadAsset(ctx context.Context, releaseID int, filename string) (*github.ReleaseAsset, error) {\n\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get abs path\")\n\t}\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open file\")\n\t}\n\n\topts := &github.UploadOptions{\n\t\t\/\/ Use base name by default\n\t\tName: filepath.Base(filename),\n\t}\n\n\tasset, res, err := c.Repositories.UploadReleaseAsset(c.Owner, c.Repo, releaseID, opts, f)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to upload release asset: %s\", filename)\n\t}\n\n\tswitch res.StatusCode {\n\tcase http.StatusCreated:\n\t\treturn asset, nil\n\tcase 422:\n\t\treturn nil, errors.Errorf(\n\t\t\t\"upload release asset: invalid status code: %s\",\n\t\t\t\"422 (this is probably because the asset already uploaded)\")\n\tdefault:\n\t\treturn nil, errors.Errorf(\n\t\t\t\"upload release asset: invalid status code: %s\", res.Status)\n\t}\n}\n\nfunc (c *GitHubClient) DeleteAsset(ctx context.Context, assetID int) error {\n\tres, err := c.Repositories.DeleteReleaseAsset(c.Owner, c.Repo, assetID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to delete release asset\")\n\t}\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn errors.Errorf(\"delete release assets: invalid status code: %s\", res.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (c *GitHubClient) ListAssets(ctx context.Context, releaseID int) ([]*github.ReleaseAsset, error) {\n\tresult := []*github.ReleaseAsset{}\n\tpage := 1\n\n\tfor {\n\t\tassets, res, err := c.Repositories.ListReleaseAssets(c.Owner, c.Repo, releaseID, &github.ListOptions{Page: page})\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to list assets\")\n\t\t}\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.Errorf(\"list release assets: invalid status code: %s\", res.Status)\n\t\t}\n\n\t\tresult = append(result, assets...)\n\n\t\tif res.NextPage <= page {\n\t\t\tbreak\n\t\t}\n\n\t\tpage = res.NextPage\n\t}\n\n\treturn result, nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/jzipfler\/htw-ava\/server\"\n\t\"github.com\/jzipfler\/htw-ava\/utils\"\n)\n\nvar (\n\tfilename string\n\tmanagerName string\n\tlogFile string\n\tipAddress string\n\tport int\n\tmanagedFile *os.File\n\tforce bool\n)\n\nfunc init() {\n\tflag.StringVar(&filename, \"filename\", \"path\/to\/file.txt\", \"A file that is managed by this process.\")\n\tflag.StringVar(&managerName, \"name\", \"Manager A\", \"Define the name of this manager.\")\n\tflag.StringVar(&logFile, \"logFile\", \"path\/to\/logfile.txt\", \"This parameter can be used to print the logging output to the given file.\")\n\tflag.StringVar(&ipAddress, \"ipAddress\", \"127.0.0.1\", \"The ip address of the actual starting node.\")\n\tflag.IntVar(&port, \"port\", 15100, \"The port of the actual starting node.\")\n\tflag.BoolVar(&force, \"force\", false, \"If force is enabled, the programm removes a existing management file and creates a new one without asking.\")\n}\n\nfunc main() {\n\n\tflag.Parse()\n\n\tif filename == \"path\/to\/file.txt\" {\n\t\tlog.Printf(\"A filename is required.\\n%s\\n\\n\", utils.ERROR_FOOTER)\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\n\tutils.InitializeLogger(logFile, \"\")\n\tutils.PrintMessage(fmt.Sprintf(\"File \\\"%s\\\" is now managed by this process.\", filename))\n\n\tif exists := utils.CheckIfFileExists(filename); exists {\n\t\tif !force {\n\t\t\tif deleteIt := askForToDeleteFile(); !deleteIt {\n\t\t\t\tfmt.Println(\"Do not delete the file and exit the program.\")\n\t\t\t\tutils.PrintMessage(fmt.Sprintf(\"The file \\\"%s\\\" already exists and should not be deleted.\", filename))\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t\tif err := os.Remove(filename); err != nil {\n\t\t\tlog.Fatalf(\"%s\\n%s\\n\", err.Error(), utils.ERROR_FOOTER)\n\t\t}\n\t\tutils.PrintMessage(fmt.Sprintf(\"Removed the file \\\"%s\\\"\", filename))\n\t}\n\n\tmanagedFile, err := os.Create(filename)\n\tutils.PrintMessage(fmt.Sprintf(\"Created the file \\\"%s\\\"\", filename))\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\\n%s\\n\", err.Error(), utils.ERROR_FOOTER)\n\t}\n\n\tmanagedFile.WriteString(\"000000\\n\")\n\tutils.PrintMessage(\"Wrote 000000 to the file.\")\n\n\tmanagedFile.Close()\n\n\tfor i := 0; i <= 100; i++ {\n\t\tif numbers, err := utils.IncreaseNumbersFromFirstLine(filename, 6); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t} else {\n\t\t\tfmt.Println(numbers)\n\t\t}\n\t}\n\n\tfor i := 0; i <= 101; i++ {\n\t\tif numbers, err := utils.DecreaseNumbersFromFirstLine(filename, 6); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t} else {\n\t\t\tfmt.Println(numbers)\n\t\t}\n\t}\n\n\tif err := utils.AppendStringToFile(filename, \"Hier könnte Ihre Werbung stehen\", false); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := utils.AppendStringToFile(filename, \" ::::: Oder vieles mehr!\", true); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := utils.AppendStringToFile(filename, \"Das stimmt!\", true); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tos.Exit(0)\n\n\tserverObject := server.New()\n\n\tserverObject.SetClientName(managerName)\n\tserverObject.SetIpAddressAsString(ipAddress)\n\tserverObject.SetPort(port)\n\tserverObject.SetUsedProtocol(\"tcp\")\n\n\tif err := server.StartServer(serverObject, nil); err != nil {\n\t\tlog.Fatalln(\"Could not start server. --> Exit.\")\n\t\tos.Exit(1)\n\t}\n\tdefer server.StopServer()\n}\n\nfunc askForToDeleteFile() bool {\n\tvar input string\n\tfmt.Printf(\"Would you like to delete the file \\\"%s\\\"? (y\/j\/n)\", filename)\n\tfmt.Print(\"\\nInput: \")\n\tif _, err := fmt.Scanln(&input); err == nil {\n\t\tswitch input {\n\t\tcase \"y\", \"j\":\n\t\t\tfmt.Println(\"File gets deleted.\")\n\t\t\treturn true\n\t\tcase \"n\":\n\t\t\tfmt.Println(input)\n\t\t\treturn false\n\t\tdefault:\n\t\t\tfmt.Println(\"Please only insert y\/j for \\\"YES\\\" or n for \\\"NO\\\".\\n\" + utils.ERROR_FOOTER)\n\t\t\tfmt.Println(\"Assume a \\\"n\\\" as input.\")\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Please only insert y\/j for \\\"YES\\\" or n for \\\"NO\\\".\\n\" + utils.ERROR_HEADER)\n\t}\n\treturn false\n}\nAdded some checks for the command line options.package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/jzipfler\/htw-ava\/server\"\n\t\"github.com\/jzipfler\/htw-ava\/utils\"\n)\n\nvar (\n\tfilename string\n\tmanagerName string\n\tlogFile string\n\tipAddress string\n\tport int\n\tmanagedFile *os.File\n\tforce bool\n)\n\nfunc init() {\n\tflag.StringVar(&filename, \"filename\", \"path\/to\/file.txt\", \"A file that is managed by this process.\")\n\tflag.StringVar(&managerName, \"name\", \"Manager A\", \"Define the name of this manager.\")\n\tflag.StringVar(&logFile, \"logFile\", \"path\/to\/logfile.txt\", \"This parameter can be used to print the logging output to the given file.\")\n\tflag.StringVar(&ipAddress, \"ipAddress\", \"127.0.0.1\", \"The ip address of the actual starting node.\")\n\tflag.IntVar(&port, \"port\", 15100, \"The port of the actual starting node.\")\n\tflag.BoolVar(&force, \"force\", false, \"If force is enabled, the programm removes a existing management file and creates a new one without asking.\")\n}\n\nfunc main() {\n\n\tvar containsAddress, containsPort, containsFilename bool\n\tfor _, argument := range os.Args {\n\t\tif strings.Contains(argument, \"-ipAddress\") {\n\t\t\tcontainsAddress = true\n\t\t}\n\t\tif strings.Contains(argument, \"-port\") {\n\t\t\tcontainsPort = true\n\t\t}\n\t\tif strings.Contains(argument, \"-filename\") {\n\t\t\tcontainsFilename = true\n\t\t}\n\t}\n\tif !containsAddress {\n\t\tlog.Printf(\"A IP address is required.\\n%s\\n\\n\", utils.ERROR_FOOTER)\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\tif !containsPort {\n\t\tlog.Printf(\"A port number is required.\\n%s\\n\\n\", utils.ERROR_FOOTER)\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\tif !containsFilename {\n\t\tlog.Printf(\"A filename is required.\\n%s\\n\\n\", utils.ERROR_FOOTER)\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\n\tflag.Parse()\n\n\tutils.InitializeLogger(logFile, \"\")\n\tutils.PrintMessage(fmt.Sprintf(\"File \\\"%s\\\" is now managed by this process.\", filename))\n\n\tif exists := utils.CheckIfFileExists(filename); exists {\n\t\tif !force {\n\t\t\tif deleteIt := askForToDeleteFile(); !deleteIt {\n\t\t\t\tfmt.Println(\"Do not delete the file and exit the program.\")\n\t\t\t\tutils.PrintMessage(fmt.Sprintf(\"The file \\\"%s\\\" already exists and should not be deleted.\", filename))\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t\tif err := os.Remove(filename); err != nil {\n\t\t\tlog.Fatalf(\"%s\\n%s\\n\", err.Error(), utils.ERROR_FOOTER)\n\t\t}\n\t\tutils.PrintMessage(fmt.Sprintf(\"Removed the file \\\"%s\\\"\", filename))\n\t}\n\n\tmanagedFile, err := os.Create(filename)\n\tutils.PrintMessage(fmt.Sprintf(\"Created the file \\\"%s\\\"\", filename))\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\\n%s\\n\", err.Error(), utils.ERROR_FOOTER)\n\t}\n\n\tmanagedFile.WriteString(\"000000\\n\")\n\tutils.PrintMessage(\"Wrote 000000 to the file.\")\n\n\tmanagedFile.Close()\n\n\tfor i := 0; i <= 100; i++ {\n\t\tif numbers, err := utils.IncreaseNumbersFromFirstLine(filename, 6); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t} else {\n\t\t\tfmt.Println(numbers)\n\t\t}\n\t}\n\n\tfor i := 0; i <= 101; i++ {\n\t\tif numbers, err := utils.DecreaseNumbersFromFirstLine(filename, 6); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t} else {\n\t\t\tfmt.Println(numbers)\n\t\t}\n\t}\n\n\tif err := utils.AppendStringToFile(filename, \"Hier könnte Ihre Werbung stehen\", false); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := utils.AppendStringToFile(filename, \" ::::: Oder vieles mehr!\", true); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := utils.AppendStringToFile(filename, \"Das stimmt!\", true); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tos.Exit(0)\n\n\tserverObject := server.New()\n\n\tserverObject.SetClientName(managerName)\n\tserverObject.SetIpAddressAsString(ipAddress)\n\tserverObject.SetPort(port)\n\tserverObject.SetUsedProtocol(\"tcp\")\n\n\tif err := server.StartServer(serverObject, nil); err != nil {\n\t\tlog.Fatalln(\"Could not start server. --> Exit.\")\n\t\tos.Exit(1)\n\t}\n\tdefer server.StopServer()\n}\n\nfunc askForToDeleteFile() bool {\n\tvar input string\n\tfmt.Printf(\"Would you like to delete the file \\\"%s\\\"? (y\/j\/n)\", filename)\n\tfmt.Print(\"\\nInput: \")\n\tif _, err := fmt.Scanln(&input); err == nil {\n\t\tswitch input {\n\t\tcase \"y\", \"j\":\n\t\t\tfmt.Println(\"File gets deleted.\")\n\t\t\treturn true\n\t\tcase \"n\":\n\t\t\tfmt.Println(input)\n\t\t\treturn false\n\t\tdefault:\n\t\t\tfmt.Println(\"Please only insert y\/j for \\\"YES\\\" or n for \\\"NO\\\".\\n\" + utils.ERROR_FOOTER)\n\t\t\tfmt.Println(\"Assume a \\\"n\\\" as input.\")\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Please only insert y\/j for \\\"YES\\\" or n for \\\"NO\\\".\\n\" + utils.ERROR_HEADER)\n\t}\n\treturn false\n}\n<|endoftext|>"} {"text":"package mym\n\n\/\/ Epsilon -- 2^(-52).\nconst Epsilon = 1.0 \/ (1 << 52)\n\n\/\/ SqrtEps -- 2^(-26).\nconst SqrtEps = 1.0 \/ (1 << 26)\nAdd `Tiny` constant (2^-1022, smallest normalized 64-bit floating point number).package mym\n\n\/\/ Epsilon -- 2^(-52).\nconst Epsilon = 1.0 \/ (1 << 52)\n\n\/\/ SqrtEps -- 2^(-26).\nconst SqrtEps = 1.0 \/ (1 << 26)\n\n\/\/ Tiny -- 2^(-1022)\nconst Tiny = 2.2250738585072013830902327173324040642192159804623318305533274168872044348139181958542831590125110206e-308\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"database\/sql\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/piotrkowalczuk\/mnemosyne\"\n\t\"github.com\/piotrkowalczuk\/sklog\"\n\t\"google.golang.org\/grpc\"\n)\n\nconst (\n\tloggerAdapterStdOut = \"stdout\"\n\tloggerFormatJSON = \"json\"\n\tloggerFormatHumane = \"humane\"\n\tloggerFormatLogFmt = \"logfmt\"\n)\n\nfunc initLogger(adapter, format string, level int, context ...interface{}) log.Logger {\n\tvar l log.Logger\n\n\tif adapter != loggerAdapterStdOut {\n\t\tstdlog.Fatal(\"service: unsupported logger adapter\")\n\t}\n\n\tswitch format {\n\tcase loggerFormatHumane:\n\t\tl = sklog.NewHumaneLogger(os.Stdout, sklog.DefaultHTTPFormatter)\n\tcase loggerFormatJSON:\n\t\tl = log.NewJSONLogger(os.Stdout)\n\tcase loggerFormatLogFmt:\n\t\tl = log.NewLogfmtLogger(os.Stdout)\n\tdefault:\n\t\tstdlog.Fatal(\"charond: unsupported logger format\")\n\t}\n\n\tl = log.NewContext(l).With(context...)\n\n\tsklog.Info(l, \"logger has been initialized successfully\", \"adapter\", adapter, \"format\", format, \"level\", level)\n\n\treturn l\n}\n\nfunc initPostgres(connectionString string, retry int, logger log.Logger) *sql.DB {\n\tvar err error\n\tvar attempts int\n\tvar postgres *sql.DB\n\n\t\/\/ Because of recursion it needs to be checked to not spawn more than one.\n\tif postgres == nil {\n\t\tpostgres, err = sql.Open(\"postgres\", connectionString)\n\t\tif err != nil {\n\t\t\tsklog.Fatal(logger, err)\n\t\t}\n\t}\n\n\t\/\/ At this moment connection is not yet established.\n\t\/\/ Ping is required.\n\tif err := postgres.Ping(); err != nil {\n\t\tif attempts > retry {\n\t\t\tsklog.Fatal(logger, err)\n\t\t}\n\n\t\tattempts++\n\t\tsklog.Error(logger, err)\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tinitPostgres(connectionString, retry, logger)\n\t} else {\n\t\tsklog.Info(logger, \"connection do postgres established successfully\", \"address\", connectionString)\n\t}\n\n\treturn postgres\n}\n\nfunc initMnemosyne(address string, logger log.Logger) (*grpc.ClientConn, mnemosyne.Mnemosyne) {\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\tsklog.Fatal(logger, err, \"address\", address)\n\t}\n\n\tsklog.Info(logger, \"rpc connection to mnemosyne has been established\", \"address\", address)\n\n\treturn conn, mnemosyne.New(conn, mnemosyne.MnemosyneOpts{})\n}\nsetup database if does not existspackage main\n\nimport (\n\t\"database\/sql\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/piotrkowalczuk\/mnemosyne\"\n\t\"github.com\/piotrkowalczuk\/sklog\"\n\t\"google.golang.org\/grpc\"\n)\n\nconst (\n\tloggerAdapterStdOut = \"stdout\"\n\tloggerFormatJSON = \"json\"\n\tloggerFormatHumane = \"humane\"\n\tloggerFormatLogFmt = \"logfmt\"\n)\n\nfunc initLogger(adapter, format string, level int, context ...interface{}) log.Logger {\n\tvar l log.Logger\n\n\tif adapter != loggerAdapterStdOut {\n\t\tstdlog.Fatal(\"service: unsupported logger adapter\")\n\t}\n\n\tswitch format {\n\tcase loggerFormatHumane:\n\t\tl = sklog.NewHumaneLogger(os.Stdout, sklog.DefaultHTTPFormatter)\n\tcase loggerFormatJSON:\n\t\tl = log.NewJSONLogger(os.Stdout)\n\tcase loggerFormatLogFmt:\n\t\tl = log.NewLogfmtLogger(os.Stdout)\n\tdefault:\n\t\tstdlog.Fatal(\"charond: unsupported logger format\")\n\t}\n\n\tl = log.NewContext(l).With(context...)\n\n\tsklog.Info(l, \"logger has been initialized successfully\", \"adapter\", adapter, \"format\", format, \"level\", level)\n\n\treturn l\n}\n\nfunc initPostgres(connectionString string, retry int, logger log.Logger) *sql.DB {\n\tvar err error\n\tvar attempts int\n\tvar postgres *sql.DB\n\n\t\/\/ Because of recursion it needs to be checked to not spawn more than one.\n\tif postgres == nil {\n\t\tpostgres, err = sql.Open(\"postgres\", connectionString)\n\t\tif err != nil {\n\t\t\tsklog.Fatal(logger, err)\n\t\t}\n\t}\n\n\t\/\/ At this moment connection is not yet established.\n\t\/\/ Ping is required.\n\tif err := postgres.Ping(); err != nil {\n\t\tif attempts > retry {\n\t\t\tsklog.Fatal(logger, err)\n\t\t}\n\n\t\tattempts++\n\t\tsklog.Error(logger, err)\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tinitPostgres(connectionString, retry, logger)\n\t} else {\n\t\terr = setupDatabase(postgres)\n\t\tif err != nil {\n\t\t\tsklog.Fatal(logger, err)\n\t\t}\n\t\tsklog.Info(logger, \"postgres connection has been established\", \"address\", connectionString)\n\t}\n\n\treturn postgres\n}\n\nfunc initMnemosyne(address string, logger log.Logger) (*grpc.ClientConn, mnemosyne.Mnemosyne) {\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\tsklog.Fatal(logger, err, \"address\", address)\n\t}\n\n\tsklog.Info(logger, \"rpc connection to mnemosyne has been established\", \"address\", address)\n\n\treturn conn, mnemosyne.New(conn, mnemosyne.MnemosyneOpts{})\n}\n<|endoftext|>"} {"text":"package services\n\nimport (\n\t\"errors\"\n\t\"github.com\/dedis\/cothority\/log\"\n\t\"github.com\/dedis\/cothority\/network\"\n\tprifi_protocol \"github.com\/lbarman\/prifi\/sda\/protocols\"\n\t\"time\"\n\t\"github.com\/lbarman\/prifi\/utils\/timing\"\n)\n\n\/\/ Packet send by relay when some node disconnected\ntype StopProtocol struct{}\n\n\/\/ ConnectionRequest messages are sent to the relay\n\/\/ by nodes that want to join the protocol.\ntype ConnectionRequest struct{}\n\n\/\/ DisconnectionRequest messages are sent to the relay\n\/\/ by nodes that want to leave the protocol.\ntype DisconnectionRequest struct{}\n\nfunc init() {\n\tnetwork.RegisterPacketType(StopProtocol{})\n\tnetwork.RegisterPacketType(ConnectionRequest{})\n\tnetwork.RegisterPacketType(DisconnectionRequest{})\n}\n\n\/\/ returns true if the PriFi SDA protocol is running (in any state : init, communicate, etc)\nfunc (s *ServiceState) IsPriFiProtocolRunning() bool {\n\tif s.priFiSDAProtocol != nil {\n\t\treturn !s.priFiSDAProtocol.HasStopped\n\t}\n\treturn false\n}\n\n\/\/ Packet send by relay; when we get it, we stop the protocol\nfunc (s *ServiceState) HandleStop(msg *network.Packet) {\n\tlog.Lvl1(\"Received a Handle Stop\")\n\ts.stopPriFiCommunicateProtocol()\n\n}\n\n\/\/ Packet send by relay when some node connected\nfunc (s *ServiceState) HandleConnection(msg *network.Packet) {\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a connection without a churnHandler\")\n\t}\n\ts.churnHandler.handleConnection(msg)\n}\n\n\/\/ Packet send by relay when some node disconnected\nfunc (s *ServiceState) HandleDisconnection(msg *network.Packet) {\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a disconnection without a churnHandler\")\n\t}\n\ts.churnHandler.handleDisconnection(msg)\n}\n\n\/\/ handleTimeout is a callback that should be called on the relay\n\/\/ when a round times out. It tries to restart PriFi with the nodes\n\/\/ that sent their ciphertext in time.\nfunc (s *ServiceState) handleTimeout(lateClients []string, lateTrustees []string) {\n\n\t\/\/ we can probably do something more clever here, since we know who disconnected. Yet let's just restart everything\n\ts.NetworkErrorHappened(errors.New(\"Timeout\"))\n}\n\n\/\/ This is a handler passed to the SDA when starting a host. The SDA usually handle all the network by itself,\n\/\/ but in our case it is useful to know when a network RESET occured, so we can kill protocols (otherwise they\n\/\/ remain in some weird state)\nfunc (s *ServiceState) NetworkErrorHappened(e error) {\n\n\tif s.role != prifi_protocol.Relay {\n\t\tlog.Lvl3(\"A network error occurred, but we're not the relay, nothing to do.\")\n\t\treturn\n\t}\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a network error without a churnHandler\")\n\t}\n\n\tlog.Error(\"A network error occurred, warning other clients.\")\n\ts.churnHandler.handleUnknownDisconnection()\n}\n\n\/\/ startPriFi starts a PriFi protocol. It is called\n\/\/ by the relay as soon as enough participants are\n\/\/ ready (one trustee and two clients).\nfunc (s *ServiceState) startPriFiCommunicateProtocol() {\n\tlog.Lvl1(\"Starting PriFi protocol\")\n\n\tif s.role != prifi_protocol.Relay {\n\t\tlog.Error(\"Trying to start PriFi protocol from a non-relay node.\")\n\t\treturn\n\t}\n\n\ttiming.StartMeasure(\"Resync\")\n\n\tvar wrapper *prifi_protocol.PriFiSDAProtocol\n\troster := s.churnHandler.createRoster()\n\n\t\/\/ Start the PriFi protocol on a flat tree with the relay as root\n\ttree := roster.GenerateNaryTreeWithRoot(100, s.churnHandler.relayIdentity)\n\tpi, err := s.CreateProtocolService(prifi_protocol.ProtocolName, tree)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to start Prifi protocol:\", err)\n\t}\n\n\t\/\/ Assert that pi has type PriFiSDAWrapper\n\twrapper = pi.(*prifi_protocol.PriFiSDAProtocol)\n\n\t\/\/assign and start the protocol\n\ts.priFiSDAProtocol = wrapper\n\n\ts.setConfigToPriFiProtocol(wrapper)\n\n\twrapper.Start()\n}\n\n\/\/ stopPriFi stops the PriFi protocol currently running.\nfunc (s *ServiceState) stopPriFiCommunicateProtocol() {\n\tlog.Lvl1(\"Stopping PriFi protocol\")\n\n\tif !s.IsPriFiProtocolRunning() {\n\t\tlog.Lvl3(\"Would stop PriFi protocol, but it's not running.\")\n\t\treturn\n\t}\n\n\tlog.Lvl2(\"A network error occurred, killing the PriFi protocol.\")\n\n\tif s.priFiSDAProtocol != nil {\n\t\ts.priFiSDAProtocol.Stop()\n\t}\n\ts.priFiSDAProtocol = nil\n\n\tif s.role == prifi_protocol.Relay {\n\n\t\tlog.Lvl2(\"A network error occurred, we're the relay, warning other clients...\")\n\n\t\tfor _, v := range s.churnHandler.getClientsIdentities() {\n\t\t\ts.SendRaw(v, &StopProtocol{})\n\t\t}\n\t\tfor _, v := range s.churnHandler.getTrusteesIdentities() {\n\t\t\ts.SendRaw(v, &StopProtocol{})\n\t\t}\n\t}\n}\n\n\/\/ autoConnect sends a connection request to the relay\n\/\/ every 10 seconds if the node is not participating to\n\/\/ a PriFi protocol.\nfunc (s *ServiceState) autoConnect(relayID *network.ServerIdentity) {\n\ts.sendConnectionRequest(relayID)\n\n\ttick := time.Tick(DELAY_BEFORE_KEEPALIVE)\n\tfor range tick {\n\t\tif !s.IsPriFiProtocolRunning() {\n\t\t\ts.sendConnectionRequest(relayID)\n\t\t}\n\t}\n}\n\n\/\/ sendConnectionRequest sends a connection request to the relay.\n\/\/ It is called by the client and trustee services at startup to\n\/\/ announce themselves to the relay.\nfunc (s *ServiceState) sendConnectionRequest(relayID *network.ServerIdentity) {\n\tlog.Lvl2(\"Sending connection request\")\n\terr := s.SendRaw(relayID, &ConnectionRequest{})\n\n\tif err != nil {\n\t\tlog.Error(\"Connection failed:\", err)\n\t}\n}\nForgot to run go fmtpackage services\n\nimport (\n\t\"errors\"\n\t\"github.com\/dedis\/cothority\/log\"\n\t\"github.com\/dedis\/cothority\/network\"\n\tprifi_protocol \"github.com\/lbarman\/prifi\/sda\/protocols\"\n\t\"github.com\/lbarman\/prifi\/utils\/timing\"\n\t\"time\"\n)\n\n\/\/ Packet send by relay when some node disconnected\ntype StopProtocol struct{}\n\n\/\/ ConnectionRequest messages are sent to the relay\n\/\/ by nodes that want to join the protocol.\ntype ConnectionRequest struct{}\n\n\/\/ DisconnectionRequest messages are sent to the relay\n\/\/ by nodes that want to leave the protocol.\ntype DisconnectionRequest struct{}\n\nfunc init() {\n\tnetwork.RegisterPacketType(StopProtocol{})\n\tnetwork.RegisterPacketType(ConnectionRequest{})\n\tnetwork.RegisterPacketType(DisconnectionRequest{})\n}\n\n\/\/ returns true if the PriFi SDA protocol is running (in any state : init, communicate, etc)\nfunc (s *ServiceState) IsPriFiProtocolRunning() bool {\n\tif s.priFiSDAProtocol != nil {\n\t\treturn !s.priFiSDAProtocol.HasStopped\n\t}\n\treturn false\n}\n\n\/\/ Packet send by relay; when we get it, we stop the protocol\nfunc (s *ServiceState) HandleStop(msg *network.Packet) {\n\tlog.Lvl1(\"Received a Handle Stop\")\n\ts.stopPriFiCommunicateProtocol()\n\n}\n\n\/\/ Packet send by relay when some node connected\nfunc (s *ServiceState) HandleConnection(msg *network.Packet) {\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a connection without a churnHandler\")\n\t}\n\ts.churnHandler.handleConnection(msg)\n}\n\n\/\/ Packet send by relay when some node disconnected\nfunc (s *ServiceState) HandleDisconnection(msg *network.Packet) {\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a disconnection without a churnHandler\")\n\t}\n\ts.churnHandler.handleDisconnection(msg)\n}\n\n\/\/ handleTimeout is a callback that should be called on the relay\n\/\/ when a round times out. It tries to restart PriFi with the nodes\n\/\/ that sent their ciphertext in time.\nfunc (s *ServiceState) handleTimeout(lateClients []string, lateTrustees []string) {\n\n\t\/\/ we can probably do something more clever here, since we know who disconnected. Yet let's just restart everything\n\ts.NetworkErrorHappened(errors.New(\"Timeout\"))\n}\n\n\/\/ This is a handler passed to the SDA when starting a host. The SDA usually handle all the network by itself,\n\/\/ but in our case it is useful to know when a network RESET occured, so we can kill protocols (otherwise they\n\/\/ remain in some weird state)\nfunc (s *ServiceState) NetworkErrorHappened(e error) {\n\n\tif s.role != prifi_protocol.Relay {\n\t\tlog.Lvl3(\"A network error occurred, but we're not the relay, nothing to do.\")\n\t\treturn\n\t}\n\tif s.churnHandler == nil {\n\t\tlog.Fatal(\"Can't handle a network error without a churnHandler\")\n\t}\n\n\tlog.Error(\"A network error occurred, warning other clients.\")\n\ts.churnHandler.handleUnknownDisconnection()\n}\n\n\/\/ startPriFi starts a PriFi protocol. It is called\n\/\/ by the relay as soon as enough participants are\n\/\/ ready (one trustee and two clients).\nfunc (s *ServiceState) startPriFiCommunicateProtocol() {\n\tlog.Lvl1(\"Starting PriFi protocol\")\n\n\tif s.role != prifi_protocol.Relay {\n\t\tlog.Error(\"Trying to start PriFi protocol from a non-relay node.\")\n\t\treturn\n\t}\n\n\ttiming.StartMeasure(\"Resync\")\n\n\tvar wrapper *prifi_protocol.PriFiSDAProtocol\n\troster := s.churnHandler.createRoster()\n\n\t\/\/ Start the PriFi protocol on a flat tree with the relay as root\n\ttree := roster.GenerateNaryTreeWithRoot(100, s.churnHandler.relayIdentity)\n\tpi, err := s.CreateProtocolService(prifi_protocol.ProtocolName, tree)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to start Prifi protocol:\", err)\n\t}\n\n\t\/\/ Assert that pi has type PriFiSDAWrapper\n\twrapper = pi.(*prifi_protocol.PriFiSDAProtocol)\n\n\t\/\/assign and start the protocol\n\ts.priFiSDAProtocol = wrapper\n\n\ts.setConfigToPriFiProtocol(wrapper)\n\n\twrapper.Start()\n}\n\n\/\/ stopPriFi stops the PriFi protocol currently running.\nfunc (s *ServiceState) stopPriFiCommunicateProtocol() {\n\tlog.Lvl1(\"Stopping PriFi protocol\")\n\n\tif !s.IsPriFiProtocolRunning() {\n\t\tlog.Lvl3(\"Would stop PriFi protocol, but it's not running.\")\n\t\treturn\n\t}\n\n\tlog.Lvl2(\"A network error occurred, killing the PriFi protocol.\")\n\n\tif s.priFiSDAProtocol != nil {\n\t\ts.priFiSDAProtocol.Stop()\n\t}\n\ts.priFiSDAProtocol = nil\n\n\tif s.role == prifi_protocol.Relay {\n\n\t\tlog.Lvl2(\"A network error occurred, we're the relay, warning other clients...\")\n\n\t\tfor _, v := range s.churnHandler.getClientsIdentities() {\n\t\t\ts.SendRaw(v, &StopProtocol{})\n\t\t}\n\t\tfor _, v := range s.churnHandler.getTrusteesIdentities() {\n\t\t\ts.SendRaw(v, &StopProtocol{})\n\t\t}\n\t}\n}\n\n\/\/ autoConnect sends a connection request to the relay\n\/\/ every 10 seconds if the node is not participating to\n\/\/ a PriFi protocol.\nfunc (s *ServiceState) autoConnect(relayID *network.ServerIdentity) {\n\ts.sendConnectionRequest(relayID)\n\n\ttick := time.Tick(DELAY_BEFORE_KEEPALIVE)\n\tfor range tick {\n\t\tif !s.IsPriFiProtocolRunning() {\n\t\t\ts.sendConnectionRequest(relayID)\n\t\t}\n\t}\n}\n\n\/\/ sendConnectionRequest sends a connection request to the relay.\n\/\/ It is called by the client and trustee services at startup to\n\/\/ announce themselves to the relay.\nfunc (s *ServiceState) sendConnectionRequest(relayID *network.ServerIdentity) {\n\tlog.Lvl2(\"Sending connection request\")\n\terr := s.SendRaw(relayID, &ConnectionRequest{})\n\n\tif err != nil {\n\t\tlog.Error(\"Connection failed:\", err)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 The Kubernetes 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 node\n\nimport (\n\t\"log\"\n\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/api\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/errors\"\n\tmetricapi \"github.com\/kubernetes\/dashboard\/src\/app\/backend\/integration\/metric\/api\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/common\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/dataselect\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/event\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/pod\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetaV1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\tk8sClient \"k8s.io\/client-go\/kubernetes\"\n)\n\n\/\/ NodeAllocatedResources describes node allocated resources.\ntype NodeAllocatedResources struct {\n\t\/\/ CPURequests is number of allocated milicores.\n\tCPURequests int64 `json:\"cpuRequests\"`\n\n\t\/\/ CPURequestsFraction is a fraction of CPU, that is allocated.\n\tCPURequestsFraction float64 `json:\"cpuRequestsFraction\"`\n\n\t\/\/ CPULimits is defined CPU limit.\n\tCPULimits int64 `json:\"cpuLimits\"`\n\n\t\/\/ CPULimitsFraction is a fraction of defined CPU limit, can be over 100%, i.e.\n\t\/\/ overcommitted.\n\tCPULimitsFraction float64 `json:\"cpuLimitsFraction\"`\n\n\t\/\/ CPUCapacity is specified node CPU capacity in milicores.\n\tCPUCapacity int64 `json:\"cpuCapacity\"`\n\n\t\/\/ MemoryRequests is a fraction of memory, that is allocated.\n\tMemoryRequests int64 `json:\"memoryRequests\"`\n\n\t\/\/ MemoryRequestsFraction is a fraction of memory, that is allocated.\n\tMemoryRequestsFraction float64 `json:\"memoryRequestsFraction\"`\n\n\t\/\/ MemoryLimits is defined memory limit.\n\tMemoryLimits int64 `json:\"memoryLimits\"`\n\n\t\/\/ MemoryLimitsFraction is a fraction of defined memory limit, can be over 100%, i.e.\n\t\/\/ overcommitted.\n\tMemoryLimitsFraction float64 `json:\"memoryLimitsFraction\"`\n\n\t\/\/ MemoryCapacity is specified node memory capacity in bytes.\n\tMemoryCapacity int64 `json:\"memoryCapacity\"`\n\n\t\/\/ AllocatedPods in number of currently allocated pods on the node.\n\tAllocatedPods int `json:\"allocatedPods\"`\n\n\t\/\/ PodCapacity is maximum number of pods, that can be allocated on the node.\n\tPodCapacity int64 `json:\"podCapacity\"`\n\n\t\/\/ PodFraction is a fraction of pods, that can be allocated on given node.\n\tPodFraction float64 `json:\"podFraction\"`\n}\n\n\/\/ NodeDetail is a presentation layer view of Kubernetes Node resource. This means it is Node plus\n\/\/ additional augmented data we can get from other sources.\ntype NodeDetail struct {\n\t\/\/ Extends list item structure.\n\tNode `json:\",inline\"`\n\n\t\/\/ NodePhase is the current lifecycle phase of the node.\n\tPhase v1.NodePhase `json:\"phase\"`\n\n\t\/\/ PodCIDR represents the pod IP range assigned to the node.\n\tPodCIDR string `json:\"podCIDR\"`\n\n\t\/\/ ID of the node assigned by the cloud provider.\n\tProviderID string `json:\"providerID\"`\n\n\t\/\/ Unschedulable controls node schedulability of new pods. By default node is schedulable.\n\tUnschedulable bool `json:\"unschedulable\"`\n\n\t\/\/ Set of ids\/uuids to uniquely identify the node.\n\tNodeInfo v1.NodeSystemInfo `json:\"nodeInfo\"`\n\n\t\/\/ Conditions is an array of current node conditions.\n\tConditions []common.Condition `json:\"conditions\"`\n\n\t\/\/ Container images of the node.\n\tContainerImages []string `json:\"containerImages\"`\n\n\t\/\/ PodListComponent contains information about pods belonging to this node.\n\tPodList pod.PodList `json:\"podList\"`\n\n\t\/\/ Events is list of events associated to the node.\n\tEventList common.EventList `json:\"eventList\"`\n\n\t\/\/ Metrics collected for this resource\n\tMetrics []metricapi.Metric `json:\"metrics\"`\n\n\t\/\/ Taints\n\tTaints []v1.Taint `json:\"taints,omitempty\"`\n\n\t\/\/ Addresses is a list of addresses reachable to the node. Queried from cloud provider, if available.\n\tAddresses []v1.NodeAddress `json:\"addresses,omitempty\"`\n\n\t\/\/ List of non-critical errors, that occurred during resource retrieval.\n\tErrors []error `json:\"errors\"`\n}\n\n\/\/ GetNodeDetail gets node details.\nfunc GetNodeDetail(client k8sClient.Interface, metricClient metricapi.MetricClient, name string,\n\tdsQuery *dataselect.DataSelectQuery) (*NodeDetail, error) {\n\tlog.Printf(\"Getting details of %s node\", name)\n\n\tnode, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Download standard metrics. Currently metrics are hard coded, but it is possible to replace\n\t\/\/ dataselect.StdMetricsDataSelect with data select provided in the request.\n\t_, metricPromises := dataselect.GenericDataSelectWithMetrics(toCells([]v1.Node{*node}),\n\t\tdsQuery,\n\t\tmetricapi.NoResourceCache, metricClient)\n\n\tpods, err := getNodePods(client, *node)\n\tnonCriticalErrors, criticalError := errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tpodList, err := GetNodePods(client, metricClient, dsQuery, name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\teventList, err := event.GetNodeEvents(client, dsQuery, node.Name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tallocatedResources, err := getNodeAllocatedResources(*node, pods)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tmetrics, _ := metricPromises.GetMetrics()\n\tnodeDetails := toNodeDetail(*node, podList, eventList, allocatedResources, metrics, nonCriticalErrors)\n\treturn &nodeDetails, nil\n}\n\nfunc getNodeAllocatedResources(node v1.Node, podList *v1.PodList) (NodeAllocatedResources, error) {\n\treqs, limits := map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}\n\n\tfor _, pod := range podList.Items {\n\t\tpodReqs, podLimits, err := PodRequestsAndLimits(&pod)\n\t\tif err != nil {\n\t\t\treturn NodeAllocatedResources{}, err\n\t\t}\n\t\tfor podReqName, podReqValue := range podReqs {\n\t\t\tif value, ok := reqs[podReqName]; !ok {\n\t\t\t\treqs[podReqName] = podReqValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podReqValue)\n\t\t\t\treqs[podReqName] = value\n\t\t\t}\n\t\t}\n\t\tfor podLimitName, podLimitValue := range podLimits {\n\t\t\tif value, ok := limits[podLimitName]; !ok {\n\t\t\t\tlimits[podLimitName] = podLimitValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podLimitValue)\n\t\t\t\tlimits[podLimitName] = value\n\t\t\t}\n\t\t}\n\t}\n\n\tcpuRequests, cpuLimits, memoryRequests, memoryLimits := reqs[v1.ResourceCPU],\n\t\tlimits[v1.ResourceCPU], reqs[v1.ResourceMemory], limits[v1.ResourceMemory]\n\n\tvar cpuRequestsFraction, cpuLimitsFraction float64 = 0, 0\n\tif capacity := float64(node.Status.Capacity.Cpu().MilliValue()); capacity > 0 {\n\t\tcpuRequestsFraction = float64(cpuRequests.MilliValue()) \/ capacity * 100\n\t\tcpuLimitsFraction = float64(cpuLimits.MilliValue()) \/ capacity * 100\n\t}\n\n\tvar memoryRequestsFraction, memoryLimitsFraction float64 = 0, 0\n\tif capacity := float64(node.Status.Capacity.Memory().MilliValue()); capacity > 0 {\n\t\tmemoryRequestsFraction = float64(memoryRequests.MilliValue()) \/ capacity * 100\n\t\tmemoryLimitsFraction = float64(memoryLimits.MilliValue()) \/ capacity * 100\n\t}\n\n\tvar podFraction float64 = 0\n\tvar podCapacity int64 = node.Status.Capacity.Pods().Value()\n\tif podCapacity > 0 {\n\t\tpodFraction = float64(len(podList.Items)) \/ float64(podCapacity) * 100\n\t}\n\n\treturn NodeAllocatedResources{\n\t\tCPURequests: cpuRequests.MilliValue(),\n\t\tCPURequestsFraction: cpuRequestsFraction,\n\t\tCPULimits: cpuLimits.MilliValue(),\n\t\tCPULimitsFraction: cpuLimitsFraction,\n\t\tCPUCapacity: node.Status.Capacity.Cpu().MilliValue(),\n\t\tMemoryRequests: memoryRequests.Value(),\n\t\tMemoryRequestsFraction: memoryRequestsFraction,\n\t\tMemoryLimits: memoryLimits.Value(),\n\t\tMemoryLimitsFraction: memoryLimitsFraction,\n\t\tMemoryCapacity: node.Status.Capacity.Memory().Value(),\n\t\tAllocatedPods: len(podList.Items),\n\t\tPodCapacity: podCapacity,\n\t\tPodFraction: podFraction,\n\t}, nil\n}\n\n\/\/ PodRequestsAndLimits returns a dictionary of all defined resources summed up for all\n\/\/ containers of the pod.\nfunc PodRequestsAndLimits(pod *v1.Pod) (reqs map[v1.ResourceName]resource.Quantity, limits map[v1.ResourceName]resource.Quantity, err error) {\n\treqs, limits = map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor name, quantity := range container.Resources.Requests {\n\t\t\tif value, ok := reqs[name]; !ok {\n\t\t\t\treqs[name] = quantity.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(quantity)\n\t\t\t\treqs[name] = value\n\t\t\t}\n\t\t}\n\t\tfor name, quantity := range container.Resources.Limits {\n\t\t\tif value, ok := limits[name]; !ok {\n\t\t\t\tlimits[name] = quantity.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(quantity)\n\t\t\t\tlimits[name] = value\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ init containers define the minimum of any resource\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tfor name, quantity := range container.Resources.Requests {\n\t\t\tvalue, ok := reqs[name]\n\t\t\tif !ok {\n\t\t\t\treqs[name] = quantity.DeepCopy()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(value) > 0 {\n\t\t\t\treqs[name] = quantity.DeepCopy()\n\t\t\t}\n\t\t}\n\t\tfor name, quantity := range container.Resources.Limits {\n\t\t\tvalue, ok := limits[name]\n\t\t\tif !ok {\n\t\t\t\tlimits[name] = quantity.DeepCopy()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(value) > 0 {\n\t\t\t\tlimits[name] = quantity.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ GetNodePods return pods list in given named node\nfunc GetNodePods(client k8sClient.Interface, metricClient metricapi.MetricClient,\n\tdsQuery *dataselect.DataSelectQuery, name string) (*pod.PodList, error) {\n\tpodList := pod.PodList{\n\t\tPods: []pod.Pod{},\n\t\tCumulativeMetrics: []metricapi.Metric{},\n\t}\n\n\tnode, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn &podList, err\n\t}\n\n\tpods, err := getNodePods(client, *node)\n\tif err != nil {\n\t\treturn &podList, err\n\t}\n\n\tevents, err := event.GetPodsEvents(client, v1.NamespaceAll, pods.Items)\n\tnonCriticalErrors, criticalError := errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn &podList, criticalError\n\t}\n\n\tpodList = pod.ToPodList(pods.Items, events, nonCriticalErrors, dsQuery, metricClient)\n\treturn &podList, nil\n}\n\nfunc getNodePods(client k8sClient.Interface, node v1.Node) (*v1.PodList, error) {\n\tfieldSelector, err := fields.ParseSelector(\"spec.nodeName=\" + node.Name +\n\t\t\",status.phase!=\" + string(v1.PodSucceeded) +\n\t\t\",status.phase!=\" + string(v1.PodFailed))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client.CoreV1().Pods(v1.NamespaceAll).List(metaV1.ListOptions{\n\t\tFieldSelector: fieldSelector.String(),\n\t})\n}\n\nfunc toNodeDetail(node v1.Node, pods *pod.PodList, eventList *common.EventList,\n\tallocatedResources NodeAllocatedResources, metrics []metricapi.Metric, nonCriticalErrors []error) NodeDetail {\n\treturn NodeDetail{\n\t\tNode: Node{\n\t\t\tObjectMeta: api.NewObjectMeta(node.ObjectMeta),\n\t\t\tTypeMeta: api.NewTypeMeta(api.ResourceKindNode),\n\t\t\tAllocatedResources: allocatedResources,\n\t\t},\n\t\tPhase: node.Status.Phase,\n\t\tProviderID: node.Spec.ProviderID,\n\t\tPodCIDR: node.Spec.PodCIDR,\n\t\tUnschedulable: node.Spec.Unschedulable,\n\t\tNodeInfo: node.Status.NodeInfo,\n\t\tConditions: getNodeConditions(node),\n\t\tContainerImages: getContainerImages(node),\n\t\tPodList: *pods,\n\t\tEventList: *eventList,\n\t\tMetrics: metrics,\n\t\tTaints: node.Spec.Taints,\n\t\tAddresses: node.Status.Addresses,\n\t\tErrors: nonCriticalErrors,\n\t}\n}\nModified the PodRequestAndLimits function and Add overhead for running a pod to the sum of requests and to non-zero limits (#4667)\/\/ Copyright 2017 The Kubernetes 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 node\n\nimport (\n\t\"log\"\n\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/api\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/errors\"\n\tmetricapi \"github.com\/kubernetes\/dashboard\/src\/app\/backend\/integration\/metric\/api\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/common\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/dataselect\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/event\"\n\t\"github.com\/kubernetes\/dashboard\/src\/app\/backend\/resource\/pod\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetaV1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\tk8sClient \"k8s.io\/client-go\/kubernetes\"\n)\n\n\/\/ NodeAllocatedResources describes node allocated resources.\ntype NodeAllocatedResources struct {\n\t\/\/ CPURequests is number of allocated milicores.\n\tCPURequests int64 `json:\"cpuRequests\"`\n\n\t\/\/ CPURequestsFraction is a fraction of CPU, that is allocated.\n\tCPURequestsFraction float64 `json:\"cpuRequestsFraction\"`\n\n\t\/\/ CPULimits is defined CPU limit.\n\tCPULimits int64 `json:\"cpuLimits\"`\n\n\t\/\/ CPULimitsFraction is a fraction of defined CPU limit, can be over 100%, i.e.\n\t\/\/ overcommitted.\n\tCPULimitsFraction float64 `json:\"cpuLimitsFraction\"`\n\n\t\/\/ CPUCapacity is specified node CPU capacity in milicores.\n\tCPUCapacity int64 `json:\"cpuCapacity\"`\n\n\t\/\/ MemoryRequests is a fraction of memory, that is allocated.\n\tMemoryRequests int64 `json:\"memoryRequests\"`\n\n\t\/\/ MemoryRequestsFraction is a fraction of memory, that is allocated.\n\tMemoryRequestsFraction float64 `json:\"memoryRequestsFraction\"`\n\n\t\/\/ MemoryLimits is defined memory limit.\n\tMemoryLimits int64 `json:\"memoryLimits\"`\n\n\t\/\/ MemoryLimitsFraction is a fraction of defined memory limit, can be over 100%, i.e.\n\t\/\/ overcommitted.\n\tMemoryLimitsFraction float64 `json:\"memoryLimitsFraction\"`\n\n\t\/\/ MemoryCapacity is specified node memory capacity in bytes.\n\tMemoryCapacity int64 `json:\"memoryCapacity\"`\n\n\t\/\/ AllocatedPods in number of currently allocated pods on the node.\n\tAllocatedPods int `json:\"allocatedPods\"`\n\n\t\/\/ PodCapacity is maximum number of pods, that can be allocated on the node.\n\tPodCapacity int64 `json:\"podCapacity\"`\n\n\t\/\/ PodFraction is a fraction of pods, that can be allocated on given node.\n\tPodFraction float64 `json:\"podFraction\"`\n}\n\n\/\/ NodeDetail is a presentation layer view of Kubernetes Node resource. This means it is Node plus\n\/\/ additional augmented data we can get from other sources.\ntype NodeDetail struct {\n\t\/\/ Extends list item structure.\n\tNode `json:\",inline\"`\n\n\t\/\/ NodePhase is the current lifecycle phase of the node.\n\tPhase v1.NodePhase `json:\"phase\"`\n\n\t\/\/ PodCIDR represents the pod IP range assigned to the node.\n\tPodCIDR string `json:\"podCIDR\"`\n\n\t\/\/ ID of the node assigned by the cloud provider.\n\tProviderID string `json:\"providerID\"`\n\n\t\/\/ Unschedulable controls node schedulability of new pods. By default node is schedulable.\n\tUnschedulable bool `json:\"unschedulable\"`\n\n\t\/\/ Set of ids\/uuids to uniquely identify the node.\n\tNodeInfo v1.NodeSystemInfo `json:\"nodeInfo\"`\n\n\t\/\/ Conditions is an array of current node conditions.\n\tConditions []common.Condition `json:\"conditions\"`\n\n\t\/\/ Container images of the node.\n\tContainerImages []string `json:\"containerImages\"`\n\n\t\/\/ PodListComponent contains information about pods belonging to this node.\n\tPodList pod.PodList `json:\"podList\"`\n\n\t\/\/ Events is list of events associated to the node.\n\tEventList common.EventList `json:\"eventList\"`\n\n\t\/\/ Metrics collected for this resource\n\tMetrics []metricapi.Metric `json:\"metrics\"`\n\n\t\/\/ Taints\n\tTaints []v1.Taint `json:\"taints,omitempty\"`\n\n\t\/\/ Addresses is a list of addresses reachable to the node. Queried from cloud provider, if available.\n\tAddresses []v1.NodeAddress `json:\"addresses,omitempty\"`\n\n\t\/\/ List of non-critical errors, that occurred during resource retrieval.\n\tErrors []error `json:\"errors\"`\n}\n\n\/\/ GetNodeDetail gets node details.\nfunc GetNodeDetail(client k8sClient.Interface, metricClient metricapi.MetricClient, name string,\n\tdsQuery *dataselect.DataSelectQuery) (*NodeDetail, error) {\n\tlog.Printf(\"Getting details of %s node\", name)\n\n\tnode, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Download standard metrics. Currently metrics are hard coded, but it is possible to replace\n\t\/\/ dataselect.StdMetricsDataSelect with data select provided in the request.\n\t_, metricPromises := dataselect.GenericDataSelectWithMetrics(toCells([]v1.Node{*node}),\n\t\tdsQuery,\n\t\tmetricapi.NoResourceCache, metricClient)\n\n\tpods, err := getNodePods(client, *node)\n\tnonCriticalErrors, criticalError := errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tpodList, err := GetNodePods(client, metricClient, dsQuery, name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\teventList, err := event.GetNodeEvents(client, dsQuery, node.Name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tallocatedResources, err := getNodeAllocatedResources(*node, pods)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tmetrics, _ := metricPromises.GetMetrics()\n\tnodeDetails := toNodeDetail(*node, podList, eventList, allocatedResources, metrics, nonCriticalErrors)\n\treturn &nodeDetails, nil\n}\n\nfunc getNodeAllocatedResources(node v1.Node, podList *v1.PodList) (NodeAllocatedResources, error) {\n\treqs, limits := map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}\n\n\tfor _, pod := range podList.Items {\n\t\tpodReqs, podLimits, err := PodRequestsAndLimits(&pod)\n\t\tif err != nil {\n\t\t\treturn NodeAllocatedResources{}, err\n\t\t}\n\t\tfor podReqName, podReqValue := range podReqs {\n\t\t\tif value, ok := reqs[podReqName]; !ok {\n\t\t\t\treqs[podReqName] = podReqValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podReqValue)\n\t\t\t\treqs[podReqName] = value\n\t\t\t}\n\t\t}\n\t\tfor podLimitName, podLimitValue := range podLimits {\n\t\t\tif value, ok := limits[podLimitName]; !ok {\n\t\t\t\tlimits[podLimitName] = podLimitValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podLimitValue)\n\t\t\t\tlimits[podLimitName] = value\n\t\t\t}\n\t\t}\n\t}\n\n\tcpuRequests, cpuLimits, memoryRequests, memoryLimits := reqs[v1.ResourceCPU],\n\t\tlimits[v1.ResourceCPU], reqs[v1.ResourceMemory], limits[v1.ResourceMemory]\n\n\tvar cpuRequestsFraction, cpuLimitsFraction float64 = 0, 0\n\tif capacity := float64(node.Status.Capacity.Cpu().MilliValue()); capacity > 0 {\n\t\tcpuRequestsFraction = float64(cpuRequests.MilliValue()) \/ capacity * 100\n\t\tcpuLimitsFraction = float64(cpuLimits.MilliValue()) \/ capacity * 100\n\t}\n\n\tvar memoryRequestsFraction, memoryLimitsFraction float64 = 0, 0\n\tif capacity := float64(node.Status.Capacity.Memory().MilliValue()); capacity > 0 {\n\t\tmemoryRequestsFraction = float64(memoryRequests.MilliValue()) \/ capacity * 100\n\t\tmemoryLimitsFraction = float64(memoryLimits.MilliValue()) \/ capacity * 100\n\t}\n\n\tvar podFraction float64 = 0\n\tvar podCapacity int64 = node.Status.Capacity.Pods().Value()\n\tif podCapacity > 0 {\n\t\tpodFraction = float64(len(podList.Items)) \/ float64(podCapacity) * 100\n\t}\n\n\treturn NodeAllocatedResources{\n\t\tCPURequests: cpuRequests.MilliValue(),\n\t\tCPURequestsFraction: cpuRequestsFraction,\n\t\tCPULimits: cpuLimits.MilliValue(),\n\t\tCPULimitsFraction: cpuLimitsFraction,\n\t\tCPUCapacity: node.Status.Capacity.Cpu().MilliValue(),\n\t\tMemoryRequests: memoryRequests.Value(),\n\t\tMemoryRequestsFraction: memoryRequestsFraction,\n\t\tMemoryLimits: memoryLimits.Value(),\n\t\tMemoryLimitsFraction: memoryLimitsFraction,\n\t\tMemoryCapacity: node.Status.Capacity.Memory().Value(),\n\t\tAllocatedPods: len(podList.Items),\n\t\tPodCapacity: podCapacity,\n\t\tPodFraction: podFraction,\n\t}, nil\n}\n\n\/\/ PodRequestsAndLimits returns a dictionary of all defined resources summed up for all\n\/\/ containers of the pod. If pod overhead is non-nil, the pod overhead is added to the\n\/\/ total container resource requests and to the total container limits which have a\n\/\/ non-zero quantity.\nfunc PodRequestsAndLimits(pod *v1.Pod) (reqs, limits v1.ResourceList, err error) {\n\treqs, limits = v1.ResourceList{}, v1.ResourceList{}\n\tfor _, container := range pod.Spec.Containers {\n\t\taddResourceList(reqs, container.Resources.Requests)\n\t\taddResourceList(limits, container.Resources.Limits)\n\t}\n\t\/\/ init containers define the minimum of any resource\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tmaxResourceList(reqs, container.Resources.Requests)\n\t\tmaxResourceList(limits, container.Resources.Limits)\n\t}\n\n\t\/\/ Add overhead for running a pod to the sum of requests and to non-zero limits:\n\tif pod.Spec.Overhead != nil {\n\t\taddResourceList(reqs, pod.Spec.Overhead)\n\n\t\tfor name, quantity := range pod.Spec.Overhead {\n\t\t\tif value, ok := limits[name]; ok && !value.IsZero() {\n\t\t\t\tvalue.Add(quantity)\n\t\t\t\tlimits[name] = value\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ addResourceList adds the resources in newList to list\nfunc addResourceList(list, new v1.ResourceList) {\n\tfor name, quantity := range new {\n\t\tif value, ok := list[name]; !ok {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t} else {\n\t\t\tvalue.Add(quantity)\n\t\t\tlist[name] = value\n\t\t}\n\t}\n}\n\n\/\/ maxResourceList sets list to the greater of list\/newList for every resource\n\/\/ either list\nfunc maxResourceList(list, new v1.ResourceList) {\n\tfor name, quantity := range new {\n\t\tif value, ok := list[name]; !ok {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif quantity.Cmp(value) > 0 {\n\t\t\t\tlist[name] = quantity.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ GetNodePods return pods list in given named node\nfunc GetNodePods(client k8sClient.Interface, metricClient metricapi.MetricClient,\n\tdsQuery *dataselect.DataSelectQuery, name string) (*pod.PodList, error) {\n\tpodList := pod.PodList{\n\t\tPods: []pod.Pod{},\n\t\tCumulativeMetrics: []metricapi.Metric{},\n\t}\n\n\tnode, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn &podList, err\n\t}\n\n\tpods, err := getNodePods(client, *node)\n\tif err != nil {\n\t\treturn &podList, err\n\t}\n\n\tevents, err := event.GetPodsEvents(client, v1.NamespaceAll, pods.Items)\n\tnonCriticalErrors, criticalError := errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn &podList, criticalError\n\t}\n\n\tpodList = pod.ToPodList(pods.Items, events, nonCriticalErrors, dsQuery, metricClient)\n\treturn &podList, nil\n}\n\nfunc getNodePods(client k8sClient.Interface, node v1.Node) (*v1.PodList, error) {\n\tfieldSelector, err := fields.ParseSelector(\"spec.nodeName=\" + node.Name +\n\t\t\",status.phase!=\" + string(v1.PodSucceeded) +\n\t\t\",status.phase!=\" + string(v1.PodFailed))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client.CoreV1().Pods(v1.NamespaceAll).List(metaV1.ListOptions{\n\t\tFieldSelector: fieldSelector.String(),\n\t})\n}\n\nfunc toNodeDetail(node v1.Node, pods *pod.PodList, eventList *common.EventList,\n\tallocatedResources NodeAllocatedResources, metrics []metricapi.Metric, nonCriticalErrors []error) NodeDetail {\n\treturn NodeDetail{\n\t\tNode: Node{\n\t\t\tObjectMeta: api.NewObjectMeta(node.ObjectMeta),\n\t\t\tTypeMeta: api.NewTypeMeta(api.ResourceKindNode),\n\t\t\tAllocatedResources: allocatedResources,\n\t\t},\n\t\tPhase: node.Status.Phase,\n\t\tProviderID: node.Spec.ProviderID,\n\t\tPodCIDR: node.Spec.PodCIDR,\n\t\tUnschedulable: node.Spec.Unschedulable,\n\t\tNodeInfo: node.Status.NodeInfo,\n\t\tConditions: getNodeConditions(node),\n\t\tContainerImages: getContainerImages(node),\n\t\tPodList: *pods,\n\t\tEventList: *eventList,\n\t\tMetrics: metrics,\n\t\tTaints: node.Spec.Taints,\n\t\tAddresses: node.Status.Addresses,\n\t\tErrors: nonCriticalErrors,\n\t}\n}\n<|endoftext|>"} {"text":"package sudoku\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"strconv\"\n)\n\ntype nakedSingleTechnique struct {\n\t*basicSolveTechnique\n}\n\ntype hiddenSingleTechnique struct {\n\t*basicSolveTechnique\n}\n\ntype obviousInCollectionTechnique struct {\n\t*basicSolveTechnique\n}\n\nfunc newFillSolveStep(cell *Cell, num int, technique SolveTechnique) *SolveStep {\n\tcellArr := []*Cell{cell}\n\tnumArr := []int{num}\n\treturn &SolveStep{technique, cellArr, numArr, nil, nil}\n}\n\nfunc (self *obviousInCollectionTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(1.0)\n}\n\nfunc (self *obviousInCollectionTechnique) Description(step *SolveStep) string {\n\tif len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tnum := step.TargetNums[0]\n\tgroupName := \"\"\n\tgroupNumber := 0\n\tswitch self.groupType {\n\tcase _GROUP_BLOCK:\n\t\tgroupName = \"block\"\n\t\tgroupNumber = step.TargetCells.Block()\n\tcase _GROUP_COL:\n\t\tgroupName = \"column\"\n\t\tgroupNumber = step.TargetCells.Col()\n\tcase _GROUP_ROW:\n\t\tgroupName = \"row\"\n\t\tgroupNumber = step.TargetCells.Row()\n\t}\n\n\treturn fmt.Sprintf(\"%s is the only cell in %s %d that is unfilled, and it must be %d\", step.TargetCells.Description(), groupName, groupNumber, num)\n}\n\nfunc (self *obviousInCollectionTechnique) Find(grid *Grid) []*SolveStep {\n\treturn obviousInCollection(grid, self, self.getter(grid))\n}\n\nfunc obviousInCollection(grid *Grid, technique SolveTechnique, collectionGetter func(index int) CellSlice) []*SolveStep {\n\tindexes := rand.Perm(DIM)\n\tvar results []*SolveStep\n\tfor _, index := range indexes {\n\t\tcollection := collectionGetter(index)\n\t\topenCells := collection.FilterByHasPossibilities()\n\t\tif len(openCells) == 1 {\n\t\t\t\/\/Okay, only one cell in this collection has an opening, which must mean it has one possibilty.\n\t\t\tcell := openCells[0]\n\t\t\tpossibilities := cell.Possibilities()\n\t\t\tif len(possibilities) != 1 {\n\t\t\t\tlog.Fatalln(\"Expected the cell to only have one possibility\")\n\t\t\t} else {\n\t\t\t\tpossibility := possibilities[0]\n\t\t\t\tstep := newFillSolveStep(cell, possibility, technique)\n\t\t\t\tif step.IsUseful(grid) {\n\t\t\t\t\tresults = append(results, step)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (self *nakedSingleTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(20.0)\n}\n\nfunc (self *nakedSingleTechnique) Description(step *SolveStep) string {\n\tif len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tnum := step.TargetNums[0]\n\treturn fmt.Sprintf(\"%d is the only remaining valid number for that cell\", num)\n}\n\nfunc (self *nakedSingleTechnique) Find(grid *Grid) []*SolveStep {\n\t\/\/TODO: test that this will find multiple if they exist.\n\tvar results []*SolveStep\n\tgetter := grid.queue().NewGetter()\n\tfor {\n\t\tobj := getter.GetSmallerThan(2)\n\t\tif obj == nil {\n\t\t\t\/\/There weren't any cells with one option left.\n\t\t\t\/\/If there weren't any, period, then results is still nil already.\n\t\t\treturn results\n\t\t}\n\t\tcell := obj.(*Cell)\n\t\tresult := newFillSolveStep(cell, cell.implicitNumber(), self)\n\t\tif result.IsUseful(grid) {\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n}\n\nfunc (self *hiddenSingleTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(18.0)\n}\n\nfunc (self *hiddenSingleTechnique) Description(step *SolveStep) string {\n\t\/\/TODO: format the text to say \"first\/second\/third\/etc\"\n\tif len(step.TargetCells) == 0 || len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tcell := step.TargetCells[0]\n\tnum := step.TargetNums[0]\n\n\tvar groupName string\n\tvar otherGroupName string\n\tvar groupNum int\n\tvar otherGroupNum string\n\tswitch self.groupType {\n\tcase _GROUP_BLOCK:\n\t\tgroupName = \"block\"\n\t\totherGroupName = \"cell\"\n\t\tgroupNum = step.TargetCells.Block()\n\t\totherGroupNum = step.TargetCells.Description()\n\tcase _GROUP_ROW:\n\t\tgroupName = \"row\"\n\t\totherGroupName = \"column\"\n\t\tgroupNum = step.TargetCells.Row()\n\t\totherGroupNum = strconv.Itoa(cell.Col())\n\tcase _GROUP_COL:\n\t\tgroupName = \"column\"\n\t\totherGroupName = \"row\"\n\t\tgroupNum = step.TargetCells.Col()\n\t\totherGroupNum = strconv.Itoa(cell.Row())\n\tdefault:\n\t\tgroupName = \"\"\n\t\totherGroupName = \"\"\n\t\tgroupNum = -1\n\t\totherGroupNum = \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%d is required in the %d %s, and %s is the only %s it fits\", num, groupNum, groupName, otherGroupNum, otherGroupName)\n}\n\nfunc (self *hiddenSingleTechnique) Find(grid *Grid) []*SolveStep {\n\t\/\/TODO: test that if there are multiple we find them both.\n\treturn necessaryInCollection(grid, self, self.getter(grid))\n}\n\nfunc necessaryInCollection(grid *Grid, technique SolveTechnique, collectionGetter func(index int) CellSlice) []*SolveStep {\n\t\/\/This will be a random item\n\tindexes := rand.Perm(DIM)\n\n\tvar results []*SolveStep\n\n\tfor _, i := range indexes {\n\t\tseenInCollection := make([]int, DIM)\n\t\tcollection := collectionGetter(i)\n\t\tfor _, cell := range collection {\n\t\t\tfor _, possibility := range cell.Possibilities() {\n\t\t\t\tseenInCollection[possibility-1]++\n\t\t\t}\n\t\t}\n\t\tseenIndexes := rand.Perm(DIM)\n\t\tfor _, index := range seenIndexes {\n\t\t\tseen := seenInCollection[index]\n\t\t\tif seen == 1 {\n\t\t\t\t\/\/Okay, we know our target number. Which cell was it?\n\t\t\t\tfor _, cell := range collection {\n\t\t\t\t\tif cell.Possible(index + 1) {\n\t\t\t\t\t\t\/\/Found it... just make sure it's useful (it would be rare for it to not be).\n\t\t\t\t\t\tresult := newFillSolveStep(cell, index+1, technique)\n\t\t\t\t\t\tif result.IsUseful(grid) {\n\t\t\t\t\t\t\tresults = append(results, result)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/Hmm, wasn't useful. Keep trying...\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\nAll of the singles techniques get the new Find signaturepackage sudoku\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"strconv\"\n)\n\ntype nakedSingleTechnique struct {\n\t*basicSolveTechnique\n}\n\ntype hiddenSingleTechnique struct {\n\t*basicSolveTechnique\n}\n\ntype obviousInCollectionTechnique struct {\n\t*basicSolveTechnique\n}\n\nfunc newFillSolveStep(cell *Cell, num int, technique SolveTechnique) *SolveStep {\n\tcellArr := []*Cell{cell}\n\tnumArr := []int{num}\n\treturn &SolveStep{technique, cellArr, numArr, nil, nil}\n}\n\nfunc (self *obviousInCollectionTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(1.0)\n}\n\nfunc (self *obviousInCollectionTechnique) Description(step *SolveStep) string {\n\tif len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tnum := step.TargetNums[0]\n\tgroupName := \"\"\n\tgroupNumber := 0\n\tswitch self.groupType {\n\tcase _GROUP_BLOCK:\n\t\tgroupName = \"block\"\n\t\tgroupNumber = step.TargetCells.Block()\n\tcase _GROUP_COL:\n\t\tgroupName = \"column\"\n\t\tgroupNumber = step.TargetCells.Col()\n\tcase _GROUP_ROW:\n\t\tgroupName = \"row\"\n\t\tgroupNumber = step.TargetCells.Row()\n\t}\n\n\treturn fmt.Sprintf(\"%s is the only cell in %s %d that is unfilled, and it must be %d\", step.TargetCells.Description(), groupName, groupNumber, num)\n}\n\nfunc (self *obviousInCollectionTechnique) Find(grid *Grid, results chan *SolveStep, done chan bool) {\n\treturn obviousInCollection(grid, self, self.getter(grid), results, done)\n}\n\nfunc obviousInCollection(grid *Grid, technique SolveTechnique, collectionGetter func(index int) CellSlice, results chan *SolveStep, done chan bool) {\n\tindexes := rand.Perm(DIM)\n\tfor _, index := range indexes {\n\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tcollection := collectionGetter(index)\n\t\topenCells := collection.FilterByHasPossibilities()\n\t\tif len(openCells) == 1 {\n\t\t\t\/\/Okay, only one cell in this collection has an opening, which must mean it has one possibilty.\n\t\t\tcell := openCells[0]\n\t\t\tpossibilities := cell.Possibilities()\n\t\t\tif len(possibilities) != 1 {\n\t\t\t\tlog.Fatalln(\"Expected the cell to only have one possibility\")\n\t\t\t} else {\n\t\t\t\tpossibility := possibilities[0]\n\t\t\t\tstep := newFillSolveStep(cell, possibility, technique)\n\t\t\t\tif step.IsUseful(grid) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase results <- step:\n\t\t\t\t\tcase <-done:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nfunc (self *nakedSingleTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(20.0)\n}\n\nfunc (self *nakedSingleTechnique) Description(step *SolveStep) string {\n\tif len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tnum := step.TargetNums[0]\n\treturn fmt.Sprintf(\"%d is the only remaining valid number for that cell\", num)\n}\n\nfunc (self *nakedSingleTechnique) Find(grid *Grid, results chan *SolveStep, done chan bool) {\n\t\/\/TODO: test that this will find multiple if they exist.\n\tgetter := grid.queue().NewGetter()\n\tfor {\n\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tobj := getter.GetSmallerThan(2)\n\t\tif obj == nil {\n\t\t\t\/\/There weren't any cells with one option left.\n\t\t\t\/\/If there weren't any, period, then results is still nil already.\n\t\t\treturn\n\t\t}\n\t\tcell := obj.(*Cell)\n\t\tstep := newFillSolveStep(cell, cell.implicitNumber(), self)\n\t\tif step.IsUseful(grid) {\n\t\t\tselect {\n\t\t\tcase results <- step:\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *hiddenSingleTechnique) HumanLikelihood() float64 {\n\treturn self.difficultyHelper(18.0)\n}\n\nfunc (self *hiddenSingleTechnique) Description(step *SolveStep) string {\n\t\/\/TODO: format the text to say \"first\/second\/third\/etc\"\n\tif len(step.TargetCells) == 0 || len(step.TargetNums) == 0 {\n\t\treturn \"\"\n\t}\n\tcell := step.TargetCells[0]\n\tnum := step.TargetNums[0]\n\n\tvar groupName string\n\tvar otherGroupName string\n\tvar groupNum int\n\tvar otherGroupNum string\n\tswitch self.groupType {\n\tcase _GROUP_BLOCK:\n\t\tgroupName = \"block\"\n\t\totherGroupName = \"cell\"\n\t\tgroupNum = step.TargetCells.Block()\n\t\totherGroupNum = step.TargetCells.Description()\n\tcase _GROUP_ROW:\n\t\tgroupName = \"row\"\n\t\totherGroupName = \"column\"\n\t\tgroupNum = step.TargetCells.Row()\n\t\totherGroupNum = strconv.Itoa(cell.Col())\n\tcase _GROUP_COL:\n\t\tgroupName = \"column\"\n\t\totherGroupName = \"row\"\n\t\tgroupNum = step.TargetCells.Col()\n\t\totherGroupNum = strconv.Itoa(cell.Row())\n\tdefault:\n\t\tgroupName = \"\"\n\t\totherGroupName = \"\"\n\t\tgroupNum = -1\n\t\totherGroupNum = \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%d is required in the %d %s, and %s is the only %s it fits\", num, groupNum, groupName, otherGroupNum, otherGroupName)\n}\n\nfunc (self *hiddenSingleTechnique) Find(grid *Grid, results chan *SolveStep, done chan bool) {\n\t\/\/TODO: test that if there are multiple we find them both.\n\treturn necessaryInCollection(grid, self, self.getter(grid), results, done)\n}\n\nfunc necessaryInCollection(grid *Grid, technique SolveTechnique, collectionGetter func(index int) CellSlice, results chan *SolveStep, done chan bool) {\n\t\/\/This will be a random item\n\tindexes := rand.Perm(DIM)\n\n\tfor _, i := range indexes {\n\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tseenInCollection := make([]int, DIM)\n\t\tcollection := collectionGetter(i)\n\t\tfor _, cell := range collection {\n\t\t\tfor _, possibility := range cell.Possibilities() {\n\t\t\t\tseenInCollection[possibility-1]++\n\t\t\t}\n\t\t}\n\t\tseenIndexes := rand.Perm(DIM)\n\t\tfor _, index := range seenIndexes {\n\t\t\tseen := seenInCollection[index]\n\t\t\tif seen == 1 {\n\t\t\t\t\/\/Okay, we know our target number. Which cell was it?\n\t\t\t\tfor _, cell := range collection {\n\t\t\t\t\tif cell.Possible(index + 1) {\n\t\t\t\t\t\t\/\/Found it... just make sure it's useful (it would be rare for it to not be).\n\t\t\t\t\t\tstep := newFillSolveStep(cell, index+1, technique)\n\t\t\t\t\t\tif step.IsUseful(grid) {\n\t\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\tcase results <- step:\n\t\t\t\t\t\t\tcase <-done:\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/Hmm, wasn't useful. Keep trying...\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/avarabyeu\/goRP\/conf\"\n\t\"github.com\/avarabyeu\/goRP\/server\"\n\n\t\"net\/http\"\n\t\"goji.io\"\n\t\"goji.io\/pat\"\n\t\"github.com\/gorilla\/handlers\"\n\n\t\"os\"\n\t\"log\"\n)\n\nfunc main() {\n\n\tcurrDir, _ := os.Getwd()\n\trpConf := conf.LoadConfig(\"\", map[string]interface{}{\"staticsPath\": currDir})\n\tsrv := server.New(rpConf)\n\n\tsrv.AddRoute(func(mux *goji.Mux) {\n\t\tmux.Use(func(next http.Handler) http.Handler {\n\t\t\treturn handlers.LoggingHandler(os.Stdout, next)\n\t\t})\n\n\t\tdir := rpConf.Get(\"staticsPath\").(string)\n\t\terr := os.Chdir(dir)\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"Dir %s not found\", dir)\n\t\t}\n\n\t\tmux.Handle(pat.Get(\"\/*\"), http.FileServer(http.Dir(dir)))\n\n\t})\n\n\tsrv.StartServer()\n\n}\norganize importspackage main\n\nimport (\n\t\"github.com\/avarabyeu\/goRP\/conf\"\n\t\"github.com\/avarabyeu\/goRP\/server\"\n\n\t\"github.com\/gorilla\/handlers\"\n\t\"goji.io\"\n\t\"goji.io\/pat\"\n\t\"net\/http\"\n\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\n\tcurrDir, _ := os.Getwd()\n\trpConf := conf.LoadConfig(\"\", map[string]interface{}{\"staticsPath\": currDir})\n\tsrv := server.New(rpConf)\n\n\tsrv.AddRoute(func(mux *goji.Mux) {\n\t\tmux.Use(func(next http.Handler) http.Handler {\n\t\t\treturn handlers.LoggingHandler(os.Stdout, next)\n\t\t})\n\n\t\tdir := rpConf.Get(\"staticsPath\").(string)\n\t\terr := os.Chdir(dir)\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"Dir %s not found\", dir)\n\t\t}\n\n\t\tmux.Handle(pat.Get(\"\/*\"), http.FileServer(http.Dir(dir)))\n\n\t})\n\n\tsrv.StartServer()\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"net\/http\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Client struct {\n\twriter http.ResponseWriter\n\tchannel chan <- string\n}\n\nfunc handleMessages(messageChan <- chan string, addChan <- chan Client, removeChan <- chan Client) {\n\t\/\/ clients := make(map[http.ResponseWriter] chan <- string)\n\n\tfor {\n\t\tselect {\n\t\tcase message := <- messageChan:\n\t\t\tlog.Print(\"New message: \", message)\n\t\tcase client := <- addChan:\n\t\t\tlog.Print(\"Client connected: \", client)\n\t\tcase client := <- removeChan:\n\t\t\tlog.Print(\"Client disconnected: \", client)\n\t\t}\n\t}\n}\n\nfunc handleStream(messageChan chan <- string, addChan chan <- Client, removeChan chan <- Client, writer http.ResponseWriter, request *http.Request) {\n\twriter.Header().Set(\"Content-Type\", \"text\/event-stream\")\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\twriter.WriteHeader(200)\n\n\tchannel := make(chan string)\n\tclient := Client{writer, channel}\n\n\taddChan <- client\n\n\tfor {\n\t\tif _, error := writer.Write([]byte(\"test\\r\\n\")); error != nil {\n\t\t\tlog.Print(\"Write: \", error)\n\t\t\tbreak\n\t\t}\n\t\twriter.(http.Flusher).Flush()\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tremoveChan <- client\n}\n\nfunc main() {\n\tmessagesChan := make(chan string)\n\taddChan := make(chan Client)\n\tremoveChan := make(chan Client)\n\n\tgo handleMessages(messagesChan, addChan, removeChan)\n\n\thttp.HandleFunc(\"\/\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thttp.ServeFile(writer, request, \"static\/index.html\")\n\t})\n\thttp.HandleFunc(\"\/static\/\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thttp.ServeFile(writer, request, request.URL.Path[1:])\n\t})\n\thttp.HandleFunc(\"\/stream\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thandleStream(messagesChan, addChan, removeChan, writer, request)\n\t})\n\n\tlog.Print(\"Starting server on :8080\")\n\n\tif error := http.ListenAndServe(\":8080\", nil); error != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", error)\n\t}\n\n\tlog.Print(\"yeah\");\n}\nremoved garbagepackage main\n\nimport (\n\t\"net\/http\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Client struct {\n\twriter http.ResponseWriter\n\tchannel chan <- string\n}\n\nfunc handleMessages(messageChan <- chan string, addChan <- chan Client, removeChan <- chan Client) {\n\t\/\/ clients := make(map[http.ResponseWriter] chan <- string)\n\n\tfor {\n\t\tselect {\n\t\tcase message := <- messageChan:\n\t\t\tlog.Print(\"New message: \", message)\n\t\tcase client := <- addChan:\n\t\t\tlog.Print(\"Client connected: \", client)\n\t\tcase client := <- removeChan:\n\t\t\tlog.Print(\"Client disconnected: \", client)\n\t\t}\n\t}\n}\n\nfunc handleStream(messageChan chan <- string, addChan chan <- Client, removeChan chan <- Client, writer http.ResponseWriter, request *http.Request) {\n\twriter.Header().Set(\"Content-Type\", \"text\/event-stream\")\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\twriter.WriteHeader(200)\n\n\tchannel := make(chan string)\n\tclient := Client{writer, channel}\n\n\taddChan <- client\n\n\tfor {\n\t\tif _, error := writer.Write([]byte(\"test\\r\\n\")); error != nil {\n\t\t\tlog.Print(\"Write: \", error)\n\t\t\tbreak\n\t\t}\n\t\twriter.(http.Flusher).Flush()\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tremoveChan <- client\n}\n\nfunc main() {\n\tmessagesChan := make(chan string)\n\taddChan := make(chan Client)\n\tremoveChan := make(chan Client)\n\n\tgo handleMessages(messagesChan, addChan, removeChan)\n\n\thttp.HandleFunc(\"\/\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thttp.ServeFile(writer, request, \"static\/index.html\")\n\t})\n\thttp.HandleFunc(\"\/static\/\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thttp.ServeFile(writer, request, request.URL.Path[1:])\n\t})\n\thttp.HandleFunc(\"\/stream\", func (writer http.ResponseWriter, request *http.Request) {\n\t\thandleStream(messagesChan, addChan, removeChan, writer, request)\n\t})\n\n\tlog.Print(\"Starting server on :8080\")\n\n\tif error := http.ListenAndServe(\":8080\", nil); error != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", error)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nconst Version string = \"0.0.1\"\n\ntype Grcron struct {\n\tStateFile string\n\tDefaultState string\n\tCurrentState string\n}\n\nfunc (gr Grcron) Validate() error {\n\t_, err := os.Stat(gr.StateFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !(gr.DefaultState == \"active\" || gr.DefaultState == \"passive\") {\n\t\treturn fmt.Errorf(\"The Value of DefaultState:%s is incorrect.\", gr.DefaultState)\n\t}\n\treturn nil\n}\n\nfunc (gr *Grcron) ParseState() error {\n\tif gr == nil {\n\t\treturn fmt.Errorf(\"Don't run nil Pointer Receiver.\")\n\t}\n\tf, err := os.Open(gr.StateFile)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsc := bufio.NewScanner(f)\n\tif !sc.Scan() {\n\t\treturn sc.Err()\n\t}\n\tst := sc.Text()\n\tswitch st {\n\tcase \"active\", \"passive\":\n\t\tgr.CurrentState = st\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"corrupted state file('%s') (content='%s'), staying at gr.DefaultState('%s')\\n\", gr.StateFile, st, gr.DefaultState)\n\t\tgr.CurrentState = gr.DefaultState\n\t}\n\treturn nil\n}\nfunc (gr Grcron) IsActive() (bool, error) {\n\tcmd := exec.Command(\"sh\", \"-c\", \"ps cax | grep -q keepalived\")\n\terr := cmd.Run()\n\tvar exitStatus int\n\tif e2, ok := err.(*exec.ExitError); ok {\n\t\tif s, ok := e2.Sys().(syscall.WaitStatus); ok {\n\t\t\texitStatus = s.ExitStatus()\n\t\t} else {\n\t\t\treturn false, fmt.Errorf(\"Unimplemented for system where exec.ExitError.Sys() is not syscall.WaitStatus.\")\n\t\t}\n\t} else {\n\t\texitStatus = 0\n\t}\n\n\tif gr.CurrentState == \"active\" && exitStatus == 0 {\n\t\treturn true, nil\n\t} else {\n\t\tif gr.CurrentState == \"active\" {\n\t\t\tfmt.Fprintf(os.Stderr, \"gr.CurrentState:active, but keepalived is probably down.\\n\")\n\t\t}\n\t\treturn false, nil\n\t}\n}\n\nfunc main() {\n\tvar (\n\t\tshowVersion bool\n\t\tdryRun bool\n\t)\n\n\tgr := &Grcron{}\n\tflag.StringVar(&gr.StateFile, \"f\", \"\/var\/run\/grcron\/state\", \"grcron state file.\")\n\tflag.StringVar(&gr.DefaultState, \"s\", \"passive\", \"grcron default state.\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"show version number.\")\n\tflag.BoolVar(&showVersion, \"v\", false, \"show version number.\")\n\tflag.BoolVar(&dryRun, \"dryrun\", false, \"dry-run.\")\n\tflag.BoolVar(&dryRun, \"n\", false, \"dry-run.\")\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif showVersion {\n\t\tfmt.Printf(\"grcron %s, %s built for %s\/%s\\n\", Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)\n\t\treturn\n\t}\n\n\tif err := gr.Validate(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tif err := gr.ParseState(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif len(args) < 1 {\n\t\tfmt.Fprintln(os.Stderr, \"not enough arguments\")\n\t\tos.Exit(1)\n\t}\n\n\tisa, err := gr.IsActive()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif dryRun {\n\t\tfmt.Printf(\"dry-run gr.CurrentState:%s, gr.IsActive:%v finished.\\n\", gr.CurrentState, isa)\n\t\treturn\n\t}\n\n\tif !isa {\n\t\treturn\n\t}\n\n\t\/\/ run !!\n\tbinary, err := exec.LookPath(args[0])\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif err := syscall.Exec(binary, args, os.Environ()); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\nkeepalivedがいないならエラーにするpackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nconst Version string = \"0.0.1\"\n\ntype Grcron struct {\n\tStateFile string\n\tDefaultState string\n\tCurrentState string\n}\n\nfunc (gr Grcron) Validate() error {\n\t_, err := os.Stat(gr.StateFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !(gr.DefaultState == \"active\" || gr.DefaultState == \"passive\") {\n\t\treturn fmt.Errorf(\"The Value of DefaultState:%s is incorrect.\", gr.DefaultState)\n\t}\n\treturn nil\n}\n\nfunc (gr *Grcron) ParseState() error {\n\tif gr == nil {\n\t\treturn fmt.Errorf(\"Don't run nil Pointer Receiver.\")\n\t}\n\tf, err := os.Open(gr.StateFile)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsc := bufio.NewScanner(f)\n\tif !sc.Scan() {\n\t\treturn sc.Err()\n\t}\n\tst := sc.Text()\n\tswitch st {\n\tcase \"active\", \"passive\":\n\t\tgr.CurrentState = st\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"corrupted state file('%s') (content='%s'), staying at gr.DefaultState('%s')\\n\", gr.StateFile, st, gr.DefaultState)\n\t\tgr.CurrentState = gr.DefaultState\n\t}\n\treturn nil\n}\nfunc (gr Grcron) IsActive() (bool, error) {\n\tcmd := exec.Command(\"sh\", \"-c\", \"ps cax | grep -q keepalived\")\n\terr := cmd.Run()\n\n\t\/\/ 異常終了はkeepalivedプロセスがいないとみなす\n\tif _, ok := err.(*exec.ExitError); ok {\n\t\treturn false, fmt.Errorf(\"keepalived is probably down.\")\n\t}\n\n\treturn gr.CurrentState == \"active\", nil\n}\n\nfunc main() {\n\tvar (\n\t\tshowVersion bool\n\t\tdryRun bool\n\t)\n\n\tgr := &Grcron{}\n\tflag.StringVar(&gr.StateFile, \"f\", \"\/var\/run\/grcron\/state\", \"grcron state file.\")\n\tflag.StringVar(&gr.DefaultState, \"s\", \"passive\", \"grcron default state.\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"show version number.\")\n\tflag.BoolVar(&showVersion, \"v\", false, \"show version number.\")\n\tflag.BoolVar(&dryRun, \"dryrun\", false, \"dry-run.\")\n\tflag.BoolVar(&dryRun, \"n\", false, \"dry-run.\")\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif showVersion {\n\t\tfmt.Printf(\"grcron %s, %s built for %s\/%s\\n\", Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)\n\t\treturn\n\t}\n\n\tif err := gr.Validate(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tif err := gr.ParseState(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif len(args) < 1 {\n\t\tfmt.Fprintln(os.Stderr, \"not enough arguments\")\n\t\tos.Exit(1)\n\t}\n\n\tisa, err := gr.IsActive()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif dryRun {\n\t\tfmt.Printf(\"dry-run gr.CurrentState:%s, gr.IsActive:%v finished.\\n\", gr.CurrentState, isa)\n\t\treturn\n\t}\n\n\tif !isa {\n\t\treturn\n\t}\n\n\t\/\/ run !!\n\tbinary, err := exec.LookPath(args[0])\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif err := syscall.Exec(binary, args, os.Environ()); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015, Timothy Bogdala \n\/\/ See the LICENSE file for more details.\n\n\/*\n\nPackage groggy is a library that makes it easier to setup custom\nlogging channels.\n\nTo use:\n\n1) Call Register() with a log name and an optional function to handle the log events.\n2) Call Log() with this log name and the data objects to log\n\nIf no optional log handlers are supplied, the default handler writes the data\nobjects out to stdout using fmt.Print(). To do this, the objects should be\nstrings or implement the fmt.Stringer interface.\n\nIf Log() is called with a log name that is not registered, it will not be able\nto call a handler, and an error will be returned.\n\nClients can call Deregister() to remove a log handler.\n\n*\/\npackage groggy\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ GroggyEvent defines a function handler for incoming logging events.\n\/\/ It's setup with a variadic argument for extra flexibility in custom handlers.\ntype GroggyEvent func(logName string, data ...interface{}) error\n\nvar (\n\t\/\/ handlers is a global registry of event handlers\n\thandlers map[string]GroggyEvent\n\n\t\/\/ make a mutex for the default sync handler\n\thandlerMutex sync.Mutex\n)\n\nfunc init() {\n\t\/\/ make sure to initialize the global map\n\thandlers = make(map[string]GroggyEvent)\n}\n\n\/\/ Register adds a new log handler to the global registry and assigns it\n\/\/ the handler function passed in. If handler is nil, then DefaultHandler is used.\n\/\/ An existing log handler can be replaced using this function.\nfunc Register(newLogName string, handler GroggyEvent) {\n\t\/\/ use DefaultHandler if a nil handler was supplied\n\tvar h GroggyEvent = handler\n\tif h == nil {\n\t\th = DefaultHandler\n\t}\n\thandlers[newLogName] = h\n}\n\n\/\/ Deregister removes the log handler from the global registry so that\n\/\/ further calls to Log with the log name do not get handled.\nfunc Deregister(logName string) {\n\tdelete(handlers, logName)\n}\n\n\/\/ DefaultHandler writes out the information assuming data members are strings\n\/\/ or anything that implements the GoStringer interface. This is not\n\/\/ considered safe for concurrency.\nfunc DefaultHandler(logName string, data ...interface{}) error {\n\tconst layout = \"15:04:05.000\"\n\tnow := time.Now()\n\tfmt.Printf(\"%s %s: \", now.Format(layout), logName)\n\tfor _, ds := range data {\n\t\tswitch v := ds.(type) {\n\t\tcase string:\n\t\t\tfmt.Print(v)\n\t\tcase fmt.Stringer:\n\t\t\tfmt.Print(v.String())\n\t\tdefault:\n\t\t\tfmt.Printf(\"\", ds)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n\treturn nil\n}\n\n\/\/ DefaultSyncHandler writes out the information assuming data members are strings\n\/\/ or anything that implements the GoStringer interface. This is considered safe\n\/\/ for concurrency.\nfunc DefaultSyncHandler(logName string, data ...interface{}) error {\n\thandlerMutex.Lock()\n\tDefaultHandler(logName, data...)\n\thandlerMutex.Unlock()\n\treturn nil\n}\n\n\/\/ Log sends the data to the handler specified by the logName. This is not\n\/\/ considered safe for concurrency by default.\nfunc Log(logName string, data ...interface{}) error {\n\th, okay := handlers[logName]\n\tif okay == false {\n\t\treturn fmt.Errorf(\"No log handler found for %s.\", logName)\n\t}\n\n\treturn h(logName, data...)\n}\n\nfunc Logsf(logName string, data ...interface{}) error {\n\th, okay := handlers[logName]\n\tif okay == false {\n\t\treturn fmt.Errorf(\"No log handler found for %s.\", logName)\n\t}\n\n\tsprintStr, okay := data[0].(string)\n\tif okay == false {\n\t\treturn fmt.Errorf(\"A format string was not passed as the second parameter.\")\n\t}\n\n\ts := fmt.Sprintf(sprintStr, data[1:]...)\n\treturn h(logName, s)\n}\nforgot to document Logsf. shame on me!\/\/ Copyright 2015, Timothy Bogdala \n\/\/ See the LICENSE file for more details.\n\n\/*\n\nPackage groggy is a library that makes it easier to setup custom\nlogging channels.\n\nTo use:\n\n1) Call Register() with a log name and an optional function to handle the log events.\n2) Call Log() with this log name and the data objects to log\n\nIf no optional log handlers are supplied, the default handler writes the data\nobjects out to stdout using fmt.Print(). To do this, the objects should be\nstrings or implement the fmt.Stringer interface.\n\nIf Log() is called with a log name that is not registered, it will not be able\nto call a handler, and an error will be returned.\n\nClients can call Deregister() to remove a log handler.\n\n*\/\npackage groggy\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ GroggyEvent defines a function handler for incoming logging events.\n\/\/ It's setup with a variadic argument for extra flexibility in custom handlers.\ntype GroggyEvent func(logName string, data ...interface{}) error\n\nvar (\n\t\/\/ handlers is a global registry of event handlers\n\thandlers map[string]GroggyEvent\n\n\t\/\/ make a mutex for the default sync handler\n\thandlerMutex sync.Mutex\n)\n\nfunc init() {\n\t\/\/ make sure to initialize the global map\n\thandlers = make(map[string]GroggyEvent)\n}\n\n\/\/ Register adds a new log handler to the global registry and assigns it\n\/\/ the handler function passed in. If handler is nil, then DefaultHandler is used.\n\/\/ An existing log handler can be replaced using this function.\nfunc Register(newLogName string, handler GroggyEvent) {\n\t\/\/ use DefaultHandler if a nil handler was supplied\n\tvar h GroggyEvent = handler\n\tif h == nil {\n\t\th = DefaultHandler\n\t}\n\thandlers[newLogName] = h\n}\n\n\/\/ Deregister removes the log handler from the global registry so that\n\/\/ further calls to Log with the log name do not get handled.\nfunc Deregister(logName string) {\n\tdelete(handlers, logName)\n}\n\n\/\/ DefaultHandler writes out the information assuming data members are strings\n\/\/ or anything that implements the GoStringer interface. This is not\n\/\/ considered safe for concurrency.\nfunc DefaultHandler(logName string, data ...interface{}) error {\n\tconst layout = \"15:04:05.000\"\n\tnow := time.Now()\n\tfmt.Printf(\"%s %s: \", now.Format(layout), logName)\n\tfor _, ds := range data {\n\t\tswitch v := ds.(type) {\n\t\tcase string:\n\t\t\tfmt.Print(v)\n\t\tcase fmt.Stringer:\n\t\t\tfmt.Print(v.String())\n\t\tdefault:\n\t\t\tfmt.Printf(\"\", ds)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n\treturn nil\n}\n\n\/\/ DefaultSyncHandler writes out the information assuming data members are strings\n\/\/ or anything that implements the GoStringer interface. This is considered safe\n\/\/ for concurrency.\nfunc DefaultSyncHandler(logName string, data ...interface{}) error {\n\thandlerMutex.Lock()\n\tDefaultHandler(logName, data...)\n\thandlerMutex.Unlock()\n\treturn nil\n}\n\n\/\/ Log sends the data to the handler specified by the logName. This is not\n\/\/ considered safe for concurrency by default.\nfunc Log(logName string, data ...interface{}) error {\n\th, okay := handlers[logName]\n\tif okay == false {\n\t\treturn fmt.Errorf(\"No log handler found for %s.\", logName)\n\t}\n\n\treturn h(logName, data...)\n}\n\n\/\/ Logsf uses the second parameter as the format string for fmt.Spritnf and\n\/\/ then sends the rest of the parameters to it. The resulting string is then\n\/\/ passed to the handler specified by logName.\nfunc Logsf(logName string, data ...interface{}) error {\n\th, okay := handlers[logName]\n\tif okay == false {\n\t\treturn fmt.Errorf(\"No log handler found for %s.\", logName)\n\t}\n\n\tsprintStr, okay := data[0].(string)\n\tif okay == false {\n\t\treturn fmt.Errorf(\"A format string was not passed as the second parameter.\")\n\t}\n\n\ts := fmt.Sprintf(sprintStr, data[1:]...)\n\treturn h(logName, s)\n}\n<|endoftext|>"} {"text":"package swarm\n\nimport (\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\t\"xd\/lib\/bittorrent\"\n\t\"xd\/lib\/bittorrent\/extensions\"\n\t\"xd\/lib\/common\"\n\t\"xd\/lib\/log\"\n\t\"xd\/lib\/util\"\n)\n\nconst DefaultMaxParallelRequests = 8\n\n\/\/ a peer connection\ntype PeerConn struct {\n\tinbound bool\n\tclosing bool\n\tc net.Conn\n\tid common.PeerID\n\tt *Torrent\n\tsendMtx sync.Mutex\n\tbf *bittorrent.Bitfield\n\tpeerChoke bool\n\tpeerInterested bool\n\tusChoke bool\n\tusInterested bool\n\tDone func()\n\tkeepalive *time.Ticker\n\tlastSend time.Time\n\ttx util.Rate\n\tlastRecv time.Time\n\trx util.Rate\n\tdownloading []*common.PieceRequest\n\tourOpts *extensions.Message\n\ttheirOpts *extensions.Message\n\tMaxParalellRequests int\n\taccess sync.Mutex\n}\n\n\/\/ get stats for this connection\nfunc (c *PeerConn) Stats() (st *PeerConnStats) {\n\tst = new(PeerConnStats)\n\tst.TX = c.tx.Rate()\n\tst.RX = c.rx.Rate()\n\tst.Addr = c.c.RemoteAddr().String()\n\tst.ID = c.id.String()\n\treturn\n}\n\nfunc makePeerConn(c net.Conn, t *Torrent, id common.PeerID, ourOpts *extensions.Message) *PeerConn {\n\tp := new(PeerConn)\n\tp.c = c\n\tp.t = t\n\tp.ourOpts = ourOpts\n\tp.peerChoke = true\n\tp.usChoke = true\n\tcopy(p.id[:], id[:])\n\tp.MaxParalellRequests = t.MaxRequests\n\tp.keepalive = time.NewTicker(time.Minute)\n\tp.downloading = []*common.PieceRequest{}\n\treturn p\n}\n\nfunc (c *PeerConn) start() {\n\tgo c.runReader()\n\tgo c.runKeepAlive()\n\tgo c.tickStats()\n}\n\nfunc (c *PeerConn) runKeepAlive() {\n\tfor !c.closing {\n\t\ttime.Sleep(time.Second)\n\t\tc.sendKeepAlive()\n\t}\n}\n\nfunc (c *PeerConn) tickStats() {\n\tfor !c.closing {\n\t\ttime.Sleep(time.Second)\n\t\tc.tx.Tick()\n\t\tc.rx.Tick()\n\t}\n}\n\nfunc (c *PeerConn) doSend(msg *common.WireMessage) {\n\tif !c.closing && msg != nil {\n\t\tc.sendMtx.Lock()\n\t\tnow := time.Now()\n\t\tc.lastSend = now\n\t\tif c.RemoteChoking() && msg.MessageID() == common.Request {\n\t\t\t\/\/ drop\n\t\t\tlog.Debugf(\"drop request because choke\")\n\t\t\tr := msg.GetPieceRequest()\n\t\t\tc.cancelDownload(r)\n\t\t} else {\n\t\t\tlog.Debugf(\"writing %d bytes\", msg.Len())\n\t\t\terr := msg.Send(c.c)\n\t\t\tif err == nil {\n\t\t\t\tif msg.MessageID() == common.Piece {\n\t\t\t\t\tc.tx.AddSample(uint64(msg.Len()))\n\t\t\t\t}\n\t\t\t\tlog.Debugf(\"wrote message %s %d bytes\", msg.MessageID(), msg.Len())\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"write error: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t\tc.sendMtx.Unlock()\n\t}\n}\n\n\/\/ queue a send of a bittorrent wire message to this peer\nfunc (c *PeerConn) Send(msg *common.WireMessage) {\n\tgo c.doSend(msg)\n}\n\nfunc (c *PeerConn) recv(msg *common.WireMessage) (err error) {\n\tc.lastRecv = time.Now()\n\tif (!msg.KeepAlive()) && msg.MessageID() == common.Piece {\n\t\tc.rx.AddSample(uint64(msg.Len()))\n\t}\n\tlog.Debugf(\"got %d bytes from %s\", msg.Len(), c.id)\n\terr = c.inboundMessage(msg)\n\treturn\n}\n\n\/\/ send choke\nfunc (c *PeerConn) Choke() {\n\tif c.usChoke {\n\t\tlog.Warnf(\"multiple chokes sent to %s\", c.id.String())\n\t} else {\n\t\tlog.Debugf(\"choke peer %s\", c.id.String())\n\t\tc.Send(common.NewWireMessage(common.Choke, nil))\n\t\tc.usChoke = true\n\t}\n}\n\n\/\/ send unchoke\nfunc (c *PeerConn) Unchoke() {\n\tif c.usChoke {\n\t\tlog.Debugf(\"unchoke peer %s\", c.id.String())\n\t\tc.Send(common.NewWireMessage(common.UnChoke, nil))\n\t\tc.usChoke = false\n\t}\n}\n\nfunc (c *PeerConn) gotDownload(p *common.PieceData) {\n\tc.access.Lock()\n\tvar downloading []*common.PieceRequest\n\tfor _, r := range c.downloading {\n\t\tif r.Matches(p) {\n\t\t\tc.t.pt.handlePieceData(p)\n\t\t} else {\n\t\t\tdownloading = append(downloading, r)\n\t\t}\n\t}\n\tc.downloading = downloading\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) cancelDownload(req *common.PieceRequest) {\n\tc.access.Lock()\n\tvar downloading []*common.PieceRequest\n\tfor _, r := range c.downloading {\n\t\tif r.Equals(req) {\n\t\t\tc.t.pt.canceledRequest(r)\n\t\t} else {\n\t\t\tdownloading = append(downloading, r)\n\t\t}\n\t}\n\tc.downloading = downloading\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) numDownloading() int {\n\tc.access.Lock()\n\ti := len(c.downloading)\n\tc.access.Unlock()\n\treturn i\n}\n\nfunc (c *PeerConn) queueDownload(req *common.PieceRequest) {\n\tif c.closing {\n\t\tc.clearDownloading()\n\t\treturn\n\t}\n\tc.access.Lock()\n\tc.downloading = append(c.downloading, req)\n\tlog.Debugf(\"ask %s for %d %d %d\", c.id.String(), req.Index, req.Begin, req.Length)\n\tc.Send(req.ToWireMessage())\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) clearDownloading() {\n\tc.access.Lock()\n\tfor _, r := range c.downloading {\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tc.downloading = []*common.PieceRequest{}\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) HasPiece(piece uint32) bool {\n\tif c.bf == nil {\n\t\t\/\/ no bitfield\n\t\treturn false\n\t}\n\treturn c.bf.Has(piece)\n}\n\n\/\/ return true if this peer is choking us otherwise return false\nfunc (c *PeerConn) RemoteChoking() bool {\n\treturn c.peerChoke\n}\n\n\/\/ return true if we are choking the remote peer otherwise return false\nfunc (c *PeerConn) Chocking() bool {\n\treturn c.usChoke\n}\n\nfunc (c *PeerConn) remoteUnchoke() {\n\tif !c.peerChoke {\n\t\tlog.Warnf(\"remote peer %s sent multiple unchokes\", c.id.String())\n\t}\n\tc.peerChoke = false\n\tlog.Debugf(\"%s unchoked us\", c.id.String())\n}\n\nfunc (c *PeerConn) remoteChoke() {\n\tif c.peerChoke {\n\t\tlog.Warnf(\"remote peer %s sent multiple chokes\", c.id.String())\n\t}\n\tc.peerChoke = true\n\tlog.Debugf(\"%s choked us\", c.id.String())\n}\n\nfunc (c *PeerConn) markInterested() {\n\tc.peerInterested = true\n\tlog.Debugf(\"%s is interested\", c.id.String())\n}\n\nfunc (c *PeerConn) markNotInterested() {\n\tc.peerInterested = false\n\tlog.Debugf(\"%s is not interested\", c.id.String())\n}\n\nfunc (c *PeerConn) Close() {\n\tif c.closing {\n\t\treturn\n\t}\n\tc.closing = true\n\tfor _, r := range c.downloading {\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tc.downloading = nil\n\tc.keepalive.Stop()\n\tlog.Debugf(\"%s closing connection\", c.id.String())\n\tc.c.Close()\n\tif c.inbound {\n\t\tc.t.removeIBConn(c)\n\t} else {\n\t\tc.t.removeOBConn(c)\n\t}\n}\n\n\/\/ run read loop\nfunc (c *PeerConn) runReader() {\n\terr := common.ReadWireMessages(c.c, c.recv)\n\tif err != nil {\n\t\tlog.Debugf(\"PeerConn() reader failed: %s\", err.Error())\n\t}\n\tc.Close()\n}\n\nfunc (c *PeerConn) inboundMessage(msg *common.WireMessage) (err error) {\n\n\tif msg.KeepAlive() {\n\t\tlog.Debugf(\"keepalive from %s\", c.id)\n\t\treturn\n\t}\n\tmsgid := msg.MessageID()\n\tlog.Debugf(\"%s from %s\", msgid.String(), c.id.String())\n\tif msgid == common.BitField {\n\t\tisnew := false\n\t\tif c.bf == nil {\n\t\t\tisnew = true\n\t\t}\n\t\tc.bf = bittorrent.NewBitfield(c.t.MetaInfo().Info.NumPieces(), msg.Payload())\n\t\tlog.Debugf(\"got bitfield from %s\", c.id.String())\n\t\t\/\/ TODO: determine if we are really interested\n\t\tm := common.NewInterested()\n\t\tc.Send(m)\n\t\tif isnew {\n\t\t\tc.usInterested = true\n\t\t\tc.Unchoke()\n\t\t\tif c.ourOpts != nil {\n\t\t\t\tc.Send(c.ourOpts.ToWireMessage())\n\t\t\t}\n\t\t\tgo c.runDownload()\n\t\t}\n\t\treturn\n\t}\n\tif msgid == common.Choke {\n\t\tc.remoteChoke()\n\t}\n\tif msgid == common.UnChoke {\n\t\tc.remoteUnchoke()\n\t}\n\tif msgid == common.Interested {\n\t\tc.markInterested()\n\t}\n\tif msgid == common.NotInterested {\n\t\tc.markNotInterested()\n\t}\n\tif msgid == common.Request {\n\t\tev := msg.GetPieceRequest()\n\t\tc.t.handlePieceRequest(c, ev)\n\t}\n\tif msgid == common.Piece {\n\t\td := msg.GetPieceData()\n\t\tif d == nil {\n\t\t\tlog.Warnf(\"invalid piece data message from %s\", c.id.String())\n\t\t\tc.Close()\n\t\t} else {\n\t\t\tc.gotDownload(d)\n\t\t}\n\t}\n\n\tif msgid == common.Have && c.bf != nil {\n\t\t\/\/ update bitfield\n\t\tidx := msg.GetHave()\n\t\tc.bf.Set(idx)\n\t}\n\tif msgid == common.Cancel {\n\t\t\/\/ TODO: check validity\n\t\tr := msg.GetPieceRequest()\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tif msgid == common.Extended {\n\t\t\/\/ handle extended options\n\t\topts := extensions.FromWireMessage(msg)\n\t\tif opts == nil {\n\t\t\tlog.Warnf(\"failed to parse extended options for %s\", c.id.String())\n\t\t} else {\n\t\t\tc.handleExtendedOpts(opts)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ handles an inbound pex message\nfunc (c *PeerConn) handlePEX(m interface{}) {\n\n\tpex, ok := m.(map[string]interface{})\n\tif ok {\n\t\tvar added interface{}\n\t\tadded, ok = pex[\"added\"]\n\t\tif ok {\n\t\t\tc.handlePEXAdded(added)\n\t\t}\n\t\tadded, ok = pex[\"added.f\"]\n\t\tif ok {\n\t\t\tc.handlePEXAddedf(added)\n\t\t}\n\t} else {\n\t\tlog.Errorf(\"invalid pex message: %q\", m)\n\t}\n}\n\n\/\/ handle inbound PEX message payload\nfunc (c *PeerConn) handlePEXAdded(m interface{}) {\n\tvar peers []common.Peer\n\tmsg := m.(string)\n\tl := len(msg) \/ 32\n\tfor l > 0 {\n\t\tvar p common.Peer\n\t\t\/\/ TODO: bounds check\n\t\tcopy(p.Compact[:], msg[(l-1)*32:l*32])\n\t\tl--\n\t\tpeers = append(peers, p)\n\t}\n\tc.t.addPeers(peers)\n}\n\nfunc (c *PeerConn) handlePEXAddedf(m interface{}) {\n\t\/\/ TODO: implement this\n}\n\nfunc (c *PeerConn) SupportsPEX() bool {\n\tif c.theirOpts == nil {\n\t\treturn false\n\t}\n\treturn c.theirOpts.PEX()\n}\n\nfunc (c *PeerConn) sendPEX(connected, disconnected []byte) {\n\tid := c.theirOpts.Extensions[extensions.PeerExchange.String()]\n\tmsg := extensions.NewPEX(id, connected, disconnected)\n\tc.Send(msg.ToWireMessage())\n}\n\nfunc (c *PeerConn) handleExtendedOpts(opts *extensions.Message) {\n\tlog.Debugf(\"got extended opts from %s: %s\", c.id.String(), opts)\n\tif opts.ID == 0 {\n\t\t\/\/ handshake\n\t\tif c.theirOpts == nil {\n\t\t\tc.theirOpts = opts.Copy()\n\t\t} else {\n\t\t\tlog.Warnf(\"got multiple extended option handshakes from %s\", c.id.String())\n\t\t}\n\t} else {\n\t\t\/\/ extended data\n\t\tif c.theirOpts == nil {\n\t\t\tlog.Warnf(\"%s gave unexpected extended message %d\", c.id.String(), opts.ID)\n\t\t} else {\n\t\t\t\/\/ lookup the extension number\n\t\t\text, ok := c.theirOpts.Lookup(opts.ID)\n\t\t\tif ok {\n\t\t\t\tif ext == extensions.PeerExchange.String() {\n\t\t\t\t\t\/\/ this is PEX message\n\t\t\t\t\tc.handlePEX(opts.Payload)\n\t\t\t\t} else if ext == extensions.XDHT.String() {\n\t\t\t\t\t\/\/ xdht message\n\t\t\t\t\terr := c.t.xdht.HandleMessage(opts, c.id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Warnf(\"error handling xdht message from %s: %s\", c.id.String(), err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Warnf(\"peer %s gave us extension for message we do not have id=%d\", c.id.String(), opts.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *PeerConn) sendKeepAlive() {\n\ttm := time.Now().Add(0 - (time.Minute * 2))\n\tif c.lastSend.Before(tm) {\n\t\tlog.Debugf(\"send keepalive to %s\", c.id.String())\n\t\tc.doSend(common.KeepAlive())\n\t}\n}\n\n\/\/ run download loop\nfunc (c *PeerConn) runDownload() {\n\tfor !c.t.Done() && !c.closing {\n\t\tif c.RemoteChoking() {\n\t\t\tlog.Debugf(\"will not download this tick, %s is choking\", c.id.String())\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ pending request\n\t\tp := c.numDownloading()\n\t\tif p >= c.MaxParalellRequests {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tr := c.t.pt.nextRequestForDownload(c.bf)\n\t\tif r == nil {\n\t\t\tlog.Debugf(\"no next piece to download for %s\", c.id.String())\n\t\t\ttime.Sleep(time.Second)\n\t\t} else {\n\t\t\tc.queueDownload(r)\n\t\t}\n\t}\n\tif c.closing {\n\t\tc.Close()\n\t} else {\n\t\tlog.Debugf(\"peer %s is 'done'\", c.id.String())\n\t}\n\n\t\/\/ done downloading\n\tif c.Done != nil {\n\t\tc.Done()\n\t}\n}\nremove keepalive tickerpackage swarm\n\nimport (\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\t\"xd\/lib\/bittorrent\"\n\t\"xd\/lib\/bittorrent\/extensions\"\n\t\"xd\/lib\/common\"\n\t\"xd\/lib\/log\"\n\t\"xd\/lib\/util\"\n)\n\nconst DefaultMaxParallelRequests = 8\n\n\/\/ a peer connection\ntype PeerConn struct {\n\tinbound bool\n\tclosing bool\n\tc net.Conn\n\tid common.PeerID\n\tt *Torrent\n\tsendMtx sync.Mutex\n\tbf *bittorrent.Bitfield\n\tpeerChoke bool\n\tpeerInterested bool\n\tusChoke bool\n\tusInterested bool\n\tDone func()\n\tlastSend time.Time\n\ttx util.Rate\n\tlastRecv time.Time\n\trx util.Rate\n\tdownloading []*common.PieceRequest\n\tourOpts *extensions.Message\n\ttheirOpts *extensions.Message\n\tMaxParalellRequests int\n\taccess sync.Mutex\n}\n\n\/\/ get stats for this connection\nfunc (c *PeerConn) Stats() (st *PeerConnStats) {\n\tst = new(PeerConnStats)\n\tst.TX = c.tx.Rate()\n\tst.RX = c.rx.Rate()\n\tst.Addr = c.c.RemoteAddr().String()\n\tst.ID = c.id.String()\n\treturn\n}\n\nfunc makePeerConn(c net.Conn, t *Torrent, id common.PeerID, ourOpts *extensions.Message) *PeerConn {\n\tp := new(PeerConn)\n\tp.c = c\n\tp.t = t\n\tp.ourOpts = ourOpts\n\tp.peerChoke = true\n\tp.usChoke = true\n\tcopy(p.id[:], id[:])\n\tp.MaxParalellRequests = t.MaxRequests\n\tp.downloading = []*common.PieceRequest{}\n\treturn p\n}\n\nfunc (c *PeerConn) start() {\n\tgo c.runReader()\n\tgo c.runKeepAlive()\n\tgo c.tickStats()\n}\n\nfunc (c *PeerConn) runKeepAlive() {\n\tfor !c.closing {\n\t\ttime.Sleep(time.Second)\n\t\tc.sendKeepAlive()\n\t}\n}\n\nfunc (c *PeerConn) tickStats() {\n\tfor !c.closing {\n\t\ttime.Sleep(time.Second)\n\t\tc.tx.Tick()\n\t\tc.rx.Tick()\n\t}\n}\n\nfunc (c *PeerConn) doSend(msg *common.WireMessage) {\n\tif !c.closing && msg != nil {\n\t\tc.sendMtx.Lock()\n\t\tnow := time.Now()\n\t\tc.lastSend = now\n\t\tif c.RemoteChoking() && msg.MessageID() == common.Request {\n\t\t\t\/\/ drop\n\t\t\tlog.Debugf(\"drop request because choke\")\n\t\t\tr := msg.GetPieceRequest()\n\t\t\tc.cancelDownload(r)\n\t\t} else {\n\t\t\tlog.Debugf(\"writing %d bytes\", msg.Len())\n\t\t\terr := msg.Send(c.c)\n\t\t\tif err == nil {\n\t\t\t\tif msg.MessageID() == common.Piece {\n\t\t\t\t\tc.tx.AddSample(uint64(msg.Len()))\n\t\t\t\t}\n\t\t\t\tlog.Debugf(\"wrote message %s %d bytes\", msg.MessageID(), msg.Len())\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"write error: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t\tc.sendMtx.Unlock()\n\t}\n}\n\n\/\/ queue a send of a bittorrent wire message to this peer\nfunc (c *PeerConn) Send(msg *common.WireMessage) {\n\tgo c.doSend(msg)\n}\n\nfunc (c *PeerConn) recv(msg *common.WireMessage) (err error) {\n\tc.lastRecv = time.Now()\n\tif (!msg.KeepAlive()) && msg.MessageID() == common.Piece {\n\t\tc.rx.AddSample(uint64(msg.Len()))\n\t}\n\tlog.Debugf(\"got %d bytes from %s\", msg.Len(), c.id)\n\terr = c.inboundMessage(msg)\n\treturn\n}\n\n\/\/ send choke\nfunc (c *PeerConn) Choke() {\n\tif c.usChoke {\n\t\tlog.Warnf(\"multiple chokes sent to %s\", c.id.String())\n\t} else {\n\t\tlog.Debugf(\"choke peer %s\", c.id.String())\n\t\tc.Send(common.NewWireMessage(common.Choke, nil))\n\t\tc.usChoke = true\n\t}\n}\n\n\/\/ send unchoke\nfunc (c *PeerConn) Unchoke() {\n\tif c.usChoke {\n\t\tlog.Debugf(\"unchoke peer %s\", c.id.String())\n\t\tc.Send(common.NewWireMessage(common.UnChoke, nil))\n\t\tc.usChoke = false\n\t}\n}\n\nfunc (c *PeerConn) gotDownload(p *common.PieceData) {\n\tc.access.Lock()\n\tvar downloading []*common.PieceRequest\n\tfor _, r := range c.downloading {\n\t\tif r.Matches(p) {\n\t\t\tc.t.pt.handlePieceData(p)\n\t\t} else {\n\t\t\tdownloading = append(downloading, r)\n\t\t}\n\t}\n\tc.downloading = downloading\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) cancelDownload(req *common.PieceRequest) {\n\tc.access.Lock()\n\tvar downloading []*common.PieceRequest\n\tfor _, r := range c.downloading {\n\t\tif r.Equals(req) {\n\t\t\tc.t.pt.canceledRequest(r)\n\t\t} else {\n\t\t\tdownloading = append(downloading, r)\n\t\t}\n\t}\n\tc.downloading = downloading\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) numDownloading() int {\n\tc.access.Lock()\n\ti := len(c.downloading)\n\tc.access.Unlock()\n\treturn i\n}\n\nfunc (c *PeerConn) queueDownload(req *common.PieceRequest) {\n\tif c.closing {\n\t\tc.clearDownloading()\n\t\treturn\n\t}\n\tc.access.Lock()\n\tc.downloading = append(c.downloading, req)\n\tlog.Debugf(\"ask %s for %d %d %d\", c.id.String(), req.Index, req.Begin, req.Length)\n\tc.Send(req.ToWireMessage())\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) clearDownloading() {\n\tc.access.Lock()\n\tfor _, r := range c.downloading {\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tc.downloading = []*common.PieceRequest{}\n\tc.access.Unlock()\n}\n\nfunc (c *PeerConn) HasPiece(piece uint32) bool {\n\tif c.bf == nil {\n\t\t\/\/ no bitfield\n\t\treturn false\n\t}\n\treturn c.bf.Has(piece)\n}\n\n\/\/ return true if this peer is choking us otherwise return false\nfunc (c *PeerConn) RemoteChoking() bool {\n\treturn c.peerChoke\n}\n\n\/\/ return true if we are choking the remote peer otherwise return false\nfunc (c *PeerConn) Chocking() bool {\n\treturn c.usChoke\n}\n\nfunc (c *PeerConn) remoteUnchoke() {\n\tif !c.peerChoke {\n\t\tlog.Warnf(\"remote peer %s sent multiple unchokes\", c.id.String())\n\t}\n\tc.peerChoke = false\n\tlog.Debugf(\"%s unchoked us\", c.id.String())\n}\n\nfunc (c *PeerConn) remoteChoke() {\n\tif c.peerChoke {\n\t\tlog.Warnf(\"remote peer %s sent multiple chokes\", c.id.String())\n\t}\n\tc.peerChoke = true\n\tlog.Debugf(\"%s choked us\", c.id.String())\n}\n\nfunc (c *PeerConn) markInterested() {\n\tc.peerInterested = true\n\tlog.Debugf(\"%s is interested\", c.id.String())\n}\n\nfunc (c *PeerConn) markNotInterested() {\n\tc.peerInterested = false\n\tlog.Debugf(\"%s is not interested\", c.id.String())\n}\n\nfunc (c *PeerConn) Close() {\n\tif c.closing {\n\t\treturn\n\t}\n\tc.closing = true\n\tfor _, r := range c.downloading {\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tc.downloading = nil\n\tlog.Debugf(\"%s closing connection\", c.id.String())\n\tc.c.Close()\n\tif c.inbound {\n\t\tc.t.removeIBConn(c)\n\t} else {\n\t\tc.t.removeOBConn(c)\n\t}\n}\n\n\/\/ run read loop\nfunc (c *PeerConn) runReader() {\n\terr := common.ReadWireMessages(c.c, c.recv)\n\tif err != nil {\n\t\tlog.Debugf(\"PeerConn() reader failed: %s\", err.Error())\n\t}\n\tc.Close()\n}\n\nfunc (c *PeerConn) inboundMessage(msg *common.WireMessage) (err error) {\n\n\tif msg.KeepAlive() {\n\t\tlog.Debugf(\"keepalive from %s\", c.id)\n\t\treturn\n\t}\n\tmsgid := msg.MessageID()\n\tlog.Debugf(\"%s from %s\", msgid.String(), c.id.String())\n\tif msgid == common.BitField {\n\t\tisnew := false\n\t\tif c.bf == nil {\n\t\t\tisnew = true\n\t\t}\n\t\tc.bf = bittorrent.NewBitfield(c.t.MetaInfo().Info.NumPieces(), msg.Payload())\n\t\tlog.Debugf(\"got bitfield from %s\", c.id.String())\n\t\t\/\/ TODO: determine if we are really interested\n\t\tm := common.NewInterested()\n\t\tc.Send(m)\n\t\tif isnew {\n\t\t\tc.usInterested = true\n\t\t\tc.Unchoke()\n\t\t\tif c.ourOpts != nil {\n\t\t\t\tc.Send(c.ourOpts.ToWireMessage())\n\t\t\t}\n\t\t\tgo c.runDownload()\n\t\t}\n\t\treturn\n\t}\n\tif msgid == common.Choke {\n\t\tc.remoteChoke()\n\t}\n\tif msgid == common.UnChoke {\n\t\tc.remoteUnchoke()\n\t}\n\tif msgid == common.Interested {\n\t\tc.markInterested()\n\t}\n\tif msgid == common.NotInterested {\n\t\tc.markNotInterested()\n\t}\n\tif msgid == common.Request {\n\t\tev := msg.GetPieceRequest()\n\t\tc.t.handlePieceRequest(c, ev)\n\t}\n\tif msgid == common.Piece {\n\t\td := msg.GetPieceData()\n\t\tif d == nil {\n\t\t\tlog.Warnf(\"invalid piece data message from %s\", c.id.String())\n\t\t\tc.Close()\n\t\t} else {\n\t\t\tc.gotDownload(d)\n\t\t}\n\t}\n\n\tif msgid == common.Have && c.bf != nil {\n\t\t\/\/ update bitfield\n\t\tidx := msg.GetHave()\n\t\tc.bf.Set(idx)\n\t}\n\tif msgid == common.Cancel {\n\t\t\/\/ TODO: check validity\n\t\tr := msg.GetPieceRequest()\n\t\tc.t.pt.canceledRequest(r)\n\t}\n\tif msgid == common.Extended {\n\t\t\/\/ handle extended options\n\t\topts := extensions.FromWireMessage(msg)\n\t\tif opts == nil {\n\t\t\tlog.Warnf(\"failed to parse extended options for %s\", c.id.String())\n\t\t} else {\n\t\t\tc.handleExtendedOpts(opts)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ handles an inbound pex message\nfunc (c *PeerConn) handlePEX(m interface{}) {\n\n\tpex, ok := m.(map[string]interface{})\n\tif ok {\n\t\tvar added interface{}\n\t\tadded, ok = pex[\"added\"]\n\t\tif ok {\n\t\t\tc.handlePEXAdded(added)\n\t\t}\n\t\tadded, ok = pex[\"added.f\"]\n\t\tif ok {\n\t\t\tc.handlePEXAddedf(added)\n\t\t}\n\t} else {\n\t\tlog.Errorf(\"invalid pex message: %q\", m)\n\t}\n}\n\n\/\/ handle inbound PEX message payload\nfunc (c *PeerConn) handlePEXAdded(m interface{}) {\n\tvar peers []common.Peer\n\tmsg := m.(string)\n\tl := len(msg) \/ 32\n\tfor l > 0 {\n\t\tvar p common.Peer\n\t\t\/\/ TODO: bounds check\n\t\tcopy(p.Compact[:], msg[(l-1)*32:l*32])\n\t\tl--\n\t\tpeers = append(peers, p)\n\t}\n\tc.t.addPeers(peers)\n}\n\nfunc (c *PeerConn) handlePEXAddedf(m interface{}) {\n\t\/\/ TODO: implement this\n}\n\nfunc (c *PeerConn) SupportsPEX() bool {\n\tif c.theirOpts == nil {\n\t\treturn false\n\t}\n\treturn c.theirOpts.PEX()\n}\n\nfunc (c *PeerConn) sendPEX(connected, disconnected []byte) {\n\tid := c.theirOpts.Extensions[extensions.PeerExchange.String()]\n\tmsg := extensions.NewPEX(id, connected, disconnected)\n\tc.Send(msg.ToWireMessage())\n}\n\nfunc (c *PeerConn) handleExtendedOpts(opts *extensions.Message) {\n\tlog.Debugf(\"got extended opts from %s: %s\", c.id.String(), opts)\n\tif opts.ID == 0 {\n\t\t\/\/ handshake\n\t\tif c.theirOpts == nil {\n\t\t\tc.theirOpts = opts.Copy()\n\t\t} else {\n\t\t\tlog.Warnf(\"got multiple extended option handshakes from %s\", c.id.String())\n\t\t}\n\t} else {\n\t\t\/\/ extended data\n\t\tif c.theirOpts == nil {\n\t\t\tlog.Warnf(\"%s gave unexpected extended message %d\", c.id.String(), opts.ID)\n\t\t} else {\n\t\t\t\/\/ lookup the extension number\n\t\t\text, ok := c.theirOpts.Lookup(opts.ID)\n\t\t\tif ok {\n\t\t\t\tif ext == extensions.PeerExchange.String() {\n\t\t\t\t\t\/\/ this is PEX message\n\t\t\t\t\tc.handlePEX(opts.Payload)\n\t\t\t\t} else if ext == extensions.XDHT.String() {\n\t\t\t\t\t\/\/ xdht message\n\t\t\t\t\terr := c.t.xdht.HandleMessage(opts, c.id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Warnf(\"error handling xdht message from %s: %s\", c.id.String(), err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Warnf(\"peer %s gave us extension for message we do not have id=%d\", c.id.String(), opts.ID)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *PeerConn) sendKeepAlive() {\n\ttm := time.Now().Add(0 - (time.Minute * 2))\n\tif c.lastSend.Before(tm) {\n\t\tlog.Debugf(\"send keepalive to %s\", c.id.String())\n\t\tc.doSend(common.KeepAlive())\n\t}\n}\n\n\/\/ run download loop\nfunc (c *PeerConn) runDownload() {\n\tfor !c.t.Done() && !c.closing {\n\t\tif c.RemoteChoking() {\n\t\t\tlog.Debugf(\"will not download this tick, %s is choking\", c.id.String())\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ pending request\n\t\tp := c.numDownloading()\n\t\tif p >= c.MaxParalellRequests {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tr := c.t.pt.nextRequestForDownload(c.bf)\n\t\tif r == nil {\n\t\t\tlog.Debugf(\"no next piece to download for %s\", c.id.String())\n\t\t\ttime.Sleep(time.Second)\n\t\t} else {\n\t\t\tc.queueDownload(r)\n\t\t}\n\t}\n\tif c.closing {\n\t\tc.Close()\n\t} else {\n\t\tlog.Debugf(\"peer %s is 'done'\", c.id.String())\n\t}\n\n\t\/\/ done downloading\n\tif c.Done != nil {\n\t\tc.Done()\n\t}\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestParsingOfEnvironmentVariables(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\tos.Args = []string{os.Args[0]}\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: some environment variables\n\tos.Setenv(\"GUBLE_HTTP_LISTEN\", \"http_listen\")\n\tdefer os.Unsetenv(\"GOBBLER_HTTP_LISTEN\")\n\n\tos.Setenv(\"GUBLE_LOG\", \"debug\")\n\tdefer os.Unsetenv(\"GUBLE_LOG\")\n\n\tos.Setenv(\"GUBLE_ENV\", \"dev\")\n\tdefer os.Unsetenv(\"GOBBLER_ENV\")\n\n\tos.Setenv(\"GUBLE_PROFILE\", \"mem\")\n\tdefer os.Unsetenv(\"GUBLE_PROFILE\")\n\n\tos.Setenv(\"GUBLE_KVS\", \"kvs-backend\")\n\tdefer os.Unsetenv(\"GUBLE_KVS\")\n\n\tos.Setenv(\"GUBLE_STORAGE_PATH\", os.TempDir())\n\tdefer os.Unsetenv(\"GUBLE_STORAGE_PATH\")\n\n\tos.Setenv(\"GUBLE_HEALTH_ENDPOINT\", \"health_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_HEALTH_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_METRICS_ENDPOINT\", \"metrics_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_METRICS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_PROMETHEUS_ENDPOINT\", \"prometheus_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_PROMETHEUS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_TOGGLES_ENDPOINT\", \"toggles_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_TOGGLES_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_MS\", \"ms-backend\")\n\tdefer os.Unsetenv(\"GUBLE_MS\")\n\n\tos.Setenv(\"GUBLE_WS\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_WS\")\n\n\tos.Setenv(\"GUBLE_WS_PREFIX\", \"\/wstream\/\")\n\tdefer os.Unsetenv(\"GUBLE_WS_PREFIX\")\n\n\tos.Setenv(\"GUBLE_FCM\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_FCM\")\n\n\tos.Setenv(\"GUBLE_FCM_API_KEY\", \"fcm-api-key\")\n\tdefer os.Unsetenv(\"GUBLE_FCM_API_KEY\")\n\n\tos.Setenv(\"GUBLE_FCM_WORKERS\", \"3\")\n\tdefer os.Unsetenv(\"GUBLE_FCM_WORKERS\")\n\n\tos.Setenv(\"GUBLE_APNS\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_APNS\")\n\n\tos.Setenv(\"GUBLE_APNS_PRODUCTION\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_PRODUCTION\")\n\n\tos.Setenv(\"GUBLE_APNS_CERT_BYTES\", \"00ff\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_CERT_BYTES\")\n\n\tos.Setenv(\"GUBLE_APNS_CERT_PASSWORD\", \"rotten\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_CERT_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_APNS_APP_TOPIC\", \"com.myapp\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_APP_TOPIC\")\n\n\tos.Setenv(\"GUBLE_NODE_ID\", \"1\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_ID\")\n\n\tos.Setenv(\"GUBLE_NODE_PORT\", \"10000\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_HOST\", \"pg-host\")\n\tdefer os.Unsetenv(\"GUBLE_PG_HOST\")\n\n\tos.Setenv(\"GUBLE_PG_PORT\", \"5432\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_USER\", \"pg-user\")\n\tdefer os.Unsetenv(\"GUBLE_PG_USER\")\n\n\tos.Setenv(\"GUBLE_PG_PASSWORD\", \"pg-password\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_PG_DBNAME\", \"pg-dbname\")\n\tdefer os.Unsetenv(\"GUBLE_PG_DBNAME\")\n\n\tos.Setenv(\"GUBLE_NODE_REMOTES\", \"127.0.0.1:8080 127.0.0.1:20002\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_REMOTES\")\n\n\tos.Setenv(\"GUBLE_KAFKA_BROKERS\", \"127.0.0.1:9092 127.0.0.1:9091\")\n\tdefer os.Unsetenv(\"GUBLE_KAFKA_BROKERS\")\n\n\tos.Setenv(\"GUBLE_SMS_KAFKA_TOPIC\", \"sms_reporting_topic\")\n\tdefer os.Unsetenv(\"GUBLE_SMS_KAFKA_TOPIC\")\n\n\tos.Setenv(\"GUBLE_SMS_TOGGLEABLE\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_SMS_TOGGLEABLE\")\n\n\t\/\/ when we parse the arguments from environment variables\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc TestParsingArgs(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: a command line\n\tos.Args = []string{os.Args[0],\n\t\t\"--http\", \"http_listen\",\n\t\t\"--env\", \"dev\",\n\t\t\"--log\", \"debug\",\n\t\t\"--profile\", \"mem\",\n\t\t\"--storage-path\", os.TempDir(),\n\t\t\"--kvs\", \"kvs-backend\",\n\t\t\"--ms\", \"ms-backend\",\n\t\t\"--health-endpoint\", \"health_endpoint\",\n\t\t\"--metrics-endpoint\", \"metrics_endpoint\",\n\t\t\"--prometheus-endpoint\", \"prometheus_endpoint\",\n\t\t\"--toggles-endpoint\", \"toggles_endpoint\",\n\t\t\"--ws\",\n\t\t\"--ws-prefix\", \"\/wstream\/\",\n\t\t\"--fcm\",\n\t\t\"--fcm-api-key\", \"fcm-api-key\",\n\t\t\"--fcm-workers\", \"3\",\n\t\t\"--apns\",\n\t\t\"--apns-production\",\n\t\t\"--apns-cert-bytes\", \"00ff\",\n\t\t\"--apns-cert-password\", \"rotten\",\n\t\t\"--apns-app-topic\", \"com.myapp\",\n\t\t\"--node-id\", \"1\",\n\t\t\"--node-port\", \"10000\",\n\t\t\"--pg-host\", \"pg-host\",\n\t\t\"--pg-port\", \"5432\",\n\t\t\"--pg-user\", \"pg-user\",\n\t\t\"--pg-password\", \"pg-password\",\n\t\t\"--pg-dbname\", \"pg-dbname\",\n\t\t\"--remotes\", \"127.0.0.1:8080 127.0.0.1:20002\",\n\t\t\"--kafka-brokers\", \"127.0.0.1:9092 127.0.0.1:9091\",\n\t\t\"--sms-kafka-topic\", \"sms_reporting_topic\",\n\t\t\"--sms-toggleable\",\n\t}\n\n\t\/\/ when we parse the arguments from command-line flags\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc assertArguments(a *assert.Assertions) {\n\ta.Equal(\"http_listen\", *Config.HttpListen)\n\ta.Equal(\"kvs-backend\", *Config.KVS)\n\ta.Equal(os.TempDir(), *Config.StoragePath)\n\ta.Equal(\"ms-backend\", *Config.MS)\n\ta.Equal(\"health_endpoint\", *Config.HealthEndpoint)\n\n\ta.Equal(\"metrics_endpoint\", *Config.MetricsEndpoint)\n\ta.Equal(\"prometheus_endpoint\", *Config.PrometheusEndpoint)\n\ta.Equal(\"toggles_endpoint\", *Config.TogglesEndpoint)\n\n\ta.Equal(true, *Config.WS.Enabled)\n\ta.Equal(\"\/wstream\/\", *Config.WS.Prefix)\n\n\ta.Equal(true, *Config.FCM.Enabled)\n\ta.Equal(\"fcm-api-key\", *Config.FCM.APIKey)\n\ta.Equal(3, *Config.FCM.Workers)\n\n\ta.Equal(true, *Config.APNS.Enabled)\n\ta.Equal(true, *Config.APNS.Production)\n\ta.Equal([]byte{0, 255}, *Config.APNS.CertificateBytes)\n\ta.Equal(\"rotten\", *Config.APNS.CertificatePassword)\n\ta.Equal(\"com.myapp\", *Config.APNS.AppTopic)\n\n\ta.Equal(uint8(1), *Config.Cluster.NodeID)\n\ta.Equal(10000, *Config.Cluster.NodePort)\n\n\ta.Equal(\"pg-host\", *Config.Postgres.Host)\n\ta.Equal(5432, *Config.Postgres.Port)\n\ta.Equal(\"pg-user\", *Config.Postgres.User)\n\ta.Equal(\"pg-password\", *Config.Postgres.Password)\n\ta.Equal(\"pg-dbname\", *Config.Postgres.DbName)\n\n\ta.Equal(\"debug\", *Config.Log)\n\ta.Equal(\"dev\", *Config.EnvName)\n\ta.Equal(\"mem\", *Config.Profile)\n\n\ta.Equal(\"[127.0.0.1:9092 127.0.0.1:9091]\", (*Config.KafkaProducer.Brokers).String())\n\ta.Equal(\"sms_reporting_topic\", *Config.SMS.KafkaReportingTopic)\n\n\ta.Equal(true, *Config.SMS.Toggleable)\n\n\tassertClusterRemotes(a)\n}\n\nfunc assertClusterRemotes(a *assert.Assertions) {\n\tip1, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:8080\")\n\tip2, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:20002\")\n\tipList := make(tcpAddrList, 0)\n\tipList = append(ipList, ip1)\n\tipList = append(ipList, ip2)\n\ta.Equal(ipList, *Config.Cluster.Remotes)\n}\n\nfunc TestPrefixEnvar(t *testing.T) {\n\tassert.Equal(t, \"GUBLE_SOMEVAR\", g(\"SOMEVAR\"))\n}fix testpackage server\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestParsingOfEnvironmentVariables(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\tos.Args = []string{os.Args[0]}\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: some environment variables\n\tos.Setenv(\"GUBLE_HTTP_LISTEN\", \"http_listen\")\n\tdefer os.Unsetenv(\"GUBLE_HTTP_LISTEN\")\n\n\tos.Setenv(\"GUBLE_LOG\", \"debug\")\n\tdefer os.Unsetenv(\"GUBLE_LOG\")\n\n\tos.Setenv(\"GUBLE_ENV\", \"dev\")\n\tdefer os.Unsetenv(\"GUBLE_ENV\")\n\n\tos.Setenv(\"GUBLE_PROFILE\", \"mem\")\n\tdefer os.Unsetenv(\"GUBLE_PROFILE\")\n\n\tos.Setenv(\"GUBLE_KVS\", \"kvs-backend\")\n\tdefer os.Unsetenv(\"GUBLE_KVS\")\n\n\tos.Setenv(\"GUBLE_STORAGE_PATH\", os.TempDir())\n\tdefer os.Unsetenv(\"GUBLE_STORAGE_PATH\")\n\n\tos.Setenv(\"GUBLE_HEALTH_ENDPOINT\", \"health_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_HEALTH_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_METRICS_ENDPOINT\", \"metrics_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_METRICS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_PROMETHEUS_ENDPOINT\", \"prometheus_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_PROMETHEUS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_TOGGLES_ENDPOINT\", \"toggles_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_TOGGLES_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_MS\", \"ms-backend\")\n\tdefer os.Unsetenv(\"GUBLE_MS\")\n\n\tos.Setenv(\"GUBLE_WS\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_WS\")\n\n\tos.Setenv(\"GUBLE_WS_PREFIX\", \"\/wstream\/\")\n\tdefer os.Unsetenv(\"GUBLE_WS_PREFIX\")\n\n\tos.Setenv(\"GUBLE_FCM\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_FCM\")\n\n\tos.Setenv(\"GUBLE_FCM_API_KEY\", \"fcm-api-key\")\n\tdefer os.Unsetenv(\"GUBLE_FCM_API_KEY\")\n\n\tos.Setenv(\"GUBLE_FCM_WORKERS\", \"3\")\n\tdefer os.Unsetenv(\"GUBLE_FCM_WORKERS\")\n\n\tos.Setenv(\"GUBLE_APNS\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_APNS\")\n\n\tos.Setenv(\"GUBLE_APNS_PRODUCTION\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_PRODUCTION\")\n\n\tos.Setenv(\"GUBLE_APNS_CERT_BYTES\", \"00ff\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_CERT_BYTES\")\n\n\tos.Setenv(\"GUBLE_APNS_CERT_PASSWORD\", \"rotten\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_CERT_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_APNS_APP_TOPIC\", \"com.myapp\")\n\tdefer os.Unsetenv(\"GUBLE_APNS_APP_TOPIC\")\n\n\tos.Setenv(\"GUBLE_NODE_ID\", \"1\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_ID\")\n\n\tos.Setenv(\"GUBLE_NODE_PORT\", \"10000\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_HOST\", \"pg-host\")\n\tdefer os.Unsetenv(\"GUBLE_PG_HOST\")\n\n\tos.Setenv(\"GUBLE_PG_PORT\", \"5432\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_USER\", \"pg-user\")\n\tdefer os.Unsetenv(\"GUBLE_PG_USER\")\n\n\tos.Setenv(\"GUBLE_PG_PASSWORD\", \"pg-password\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_PG_DBNAME\", \"pg-dbname\")\n\tdefer os.Unsetenv(\"GUBLE_PG_DBNAME\")\n\n\tos.Setenv(\"GUBLE_NODE_REMOTES\", \"127.0.0.1:8080 127.0.0.1:20002\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_REMOTES\")\n\n\tos.Setenv(\"GUBLE_KAFKA_BROKERS\", \"127.0.0.1:9092 127.0.0.1:9091\")\n\tdefer os.Unsetenv(\"GUBLE_KAFKA_BROKERS\")\n\n\tos.Setenv(\"GUBLE_SMS_KAFKA_TOPIC\", \"sms_reporting_topic\")\n\tdefer os.Unsetenv(\"GUBLE_SMS_KAFKA_TOPIC\")\n\n\tos.Setenv(\"GUBLE_SMS_TOGGLEABLE\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_SMS_TOGGLEABLE\")\n\n\t\/\/ when we parse the arguments from environment variables\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc TestParsingArgs(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: a command line\n\tos.Args = []string{os.Args[0],\n\t\t\"--http\", \"http_listen\",\n\t\t\"--env\", \"dev\",\n\t\t\"--log\", \"debug\",\n\t\t\"--profile\", \"mem\",\n\t\t\"--storage-path\", os.TempDir(),\n\t\t\"--kvs\", \"kvs-backend\",\n\t\t\"--ms\", \"ms-backend\",\n\t\t\"--health-endpoint\", \"health_endpoint\",\n\t\t\"--metrics-endpoint\", \"metrics_endpoint\",\n\t\t\"--prometheus-endpoint\", \"prometheus_endpoint\",\n\t\t\"--toggles-endpoint\", \"toggles_endpoint\",\n\t\t\"--ws\",\n\t\t\"--ws-prefix\", \"\/wstream\/\",\n\t\t\"--fcm\",\n\t\t\"--fcm-api-key\", \"fcm-api-key\",\n\t\t\"--fcm-workers\", \"3\",\n\t\t\"--apns\",\n\t\t\"--apns-production\",\n\t\t\"--apns-cert-bytes\", \"00ff\",\n\t\t\"--apns-cert-password\", \"rotten\",\n\t\t\"--apns-app-topic\", \"com.myapp\",\n\t\t\"--node-id\", \"1\",\n\t\t\"--node-port\", \"10000\",\n\t\t\"--pg-host\", \"pg-host\",\n\t\t\"--pg-port\", \"5432\",\n\t\t\"--pg-user\", \"pg-user\",\n\t\t\"--pg-password\", \"pg-password\",\n\t\t\"--pg-dbname\", \"pg-dbname\",\n\t\t\"--remotes\", \"127.0.0.1:8080 127.0.0.1:20002\",\n\t\t\"--kafka-brokers\", \"127.0.0.1:9092 127.0.0.1:9091\",\n\t\t\"--sms-kafka-topic\", \"sms_reporting_topic\",\n\t\t\"--sms-toggleable\",\n\t}\n\n\t\/\/ when we parse the arguments from command-line flags\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc assertArguments(a *assert.Assertions) {\n\ta.Equal(\"http_listen\", *Config.HttpListen)\n\ta.Equal(\"kvs-backend\", *Config.KVS)\n\ta.Equal(os.TempDir(), *Config.StoragePath)\n\ta.Equal(\"ms-backend\", *Config.MS)\n\ta.Equal(\"health_endpoint\", *Config.HealthEndpoint)\n\n\ta.Equal(\"metrics_endpoint\", *Config.MetricsEndpoint)\n\ta.Equal(\"prometheus_endpoint\", *Config.PrometheusEndpoint)\n\ta.Equal(\"toggles_endpoint\", *Config.TogglesEndpoint)\n\n\ta.Equal(true, *Config.WS.Enabled)\n\ta.Equal(\"\/wstream\/\", *Config.WS.Prefix)\n\n\ta.Equal(true, *Config.FCM.Enabled)\n\ta.Equal(\"fcm-api-key\", *Config.FCM.APIKey)\n\ta.Equal(3, *Config.FCM.Workers)\n\n\ta.Equal(true, *Config.APNS.Enabled)\n\ta.Equal(true, *Config.APNS.Production)\n\ta.Equal([]byte{0, 255}, *Config.APNS.CertificateBytes)\n\ta.Equal(\"rotten\", *Config.APNS.CertificatePassword)\n\ta.Equal(\"com.myapp\", *Config.APNS.AppTopic)\n\n\ta.Equal(uint8(1), *Config.Cluster.NodeID)\n\ta.Equal(10000, *Config.Cluster.NodePort)\n\n\ta.Equal(\"pg-host\", *Config.Postgres.Host)\n\ta.Equal(5432, *Config.Postgres.Port)\n\ta.Equal(\"pg-user\", *Config.Postgres.User)\n\ta.Equal(\"pg-password\", *Config.Postgres.Password)\n\ta.Equal(\"pg-dbname\", *Config.Postgres.DbName)\n\n\ta.Equal(\"debug\", *Config.Log)\n\ta.Equal(\"dev\", *Config.EnvName)\n\ta.Equal(\"mem\", *Config.Profile)\n\n\ta.Equal(\"[127.0.0.1:9092 127.0.0.1:9091]\", (*Config.KafkaProducer.Brokers).String())\n\ta.Equal(\"sms_reporting_topic\", *Config.SMS.KafkaReportingTopic)\n\n\ta.Equal(true, *Config.SMS.Toggleable)\n\n\tassertClusterRemotes(a)\n}\n\nfunc assertClusterRemotes(a *assert.Assertions) {\n\tip1, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:8080\")\n\tip2, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:20002\")\n\tipList := make(tcpAddrList, 0)\n\tipList = append(ipList, ip1)\n\tipList = append(ipList, ip2)\n\ta.Equal(ipList, *Config.Cluster.Remotes)\n}\n\nfunc TestPrefixEnvar(t *testing.T) {\n\tassert.Equal(t, \"GUBLE_SOMEVAR\", g(\"SOMEVAR\"))\n}\n<|endoftext|>"} {"text":"package utils\n\nimport \"testing\"\nimport \"github.com\/stretchr\/testify\/assert\"\n\nfunc TestHashingPlaintext(t *testing.T) {\n\ts, err := NewScrypt()\n\tassert.NotNil(t, s)\n\tassert.Nil(t, err)\n\n\thash, err := s.HashPlaintext(\"my lil plaintext\")\n\tassert.NotEmpty(t, hash)\n\tassert.Contains(t, hash, \"32768@8@1\")\n\tassert.Nil(t, err)\n}\n\nfunc TestMatchingPlaintext(t *testing.T) {\n\ts, err := NewScrypt()\n\tassert.NotNil(t, s)\n\tassert.Nil(t, err)\n\n\thash, err := s.HashPlaintext(\"my lil plaintext\")\n\tassert.NotEmpty(t, hash)\n\tassert.Contains(t, hash, \"32768@8@1\")\n\tassert.Nil(t, err)\n\n\ts2, err := LoadScryptFromHash(hash)\n\tassert.NotNil(t, s2)\n\tassert.Nil(t, err)\n\n\tmatch, err := s2.MatchesPlaintext(\"my lil plaintext\")\n\tassert.True(t, match)\n\tassert.Nil(t, err)\n}\n\nfunc TestBarfOnLoadingGarbage(t *testing.T) {\n s, err := LoadScryptFromHash(\"123\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"asd\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n\ts, err = LoadScryptFromHash(\"123@456\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"asd@lol\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@789\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"asd@lol@wtf\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@789@foo@bar\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"asd@lol@wtf@bbq@kfc\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n}\n\nfunc BenchmarkPlaintextEncryption(b *testing.B) {\n\ts, _ := NewScrypt()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\ts.HashPlaintext(\"my lil plaintext\")\n\t}\n}\nTweaked test to hopefully cover more.package utils\n\nimport \"testing\"\nimport \"github.com\/stretchr\/testify\/assert\"\n\nfunc TestHashingPlaintext(t *testing.T) {\n\ts, err := NewScrypt()\n\tassert.NotNil(t, s)\n\tassert.Nil(t, err)\n\n\thash, err := s.HashPlaintext(\"my lil plaintext\")\n\tassert.NotEmpty(t, hash)\n\tassert.Contains(t, hash, \"32768@8@1\")\n\tassert.Nil(t, err)\n}\n\nfunc TestMatchingPlaintext(t *testing.T) {\n\ts, err := NewScrypt()\n\tassert.NotNil(t, s)\n\tassert.Nil(t, err)\n\n\thash, err := s.HashPlaintext(\"my lil plaintext\")\n\tassert.NotEmpty(t, hash)\n\tassert.Contains(t, hash, \"32768@8@1\")\n\tassert.Nil(t, err)\n\n\ts2, err := LoadScryptFromHash(hash)\n\tassert.NotNil(t, s2)\n\tassert.Nil(t, err)\n\n\tmatch, err := s2.MatchesPlaintext(\"my lil plaintext\")\n\tassert.True(t, match)\n\tassert.Nil(t, err)\n}\n\nfunc TestBarfOnLoadingGarbage(t *testing.T) {\n s, err := LoadScryptFromHash(\"123\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n\ts, err = LoadScryptFromHash(\"123@456\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@789\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@789@012\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"asd@lol@wtf@bbq@kfc\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@asd@lol@bbq@kfc\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@wtf@bbq@kfc\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n\n s, err = LoadScryptFromHash(\"123@456@789@bbq@kfc\")\n\tassert.Nil(t, s)\n\tassert.NotNil(t, err)\n}\n\nfunc BenchmarkPlaintextEncryption(b *testing.B) {\n\ts, _ := NewScrypt()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\ts.HashPlaintext(\"my lil plaintext\")\n\t}\n}\n<|endoftext|>"} {"text":"package service\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ninjasphere\/app-presets\/model\"\n\t\"github.com\/ninjasphere\/go-ninja\/api\"\n\t\"github.com\/ninjasphere\/go-ninja\/logger\"\n)\n\ntype PresetsService struct {\n\tModel *model.Presets\n\tSave func(*model.Presets)\n\tConn *ninja.Connection\n\tLog *logger.Logger\n\tinitialized bool\n}\n\nfunc (ps *PresetsService) Init() error {\n\tif ps.Log == nil {\n\t\treturn fmt.Errorf(\"illegal state: no logger\")\n\t}\n\tif ps.Model == nil {\n\t\treturn fmt.Errorf(\"illegal state: Model is nil\")\n\t}\n\tif ps.Save == nil {\n\t\treturn fmt.Errorf(\"illegal state: Save is nil\")\n\t}\n\tif ps.Conn == nil {\n\t\treturn fmt.Errorf(\"illegal state: Conn is nil\")\n\t}\n\tps.initialized = true\n\treturn nil\n}\n\nfunc (ps *PresetsService) Destroy() error {\n\tps.initialized = false\n\treturn nil\n}\n\nfunc (ps *PresetsService) checkInit() {\n\tif ps.Log == nil {\n\t\tps.Log = logger.GetLogger(\"com.ninja.app-presets\")\n\t}\n\tif !ps.initialized {\n\t\tps.Log.Fatalf(\"illegal state: the service is not initialized\")\n\t}\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#listPresetable\nfunc (ps *PresetsService) ListPresetable(scope string) ([]*model.ThingState, error) {\n\tps.checkInit()\n\treturn make([]*model.ThingState, 0, 0), fmt.Errorf(\"unimplemented function: ListPresetable\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#fetchScenes\nfunc (ps *PresetsService) FetchScenes(scope string) ([]model.Scene, error) {\n\treturn make([]model.Scene, 0, 0), fmt.Errorf(\"unimplemented function: FetchScenes\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#fetchScene\nfunc (ps *PresetsService) FetchScene(id string) (*model.Scene, error) {\n\treturn nil, fmt.Errorf(\"unimplemented function: FetchScene\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#storeScene\nfunc (ps *PresetsService) StoreScene(model *model.Scene) error {\n\treturn fmt.Errorf(\"unimplemented function: StoreScene\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#applyScene\nfunc (ps *PresetsService) ApplyScene(id string) error {\n\treturn fmt.Errorf(\"unimplemented function: ApplyScene\")\n}\nImplement PresetService FetchScenes.package service\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ninjasphere\/app-presets\/model\"\n\t\"github.com\/ninjasphere\/go-ninja\/api\"\n\t\"github.com\/ninjasphere\/go-ninja\/logger\"\n)\n\ntype PresetsService struct {\n\tModel *model.Presets\n\tSave func(*model.Presets)\n\tConn *ninja.Connection\n\tLog *logger.Logger\n\tinitialized bool\n}\n\nfunc (ps *PresetsService) Init() error {\n\tif ps.Log == nil {\n\t\treturn fmt.Errorf(\"illegal state: no logger\")\n\t}\n\tif ps.Model == nil {\n\t\treturn fmt.Errorf(\"illegal state: Model is nil\")\n\t}\n\tif ps.Save == nil {\n\t\treturn fmt.Errorf(\"illegal state: Save is nil\")\n\t}\n\tif ps.Conn == nil {\n\t\treturn fmt.Errorf(\"illegal state: Conn is nil\")\n\t}\n\tps.initialized = true\n\treturn nil\n}\n\nfunc (ps *PresetsService) Destroy() error {\n\tps.initialized = false\n\treturn nil\n}\n\nfunc (ps *PresetsService) checkInit() {\n\tif ps.Log == nil {\n\t\tps.Log = logger.GetLogger(\"com.ninja.app-presets\")\n\t}\n\tif !ps.initialized {\n\t\tps.Log.Fatalf(\"illegal state: the service is not initialized\")\n\t}\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#listPresetable\nfunc (ps *PresetsService) ListPresetable(scope string) ([]*model.ThingState, error) {\n\tps.checkInit()\n\treturn make([]*model.ThingState, 0, 0), fmt.Errorf(\"unimplemented function: ListPresetable\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#fetchScenes\nfunc (ps *PresetsService) FetchScenes(scope string) ([]*model.Scene, error) {\n\tps.checkInit()\n\tcollect := make([]*model.Scene, 0, 0)\n\tfor _, m := range ps.Model.Scenes {\n\t\tif m.Scope == scope {\n\t\t\tcollect = append(collect, m)\n\t\t}\n\t}\n\treturn collect, nil\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#fetchScene\nfunc (ps *PresetsService) FetchScene(id string) (*model.Scene, error) {\n\treturn nil, fmt.Errorf(\"unimplemented function: FetchScene\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#storeScene\nfunc (ps *PresetsService) StoreScene(model *model.Scene) error {\n\treturn fmt.Errorf(\"unimplemented function: StoreScene\")\n}\n\n\/\/ see: http:\/\/schema.ninjablocks.com\/service\/presets#applyScene\nfunc (ps *PresetsService) ApplyScene(id string) error {\n\treturn fmt.Errorf(\"unimplemented function: ApplyScene\")\n}\n<|endoftext|>"} {"text":"package httpclient\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)\n\ntype Encoding string\n\nconst (\n\tEncodingJSON = \"JSON\"\n)\n\ntype RequestData struct {\n\tMethod string\n\tPath string\n\tParams url.Values\n\tFullURL string \/\/ optional\n\tHeaders http.Header\n\tReqReader io.Reader\n\tReqEncoding Encoding\n\tReqValue interface{}\n\tExpectedStatus []int\n\tIgnoreRedirects bool\n\tRespEncoding Encoding\n\tRespValue interface{}\n}\n\ntype InvalidStatusError struct {\n\tExpected []int\n\tGot int\n}\n\nfunc (e InvalidStatusError) Error() string {\n\treturn fmt.Sprintf(\"Invalid response status! Got %d, expected %d\", e.Got, e.Expected)\n}\n\ntype HTTPClient struct {\n\tBaseURL *url.URL\n\tHeaders http.Header\n\tClient *http.Client\n\tPostHooks map[int]func(*http.Request, *http.Response) error\n}\n\nfunc New() (httpClient *HTTPClient) {\n\treturn &HTTPClient{\n\t\tClient: HttpClient,\n\t\tHeaders: make(http.Header),\n\t\tPostHooks: make(map[int]func(*http.Request, *http.Response) error),\n\t}\n}\n\nfunc Insecure() (httpClient *HTTPClient) {\n\treturn &HTTPClient{\n\t\tClient: InsecureHttpClient,\n\t\tHeaders: make(http.Header),\n\t\tPostHooks: make(map[int]func(*http.Request, *http.Response) error),\n\t}\n}\n\nfunc (c *HTTPClient) SetPostHook(onStatus int, hook func(*http.Request, *http.Response) error) {\n\tc.PostHooks[onStatus] = hook\n}\n\nfunc (c *HTTPClient) buildURL(req *RequestData) string {\n\tif req.FullURL != \"\" {\n\t\treturn req.FullURL\n\t}\n\n\tbu := c.BaseURL\n\n\tu := url.URL{\n\t\tScheme: bu.Scheme,\n\t\tHost: bu.Host,\n\t\tPath: bu.Path + req.Path,\n\t}\n\n\tif req.Params != nil {\n\t\tu.RawQuery = req.Params.Encode()\n\t}\n\n\treturn u.String()\n}\n\nfunc (c *HTTPClient) setHeaders(req *RequestData, httpReq *http.Request) {\n\n\tswitch req.ReqEncoding {\n\tcase EncodingJSON:\n\t\thttpReq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\tswitch req.RespEncoding {\n\tcase EncodingJSON:\n\t\thttpReq.Header.Set(\"Accept\", \"application\/json\")\n\t}\n\n\tif c.Headers != nil {\n\t\tfor key, values := range c.Headers {\n\t\t\tfor _, value := range values {\n\t\t\t\thttpReq.Header.Set(key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif req.Headers != nil {\n\t\tfor key, values := range req.Headers {\n\t\t\tfor _, value := range values {\n\t\t\t\thttpReq.Header.Set(key, value)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *HTTPClient) checkStatus(req *RequestData, response *http.Response) (err error) {\n\tif req.ExpectedStatus != nil {\n\t\tstatusOk := false\n\n\t\tfor _, status := range req.ExpectedStatus {\n\t\t\tif response.StatusCode == status {\n\t\t\t\tstatusOk = true\n\t\t\t}\n\t\t}\n\n\t\tif !statusOk {\n\t\t\terr = InvalidStatusError{req.ExpectedStatus, response.StatusCode}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) unmarshalResponse(req *RequestData, response *http.Response) (err error) {\n\tvar buf []byte\n\n\tswitch req.RespEncoding {\n\tcase EncodingJSON:\n\t\tdefer response.Body.Close()\n\n\t\tif buf, err = ioutil.ReadAll(response.Body); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = json.Unmarshal(buf, req.RespValue)\n\n\t\treturn\n\t}\n\n\tswitch req.RespValue.(type) {\n\tcase *[]byte:\n\t\tdefer response.Body.Close()\n\n\t\tif buf, err = ioutil.ReadAll(response.Body); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\trespVal := req.RespValue.(*[]byte)\n\t\t*respVal = buf\n\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) marshalRequest(req *RequestData) (err error) {\n\tif req.ReqValue != nil && req.ReqEncoding != \"\" && req.ReqReader == nil {\n\t\tvar buf []byte\n\t\tbuf, err = json.Marshal(req.ReqValue)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treq.ReqReader = bytes.NewReader(buf)\n\t}\n\treturn\n}\n\nfunc (c *HTTPClient) runPostHook(req *http.Request, response *http.Response) (err error) {\n\thook, ok := c.PostHooks[response.StatusCode]\n\n\tif ok {\n\t\terr = hook(req, response)\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) Request(req *RequestData) (response *http.Response, err error) {\n\treqURL := c.buildURL(req)\n\n\terr = c.marshalRequest(req)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tr, err := http.NewRequest(req.Method, reqURL, req.ReqReader)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc.setHeaders(req, r)\n\n\tif req.IgnoreRedirects {\n\t\ttransport := c.Client.Transport\n\n\t\tif transport == nil {\n\t\t\ttransport = http.DefaultTransport\n\t\t}\n\n\t\tresponse, err = transport.RoundTrip(r)\n\t} else {\n\t\tresponse, err = c.Client.Do(r)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = c.runPostHook(r, response); err != nil {\n\t\treturn\n\t}\n\n\tif err = c.checkStatus(req, response); err != nil {\n\t\treturn\n\t}\n\n\tif err = c.unmarshalResponse(req, response); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\nadded RespConsumepackage httpclient\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)\n\ntype Encoding string\n\nconst (\n\tEncodingJSON = \"JSON\"\n)\n\ntype RequestData struct {\n\tMethod string\n\tPath string\n\tParams url.Values\n\tFullURL string \/\/ optional\n\tHeaders http.Header\n\tReqReader io.Reader\n\tReqEncoding Encoding\n\tReqValue interface{}\n\tExpectedStatus []int\n\tIgnoreRedirects bool\n\tRespEncoding Encoding\n\tRespValue interface{}\n\tRespConsume bool\n}\n\ntype InvalidStatusError struct {\n\tExpected []int\n\tGot int\n}\n\nfunc (e InvalidStatusError) Error() string {\n\treturn fmt.Sprintf(\"Invalid response status! Got %d, expected %d\", e.Got, e.Expected)\n}\n\ntype HTTPClient struct {\n\tBaseURL *url.URL\n\tHeaders http.Header\n\tClient *http.Client\n\tPostHooks map[int]func(*http.Request, *http.Response) error\n}\n\nfunc New() (httpClient *HTTPClient) {\n\treturn &HTTPClient{\n\t\tClient: HttpClient,\n\t\tHeaders: make(http.Header),\n\t\tPostHooks: make(map[int]func(*http.Request, *http.Response) error),\n\t}\n}\n\nfunc Insecure() (httpClient *HTTPClient) {\n\treturn &HTTPClient{\n\t\tClient: InsecureHttpClient,\n\t\tHeaders: make(http.Header),\n\t\tPostHooks: make(map[int]func(*http.Request, *http.Response) error),\n\t}\n}\n\nfunc (c *HTTPClient) SetPostHook(onStatus int, hook func(*http.Request, *http.Response) error) {\n\tc.PostHooks[onStatus] = hook\n}\n\nfunc (c *HTTPClient) buildURL(req *RequestData) string {\n\tif req.FullURL != \"\" {\n\t\treturn req.FullURL\n\t}\n\n\tbu := c.BaseURL\n\n\tu := url.URL{\n\t\tScheme: bu.Scheme,\n\t\tHost: bu.Host,\n\t\tPath: bu.Path + req.Path,\n\t}\n\n\tif req.Params != nil {\n\t\tu.RawQuery = req.Params.Encode()\n\t}\n\n\treturn u.String()\n}\n\nfunc (c *HTTPClient) setHeaders(req *RequestData, httpReq *http.Request) {\n\n\tswitch req.ReqEncoding {\n\tcase EncodingJSON:\n\t\thttpReq.Header.Set(\"Content-Type\", \"application\/json\")\n\t}\n\n\tswitch req.RespEncoding {\n\tcase EncodingJSON:\n\t\thttpReq.Header.Set(\"Accept\", \"application\/json\")\n\t}\n\n\tif c.Headers != nil {\n\t\tfor key, values := range c.Headers {\n\t\t\tfor _, value := range values {\n\t\t\t\thttpReq.Header.Set(key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\tif req.Headers != nil {\n\t\tfor key, values := range req.Headers {\n\t\t\tfor _, value := range values {\n\t\t\t\thttpReq.Header.Set(key, value)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *HTTPClient) checkStatus(req *RequestData, response *http.Response) (err error) {\n\tif req.ExpectedStatus != nil {\n\t\tstatusOk := false\n\n\t\tfor _, status := range req.ExpectedStatus {\n\t\t\tif response.StatusCode == status {\n\t\t\t\tstatusOk = true\n\t\t\t}\n\t\t}\n\n\t\tif !statusOk {\n\t\t\terr = InvalidStatusError{req.ExpectedStatus, response.StatusCode}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) unmarshalResponse(req *RequestData, response *http.Response) (err error) {\n\tvar buf []byte\n\n\tswitch req.RespEncoding {\n\tcase EncodingJSON:\n\t\tdefer response.Body.Close()\n\n\t\tif buf, err = ioutil.ReadAll(response.Body); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = json.Unmarshal(buf, req.RespValue)\n\n\t\treturn\n\t}\n\n\tswitch req.RespValue.(type) {\n\tcase *[]byte:\n\t\tdefer response.Body.Close()\n\n\t\tif buf, err = ioutil.ReadAll(response.Body); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\trespVal := req.RespValue.(*[]byte)\n\t\t*respVal = buf\n\n\t\treturn\n\t}\n\n\tif req.RespConsume {\n\t\tdefer response.Body.Close()\n\t\tioutil.ReadAll(response.Body)\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) marshalRequest(req *RequestData) (err error) {\n\tif req.ReqValue != nil && req.ReqEncoding != \"\" && req.ReqReader == nil {\n\t\tvar buf []byte\n\t\tbuf, err = json.Marshal(req.ReqValue)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treq.ReqReader = bytes.NewReader(buf)\n\t}\n\treturn\n}\n\nfunc (c *HTTPClient) runPostHook(req *http.Request, response *http.Response) (err error) {\n\thook, ok := c.PostHooks[response.StatusCode]\n\n\tif ok {\n\t\terr = hook(req, response)\n\t}\n\n\treturn\n}\n\nfunc (c *HTTPClient) Request(req *RequestData) (response *http.Response, err error) {\n\treqURL := c.buildURL(req)\n\n\terr = c.marshalRequest(req)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tr, err := http.NewRequest(req.Method, reqURL, req.ReqReader)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc.setHeaders(req, r)\n\n\tif req.IgnoreRedirects {\n\t\ttransport := c.Client.Transport\n\n\t\tif transport == nil {\n\t\t\ttransport = http.DefaultTransport\n\t\t}\n\n\t\tresponse, err = transport.RoundTrip(r)\n\t} else {\n\t\tresponse, err = c.Client.Do(r)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = c.runPostHook(r, response); err != nil {\n\t\treturn\n\t}\n\n\tif err = c.checkStatus(req, response); err != nil {\n\t\treturn\n\t}\n\n\tif err = c.unmarshalResponse(req, response); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n<|endoftext|>"} {"text":"package check\n\nimport \"fmt\"\n\nvar baseTemplate = `# Save as MyRule.yml on your StylesPath\n# See https:\/\/valelint.github.io\/styles\/#check-types for more info\n%s\n`\nvar existenceTemplate = `extends: existence\n# \"%s\" will be replaced by the active token\nmessage: \"found '%s'!\"\nignorecase: false\n# \"suggestion\", \"warning\" or \"error\"\nlevel: warning\ntokens:\n - XXX\n - FIXME\n - TODO\n - NOTE`\n\nvar substitutionTemplate = `extends: substitution\nmessage: Consider using '%s' instead of '%s'\nignorecase: false\n# \"suggestion\", \"warning\" or \"error\"\nlevel: warning\n# swap maps tokens in form of bad: good\nswap:\n abundance: plenty\n accelerate: speed up`\n\nvar checkToTemplate = map[string]string{\n\t\"existence\": existenceTemplate,\n\t\"substitution\": substitutionTemplate,\n}\n\n\/\/ GetTemplate makes a template for the given extension point.\nfunc GetTemplate(name string) string {\n\tif template, ok := checkToTemplate[name]; ok {\n\t\treturn fmt.Sprintf(baseTemplate, template)\n\t}\n\treturn \"\"\n}\nfeat: finish templatespackage check\n\nimport \"fmt\"\n\nvar baseTemplate = `# Save as MyRule.yml on your StylesPath\n# See https:\/\/valelint.github.io\/styles\/#check-types for more info\n# \"suggestion\", \"warning\" or \"error\"\nlevel: warning\n# Text describing this rule (generally longer than 'message').\ndescription: '...'\n# A link the source or reference.\nlink: '...'\n%s`\n\nvar existenceTemplate = `extends: existence\n# \"%s\" will be replaced by the active token\nmessage: \"found '%s'!\"\nignorecase: false\ntokens:\n - XXX\n - FIXME\n - TODO\n - NOTE`\n\nvar substitutionTemplate = `extends: substitution\nmessage: Consider using '%s' instead of '%s'\nignorecase: false\n# swap maps tokens in form of bad: good\nswap:\n abundance: plenty\n accelerate: speed up`\n\nvar occurrenceTemplate = `extends: occurrence\nmessage: \"More than 3 commas!\"\n# Here, we're counting the number of times a comma appears in a sentence.\n# If it occurs more than 3 times, we'll flag it.\nscope: sentence\nignorecase: false\nmax: 3\ntoken: ','`\n\nvar conditionalTemplate = `extends: conditional\nmessage: \"'%s' has no definition\"\nscope: text\nignorecase: false\n# Ensures that the existence of 'first' implies the existence of 'second'.\nfirst: \\b([A-Z]{3,5})\\b\nsecond: (?:\\b[A-Z][a-z]+ )+\\(([A-Z]{3,5})\\)\n# ... with the exception of these:\nexceptions:\n - ABC\n - ADD`\n\nvar consistencyTemplate = `extends: consistency\nmessage: \"Inconsistent spelling of '%s'\"\nscope: text\nignorecase: true\nnonword: false\n# We only want one of these to appear.\neither:\n advisor: adviser\n centre: center`\n\nvar repetitionTemplate = `extends: repetition\nmessage: \"'%s' is repeated!\"\nscope: paragraph\nignorecase: false\n# Will flag repeated occurances of the same token (e.g., \"this this\").\ntokens:\n - '[^\\s]+'`\n\nvar checkToTemplate = map[string]string{\n\t\"existence\": existenceTemplate,\n\t\"substitution\": substitutionTemplate,\n\t\"occurrence\": occurrenceTemplate,\n\t\"conditional\": conditionalTemplate,\n\t\"consistency\": consistencyTemplate,\n\t\"repetition\": repetitionTemplate,\n}\n\n\/\/ GetTemplate makes a template for the given extension point.\nfunc GetTemplate(name string) string {\n\tif template, ok := checkToTemplate[name]; ok {\n\t\treturn fmt.Sprintf(baseTemplate, template)\n\t}\n\treturn \"\"\n}\n<|endoftext|>"} {"text":"package service\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Service defaults.\n\tDefaultStartTimeout = 1 * time.Second\n\tDefaultStartRetries = 3\n\tDefaultStopSignal = syscall.SIGINT\n\tDefaultStopTimeout = 5 * time.Second\n\tDefaultStopRestart = true\n\n\t\/\/ Service commands.\n\tStart = \"start\"\n\tStop = \"stop\"\n\tRestart = \"restart\"\n\tShutdown = \"shutdown\"\n\n\t\/\/ Service states.\n\tStarting = \"starting\"\n\tRunning = \"running\"\n\tStopping = \"stopping\"\n\tStopped = \"stopped\"\n\tExited = \"exited\"\n\tBackoff = \"backoff\"\n)\n\n\/\/ Command is sent to a Service to initiate a state change.\ntype Command struct {\n\tName string\n\tResponse chan<- Response\n}\n\n\/\/ respond creates and sends a command Response.\nfunc (cmd Command) respond(service *Service, err error) {\n\tif cmd.Response != nil {\n\t\tcmd.Response <- Response{service, cmd.Name, err}\n\t}\n}\n\n\/\/ Response contains the result of a Command.\ntype Response struct {\n\tService *Service\n\tName string\n\tError error\n}\n\n\/\/ Success returns True if the Command was successful.\nfunc (r Response) Success() bool {\n\treturn r.Error == nil\n}\n\n\/\/ Event is sent by a Service on a state change.\ntype Event struct {\n\tService *Service\n\tState string\n}\n\n\/\/ Service represents a controllable process. Exported fields may be set to configure the service.\ntype Service struct {\n\tDirectory string \/\/ The process's working directory. Defaults to the current directory.\n\tEnvironment []string \/\/ The environment of the process. Defaults to nil which indicatesA the current environment.\n\tStartTimeout time.Duration \/\/ How long the process has to run before it's considered Running.\n\tStartRetries int \/\/ How many times to restart a process if it fails to start. Defaults to 3.\n\tStopSignal syscall.Signal \/\/ The signal to send when stopping the process. Defaults to SIGINT.\n\tStopTimeout time.Duration \/\/ How long to wait for a process to stop before sending a SIGKILL. Defaults to 5s.\n\tStopRestart bool \/\/ Whether or not to restart the process if it exits unexpectedly. Defaults to true.\n\tStdout io.Writer \/\/ Where to send the process's stdout. Defaults to \/dev\/null.\n\tStderr io.Writer \/\/ Where to send the process's stderr. Defaults to \/dev\/null.\n\targs []string \/\/ The command line of the process to run.\n\tcommand *exec.Cmd \/\/ The os\/exec command running the process.\n\tstate string \/\/ The state of the Service.\n}\n\n\/\/ New creates a new service with the default configution.\nfunc NewService(args []string) (svc *Service, err error) {\n\tif cwd, err := os.Getwd(); err == nil {\n\t\tsvc = &Service{\n\t\t\tcwd,\n\t\t\tnil,\n\t\t\tDefaultStartTimeout,\n\t\t\tDefaultStartRetries,\n\t\t\tDefaultStopSignal,\n\t\t\tDefaultStopTimeout,\n\t\t\tDefaultStopRestart,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\targs,\n\t\t\tnil,\n\t\t\tStopped,\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ State gets the current state of the service.\nfunc (s Service) State() string {\n\treturn s.state\n}\n\n\/\/ Pid gets the PID of the service or 0 if not Running or Stopping.\nfunc (s Service) Pid() int {\n\tif s.state != Running && s.state != Stopping {\n\t\treturn 0\n\t}\n\treturn s.command.Process.Pid\n}\n\nfunc (s Service) makeCommand() *exec.Cmd {\n\tcmd := exec.Command(s.args[0], s.args[1:]...)\n\tcmd.Stdout = s.Stdout\n\tcmd.Stderr = s.Stderr\n\tcmd.Stdin = nil\n\tcmd.Env = s.Environment\n\tcmd.Dir = s.Directory\n\treturn cmd\n}\n\nfunc (s *Service) Run(commands <-chan Command, events chan<- Event) {\n\tvar lastCommand *Command\n\tstates := make(chan string)\n\tquit := make(chan bool, 2)\n\tkill := make(chan int, 2)\n\tretries := 0\n\n\tdefer func() {\n\t\tclose(states)\n\t\tclose(quit)\n\t\tclose(kill)\n\t}()\n\n\tsendEvent := func(state string) {\n\t\ts.state = state\n\t\tevents <- Event{s, state}\n\t}\n\n\tsendInvalidCmd := func(cmd *Command, state string) {\n\t\tif cmd != nil {\n\t\t\tcmd.respond(s, errors.New(fmt.Sprintf(\"invalid state transition: %s -> %s\", s.state, state)))\n\t\t}\n\t}\n\n\tstart := func(cmd *Command) {\n\t\tif s.state != Stopped && s.state != Exited && s.state != Backoff {\n\t\t\tsendInvalidCmd(cmd, Starting)\n\t\t\treturn\n\t\t}\n\n\t\tsendEvent(Starting)\n\t\tgo func() {\n\t\t\ts.command = s.makeCommand()\n\t\t\tstartTime := time.Now()\n\t\t\tif err := s.command.Start(); err == nil { \/\/TODO: Don't swallow this error.\n\t\t\t\tstates <- Running\n\t\t\t\ts.command.Wait()\n\t\t\t\tif time.Now().Sub(startTime) > s.StartTimeout {\n\t\t\t\t\tstates <- Backoff\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tstates <- Exited\n\t\t}()\n\t}\n\n\tstop := func(cmd *Command) {\n\t\tif s.state != Running {\n\t\t\tsendInvalidCmd(cmd, Stopping)\n\t\t\treturn\n\t\t}\n\n\t\tsendEvent(Stopping)\n\t\tpid := s.Pid()\n\t\ts.command.Process.Signal(s.StopSignal) \/\/TODO: Check for error.\n\t\tgo func() {\n\t\t\ttime.Sleep(s.StopTimeout)\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tif _, ok := err.(runtime.Error); !ok {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tkill <- pid\n\t\t}()\n\t}\n\n\tshutdown := func(cmd *Command, lastCmd *Command) {\n\t\tif lastCmd != nil {\n\t\t\tlastCmd.respond(s, errors.New(\"service is shutting down\"))\n\t\t}\n\t\tif s.state == Stopped || s.state == Exited {\n\t\t\tquit <- true\n\t\t} else if s.state == Running {\n\t\t\tstop(cmd)\n\t\t}\n\t}\n\n\tonRunning := func(cmd *Command) {\n\t\tsendEvent(Running)\n\t\tif cmd != nil {\n\t\t\tswitch cmd.Name {\n\t\t\tcase Start:\n\t\t\t\tfallthrough\n\t\t\tcase Restart:\n\t\t\t\tcmd.respond(s, nil)\n\t\t\tcase Shutdown:\n\t\t\t\tstop(cmd)\n\t\t\t}\n\t\t}\n\t}\n\n\tonStopped := func(cmd *Command) {\n\t\tsendEvent(Stopped)\n\t\tif cmd != nil {\n\t\t\tswitch cmd.Name {\n\t\t\tcase Restart:\n\t\t\t\tstart(cmd)\n\t\t\tcase Stop:\n\t\t\t\tcmd.respond(s, nil)\n\t\t\tcase Shutdown:\n\t\t\t\tquit <- true\n\t\t\t}\n\t\t}\n\t}\n\n\tonExited := func(cmd *Command) {\n\t\tsendEvent(Exited)\n\t\tif s.StopRestart {\n\t\t\tstart(cmd)\n\t\t}\n\t}\n\n\tonBackoff := func(cmd *Command) {\n\t\tif retries < s.StartRetries {\n\t\t\tsendEvent(Backoff)\n\t\t\tstart(cmd)\n\t\t\tretries++\n\t\t} else {\n\t\t\tsendEvent(Exited)\n\t\t\tretries = 0\n\t\t}\n\t}\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase state := <-states:\n\t\t\t\/\/ running, exited\n\t\t\tswitch state {\n\t\t\tcase Running:\n\t\t\t\tonRunning(lastCommand)\n\t\t\tcase Exited:\n\t\t\t\tif s.state == Stopping {\n\t\t\t\t\tonStopped(lastCommand)\n\t\t\t\t} else {\n\t\t\t\t\tonExited(lastCommand)\n\t\t\t\t}\n\t\t\tcase Backoff:\n\t\t\t\tonBackoff(lastCommand)\n\t\t\t}\n\t\t\tif lastCommand != nil {\n\t\t\t\tif lastCommand.Name == Restart && s.state == Running {\n\t\t\t\t\tlastCommand = nil\n\t\t\t\t} else if lastCommand.Name != Restart && lastCommand.Name != Shutdown {\n\t\t\t\t\tlastCommand = nil\n\t\t\t\t}\n\t\t\t}\n\t\tcase command := <-commands:\n\t\t\tif lastCommand == nil || lastCommand.Name != Shutdown { \/\/ Shutdown cannot be overriden!\n\t\t\t\tswitch command.Name {\n\t\t\t\tcase Start:\n\t\t\t\t\tstart(&command)\n\t\t\t\tcase Stop:\n\t\t\t\t\tstop(&command)\n\t\t\t\tcase Restart:\n\t\t\t\t\tstop(&command)\n\t\t\t\tcase Shutdown:\n\t\t\t\t\tshutdown(&command, lastCommand)\n\t\t\t\t}\n\t\t\t\tlastCommand = &command\n\t\t\t} else {\n\t\t\t\tcommand.respond(s, errors.New(\"service is shutting down\"))\n\t\t\t}\n\t\tcase <-quit:\n\t\t\tif lastCommand != nil {\n\t\t\t\tlastCommand.respond(s, nil)\n\t\t\t}\n\t\t\tbreak loop\n\t\tcase pid := <-kill:\n\t\t\tif pid == s.Pid() {\n\t\t\t\ts.command.Process.Kill() \/\/TODO: Check for error.\n\t\t\t}\n\t\t}\n\t}\n}\nSend errors on exit and start failures.package service\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Service defaults.\n\tDefaultStartTimeout = 1 * time.Second\n\tDefaultStartRetries = 3\n\tDefaultStopSignal = syscall.SIGINT\n\tDefaultStopTimeout = 5 * time.Second\n\tDefaultStopRestart = true\n\n\t\/\/ Service commands.\n\tStart = \"start\"\n\tStop = \"stop\"\n\tRestart = \"restart\"\n\tShutdown = \"shutdown\"\n\n\t\/\/ Service states.\n\tStarting = \"starting\"\n\tRunning = \"running\"\n\tStopping = \"stopping\"\n\tStopped = \"stopped\"\n\tExited = \"exited\"\n\tBackoff = \"backoff\"\n)\n\n\/\/ Command is sent to a Service to initiate a state change.\ntype Command struct {\n\tName string\n\tResponse chan<- Response\n}\n\n\/\/ respond creates and sends a command Response.\nfunc (cmd Command) respond(service *Service, err error) {\n\tif cmd.Response != nil {\n\t\tcmd.Response <- Response{service, cmd.Name, err}\n\t}\n}\n\n\/\/ Response contains the result of a Command.\ntype Response struct {\n\tService *Service\n\tName string\n\tError error\n}\n\n\/\/ Success returns True if the Command was successful.\nfunc (r Response) Success() bool {\n\treturn r.Error == nil\n}\n\n\/\/ Event is sent by a Service on a state change.\ntype Event struct {\n\tService *Service \/\/ The service from which the event originated.\n\tState string \/\/ The new state of the service.\n\tError error \/\/ An error indicating why the service is in Exited or Backoff.\n}\n\n\/\/ ExitError indicated why the service entered an Exited or Backoff state.\ntype ExitError string\n\n\/\/ Error returns the error message of the ExitError.\nfunc (err ExitError) Error() string {\n\treturn string(err)\n}\n\n\/\/ Service represents a controllable process. Exported fields may be set to configure the service.\ntype Service struct {\n\tDirectory string \/\/ The process's working directory. Defaults to the current directory.\n\tEnvironment []string \/\/ The environment of the process. Defaults to nil which indicatesA the current environment.\n\tStartTimeout time.Duration \/\/ How long the process has to run before it's considered Running.\n\tStartRetries int \/\/ How many times to restart a process if it fails to start. Defaults to 3.\n\tStopSignal syscall.Signal \/\/ The signal to send when stopping the process. Defaults to SIGINT.\n\tStopTimeout time.Duration \/\/ How long to wait for a process to stop before sending a SIGKILL. Defaults to 5s.\n\tStopRestart bool \/\/ Whether or not to restart the process if it exits unexpectedly. Defaults to true.\n\tStdout io.Writer \/\/ Where to send the process's stdout. Defaults to \/dev\/null.\n\tStderr io.Writer \/\/ Where to send the process's stderr. Defaults to \/dev\/null.\n\targs []string \/\/ The command line of the process to run.\n\tcommand *exec.Cmd \/\/ The os\/exec command running the process.\n\tstate string \/\/ The state of the Service.\n}\n\n\/\/ New creates a new service with the default configution.\nfunc NewService(args []string) (svc *Service, err error) {\n\tif cwd, err := os.Getwd(); err == nil {\n\t\tsvc = &Service{\n\t\t\tcwd,\n\t\t\tnil,\n\t\t\tDefaultStartTimeout,\n\t\t\tDefaultStartRetries,\n\t\t\tDefaultStopSignal,\n\t\t\tDefaultStopTimeout,\n\t\t\tDefaultStopRestart,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\targs,\n\t\t\tnil,\n\t\t\tStopped,\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ State gets the current state of the service.\nfunc (s Service) State() string {\n\treturn s.state\n}\n\n\/\/ Pid gets the PID of the service or 0 if not Running or Stopping.\nfunc (s Service) Pid() int {\n\tif s.state != Running && s.state != Stopping {\n\t\treturn 0\n\t}\n\treturn s.command.Process.Pid\n}\n\nfunc (s Service) makeCommand() *exec.Cmd {\n\tcmd := exec.Command(s.args[0], s.args[1:]...)\n\tcmd.Stdout = s.Stdout\n\tcmd.Stderr = s.Stderr\n\tcmd.Stdin = nil\n\tcmd.Env = s.Environment\n\tcmd.Dir = s.Directory\n\treturn cmd\n}\n\nfunc (s *Service) Run(commands <-chan Command, events chan<- Event) {\n\ttype ProcessState struct {\n\t\tState string\n\t\tError error\n\t}\n\n\tvar lastCommand *Command\n\tstates := make(chan ProcessState)\n\tquit := make(chan bool, 2)\n\tkill := make(chan int, 2)\n\tretries := 0\n\n\tdefer func() {\n\t\tclose(states)\n\t\tclose(quit)\n\t\tclose(kill)\n\t}()\n\n\tsendEvent := func(state string, err error) {\n\t\ts.state = state\n\t\tevents <- Event{s, state, err}\n\t}\n\n\tsendInvalidCmd := func(cmd *Command, state string) {\n\t\tif cmd != nil {\n\t\t\tcmd.respond(s, errors.New(fmt.Sprintf(\"invalid state transition: %s -> %s\", s.state, state)))\n\t\t}\n\t}\n\n\tstart := func(cmd *Command) {\n\t\tif s.state != Stopped && s.state != Exited && s.state != Backoff {\n\t\t\tsendInvalidCmd(cmd, Starting)\n\t\t\treturn\n\t\t}\n\n\t\tsendEvent(Starting, nil)\n\t\tgo func() {\n\t\t\ts.command = s.makeCommand()\n\t\t\tstartTime := time.Now()\n\t\t\tif err := s.command.Start(); err == nil {\n\t\t\t\tstates <- ProcessState{Running, nil}\n\t\t\t\texitErr := s.command.Wait()\n\n\t\t\t\tmsg := \"\"\n\t\t\t\tif time.Now().Sub(startTime) < s.StartTimeout {\n\t\t\t\t\tif exitErr == nil {\n\t\t\t\t\t\tmsg = \"process exited prematurely with success\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmsg = fmt.Sprintf(\"process exited prematurely with failure: %s\", exitErr)\n\t\t\t\t\t}\n\t\t\t\t\tstates <- ProcessState{Backoff, ExitError(msg)}\n\t\t\t\t} else {\n\t\t\t\t\tif exitErr == nil {\n\t\t\t\t\t\tmsg = \"process exited normally with success\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmsg = fmt.Sprintf(\"process exited normally with failure: %s\", exitErr)\n\t\t\t\t\t}\n\t\t\t\t\tstates <- ProcessState{Exited, ExitError(msg)}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstates <- ProcessState{Exited, err}\n\t\t\t}\n\t\t}()\n\t}\n\n\tstop := func(cmd *Command) {\n\t\tif s.state != Running {\n\t\t\tsendInvalidCmd(cmd, Stopping)\n\t\t\treturn\n\t\t}\n\n\t\tsendEvent(Stopping, nil)\n\t\tpid := s.Pid()\n\t\ts.command.Process.Signal(s.StopSignal) \/\/TODO: Check for error.\n\t\tgo func() {\n\t\t\ttime.Sleep(s.StopTimeout)\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tif _, ok := err.(runtime.Error); !ok {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tkill <- pid\n\t\t}()\n\t}\n\n\tshutdown := func(cmd *Command, lastCmd *Command) {\n\t\tif lastCmd != nil {\n\t\t\tlastCmd.respond(s, errors.New(\"service is shutting down\"))\n\t\t}\n\t\tif s.state == Stopped || s.state == Exited {\n\t\t\tquit <- true\n\t\t} else if s.state == Running {\n\t\t\tstop(cmd)\n\t\t}\n\t}\n\n\tonRunning := func(cmd *Command) {\n\t\tsendEvent(Running, nil)\n\t\tif cmd != nil {\n\t\t\tswitch cmd.Name {\n\t\t\tcase Start:\n\t\t\t\tfallthrough\n\t\t\tcase Restart:\n\t\t\t\tcmd.respond(s, nil)\n\t\t\tcase Shutdown:\n\t\t\t\tstop(cmd)\n\t\t\t}\n\t\t}\n\t}\n\n\tonStopped := func(cmd *Command) {\n\t\tsendEvent(Stopped, nil)\n\t\tif cmd != nil {\n\t\t\tswitch cmd.Name {\n\t\t\tcase Restart:\n\t\t\t\tstart(cmd)\n\t\t\tcase Stop:\n\t\t\t\tcmd.respond(s, nil)\n\t\t\tcase Shutdown:\n\t\t\t\tquit <- true\n\t\t\t}\n\t\t}\n\t}\n\n\tonExited := func(cmd *Command, err error) {\n\t\tsendEvent(Exited, err)\n\t\tif s.StopRestart {\n\t\t\tstart(cmd)\n\t\t}\n\t}\n\n\tonBackoff := func(cmd *Command, err error) {\n\t\tif retries < s.StartRetries {\n\t\t\tsendEvent(Backoff, err)\n\t\t\tstart(cmd)\n\t\t\tretries++\n\t\t} else {\n\t\t\tsendEvent(Exited, err)\n\t\t\tretries = 0\n\t\t}\n\t}\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase state := <-states:\n\t\t\t\/\/ running, exited\n\t\t\tswitch state.State {\n\t\t\tcase Running:\n\t\t\t\tonRunning(lastCommand)\n\t\t\tcase Exited:\n\t\t\t\tif s.state == Stopping {\n\t\t\t\t\tonStopped(lastCommand)\n\t\t\t\t} else {\n\t\t\t\t\tonExited(lastCommand, state.Error)\n\t\t\t\t}\n\t\t\tcase Backoff:\n\t\t\t\tonBackoff(lastCommand, state.Error)\n\t\t\t}\n\t\t\tif lastCommand != nil {\n\t\t\t\tif lastCommand.Name == Restart && s.state == Running {\n\t\t\t\t\tlastCommand = nil\n\t\t\t\t} else if lastCommand.Name != Restart && lastCommand.Name != Shutdown {\n\t\t\t\t\tlastCommand = nil\n\t\t\t\t}\n\t\t\t}\n\t\tcase command := <-commands:\n\t\t\tif lastCommand == nil || lastCommand.Name != Shutdown {\n\t\t\t\tswitch command.Name {\n\t\t\t\tcase Start:\n\t\t\t\t\tstart(&command)\n\t\t\t\tcase Stop:\n\t\t\t\t\tstop(&command)\n\t\t\t\tcase Restart:\n\t\t\t\t\tstop(&command)\n\t\t\t\tcase Shutdown:\n\t\t\t\t\tshutdown(&command, lastCommand)\n\t\t\t\t}\n\t\t\t\tlastCommand = &command\n\t\t\t} else {\n\t\t\t\tcommand.respond(s, errors.New(\"service is shutting down\"))\n\t\t\t}\n\t\tcase <-quit:\n\t\t\tif lastCommand != nil {\n\t\t\t\tlastCommand.respond(s, nil)\n\t\t\t}\n\t\t\tbreak loop\n\t\tcase pid := <-kill:\n\t\t\tif pid == s.Pid() {\n\t\t\t\ts.command.Process.Kill() \/\/TODO: Check for error.\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package check\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/errata-ai\/vale\/core\"\n\t\"github.com\/jdkato\/prose\/transform\"\n)\n\nfunc lower(s string, ignore []string) bool {\n\treturn s == strings.ToLower(s) || core.StringInSlice(s, ignore)\n}\n\nfunc upper(s string, ignore []string) bool {\n\treturn s == strings.ToUpper(s) || core.StringInSlice(s, ignore)\n}\n\nfunc title(s string, ignore []string, tc *transform.TitleConverter) bool {\n\tcount := 0.0\n\twords := 0.0\n\texpected := strings.Fields(tc.Title(s))\n\tfor i, word := range strings.Fields(s) {\n\t\tif word == expected[i] || core.StringInSlice(word, ignore) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) > 0.8\n}\n\nfunc sentence(s string, ignore []string) bool {\n\tcount := 0.0\n\twords := 0.0\n\tfor i, w := range strings.Fields(s) {\n\t\tif core.StringInSlice(w, ignore) {\n\t\t\tcount++\n\t\t} else if i == 0 && w != strings.Title(strings.ToLower(w)) {\n\t\t\treturn false\n\t\t} else if i == 0 || w == strings.ToLower(w) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) > 0.8\n}\n\nvar varToFunc = map[string]func(string, []string) bool{\n\t\"$lower\": lower,\n\t\"$upper\": upper,\n\t\"$sentence\": sentence,\n}\n\nvar readabilityMetrics = []string{\n\t\"Gunning Fog\",\n\t\"Coleman-Liau\",\n\t\"Flesch-Kincaid\",\n\t\"SMOG\",\n\t\"Automated Readability\",\n}\nrefactor: ignore all-caps words in 'capitalization'package check\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/errata-ai\/vale\/core\"\n\t\"github.com\/jdkato\/prose\/transform\"\n)\n\nfunc lower(s string, ignore []string) bool {\n\treturn s == strings.ToLower(s) || core.StringInSlice(s, ignore)\n}\n\nfunc upper(s string, ignore []string) bool {\n\treturn s == strings.ToUpper(s) || core.StringInSlice(s, ignore)\n}\n\nfunc title(s string, ignore []string, tc *transform.TitleConverter) bool {\n\tcount := 0.0\n\twords := 0.0\n\texpected := strings.Fields(tc.Title(s))\n\tfor i, word := range strings.Fields(s) {\n\t\tif word == expected[i] || core.StringInSlice(word, ignore) {\n\t\t\tcount++\n\t\t} else if word == strings.ToUpper(word) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) > 0.8\n}\n\nfunc sentence(s string, ignore []string) bool {\n\tcount := 0.0\n\twords := 0.0\n\tfor i, w := range strings.Fields(s) {\n\t\tif core.StringInSlice(w, ignore) || w == strings.ToUpper(w) {\n\t\t\tcount++\n\t\t} else if i == 0 && w != strings.Title(strings.ToLower(w)) {\n\t\t\treturn false\n\t\t} else if i == 0 || w == strings.ToLower(w) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) > 0.8\n}\n\nvar varToFunc = map[string]func(string, []string) bool{\n\t\"$lower\": lower,\n\t\"$upper\": upper,\n\t\"$sentence\": sentence,\n}\n\nvar readabilityMetrics = []string{\n\t\"Gunning Fog\",\n\t\"Coleman-Liau\",\n\t\"Flesch-Kincaid\",\n\t\"SMOG\",\n\t\"Automated Readability\",\n}\n<|endoftext|>"} {"text":"package check\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/jdkato\/prose\/transform\"\n\t\"github.com\/xrash\/smetrics\"\n)\n\nfunc lower(s string) bool { return s == strings.ToLower(s) }\nfunc upper(s string) bool { return s == strings.ToUpper(s) }\n\nfunc title(s string) bool {\n\treturn smetrics.Jaro(s, transform.Title(s)) > 0.97\n}\n\nfunc sentence(s string) bool {\n\tcount := 0.0\n\twords := 0.0\n\tfor i, w := range strings.Fields(s) {\n\t\tif i > 0 && w == strings.Title(w) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) < 0.4\n}\n\nvar varToFunc = map[string]func(string) bool{\n\t\"$title\": title,\n\t\"$lower\": lower,\n\t\"$upper\": upper,\n\t\"$sentence\": sentence,\n}\nfix: call `ToLower` before `Title`package check\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/jdkato\/prose\/transform\"\n\t\"github.com\/xrash\/smetrics\"\n)\n\nfunc lower(s string) bool { return s == strings.ToLower(s) }\nfunc upper(s string) bool { return s == strings.ToUpper(s) }\n\nfunc title(s string) bool {\n\treturn smetrics.Jaro(s, transform.Title(s)) > 0.97\n}\n\nfunc sentence(s string) bool {\n\tcount := 0.0\n\twords := 0.0\n\tfor i, w := range strings.Fields(s) {\n\t\tif i > 0 && w == strings.Title(strings.ToLower(w)) {\n\t\t\tcount++\n\t\t}\n\t\twords++\n\t}\n\treturn (count \/ words) < 0.4\n}\n\nvar varToFunc = map[string]func(string) bool{\n\t\"$title\": title,\n\t\"$lower\": lower,\n\t\"$upper\": upper,\n\t\"$sentence\": sentence,\n}\n<|endoftext|>"} {"text":"package checker\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/mackerelio\/mackerel-agent\/config\"\n\tcli \"gopkg.in\/urfave\/cli.v1\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nvar Command = cli.Command{\n\tName: \"run-checks\",\n\tUsage: \"run check commands in mackerel-agent.conf\",\n\tDescription: `\n Execute command of check plugins in mackerel-agent.conf all at once.\n It is used for checking setting and operation of the check plugins.\n\tThe result is output to stdout in TAP format. If any check fails,\n\tit exits non-zero.\n`,\n\tAction: doRunChecks,\n}\n\nfunc doRunChecks(c *cli.Context) error {\n\tconfFile := c.GlobalString(\"conf\")\n\tconf, err := config.LoadConfig(confFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcheckers := make([]checker, len(conf.CheckPlugins))\n\ti := 0\n\tfor name, p := range conf.CheckPlugins {\n\t\tcheckers[i] = &checkPluginChecker{\n\t\t\tname: name,\n\t\t\tcp: p,\n\t\t}\n\t\ti++\n\t}\n\treturn runChecks(checkers, os.Stdout)\n}\n\ntype result struct {\n\tName string `yaml:\"-\"`\n\tMemo string `yaml:\"memo,omitempty\"`\n\tCmd []string `yaml:\"command,flow\"`\n\tStdout string `yaml:\"stdout,omitempty\"`\n\tStderr string `yaml:\"stderr,omitempty\"`\n\tExitCode int `yaml:\"exitCode,omitempty\"`\n\tErrMsg string `yaml:\"error,omitempty\"`\n}\n\nfunc (re *result) ok() bool {\n\treturn re.ExitCode == 0 && re.ErrMsg == \"\"\n}\n\nfunc (re *result) tapFormat(num int) string {\n\tokOrNot := \"ok\"\n\tif !re.ok() {\n\t\tokOrNot = \"not ok\"\n\t}\n\tb, _ := yaml.Marshal(re)\n\t\/\/ indent\n\tyamlStr := \" \" + strings.Replace(strings.TrimSpace(string(b)), \"\\n\", \"\\n \", -1)\n\treturn fmt.Sprintf(\"%s %d - %s\\n ---\\n%s\\n ...\",\n\t\tokOrNot, num, re.Name, yamlStr)\n}\n\ntype checkPluginChecker struct {\n\tname string\n\tcp *config.CheckPlugin\n}\n\nfunc (cpc *checkPluginChecker) check() *result {\n\tp := cpc.cp\n\tstdout, stderr, exitCode, err := p.Command.Run()\n\tcmd := p.Command.Args\n\tif len(cmd) == 0 {\n\t\tcmd = append(cmd, p.Command.Cmd)\n\t}\n\terrMsg := \"\"\n\tif err != nil {\n\t\terrMsg = err.Error()\n\t}\n\treturn &result{\n\t\tName: cpc.name,\n\t\tMemo: p.Memo,\n\t\tCmd: cmd,\n\t\tExitCode: exitCode,\n\t\tStdout: strings.TrimSpace(stdout),\n\t\tStderr: strings.TrimSpace(stderr),\n\t\tErrMsg: errMsg,\n\t}\n}\n\ntype checker interface {\n\tcheck() *result\n}\n\nfunc runChecks(checkers []checker, w io.Writer) error {\n\tch := make(chan *result)\n\ttotal := len(checkers)\n\tgo func() {\n\t\twg := &sync.WaitGroup{}\n\t\twg.Add(total)\n\t\tfor _, c := range checkers {\n\t\t\tgo func(c checker) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tch <- c.check()\n\t\t\t}(c)\n\t\t}\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\tfmt.Fprintln(w, \"TAP version 13\")\n\tfmt.Fprintf(w, \"1..%d\\n\", total)\n\ttestNum, errNum := 1, 0\n\tfor re := range ch {\n\t\tfmt.Fprintln(w, re.tapFormat(testNum))\n\t\ttestNum++\n\t\tif !re.ok() {\n\t\t\terrNum++\n\t\t}\n\t}\n\tif errNum > 0 {\n\t\treturn fmt.Errorf(\"Failed %d\/%d tests, %3.2f%% okay\",\n\t\t\terrNum, total, float64(100*(total-errNum))\/float64(total))\n\t}\n\treturn nil\n}\nadd comment docpackage checker\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/mackerelio\/mackerel-agent\/config\"\n\tcli \"gopkg.in\/urfave\/cli.v1\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\n\/\/ Command is command definition of mkr run-checks\nvar Command = cli.Command{\n\tName: \"run-checks\",\n\tUsage: \"run check commands in mackerel-agent.conf\",\n\tDescription: `\n Execute command of check plugins in mackerel-agent.conf all at once.\n It is used for checking setting and operation of the check plugins.\n\tThe result is output to stdout in TAP format. If any check fails,\n\tit exits non-zero.\n`,\n\tAction: doRunChecks,\n}\n\nfunc doRunChecks(c *cli.Context) error {\n\tconfFile := c.GlobalString(\"conf\")\n\tconf, err := config.LoadConfig(confFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcheckers := make([]checker, len(conf.CheckPlugins))\n\ti := 0\n\tfor name, p := range conf.CheckPlugins {\n\t\tcheckers[i] = &checkPluginChecker{\n\t\t\tname: name,\n\t\t\tcp: p,\n\t\t}\n\t\ti++\n\t}\n\treturn runChecks(checkers, os.Stdout)\n}\n\ntype result struct {\n\tName string `yaml:\"-\"`\n\tMemo string `yaml:\"memo,omitempty\"`\n\tCmd []string `yaml:\"command,flow\"`\n\tStdout string `yaml:\"stdout,omitempty\"`\n\tStderr string `yaml:\"stderr,omitempty\"`\n\tExitCode int `yaml:\"exitCode,omitempty\"`\n\tErrMsg string `yaml:\"error,omitempty\"`\n}\n\nfunc (re *result) ok() bool {\n\treturn re.ExitCode == 0 && re.ErrMsg == \"\"\n}\n\nfunc (re *result) tapFormat(num int) string {\n\tokOrNot := \"ok\"\n\tif !re.ok() {\n\t\tokOrNot = \"not ok\"\n\t}\n\tb, _ := yaml.Marshal(re)\n\t\/\/ indent\n\tyamlStr := \" \" + strings.Replace(strings.TrimSpace(string(b)), \"\\n\", \"\\n \", -1)\n\treturn fmt.Sprintf(\"%s %d - %s\\n ---\\n%s\\n ...\",\n\t\tokOrNot, num, re.Name, yamlStr)\n}\n\ntype checkPluginChecker struct {\n\tname string\n\tcp *config.CheckPlugin\n}\n\nfunc (cpc *checkPluginChecker) check() *result {\n\tp := cpc.cp\n\tstdout, stderr, exitCode, err := p.Command.Run()\n\tcmd := p.Command.Args\n\tif len(cmd) == 0 {\n\t\tcmd = append(cmd, p.Command.Cmd)\n\t}\n\terrMsg := \"\"\n\tif err != nil {\n\t\terrMsg = err.Error()\n\t}\n\treturn &result{\n\t\tName: cpc.name,\n\t\tMemo: p.Memo,\n\t\tCmd: cmd,\n\t\tExitCode: exitCode,\n\t\tStdout: strings.TrimSpace(stdout),\n\t\tStderr: strings.TrimSpace(stderr),\n\t\tErrMsg: errMsg,\n\t}\n}\n\ntype checker interface {\n\tcheck() *result\n}\n\nfunc runChecks(checkers []checker, w io.Writer) error {\n\tch := make(chan *result)\n\ttotal := len(checkers)\n\tgo func() {\n\t\twg := &sync.WaitGroup{}\n\t\twg.Add(total)\n\t\tfor _, c := range checkers {\n\t\t\tgo func(c checker) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tch <- c.check()\n\t\t\t}(c)\n\t\t}\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\tfmt.Fprintln(w, \"TAP version 13\")\n\tfmt.Fprintf(w, \"1..%d\\n\", total)\n\ttestNum, errNum := 1, 0\n\tfor re := range ch {\n\t\tfmt.Fprintln(w, re.tapFormat(testNum))\n\t\ttestNum++\n\t\tif !re.ok() {\n\t\t\terrNum++\n\t\t}\n\t}\n\tif errNum > 0 {\n\t\treturn fmt.Errorf(\"Failed %d\/%d tests, %3.2f%% okay\",\n\t\t\terrNum, total, float64(100*(total-errNum))\/float64(total))\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package services\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/generator\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/runner\"\n\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/assets\"\n)\n\ntype Plan struct {\n\tName string `json:\"name\"`\n\tID string `json:\"id\"`\n}\n\ntype ServiceBroker struct {\n\tName string\n\tPath string\n\tcontext helpers.SuiteContext\n\tService struct {\n\t\tName string `json:\"name\"`\n\t\tID string `json:\"id\"`\n\t\tDashboardClient struct {\n\t\t\tID string `json:\"id\"`\n\t\t\tSecret string `json:\"secret\"`\n\t\t\tRedirectUri string `json:\"redirect_uri\"`\n\t\t}\n\t}\n\tSyncPlans []Plan\n\tAsyncPlans []Plan\n}\n\ntype ServicesResponse struct {\n\tResources []ServiceResponse\n}\n\ntype ServiceResponse struct {\n\tEntity struct {\n\t\tLabel string\n\t\tServicePlans []ServicePlanResponse `json:\"service_plans\"`\n\t}\n}\n\ntype ServicePlanResponse struct {\n\tEntity struct {\n\t\tName string\n\t\tPublic bool\n\t}\n\tMetadata struct {\n\t\tUrl string\n\t\tGuid string\n\t}\n}\n\ntype ServiceInstance struct {\n\tMetadata struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n}\n\ntype ServiceInstanceResponse struct {\n\tResources []ServiceInstance\n}\n\ntype SpaceJson struct {\n\tResources []struct {\n\t\tMetadata struct {\n\t\t\tGuid string\n\t\t}\n\t}\n}\n\nfunc NewServiceBroker(name string, path string, context helpers.SuiteContext) ServiceBroker {\n\tb := ServiceBroker{}\n\tb.Path = path\n\tb.Name = name\n\tb.Service.Name = generator.RandomName()\n\tb.Service.ID = generator.RandomName()\n\tb.SyncPlans = []Plan{\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t}\n\tb.AsyncPlans = []Plan{\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t}\n\tb.Service.DashboardClient.ID = generator.RandomName()\n\tb.Service.DashboardClient.Secret = generator.RandomName()\n\tb.Service.DashboardClient.RedirectUri = generator.RandomName()\n\tb.context = context\n\treturn b\n}\n\nfunc (b ServiceBroker) Push() {\n\tExpect(cf.Cf(\"push\", b.Name, \"-p\", b.Path).Wait(BROKER_START_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Configure() {\n\tExpect(runner.Curl(helpers.AppUri(b.Name, \"\/config\"), \"-d\", b.ToJSON()).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Restart() {\n\tExpect(cf.Cf(\"restart\", b.Name).Wait(BROKER_START_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Create() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"create-service-broker\", b.Name, \"username\", \"password\", helpers.AppUri(b.Name, \"\")).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t\tExpect(cf.Cf(\"service-brokers\").Wait(DEFAULT_TIMEOUT)).To(Say(b.Name))\n\t})\n}\n\nfunc (b ServiceBroker) Update() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"update-service-broker\", b.Name, \"username\", \"password\", helpers.AppUri(b.Name, \"\")).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n}\n\nfunc (b ServiceBroker) Delete() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"delete-service-broker\", b.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\n\t\tbrokers := cf.Cf(\"service-brokers\").Wait(DEFAULT_TIMEOUT)\n\t\tExpect(brokers).To(Exit(0))\n\t\tExpect(brokers.Out.Contents()).ToNot(ContainSubstring(b.Name))\n\t})\n}\n\nfunc (b ServiceBroker) Destroy() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"purge-service-offering\", b.Service.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n\tb.Delete()\n\tExpect(cf.Cf(\"delete\", b.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) ToJSON() string {\n\tbytes, err := ioutil.ReadFile(assets.NewAssets().ServiceBroker + \"\/cats.json\")\n\tExpect(err).To(BeNil())\n\n\treplacer := strings.NewReplacer(\n\t\t\"\", b.Service.Name,\n\t\t\"\", b.Service.ID,\n\t\t\"\", b.Service.DashboardClient.ID,\n\t\t\"\", b.Service.DashboardClient.Secret,\n\t\t\"\", b.Service.DashboardClient.RedirectUri,\n\t\t\"\", b.SyncPlans[0].Name,\n\t\t\"\", b.SyncPlans[0].ID,\n\t\t\"\", b.SyncPlans[1].Name,\n\t\t\"\", b.SyncPlans[1].ID,\n\t\t\"\", b.AsyncPlans[0].Name,\n\t\t\"\", b.AsyncPlans[0].ID,\n\t\t\"\", b.AsyncPlans[1].Name,\n\t\t\"\", b.AsyncPlans[1].ID,\n\t)\n\n\treturn replacer.Replace(string(bytes))\n}\n\nfunc (b ServiceBroker) PublicizePlans() {\n\turl := fmt.Sprintf(\"\/v2\/services?inline-relations-depth=1&q=label:%s\", b.Service.Name)\n\tvar session *Session\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tsession = cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\t\tExpect(session).To(Exit(0))\n\t})\n\tstructure := ServicesResponse{}\n\tjson.Unmarshal(session.Out.Contents(), &structure)\n\n\tfor _, service := range structure.Resources {\n\t\tif service.Entity.Label == b.Service.Name {\n\t\t\tfor _, plan := range service.Entity.ServicePlans {\n\t\t\t\tif b.HasPlan(plan.Entity.Name) {\n\t\t\t\t\tb.PublicizePlan(plan.Metadata.Url)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (b ServiceBroker) HasPlan(planName string) bool {\n\tfor _, plan := range b.Plans() {\n\t\tif plan.Name == planName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (b ServiceBroker) PublicizePlan(url string) {\n\tjsonMap := make(map[string]bool)\n\tjsonMap[\"public\"] = true\n\tplanJson, _ := json.Marshal(jsonMap)\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"curl\", url, \"-X\", \"PUT\", \"-d\", string(planJson)).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n}\n\nfunc (b ServiceBroker) CreateServiceInstance(instanceName string) string {\n\tExpect(cf.Cf(\"create-service\", b.Service.Name, b.SyncPlans[0].Name, instanceName).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\turl := fmt.Sprintf(\"\/v2\/service_instances?q=name:%s\", instanceName)\n\tserviceInstance := ServiceInstanceResponse{}\n\tcurl := cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\tExpect(curl).To(Exit(0))\n\tjson.Unmarshal(curl.Out.Contents(), &serviceInstance)\n\treturn serviceInstance.Resources[0].Metadata.Guid\n}\n\nfunc (b ServiceBroker) GetSpaceGuid() string {\n\turl := fmt.Sprintf(\"\/v2\/spaces?q=name%%3A%s\", b.context.RegularUserContext().Space)\n\tjsonResults := SpaceJson{}\n\tcurl := cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\tExpect(curl).To(Exit(0))\n\tjson.Unmarshal(curl.Out.Contents(), &jsonResults)\n\treturn jsonResults.Resources[0].Metadata.Guid\n}\n\nfunc (b ServiceBroker) Plans() []Plan {\n\tplans := make([]Plan, 0)\n\tplans = append(plans, b.SyncPlans...)\n\tplans = append(plans, b.AsyncPlans...)\n\treturn plans\n}\nServices tests can use diego when availablepackage services\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/generator\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/runner\"\n\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/assets\"\n)\n\ntype Plan struct {\n\tName string `json:\"name\"`\n\tID string `json:\"id\"`\n}\n\ntype ServiceBroker struct {\n\tName string\n\tPath string\n\tcontext helpers.SuiteContext\n\tService struct {\n\t\tName string `json:\"name\"`\n\t\tID string `json:\"id\"`\n\t\tDashboardClient struct {\n\t\t\tID string `json:\"id\"`\n\t\t\tSecret string `json:\"secret\"`\n\t\t\tRedirectUri string `json:\"redirect_uri\"`\n\t\t}\n\t}\n\tSyncPlans []Plan\n\tAsyncPlans []Plan\n}\n\ntype ServicesResponse struct {\n\tResources []ServiceResponse\n}\n\ntype ServiceResponse struct {\n\tEntity struct {\n\t\tLabel string\n\t\tServicePlans []ServicePlanResponse `json:\"service_plans\"`\n\t}\n}\n\ntype ServicePlanResponse struct {\n\tEntity struct {\n\t\tName string\n\t\tPublic bool\n\t}\n\tMetadata struct {\n\t\tUrl string\n\t\tGuid string\n\t}\n}\n\ntype ServiceInstance struct {\n\tMetadata struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n}\n\ntype ServiceInstanceResponse struct {\n\tResources []ServiceInstance\n}\n\ntype SpaceJson struct {\n\tResources []struct {\n\t\tMetadata struct {\n\t\t\tGuid string\n\t\t}\n\t}\n}\n\nfunc NewServiceBroker(name string, path string, context helpers.SuiteContext) ServiceBroker {\n\tb := ServiceBroker{}\n\tb.Path = path\n\tb.Name = name\n\tb.Service.Name = generator.RandomName()\n\tb.Service.ID = generator.RandomName()\n\tb.SyncPlans = []Plan{\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t}\n\tb.AsyncPlans = []Plan{\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t\t{Name: generator.RandomName(), ID: generator.RandomName()},\n\t}\n\tb.Service.DashboardClient.ID = generator.RandomName()\n\tb.Service.DashboardClient.Secret = generator.RandomName()\n\tb.Service.DashboardClient.RedirectUri = generator.RandomName()\n\tb.context = context\n\treturn b\n}\n\nfunc (b ServiceBroker) Push() {\n\tExpect(cf.Cf(\"push\", b.Name, \"-p\", b.Path, \"--no-start\").Wait(BROKER_START_TIMEOUT)).To(Exit(0))\n\tif helpers.LoadConfig().UseDiego {\n\t\tappGuid := strings.TrimSpace(string(cf.Cf(\"app\", b.Name, \"--guid\").Wait(DEFAULT_TIMEOUT).Out.Contents()))\n\t\tcf.Cf(\"curl\",\n\t\t\tfmt.Sprintf(\"\/v2\/apps\/%s\", appGuid),\n\t\t\t\"-X\", \"PUT\",\n\t\t\t\"-d\", \"{\\\"diego\\\": true}\",\n\t\t).Wait(DEFAULT_TIMEOUT)\n\t}\n\tExpect(cf.Cf(\"start\", b.Name).Wait(BROKER_START_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Configure() {\n\tExpect(runner.Curl(helpers.AppUri(b.Name, \"\/config\"), \"-d\", b.ToJSON()).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Restart() {\n\tExpect(cf.Cf(\"restart\", b.Name).Wait(BROKER_START_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) Create() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"create-service-broker\", b.Name, \"username\", \"password\", helpers.AppUri(b.Name, \"\")).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t\tExpect(cf.Cf(\"service-brokers\").Wait(DEFAULT_TIMEOUT)).To(Say(b.Name))\n\t})\n}\n\nfunc (b ServiceBroker) Update() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"update-service-broker\", b.Name, \"username\", \"password\", helpers.AppUri(b.Name, \"\")).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n}\n\nfunc (b ServiceBroker) Delete() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"delete-service-broker\", b.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\n\t\tbrokers := cf.Cf(\"service-brokers\").Wait(DEFAULT_TIMEOUT)\n\t\tExpect(brokers).To(Exit(0))\n\t\tExpect(brokers.Out.Contents()).ToNot(ContainSubstring(b.Name))\n\t})\n}\n\nfunc (b ServiceBroker) Destroy() {\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"purge-service-offering\", b.Service.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n\tb.Delete()\n\tExpect(cf.Cf(\"delete\", b.Name, \"-f\").Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n}\n\nfunc (b ServiceBroker) ToJSON() string {\n\tbytes, err := ioutil.ReadFile(assets.NewAssets().ServiceBroker + \"\/cats.json\")\n\tExpect(err).To(BeNil())\n\n\treplacer := strings.NewReplacer(\n\t\t\"\", b.Service.Name,\n\t\t\"\", b.Service.ID,\n\t\t\"\", b.Service.DashboardClient.ID,\n\t\t\"\", b.Service.DashboardClient.Secret,\n\t\t\"\", b.Service.DashboardClient.RedirectUri,\n\t\t\"\", b.SyncPlans[0].Name,\n\t\t\"\", b.SyncPlans[0].ID,\n\t\t\"\", b.SyncPlans[1].Name,\n\t\t\"\", b.SyncPlans[1].ID,\n\t\t\"\", b.AsyncPlans[0].Name,\n\t\t\"\", b.AsyncPlans[0].ID,\n\t\t\"\", b.AsyncPlans[1].Name,\n\t\t\"\", b.AsyncPlans[1].ID,\n\t)\n\n\treturn replacer.Replace(string(bytes))\n}\n\nfunc (b ServiceBroker) PublicizePlans() {\n\turl := fmt.Sprintf(\"\/v2\/services?inline-relations-depth=1&q=label:%s\", b.Service.Name)\n\tvar session *Session\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tsession = cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\t\tExpect(session).To(Exit(0))\n\t})\n\tstructure := ServicesResponse{}\n\tjson.Unmarshal(session.Out.Contents(), &structure)\n\n\tfor _, service := range structure.Resources {\n\t\tif service.Entity.Label == b.Service.Name {\n\t\t\tfor _, plan := range service.Entity.ServicePlans {\n\t\t\t\tif b.HasPlan(plan.Entity.Name) {\n\t\t\t\t\tb.PublicizePlan(plan.Metadata.Url)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (b ServiceBroker) HasPlan(planName string) bool {\n\tfor _, plan := range b.Plans() {\n\t\tif plan.Name == planName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (b ServiceBroker) PublicizePlan(url string) {\n\tjsonMap := make(map[string]bool)\n\tjsonMap[\"public\"] = true\n\tplanJson, _ := json.Marshal(jsonMap)\n\tcf.AsUser(b.context.AdminUserContext(), DEFAULT_TIMEOUT, func() {\n\t\tExpect(cf.Cf(\"curl\", url, \"-X\", \"PUT\", \"-d\", string(planJson)).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\t})\n}\n\nfunc (b ServiceBroker) CreateServiceInstance(instanceName string) string {\n\tExpect(cf.Cf(\"create-service\", b.Service.Name, b.SyncPlans[0].Name, instanceName).Wait(DEFAULT_TIMEOUT)).To(Exit(0))\n\turl := fmt.Sprintf(\"\/v2\/service_instances?q=name:%s\", instanceName)\n\tserviceInstance := ServiceInstanceResponse{}\n\tcurl := cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\tExpect(curl).To(Exit(0))\n\tjson.Unmarshal(curl.Out.Contents(), &serviceInstance)\n\treturn serviceInstance.Resources[0].Metadata.Guid\n}\n\nfunc (b ServiceBroker) GetSpaceGuid() string {\n\turl := fmt.Sprintf(\"\/v2\/spaces?q=name%%3A%s\", b.context.RegularUserContext().Space)\n\tjsonResults := SpaceJson{}\n\tcurl := cf.Cf(\"curl\", url).Wait(DEFAULT_TIMEOUT)\n\tExpect(curl).To(Exit(0))\n\tjson.Unmarshal(curl.Out.Contents(), &jsonResults)\n\treturn jsonResults.Resources[0].Metadata.Guid\n}\n\nfunc (b ServiceBroker) Plans() []Plan {\n\tplans := make([]Plan, 0)\n\tplans = append(plans, b.SyncPlans...)\n\tplans = append(plans, b.AsyncPlans...)\n\treturn plans\n}\n<|endoftext|>"} {"text":"package eyego\n\nimport (\n\t\"io\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"crypto\/md5\"\n)\n\ntype ChecksumReader struct {\n\tdelegate io.Reader\n\tbuf [\/*512*\/]byte\n\tptr int\n\tchecksums []uint16\n\tself *ChecksumReader\n}\n\nfunc NewChecksumReader(r io.Reader) ChecksumReader {\n\tcr := ChecksumReader {\n\t\tdelegate: r,\n\t\tptr: 0,\n\t\tbuf: make([]byte, 512),\n\t\tchecksums: make([]uint16, 0, 16)}\n\tcr.self = &cr\n\treturn cr\n}\n\nfunc (cr ChecksumReader) Read(p []byte) (n int, err error){\n\tn, err = cr.delegate.Read(p)\n\n\tif err == nil {\n\t\tcr.appendBytes(p, n)\n\t}\n\n\treturn n, nil\n}\n\nfunc (cr ChecksumReader) Checksum(uploadKey string) string {\n\n\tb, _ := hex.DecodeString(uploadKey)\n\n\tif len(b) % 2 != 0 { panic(\"Bad upload key\")}\n\n\th := md5.New()\n\n\tfor i := 0; i < len(cr.checksums); i++ {\n\t\th.Write([]byte{\n\t\t\tbyte(cr.checksums[i]),\n\t\t\tbyte(cr.checksums[i] >> 8)})\n\t}\n\n\th.Write(b)\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc (cr ChecksumReader) appendBytes(b []byte, len int) {\n\n\tcr = *cr.self\n\tif cr.ptr + len >= 512 {\n\t\tcopy(cr.buf[cr.ptr:512], b[0:512-cr.ptr]) \/\/copy bytes to fill temp buffer\n\t\tcr.checksums = append(cr.checksums, tcp_checksum(cr.buf))\n\t\tcr.buf = cr.buf[:0]\n\t\tcopy(cr.buf, b[512-cr.ptr:len]) \/\/copy remaining bytes\n\t\tcr.ptr = len - (512 - cr.ptr)\n\t} else { \/\/\n\t\tcopy(cr.buf[cr.ptr:cr.ptr+len], b[0:len])\n\t\tcr.ptr += len\n\t}\n}\n\nfunc tcp_checksum(b []byte) uint16 {\n\tif len(b) % 2 != 0 { panic(fmt.Sprintf(\"tcp checksum bad length: %d\", len(b))) }\n\n\tvar sum uint32 = 0\n\tvar tmp uint16\n\n\tfor c := 0; c < len(b); c = c + 2 {\n\t\ttmp = uint16(b[c]) | uint16(b[c+1]) << 8\n\t\tsum += uint32(tmp)\n\t}\n\n\tsum = (sum >> 16) + (sum & 0xffff)\n\tsum += (sum >> 16)\n\treturn uint16(^sum)\n}\nfixed err returnpackage eyego\n\nimport (\n\t\"io\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"crypto\/md5\"\n)\n\ntype ChecksumReader struct {\n\tdelegate io.Reader\n\tbuf [\/*512*\/]byte\n\tptr int\n\tchecksums []uint16\n\tself *ChecksumReader\n}\n\nfunc NewChecksumReader(r io.Reader) ChecksumReader {\n\tcr := ChecksumReader {\n\t\tdelegate: r,\n\t\tptr: 0,\n\t\tbuf: make([]byte, 512),\n\t\tchecksums: make([]uint16, 0, 16)}\n\tcr.self = &cr\n\treturn cr\n}\n\nfunc (cr ChecksumReader) Read(p []byte) (n int, err error){\n\tn, err = cr.delegate.Read(p)\n\n\tif err == nil {\n\t\tcr.appendBytes(p, n)\n\t}\n\n\treturn n, err\n}\n\nfunc (cr ChecksumReader) Checksum(uploadKey string) string {\n\n\tb, _ := hex.DecodeString(uploadKey)\n\n\tif len(b) % 2 != 0 { panic(\"Bad upload key\")}\n\n\th := md5.New()\n\n\tfor i := 0; i < len(cr.checksums); i++ {\n\t\th.Write([]byte{\n\t\t\tbyte(cr.checksums[i]),\n\t\t\tbyte(cr.checksums[i] >> 8)})\n\t}\n\n\th.Write(b)\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc (cr ChecksumReader) appendBytes(b []byte, len int) {\n\n\tcr = *cr.self\n\tif cr.ptr + len >= 512 {\n\t\tcopy(cr.buf[cr.ptr:512], b[0:512-cr.ptr]) \/\/copy bytes to fill temp buffer\n\t\tcr.checksums = append(cr.checksums, tcp_checksum(cr.buf))\n\t\tcr.buf = cr.buf[:0]\n\t\tcopy(cr.buf, b[512-cr.ptr:len]) \/\/copy remaining bytes\n\t\tcr.ptr = len - (512 - cr.ptr)\n\t} else { \/\/\n\t\tcopy(cr.buf[cr.ptr:cr.ptr+len], b[0:len])\n\t\tcr.ptr += len\n\t}\n}\n\nfunc tcp_checksum(b []byte) uint16 {\n\tif len(b) % 2 != 0 { panic(fmt.Sprintf(\"tcp checksum bad length: %d\", len(b))) }\n\n\tvar sum uint32 = 0\n\tvar tmp uint16\n\n\tfor c := 0; c < len(b); c = c + 2 {\n\t\ttmp = uint16(b[c]) | uint16(b[c+1]) << 8\n\t\tsum += uint32(tmp)\n\t}\n\n\tsum = (sum >> 16) + (sum & 0xffff)\n\tsum += (sum >> 16)\n\treturn uint16(^sum)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/PreetamJinka\/ethernetdecode\"\n\t\"github.com\/PreetamJinka\/sflow-go\"\n\n\t\"fmt\"\n\t\"net\"\n)\n\nfunc main() {\n\topened := 0\n\tclosed := 0\n\n\tudpAddr, _ := net.ResolveUDPAddr(\"udp\", \":6343\")\n\tconn, err := net.ListenUDP(\"udp\", udpAddr)\n\n\tfmt.Println(err)\n\n\tbuf := make([]byte, 65535)\n\n\tfor {\n\t\tn, _, err := conn.ReadFromUDP(buf)\n\t\tif err == nil {\n\t\t\tdatagram := sflow.Decode(buf[0:n])\n\t\t\tfor _, sample := range datagram.Samples {\n\t\t\t\tswitch sample.SampleType() {\n\t\t\t\tcase sflow.TypeFlowSample:\n\t\t\t\t\tfs := sample.(sflow.FlowSample)\n\t\t\t\t\tfor _, record := range fs.Records {\n\t\t\t\t\t\tif record.RecordType() == sflow.TypeRawPacketFlow {\n\t\t\t\t\t\t\tr := record.(sflow.RawPacketFlowRecord)\n\t\t\t\t\t\t\t_, ipHdr, protoHdr := ethernetdecode.Decode(r.Header)\n\t\t\t\t\t\t\tif ipHdr != nil && ipHdr.IpVersion() == 4 {\n\t\t\t\t\t\t\t\tipv4 := ipHdr.(ethernetdecode.Ipv4Header)\n\t\t\t\t\t\t\t\tswitch protoHdr.Protocol() {\n\t\t\t\t\t\t\t\tcase ethernetdecode.ProtocolTcp:\n\t\t\t\t\t\t\t\t\ttcp := protoHdr.(ethernetdecode.TcpHeader)\n\n\t\t\t\t\t\t\t\t\t\/\/ SYN+ACK flags\n\t\t\t\t\t\t\t\t\tif tcp.Flags&18 != 0 {\n\t\t\t\t\t\t\t\t\t\topened++\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\/\/ FIN+ACK flags\n\t\t\t\t\t\t\t\t\tif tcp.Flags&17 != 0 {\n\t\t\t\t\t\t\t\t\t\tclosed++\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase ethernetdecode.ProtocolUdp:\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfmt.Printf(\"src: %v => dst: %v\\n\", net.IP(ipv4.Source[:]), net.IP(ipv4.Destination[:]))\n\t\t\t\t\t\t\t\tfmt.Printf(\"TCP connections opened: %d, closed: %d\\n\", opened, closed)\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\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\nFix connection open checkpackage main\n\nimport (\n\t\"github.com\/PreetamJinka\/ethernetdecode\"\n\t\"github.com\/PreetamJinka\/sflow-go\"\n\n\t\"fmt\"\n\t\"net\"\n)\n\nfunc main() {\n\topened := 0\n\tclosed := 0\n\n\tudpAddr, _ := net.ResolveUDPAddr(\"udp\", \":6343\")\n\tconn, err := net.ListenUDP(\"udp\", udpAddr)\n\n\tfmt.Println(err)\n\n\tbuf := make([]byte, 65535)\n\n\tfor {\n\t\tn, _, err := conn.ReadFromUDP(buf)\n\t\tif err == nil {\n\t\t\tdatagram := sflow.Decode(buf[0:n])\n\t\t\tfor _, sample := range datagram.Samples {\n\t\t\t\tswitch sample.SampleType() {\n\t\t\t\tcase sflow.TypeFlowSample:\n\t\t\t\t\tfs := sample.(sflow.FlowSample)\n\t\t\t\t\tfor _, record := range fs.Records {\n\t\t\t\t\t\tif record.RecordType() == sflow.TypeRawPacketFlow {\n\t\t\t\t\t\t\tr := record.(sflow.RawPacketFlowRecord)\n\t\t\t\t\t\t\t_, ipHdr, protoHdr := ethernetdecode.Decode(r.Header)\n\t\t\t\t\t\t\tif ipHdr != nil && ipHdr.IpVersion() == 4 {\n\t\t\t\t\t\t\t\tipv4 := ipHdr.(ethernetdecode.Ipv4Header)\n\t\t\t\t\t\t\t\tswitch protoHdr.Protocol() {\n\t\t\t\t\t\t\t\tcase ethernetdecode.ProtocolTcp:\n\t\t\t\t\t\t\t\t\ttcp := protoHdr.(ethernetdecode.TcpHeader)\n\n\t\t\t\t\t\t\t\t\t\/\/ SYN+ACK flags\n\t\t\t\t\t\t\t\t\tif tcp.Flags&3 == 2 {\n\t\t\t\t\t\t\t\t\t\topened++\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\/\/ FIN+ACK flags\n\t\t\t\t\t\t\t\t\tif tcp.Flags&17 != 0 {\n\t\t\t\t\t\t\t\t\t\tclosed++\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase ethernetdecode.ProtocolUdp:\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfmt.Printf(\"src: %v => dst: %v\\n\", net.IP(ipv4.Source[:]), net.IP(ipv4.Destination[:]))\n\t\t\t\t\t\t\t\tfmt.Printf(\"TCP connections opened: %d, closed: %d\\n\", opened, closed)\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\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 The SurgeMQ Authors. All rights reserved.\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 session\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"github.com\/troian\/surgemq\"\n\t\"github.com\/troian\/surgemq\/message\"\n\tpersistenceTypes \"github.com\/troian\/surgemq\/persistence\/types\"\n\t\"github.com\/troian\/surgemq\/systree\"\n\t\"github.com\/troian\/surgemq\/topics\"\n\t\"github.com\/troian\/surgemq\/types\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ ErrNotAccepted new connection does not meet requirements\n\tErrNotAccepted = errors.New(\"Connection not accepted\")\n\n\t\/\/ ErrDupNotAllowed case when new client with existing ID connected\n\tErrDupNotAllowed = errors.New(\"duplicate not allowed\")\n)\n\n\/\/ Config manager configuration\ntype Config struct {\n\t\/\/ Topics manager for all the client subscriptions\n\tTopicsMgr *topics.Manager\n\n\t\/\/ The number of seconds to wait for the CONNACK message before disconnecting.\n\t\/\/ If not set then default to 2 seconds.\n\tConnectTimeout int\n\n\t\/\/ The number of seconds to wait for any ACK messages before failing.\n\t\/\/ If not set then default to 20 seconds.\n\tAckTimeout int\n\n\t\/\/ The number of times to retry sending a packet if ACK is not received.\n\t\/\/ If no set then default to 3 retries.\n\tTimeoutRetries int\n\n\tMetric struct {\n\t\tPackets systree.PacketsMetric\n\t\tSessions systree.SessionsStat\n\t\tSession systree.SessionStat\n\t}\n\n\tOnDup types.DuplicateConfig\n\n\tPersist persistenceTypes.Sessions\n}\n\ntype sessionsList struct {\n\tlist map[string]*Type\n\tlock sync.RWMutex\n\tcount sync.WaitGroup\n}\n\n\/\/ Manager interface\ntype Manager struct {\n\tconfig Config\n\tsessions struct {\n\t\tactive sessionsList\n\t\tsuspended sessionsList\n\t}\n\tlock sync.Mutex\n\tquit chan struct{}\n}\n\n\/\/ NewManager alloc new\nfunc NewManager(cfg Config) (*Manager, error) {\n\t\/\/if config.Stat == nil {\n\t\/\/\treturn nil, errors.New(\"No stat provider\")\n\t\/\/}\n\n\tif cfg.Persist == nil {\n\t\treturn nil, errors.New(\"No persist provider\")\n\t}\n\n\tm := &Manager{\n\t\tconfig: cfg,\n\t\tquit: make(chan struct{}),\n\t}\n\n\tm.sessions.active.list = make(map[string]*Type)\n\tm.sessions.suspended.list = make(map[string]*Type)\n\n\t\/\/ 1. load persisted sessions\n\tpersistedSessions, err := m.config.Persist.GetAll()\n\tif err == nil {\n\t\tfor _, s := range persistedSessions {\n\t\t\t\/\/ 2. restore only those having persisted subscriptions\n\t\t\tif subscriptions, err := s.Subscriptions().Get(); err == nil && len(subscriptions) > 0 {\n\t\t\t\tsCfg := config{\n\t\t\t\t\ttopicsMgr: m.config.TopicsMgr,\n\t\t\t\t\tconnectTimeout: m.config.ConnectTimeout,\n\t\t\t\t\tackTimeout: m.config.AckTimeout,\n\t\t\t\t\ttimeoutRetries: m.config.TimeoutRetries,\n\t\t\t\t\tsubscriptions: subscriptions,\n\t\t\t\t\tid: s.ID(),\n\t\t\t\t\tcallbacks: managerCallbacks{\n\t\t\t\t\t\tonDisconnect: m.onDisconnect,\n\t\t\t\t\t\tonClose: m.onClose,\n\t\t\t\t\t\tonPublish: m.onPublish,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tsCfg.metric.session = m.config.Metric.Session\n\t\t\t\tsCfg.metric.packets = m.config.Metric.Packets\n\n\t\t\t\tif ses, err := newSession(sCfg); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't start persisted session [%s]: %s\", s.ID(), err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tm.sessions.suspended.list[s.ID()] = ses\n\t\t\t\t\tm.sessions.suspended.count.Add(1)\n\t\t\t\t\tif err = s.Subscriptions().Delete(); err != nil {\n\t\t\t\t\t\tappLog.Errorf(\"Couldn't wipe subscriptions after restore [%s]: %s\", s.ID(), err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn m, nil\n}\n\n\/\/ Start try start new session\nfunc (m *Manager) Start(msg *message.ConnectMessage, resp *message.ConnAckMessage, conn io.Closer) error {\n\tvar err error\n\tvar ses *Type\n\tpresent := false\n\n\tdefer func() {\n\t\tresp.SetSessionPresent(present)\n\n\t\tif err = m.writeMessage(conn, resp); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't write CONNACK: %s\", err.Error())\n\t\t}\n\t\tif err == nil {\n\t\t\tif ses != nil {\n\t\t\t\t\/\/ try start session\n\t\t\t\tif err = ses.start(msg, conn); err != nil {\n\t\t\t\t\t\/\/ should never get into this section.\n\t\t\t\t\t\/\/ if so this code does not work as expected :)\n\t\t\t\t\tappLog.Errorf(\"Something really bad happened: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-m.quit:\n\t\tresp.SetReturnCode(message.ErrServerUnavailable)\n\t\treturn errors.New(\"Not running\")\n\tdefault:\n\t}\n\n\tif resp.ReturnCode() != message.ConnectionAccepted {\n\t\treturn ErrNotAccepted\n\t}\n\n\t\/\/ serialize access to multiple starts\n\tdefer m.lock.Unlock()\n\tm.lock.Lock()\n\n\tid := string(msg.ClientID())\n\tif len(id) == 0 {\n\t\tid = m.genSessionID()\n\t}\n\n\tm.sessions.active.lock.Lock()\n\tses = m.sessions.active.list[id]\n\n\t\/\/ there is no such active session\n\t\/\/ proceed to either persisted or new one\n\tif ses == nil {\n\t\tses, present, err = m.allocSession(id, msg, resp)\n\t} else {\n\t\treplaced := true\n\t\t\/\/ session already exists thus duplicate case happened\n\t\tif !m.config.OnDup.Replace {\n\t\t\t\/\/ duplicate prohibited. send identifier rejected\n\t\t\tresp.SetReturnCode(message.ErrIdentifierRejected)\n\t\t\terr = ErrDupNotAllowed\n\t\t\treplaced = false\n\t\t} else {\n\t\t\t\/\/ duplicate allowed stop current session\n\t\t\tm.sessions.active.lock.Unlock()\n\t\t\tses.stop()\n\t\t\tm.sessions.active.lock.Lock()\n\n\t\t\t\/\/ previous session stopped\n\t\t\t\/\/ lets create new one\n\t\t\tses, present, err = m.allocSession(id, msg, resp)\n\t\t}\n\n\t\t\/\/ notify subscriber about dup attempt\n\t\tif m.config.OnDup.OnAttempt != nil {\n\t\t\tm.config.OnDup.OnAttempt(id, replaced)\n\t\t}\n\t}\n\n\tm.sessions.active.lock.Unlock()\n\n\treturn nil\n}\n\n\/\/ Shutdown manager\nfunc (m *Manager) Shutdown() error {\n\tdefer m.lock.Unlock()\n\tm.lock.Lock()\n\n\tselect {\n\tcase <-m.quit:\n\t\treturn errors.New(\"already stopped\")\n\tdefault:\n\t}\n\n\tclose(m.quit)\n\n\t\/\/ 1. Now signal all active sessions to finish\n\tm.sessions.active.lock.Lock()\n\tfor _, s := range m.sessions.active.list {\n\t\ts.stop()\n\t}\n\tm.sessions.active.lock.Unlock()\n\n\t\/\/ 2. Wait until all active sessions stopped\n\tm.sessions.active.count.Wait()\n\n\t\/\/ 3. wipe list\n\tm.sessions.active.list = make(map[string]*Type)\n\n\t\/\/ 4. Signal suspended sessions to exit\n\tfor _, s := range m.sessions.suspended.list {\n\t\ts.stop()\n\t}\n\n\t\/\/ 2. Wait until suspended sessions stopped\n\tm.sessions.suspended.count.Wait()\n\n\t\/\/ 4. wipe list\n\tm.sessions.suspended.list = make(map[string]*Type)\n\n\treturn nil\n}\n\nfunc (m *Manager) genSessionID() string {\n\tb := make([]byte, 15)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(b)\n}\n\nfunc (m *Manager) allocSession(id string, msg *message.ConnectMessage, resp *message.ConnAckMessage) (*Type, bool, error) {\n\tvar ses *Type\n\tpresent := false\n\tvar err error\n\n\tsConfig := config{\n\t\ttopicsMgr: m.config.TopicsMgr,\n\t\tconnectTimeout: m.config.ConnectTimeout,\n\t\tackTimeout: m.config.AckTimeout,\n\t\ttimeoutRetries: m.config.TimeoutRetries,\n\t\tsubscriptions: make(message.TopicsQoS),\n\t\tid: id,\n\t\tcallbacks: managerCallbacks{\n\t\t\tonDisconnect: m.onDisconnect,\n\t\t\tonClose: m.onClose,\n\t\t\tonPublish: m.onPublish,\n\t\t},\n\t}\n\n\tsConfig.metric.session = m.config.Metric.Session\n\tsConfig.metric.packets = m.config.Metric.Packets\n\n\tvar pSes persistenceTypes.Session\n\n\t\/\/ if session is non-clean look for persistence\n\tif !msg.CleanSession() {\n\t\t\/\/ 1. search over suspended sessions with active subscriptions\n\t\tm.sessions.suspended.lock.Lock()\n\t\tif s, ok := m.sessions.suspended.list[id]; ok {\n\t\t\t\/\/ session exists. acquire it\n\t\t\tdelete(m.sessions.suspended.list, id)\n\t\t\tm.sessions.suspended.count.Done()\n\n\t\t\tses = s\n\t\t\tpresent = true\n\n\t\t\t\/\/ do not check error here.\n\t\t\t\/\/ if session has not been found there is no any persisted messages for it\n\t\t\tpSes, _ = m.config.Persist.Get(id)\n\t\t} else {\n\t\t\t\/\/ no such session in persisted list. It might be shutdown\n\t\t\tif pSes, err = m.config.Persist.Get(id); err != nil {\n\t\t\t\t\/\/ No such session exists at all. Just create new\n\t\t\t\tappLog.Debugf(\"Create new persist entry for [%s]\", id)\n\t\t\t\tif _, err = m.config.Persist.New(id); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't create persis object for session [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Session exists and is in shutdown state\n\t\t\t\tappLog.Debugf(\"Restore session [%s] from shutdown\", id)\n\t\t\t\tpresent = true\n\t\t\t}\n\t\t}\n\n\t\tm.sessions.suspended.lock.Unlock()\n\t} else {\n\t\t\/\/ Session might change from non-clean to clean state\n\t\t\/\/ if so make sure it does not exists in persistence db\n\t\t\/\/ check if it was suspended\n\t\tm.sessions.suspended.lock.Lock()\n\t\tif suspended, ok := m.sessions.suspended.list[id]; ok {\n\t\t\tsuspended.stop()\n\t\t\tdelete(m.sessions.suspended.list, id)\n\t\t}\n\t\tm.sessions.suspended.lock.Unlock()\n\t\tif err = m.config.Persist.Delete(id); err != nil {\n\t\t\tappLog.Tracef(\"Couldn't wipe session after restore [%s]: %s\", id, err.Error())\n\t\t}\n\t}\n\n\tif ses == nil {\n\t\tif ses, err = newSession(sConfig); err != nil {\n\t\t\tses = nil\n\t\t\tresp.SetReturnCode(message.ErrServerUnavailable)\n\t\t\tif !msg.CleanSession() {\n\t\t\t\tif err = m.config.Persist.Delete(id); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't wipe session after restore [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif ses != nil {\n\t\t\/\/ restore messages if it was shutdown non-clean session\n\t\tif pSes != nil {\n\t\t\tif msg, err := pSes.Messages().Load(); err == nil {\n\t\t\t\tses.restore(&msg)\n\t\t\t\tif err = pSes.Messages().Delete(); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't wipe messages after restore [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm.sessions.active.list[id] = ses\n\t\tm.sessions.active.count.Add(1)\n\t}\n\n\treturn ses, present, err\n}\n\n\/\/ close is only invoked for non-clean session\nfunc (m *Manager) onClose(id string, s message.TopicsQoS) {\n\tdefer m.sessions.suspended.count.Done()\n\n\tses, err := m.config.Persist.Get(id)\n\tif err != nil {\n\t\tappLog.Errorf(\"Trying to persist session that has not been initiated for persistence [%s]: %s\", id, err.Error())\n\t} else {\n\t\tif err = ses.Subscriptions().Add(s); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't persist subscriptions [%s]: %s\", id, err.Error())\n\t\t}\n\t}\n}\n\nfunc (m *Manager) onPublish(id string, msg *message.PublishMessage) {\n\tif ses, err := m.config.Persist.Get(id); err == nil {\n\t\tif err = ses.Messages().Store(\"out\", []message.Provider{msg}); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't store messages [%s]: %s\", id, err.Error())\n\t\t}\n\t} else {\n\t\tappLog.Errorf(\"Couldn't persist message for shutdown session [%s]: %s\", id, err.Error())\n\t}\n}\n\nfunc (m *Manager) onDisconnect(id string, messages *persistenceTypes.SessionMessages, shutdown bool) {\n\tdefer m.sessions.active.count.Done()\n\n\tif messages != nil {\n\t\tif ses, err := m.config.Persist.Get(id); err != nil {\n\t\t\tappLog.Errorf(\"Trying to persist session that has not been initiated for persistence [%s]: %s\", id, err.Error())\n\t\t} else {\n\t\t\tif len(messages.Out.Messages) > 0 {\n\t\t\t\tif err = ses.Messages().Store(\"out\", messages.Out.Messages); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't persist messages [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(messages.In.Messages) > 0 {\n\t\t\t\tif err = ses.Messages().Store(\"in\", messages.In.Messages); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't persist messages [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !shutdown {\n\t\t\t\/\/ copy session to persisted list\n\t\t\tm.sessions.suspended.lock.Lock()\n\t\t\tm.sessions.active.lock.Lock()\n\t\t\tm.sessions.suspended.list[id] = m.sessions.active.list[id]\n\t\t\tm.sessions.active.lock.Unlock()\n\t\t\tm.sessions.suspended.lock.Unlock()\n\t\t\tm.sessions.suspended.count.Add(1)\n\t\t}\n\t}\n\n\tselect {\n\tcase <-m.quit:\n\t\t\/\/ if manager is about to shutdown do nothing\n\tdefault:\n\t\tm.sessions.active.lock.Lock()\n\t\tdelete(m.sessions.active.list, id)\n\t\tm.sessions.active.lock.Unlock()\n\t}\n}\n\n\/\/ WriteMessage into connection\nfunc (m *Manager) writeMessage(conn io.Closer, msg message.Provider) error {\n\tbuf := make([]byte, msg.Len())\n\t_, err := msg.Encode(buf)\n\tif err != nil {\n\t\tappLog.Debugf(\"Write error: %v\", err)\n\t\treturn err\n\t}\n\tappLog.Debugf(\"Writing: %s\", msg)\n\n\treturn m.writeMessageBuffer(conn, buf)\n}\n\nfunc (m *Manager) writeMessageBuffer(c io.Closer, b []byte) error {\n\tif c == nil {\n\t\treturn surgemq.ErrInvalidConnectionType\n\t}\n\n\tconn, ok := c.(net.Conn)\n\tif !ok {\n\t\treturn surgemq.ErrInvalidConnectionType\n\t}\n\n\t_, err := conn.Write(b)\n\treturn err\n}\nFix var shadow\/\/ Copyright (c) 2014 The SurgeMQ Authors. All rights reserved.\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 session\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"github.com\/troian\/surgemq\"\n\t\"github.com\/troian\/surgemq\/message\"\n\tpersistenceTypes \"github.com\/troian\/surgemq\/persistence\/types\"\n\t\"github.com\/troian\/surgemq\/systree\"\n\t\"github.com\/troian\/surgemq\/topics\"\n\t\"github.com\/troian\/surgemq\/types\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ ErrNotAccepted new connection does not meet requirements\n\tErrNotAccepted = errors.New(\"Connection not accepted\")\n\n\t\/\/ ErrDupNotAllowed case when new client with existing ID connected\n\tErrDupNotAllowed = errors.New(\"duplicate not allowed\")\n)\n\n\/\/ Config manager configuration\ntype Config struct {\n\t\/\/ Topics manager for all the client subscriptions\n\tTopicsMgr *topics.Manager\n\n\t\/\/ The number of seconds to wait for the CONNACK message before disconnecting.\n\t\/\/ If not set then default to 2 seconds.\n\tConnectTimeout int\n\n\t\/\/ The number of seconds to wait for any ACK messages before failing.\n\t\/\/ If not set then default to 20 seconds.\n\tAckTimeout int\n\n\t\/\/ The number of times to retry sending a packet if ACK is not received.\n\t\/\/ If no set then default to 3 retries.\n\tTimeoutRetries int\n\n\tMetric struct {\n\t\tPackets systree.PacketsMetric\n\t\tSessions systree.SessionsStat\n\t\tSession systree.SessionStat\n\t}\n\n\tOnDup types.DuplicateConfig\n\n\tPersist persistenceTypes.Sessions\n}\n\ntype sessionsList struct {\n\tlist map[string]*Type\n\tlock sync.RWMutex\n\tcount sync.WaitGroup\n}\n\n\/\/ Manager interface\ntype Manager struct {\n\tconfig Config\n\tsessions struct {\n\t\tactive sessionsList\n\t\tsuspended sessionsList\n\t}\n\tlock sync.Mutex\n\tquit chan struct{}\n}\n\n\/\/ NewManager alloc new\nfunc NewManager(cfg Config) (*Manager, error) {\n\t\/\/if config.Stat == nil {\n\t\/\/\treturn nil, errors.New(\"No stat provider\")\n\t\/\/}\n\n\tif cfg.Persist == nil {\n\t\treturn nil, errors.New(\"No persist provider\")\n\t}\n\n\tm := &Manager{\n\t\tconfig: cfg,\n\t\tquit: make(chan struct{}),\n\t}\n\n\tm.sessions.active.list = make(map[string]*Type)\n\tm.sessions.suspended.list = make(map[string]*Type)\n\n\t\/\/ 1. load persisted sessions\n\tpersistedSessions, err := m.config.Persist.GetAll()\n\tif err == nil {\n\t\tfor _, s := range persistedSessions {\n\t\t\t\/\/ 2. restore only those having persisted subscriptions\n\t\t\tif subscriptions, err := s.Subscriptions().Get(); err == nil && len(subscriptions) > 0 {\n\t\t\t\tsCfg := config{\n\t\t\t\t\ttopicsMgr: m.config.TopicsMgr,\n\t\t\t\t\tconnectTimeout: m.config.ConnectTimeout,\n\t\t\t\t\tackTimeout: m.config.AckTimeout,\n\t\t\t\t\ttimeoutRetries: m.config.TimeoutRetries,\n\t\t\t\t\tsubscriptions: subscriptions,\n\t\t\t\t\tid: s.ID(),\n\t\t\t\t\tcallbacks: managerCallbacks{\n\t\t\t\t\t\tonDisconnect: m.onDisconnect,\n\t\t\t\t\t\tonClose: m.onClose,\n\t\t\t\t\t\tonPublish: m.onPublish,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tsCfg.metric.session = m.config.Metric.Session\n\t\t\t\tsCfg.metric.packets = m.config.Metric.Packets\n\n\t\t\t\tif ses, err := newSession(sCfg); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't start persisted session [%s]: %s\", s.ID(), err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tm.sessions.suspended.list[s.ID()] = ses\n\t\t\t\t\tm.sessions.suspended.count.Add(1)\n\t\t\t\t\tif err = s.Subscriptions().Delete(); err != nil {\n\t\t\t\t\t\tappLog.Errorf(\"Couldn't wipe subscriptions after restore [%s]: %s\", s.ID(), err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn m, nil\n}\n\n\/\/ Start try start new session\nfunc (m *Manager) Start(msg *message.ConnectMessage, resp *message.ConnAckMessage, conn io.Closer) error {\n\tvar err error\n\tvar ses *Type\n\tpresent := false\n\n\tdefer func() {\n\t\tresp.SetSessionPresent(present)\n\n\t\tif err = m.writeMessage(conn, resp); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't write CONNACK: %s\", err.Error())\n\t\t}\n\t\tif err == nil {\n\t\t\tif ses != nil {\n\t\t\t\t\/\/ try start session\n\t\t\t\tif err = ses.start(msg, conn); err != nil {\n\t\t\t\t\t\/\/ should never get into this section.\n\t\t\t\t\t\/\/ if so this code does not work as expected :)\n\t\t\t\t\tappLog.Errorf(\"Something really bad happened: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-m.quit:\n\t\tresp.SetReturnCode(message.ErrServerUnavailable)\n\t\treturn errors.New(\"Not running\")\n\tdefault:\n\t}\n\n\tif resp.ReturnCode() != message.ConnectionAccepted {\n\t\treturn ErrNotAccepted\n\t}\n\n\t\/\/ serialize access to multiple starts\n\tdefer m.lock.Unlock()\n\tm.lock.Lock()\n\n\tid := string(msg.ClientID())\n\tif len(id) == 0 {\n\t\tid = m.genSessionID()\n\t}\n\n\tm.sessions.active.lock.Lock()\n\tses = m.sessions.active.list[id]\n\n\t\/\/ there is no such active session\n\t\/\/ proceed to either persisted or new one\n\tif ses == nil {\n\t\tses, present, err = m.allocSession(id, msg, resp)\n\t} else {\n\t\treplaced := true\n\t\t\/\/ session already exists thus duplicate case happened\n\t\tif !m.config.OnDup.Replace {\n\t\t\t\/\/ duplicate prohibited. send identifier rejected\n\t\t\tresp.SetReturnCode(message.ErrIdentifierRejected)\n\t\t\terr = ErrDupNotAllowed\n\t\t\treplaced = false\n\t\t} else {\n\t\t\t\/\/ duplicate allowed stop current session\n\t\t\tm.sessions.active.lock.Unlock()\n\t\t\tses.stop()\n\t\t\tm.sessions.active.lock.Lock()\n\n\t\t\t\/\/ previous session stopped\n\t\t\t\/\/ lets create new one\n\t\t\tses, present, err = m.allocSession(id, msg, resp)\n\t\t}\n\n\t\t\/\/ notify subscriber about dup attempt\n\t\tif m.config.OnDup.OnAttempt != nil {\n\t\t\tm.config.OnDup.OnAttempt(id, replaced)\n\t\t}\n\t}\n\n\tm.sessions.active.lock.Unlock()\n\n\treturn nil\n}\n\n\/\/ Shutdown manager\nfunc (m *Manager) Shutdown() error {\n\tdefer m.lock.Unlock()\n\tm.lock.Lock()\n\n\tselect {\n\tcase <-m.quit:\n\t\treturn errors.New(\"already stopped\")\n\tdefault:\n\t}\n\n\tclose(m.quit)\n\n\t\/\/ 1. Now signal all active sessions to finish\n\tm.sessions.active.lock.Lock()\n\tfor _, s := range m.sessions.active.list {\n\t\ts.stop()\n\t}\n\tm.sessions.active.lock.Unlock()\n\n\t\/\/ 2. Wait until all active sessions stopped\n\tm.sessions.active.count.Wait()\n\n\t\/\/ 3. wipe list\n\tm.sessions.active.list = make(map[string]*Type)\n\n\t\/\/ 4. Signal suspended sessions to exit\n\tfor _, s := range m.sessions.suspended.list {\n\t\ts.stop()\n\t}\n\n\t\/\/ 2. Wait until suspended sessions stopped\n\tm.sessions.suspended.count.Wait()\n\n\t\/\/ 4. wipe list\n\tm.sessions.suspended.list = make(map[string]*Type)\n\n\treturn nil\n}\n\nfunc (m *Manager) genSessionID() string {\n\tb := make([]byte, 15)\n\tif _, err := io.ReadFull(rand.Reader, b); err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(b)\n}\n\nfunc (m *Manager) allocSession(id string, msg *message.ConnectMessage, resp *message.ConnAckMessage) (*Type, bool, error) {\n\tvar ses *Type\n\tpresent := false\n\tvar err error\n\n\tsConfig := config{\n\t\ttopicsMgr: m.config.TopicsMgr,\n\t\tconnectTimeout: m.config.ConnectTimeout,\n\t\tackTimeout: m.config.AckTimeout,\n\t\ttimeoutRetries: m.config.TimeoutRetries,\n\t\tsubscriptions: make(message.TopicsQoS),\n\t\tid: id,\n\t\tcallbacks: managerCallbacks{\n\t\t\tonDisconnect: m.onDisconnect,\n\t\t\tonClose: m.onClose,\n\t\t\tonPublish: m.onPublish,\n\t\t},\n\t}\n\n\tsConfig.metric.session = m.config.Metric.Session\n\tsConfig.metric.packets = m.config.Metric.Packets\n\n\tvar pSes persistenceTypes.Session\n\n\t\/\/ if session is non-clean look for persistence\n\tif !msg.CleanSession() {\n\t\t\/\/ 1. search over suspended sessions with active subscriptions\n\t\tm.sessions.suspended.lock.Lock()\n\t\tif s, ok := m.sessions.suspended.list[id]; ok {\n\t\t\t\/\/ session exists. acquire it\n\t\t\tdelete(m.sessions.suspended.list, id)\n\t\t\tm.sessions.suspended.count.Done()\n\n\t\t\tses = s\n\t\t\tpresent = true\n\n\t\t\t\/\/ do not check error here.\n\t\t\t\/\/ if session has not been found there is no any persisted messages for it\n\t\t\tpSes, _ = m.config.Persist.Get(id)\n\t\t} else {\n\t\t\t\/\/ no such session in persisted list. It might be shutdown\n\t\t\tif pSes, err = m.config.Persist.Get(id); err != nil {\n\t\t\t\t\/\/ No such session exists at all. Just create new\n\t\t\t\tappLog.Debugf(\"Create new persist entry for [%s]\", id)\n\t\t\t\tif _, err = m.config.Persist.New(id); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't create persis object for session [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Session exists and is in shutdown state\n\t\t\t\tappLog.Debugf(\"Restore session [%s] from shutdown\", id)\n\t\t\t\tpresent = true\n\t\t\t}\n\t\t}\n\n\t\tm.sessions.suspended.lock.Unlock()\n\t} else {\n\t\t\/\/ Session might change from non-clean to clean state\n\t\t\/\/ if so make sure it does not exists in persistence db\n\t\t\/\/ check if it was suspended\n\t\tm.sessions.suspended.lock.Lock()\n\t\tif suspended, ok := m.sessions.suspended.list[id]; ok {\n\t\t\tsuspended.stop()\n\t\t\tdelete(m.sessions.suspended.list, id)\n\t\t}\n\t\tm.sessions.suspended.lock.Unlock()\n\t\tif err = m.config.Persist.Delete(id); err != nil {\n\t\t\tappLog.Tracef(\"Couldn't wipe session after restore [%s]: %s\", id, err.Error())\n\t\t}\n\t}\n\n\tif ses == nil {\n\t\tif ses, err = newSession(sConfig); err != nil {\n\t\t\tses = nil\n\t\t\tresp.SetReturnCode(message.ErrServerUnavailable)\n\t\t\tif !msg.CleanSession() {\n\t\t\t\tif err = m.config.Persist.Delete(id); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't wipe session after restore [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif ses != nil {\n\t\t\/\/ restore messages if it was shutdown non-clean session\n\t\tif pSes != nil {\n\t\t\tvar storedMessages persistenceTypes.SessionMessages\n\t\t\tif storedMessages, err = pSes.Messages().Load(); err == nil {\n\t\t\t\tses.restore(&storedMessages)\n\t\t\t\tif err = pSes.Messages().Delete(); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't wipe messages after restore [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm.sessions.active.list[id] = ses\n\t\tm.sessions.active.count.Add(1)\n\t}\n\n\treturn ses, present, err\n}\n\n\/\/ close is only invoked for non-clean session\nfunc (m *Manager) onClose(id string, s message.TopicsQoS) {\n\tdefer m.sessions.suspended.count.Done()\n\n\tses, err := m.config.Persist.Get(id)\n\tif err != nil {\n\t\tappLog.Errorf(\"Trying to persist session that has not been initiated for persistence [%s]: %s\", id, err.Error())\n\t} else {\n\t\tif err = ses.Subscriptions().Add(s); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't persist subscriptions [%s]: %s\", id, err.Error())\n\t\t}\n\t}\n}\n\nfunc (m *Manager) onPublish(id string, msg *message.PublishMessage) {\n\tif ses, err := m.config.Persist.Get(id); err == nil {\n\t\tif err = ses.Messages().Store(\"out\", []message.Provider{msg}); err != nil {\n\t\t\tappLog.Errorf(\"Couldn't store messages [%s]: %s\", id, err.Error())\n\t\t}\n\t} else {\n\t\tappLog.Errorf(\"Couldn't persist message for shutdown session [%s]: %s\", id, err.Error())\n\t}\n}\n\nfunc (m *Manager) onDisconnect(id string, messages *persistenceTypes.SessionMessages, shutdown bool) {\n\tdefer m.sessions.active.count.Done()\n\n\tif messages != nil {\n\t\tif ses, err := m.config.Persist.Get(id); err != nil {\n\t\t\tappLog.Errorf(\"Trying to persist session that has not been initiated for persistence [%s]: %s\", id, err.Error())\n\t\t} else {\n\t\t\tif len(messages.Out.Messages) > 0 {\n\t\t\t\tif err = ses.Messages().Store(\"out\", messages.Out.Messages); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't persist messages [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(messages.In.Messages) > 0 {\n\t\t\t\tif err = ses.Messages().Store(\"in\", messages.In.Messages); err != nil {\n\t\t\t\t\tappLog.Errorf(\"Couldn't persist messages [%s]: %s\", id, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !shutdown {\n\t\t\t\/\/ copy session to persisted list\n\t\t\tm.sessions.suspended.lock.Lock()\n\t\t\tm.sessions.active.lock.Lock()\n\t\t\tm.sessions.suspended.list[id] = m.sessions.active.list[id]\n\t\t\tm.sessions.active.lock.Unlock()\n\t\t\tm.sessions.suspended.lock.Unlock()\n\t\t\tm.sessions.suspended.count.Add(1)\n\t\t}\n\t}\n\n\tselect {\n\tcase <-m.quit:\n\t\t\/\/ if manager is about to shutdown do nothing\n\tdefault:\n\t\tm.sessions.active.lock.Lock()\n\t\tdelete(m.sessions.active.list, id)\n\t\tm.sessions.active.lock.Unlock()\n\t}\n}\n\n\/\/ WriteMessage into connection\nfunc (m *Manager) writeMessage(conn io.Closer, msg message.Provider) error {\n\tbuf := make([]byte, msg.Len())\n\t_, err := msg.Encode(buf)\n\tif err != nil {\n\t\tappLog.Debugf(\"Write error: %v\", err)\n\t\treturn err\n\t}\n\tappLog.Debugf(\"Writing: %s\", msg)\n\n\treturn m.writeMessageBuffer(conn, buf)\n}\n\nfunc (m *Manager) writeMessageBuffer(c io.Closer, b []byte) error {\n\tif c == nil {\n\t\treturn surgemq.ErrInvalidConnectionType\n\t}\n\n\tconn, ok := c.(net.Conn)\n\tif !ok {\n\t\treturn surgemq.ErrInvalidConnectionType\n\t}\n\n\t_, err := conn.Write(b)\n\treturn err\n}\n<|endoftext|>"} {"text":"package ssh\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/blacknon\/lssh\/conf\"\n\t\"github.com\/shavac\/gexpect\"\n)\n\n\/\/ OS ssh command Rapper\nfunc ConnectSsh(connectServer string, serverList conf.Config) {\n\tconnectUser := serverList.Server[connectServer].User\n\tconnectAddr := serverList.Server[connectServer].Addr\n\tvar connectPort string\n\tif serverList.Server[connectServer].Port == \"\" {\n\t\tconnectPort = \"22\"\n\t} else {\n\t\tconnectPort = serverList.Server[connectServer].Port\n\t}\n\tconnectPass := serverList.Server[connectServer].Pass\n\tconnectKey := serverList.Server[connectServer].Key\n\n\tconnectHost := connectUser + \"@\" + connectAddr\n\n\tif connectKey != \"\" {\n\t\t\/\/child, _ := gexpect.NewSubProcess(\"\/usr\/bin\/ssh\", \"-i\", connectKey, connectHost, \"-p\", connectPort)\n\t\tchild, _ := gexpect.NewSubProcess(\"\/usr\/bin\/ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-i\", connectKey, connectHost, \"-p\", connectPort)\n\t\tif err := child.Start(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tdefer child.Close()\n\n\t\tchild.InteractTimeout(86400 * time.Second)\n\t} else {\n\t\t\/\/child, _ := gexpect.NewSubProcess(\"\/usr\/bin\/ssh\", connectHost, \"-p\", connectPort)\n\t\tchild, _ := gexpect.NewSubProcess(\"\/usr\/bin\/ssh\", \"-o\", \"StrictHostKeyChecking=no\", connectHost, \"-p\", connectPort)\n\t\tif err := child.Start(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tdefer child.Close()\n\t\tif connectPass != \"\" {\n\t\t\tif idx, _ := child.ExpectTimeout(20*time.Second, regexp.MustCompile(\"word:\")); idx >= 0 {\n\t\t\t\tchild.SendLine(connectPass)\n\t\t\t}\n\t\t}\n\t\tchild.InteractTimeout(86400 * time.Second)\n\t}\n}\nssh command refactpackage ssh\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/blacknon\/lssh\/conf\"\n\t\"github.com\/shavac\/gexpect\"\n)\n\n\/\/ OS ssh command Rapper\nfunc ConnectSsh(connectServer string, serverList conf.Config) {\n\tconnectUser := serverList.Server[connectServer].User\n\tconnectAddr := serverList.Server[connectServer].Addr\n\tvar connectPort string\n\tif serverList.Server[connectServer].Port == \"\" {\n\t\tconnectPort = \"22\"\n\t} else {\n\t\tconnectPort = serverList.Server[connectServer].Port\n\t}\n\tconnectPass := serverList.Server[connectServer].Pass\n\tconnectKey := serverList.Server[connectServer].Key\n\tconnectHost := connectUser + \"@\" + connectAddr\n\n\t\/\/ ssh command Args\n\tconnectArgStr := \"\"\n\tif connectKey != \"\" {\n\t\tconnectArgStr = \"-i \" + connectKey + \" \" + connectHost + \" -p \" + connectPort\n\t} else {\n\t\tconnectArgStr = connectHost + \" -p \" + connectPort\n\t}\n\tconnectArgMap := strings.Split(connectArgStr, \" \")\n\n\t\/\/ exec ssh command\n\tchild, _ := gexpect.NewSubProcess(\"\/usr\/bin\/ssh\", connectArgMap...)\n\tif err := child.Start(); err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer child.Close()\n\n\t\/\/ Password Input\n\tif connectPass != \"\" {\n\t\tif idx, _ := child.ExpectTimeout(20*time.Second, regexp.MustCompile(\"word:\")); idx >= 0 {\n\t\t\tchild.SendLine(connectPass)\n\t\t}\n\t}\n\n\t\/\/ timeout\n\tchild.InteractTimeout(86400 * time.Second)\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) nano Author. All Rights Reserved.\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 all\n\/\/ 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 THE\n\/\/ SOFTWARE.\n\npackage session\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/lonnng\/nano\/service\"\n)\n\n\/\/ NetworkEntity represent low-level network instance\ntype NetworkEntity interface {\n\tPush(route string, v interface{}) error\n\tResponse(v interface{}) error\n\tClose() error\n\tRemoteAddr() net.Addr\n}\n\nvar (\n\t\/\/ErrIllegalUID represents a invalid uid\n\tErrIllegalUID = errors.New(\"illegal uid\")\n)\n\n\/\/ Session represents a client session which could storage temp data during low-level\n\/\/ keep connected, all data will be released when the low-level connection was broken.\n\/\/ Session instance related to the client will be passed to Handler method as the first\n\/\/ parameter.\ntype Session struct {\n\tsync.RWMutex \/\/ protect data\n\tid int64 \/\/ session global unique id\n\tuid int64 \/\/ binding user id\n\tLastRID uint \/\/ last request id\n\tlastTime int64 \/\/ last heartbeat time\n\tentity NetworkEntity \/\/ low-level network entity\n\tdata map[string]interface{} \/\/ session data store\n}\n\n\/\/ New returns a new session instance\n\/\/ a NetworkEntity represent low-level network instance\nfunc New(entity NetworkEntity) *Session {\n\treturn &Session{\n\t\tid: service.Connections.SessionID(),\n\t\tentity: entity,\n\t\tdata: make(map[string]interface{}),\n\t\tlastTime: time.Now().Unix(),\n\t}\n}\n\n\/\/ Push message to client\nfunc (s *Session) Push(route string, v interface{}) error {\n\treturn s.entity.Push(route, v)\n}\n\n\/\/ Response message to client\nfunc (s *Session) Response(v interface{}) error {\n\treturn s.entity.Response(v)\n}\n\n\/\/ ID returns the session id\nfunc (s *Session) ID() int64 {\n\treturn s.id\n}\n\n\/\/ Uid returns UID that bind to current session\nfunc (s *Session) Uid() int64 {\n\treturn atomic.LoadInt64(&s.uid)\n}\n\n\/\/ Bind bind UID to current session\nfunc (s *Session) Bind(uid int64) error {\n\tif uid < 1 {\n\t\treturn ErrIllegalUID\n\t}\n\n\tatomic.StoreInt64(&s.uid, uid)\n\treturn nil\n}\n\n\/\/ Close terminate current session, session related data will not be released,\n\/\/ all related data should be Clear explicitly in Session closed callback\nfunc (s *Session) Close() {\n\ts.entity.Close()\n}\n\n\/\/ RemoteAddr returns the remote network address.\nfunc (s *Session) RemoteAddr() net.Addr {\n\treturn s.entity.RemoteAddr()\n}\n\n\/\/ Remove delete data associated with the key from session storage\nfunc (s *Session) Remove(key string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tdelete(s.data, key)\n}\n\n\/\/ Set associates value with the key in session storage\nfunc (s *Session) Set(key string, value interface{}) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.data[key] = value\n}\n\n\/\/ HasKey decides whether a key has associated value\nfunc (s *Session) HasKey(key string) bool {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\t_, has := s.data[key]\n\treturn has\n}\n\n\/\/ Int returns the value associated with the key as a int.\nfunc (s *Session) Int(key string) int {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int8 returns the value associated with the key as a int8.\nfunc (s *Session) Int8(key string) int8 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int8)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int16 returns the value associated with the key as a int16.\nfunc (s *Session) Int16(key string) int16 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int16)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int32 returns the value associated with the key as a int32.\nfunc (s *Session) Int32(key string) int32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int64 returns the value associated with the key as a int64.\nfunc (s *Session) Int64(key string) int64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint returns the value associated with the key as a uint.\nfunc (s *Session) Uint(key string) uint {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint8 returns the value associated with the key as a uint8.\nfunc (s *Session) Uint8(key string) uint8 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint8)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint16 returns the value associated with the key as a uint16.\nfunc (s *Session) Uint16(key string) uint16 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint16)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint32 returns the value associated with the key as a uint32.\nfunc (s *Session) Uint32(key string) uint32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint64 returns the value associated with the key as a uint64.\nfunc (s *Session) Uint64(key string) uint64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Float32 returns the value associated with the key as a float32.\nfunc (s *Session) Float32(key string) float32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(float32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Float64 returns the value associated with the key as a float64.\nfunc (s *Session) Float64(key string) float64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(float64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ String returns the value associated with the key as a string.\nfunc (s *Session) String(key string) string {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\tvalue, ok := v.(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn value\n}\n\n\/\/ String returns the value associated with the key as a interface{}.\nfunc (s *Session) Value(key string) interface{} {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.data[key]\n}\n\n\/\/ State returns all session state\nfunc (s *Session) State() map[string]interface{} {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.data\n}\n\n\/\/ Restore session state after reconnect\nfunc (s *Session) Restore(data map[string]interface{}) {\n\ts.data = data\n}\n\n\/\/ Clear releases all data related to current session\nfunc (s *Session) Clear() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.uid = 0\n\ts.data = map[string]interface{}{}\n}\nmore comments\/\/ Copyright (c) nano Author. All Rights Reserved.\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 all\n\/\/ 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 THE\n\/\/ SOFTWARE.\n\npackage session\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/lonnng\/nano\/service\"\n)\n\n\/\/ NetworkEntity represent low-level network instance\ntype NetworkEntity interface {\n\tPush(route string, v interface{}) error\n\tResponse(v interface{}) error\n\tClose() error\n\tRemoteAddr() net.Addr\n}\n\nvar (\n\t\/\/ErrIllegalUID represents a invalid uid\n\tErrIllegalUID = errors.New(\"illegal uid\")\n)\n\n\/\/ Session represents a client session which could storage temp data during low-level\n\/\/ keep connected, all data will be released when the low-level connection was broken.\n\/\/ Session instance related to the client will be passed to Handler method as the first\n\/\/ parameter.\ntype Session struct {\n\tsync.RWMutex \/\/ protect data\n\tid int64 \/\/ session global unique id\n\tuid int64 \/\/ binding user id\n\tLastRID uint \/\/ last request id\n\tlastTime int64 \/\/ last heartbeat time\n\tentity NetworkEntity \/\/ low-level network entity\n\tdata map[string]interface{} \/\/ session data store\n}\n\n\/\/ New returns a new session instance\n\/\/ a NetworkEntity represent low-level network instance\nfunc New(entity NetworkEntity) *Session {\n\treturn &Session{\n\t\tid: service.Connections.SessionID(),\n\t\tentity: entity,\n\t\tdata: make(map[string]interface{}),\n\t\tlastTime: time.Now().Unix(),\n\t}\n}\n\n\/\/ Push message to client\nfunc (s *Session) Push(route string, v interface{}) error {\n\treturn s.entity.Push(route, v)\n}\n\n\/\/ Response message to client\nfunc (s *Session) Response(v interface{}) error {\n\treturn s.entity.Response(v)\n}\n\n\/\/ ID returns the session id\nfunc (s *Session) ID() int64 {\n\treturn s.id\n}\n\n\/\/ Uid returns UID that bind to current session\nfunc (s *Session) Uid() int64 {\n\treturn atomic.LoadInt64(&s.uid)\n}\n\n\/\/ Bind bind UID to current session\nfunc (s *Session) Bind(uid int64) error {\n\tif uid < 1 {\n\t\treturn ErrIllegalUID\n\t}\n\n\tatomic.StoreInt64(&s.uid, uid)\n\treturn nil\n}\n\n\/\/ Close terminate current session, session related data will not be released,\n\/\/ all related data should be Clear explicitly in Session closed callback\nfunc (s *Session) Close() {\n\ts.entity.Close()\n}\n\n\/\/ RemoteAddr returns the remote network address.\nfunc (s *Session) RemoteAddr() net.Addr {\n\treturn s.entity.RemoteAddr()\n}\n\n\/\/ Remove delete data associated with the key from session storage\nfunc (s *Session) Remove(key string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tdelete(s.data, key)\n}\n\n\/\/ Set associates value with the key in session storage\nfunc (s *Session) Set(key string, value interface{}) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.data[key] = value\n}\n\n\/\/ HasKey decides whether a key has associated value\nfunc (s *Session) HasKey(key string) bool {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\t_, has := s.data[key]\n\treturn has\n}\n\n\/\/ Int returns the value associated with the key as a int.\nfunc (s *Session) Int(key string) int {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int8 returns the value associated with the key as a int8.\nfunc (s *Session) Int8(key string) int8 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int8)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int16 returns the value associated with the key as a int16.\nfunc (s *Session) Int16(key string) int16 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int16)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int32 returns the value associated with the key as a int32.\nfunc (s *Session) Int32(key string) int32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Int64 returns the value associated with the key as a int64.\nfunc (s *Session) Int64(key string) int64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(int64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint returns the value associated with the key as a uint.\nfunc (s *Session) Uint(key string) uint {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint8 returns the value associated with the key as a uint8.\nfunc (s *Session) Uint8(key string) uint8 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint8)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint16 returns the value associated with the key as a uint16.\nfunc (s *Session) Uint16(key string) uint16 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint16)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint32 returns the value associated with the key as a uint32.\nfunc (s *Session) Uint32(key string) uint32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Uint64 returns the value associated with the key as a uint64.\nfunc (s *Session) Uint64(key string) uint64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(uint64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Float32 returns the value associated with the key as a float32.\nfunc (s *Session) Float32(key string) float32 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(float32)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ Float64 returns the value associated with the key as a float64.\nfunc (s *Session) Float64(key string) float64 {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tvalue, ok := v.(float64)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn value\n}\n\n\/\/ String returns the value associated with the key as a string.\nfunc (s *Session) String(key string) string {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tv, ok := s.data[key]\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\tvalue, ok := v.(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn value\n}\n\n\/\/ Value returns the value associated with the key as a interface{}.\nfunc (s *Session) Value(key string) interface{} {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.data[key]\n}\n\n\/\/ State returns all session state\nfunc (s *Session) State() map[string]interface{} {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.data\n}\n\n\/\/ Restore session state after reconnect\nfunc (s *Session) Restore(data map[string]interface{}) {\n\ts.data = data\n}\n\n\/\/ Clear releases all data related to current session\nfunc (s *Session) Clear() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.uid = 0\n\ts.data = map[string]interface{}{}\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/heroku\/busl\/broker\"\n\t\"github.com\/heroku\/busl\/util\"\n\t. \"gopkg.in\/check.v1\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype HttpServerSuite struct{}\n\nvar _ = Suite(&HttpServerSuite{})\nvar sf = fmt.Sprintf\n\nfunc newRequest(method, url, body string) *http.Request {\n\treturn newRequestFromReader(method, url, bytes.NewBufferString(body))\n}\n\nfunc newRequestFromReader(method, url string, reader io.Reader) *http.Request {\n\trequest, _ := http.NewRequest(method, url, reader)\n\turlParts := strings.Split(url, \"\/\")\n\tif method == \"POST\" {\n\t\trequest.TransferEncoding = []string{\"chunked\"}\n\t\trequest.Header.Add(\"Transfer-Encoding\", \"chunked\")\n\t}\n\tif len(urlParts) == 3 {\n\t\tstreamId := urlParts[2]\n\t\tsetStreamId(request, streamId)\n\t}\n\treturn request\n}\n\nfunc setStreamId(req *http.Request, streamId string) {\n\treq.URL.RawQuery = \"%3Auuid=\" + streamId + \"&\"\n}\n\nfunc (s *HttpServerSuite) TestMkstream(c *C) {\n\trequest := newRequest(\"POST\", \"\/streams\", \"\")\n\tresponse := httptest.NewRecorder()\n\n\tmkstream(response, request)\n\n\tc.Assert(response.Code, Equals, 200)\n\tc.Assert(response.Body.String(), HasLen, 32)\n}\n\nfunc (s *HttpServerSuite) Test410(c *C) {\n\tstreamId, _ := util.NewUUID()\n\trequest := newRequest(\"GET\", \"\/streams\/\"+string(streamId), \"\")\n\tresponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tsub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusNotFound)\n\tc.Assert(response.Body.String(), Equals, \"Channel is not registered.\\n\")\n}\n\nfunc (s *HttpServerSuite) TestPubNotRegistered(c *C) {\n\tstreamId, _ := util.NewUUID()\n\trequest := newRequest(\"POST\", \"\/streams\/\"+string(streamId), \"\")\n\tresponse := httptest.NewRecorder()\n\n\tpub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusNotFound)\n}\n\nfunc (s *HttpServerSuite) TestPubWithoutTransferEncoding(c *C) {\n\trequest, _ := http.NewRequest(\"POST\", \"\/streams\/1234\", nil)\n\tsetStreamId(request, \"1234\")\n\tresponse := httptest.NewRecorder()\n\n\tpub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusBadRequest)\n\tc.Assert(response.Body.String(), Equals, \"A chunked Transfer-Encoding header is required.\\n\")\n}\n\nfunc (s *HttpServerSuite) TestSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\twriter, _ := broker.NewWriter(streamId)\n\n\trequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tresponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\twaiter := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tsub(response, request)\n\t})\n\n\twriter.Write([]byte(\"busl1\"))\n\twriter.Close()\n\t<-waiter\n\n\tc.Assert(response.Code, Equals, http.StatusOK)\n\tc.Assert(response.Body.String(), Equals, \"busl1\")\n}\n\nfunc (s *HttpServerSuite) TestPubSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\n\tbody := new(bytes.Buffer)\n\tbodyCloser := ioutil.NopCloser(body)\n\n\tpubRequest := newRequestFromReader(\"POST\", sf(\"\/streams\/%s\", streamId), bodyCloser)\n\tpubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tpubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tpub(pubResponse, pubRequest)\n\t})\n\n\tsubRequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tsubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tsubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tsub(subResponse, subRequest)\n\t})\n\n\tfor _, m := range []string{\"first\", \" \", \"second\", \" \", \"third\"} {\n\t\tbody.Write([]byte(m))\n\t}\n\n\tbodyCloser.Close()\n\t<-pubBlocker\n\t<-subBlocker\n\n\tc.Assert(subResponse.Code, Equals, http.StatusOK)\n\tc.Assert(subResponse.Body.String(), Equals, \"first second third\")\n}\n\nfunc (s *HttpServerSuite) TestBinaryPubSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\n\tbody := new(bytes.Buffer)\n\tbodyCloser := ioutil.NopCloser(body)\n\n\tpubRequest := newRequestFromReader(\"POST\", sf(\"\/streams\/%s\", streamId), bodyCloser)\n\tpubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tpubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tpub(pubResponse, pubRequest)\n\t})\n\n\tsubRequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tsubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tsubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tsub(subResponse, subRequest)\n\t})\n\n\texpected := []byte{0x1f, 0x8b, 0x08, 0x00, 0x3f, 0x6b, 0xe1, 0x53, 0x00, 0x03, 0xed, 0xce, 0xb1, 0x0a, 0xc2, 0x30}\n\tfor _, m := range expected {\n\t\tbody.Write([]byte{m})\n\t}\n\n\tbodyCloser.Close()\n\t<-pubBlocker\n\t<-subBlocker\n\n\tc.Assert(subResponse.Code, Equals, http.StatusOK)\n\tc.Assert(subResponse.Body.Bytes(), DeepEquals, expected)\n}\n\nfunc (s *HttpServerSuite) TestSubWaitingPub(c *C) {\n\t\/\/ Start the server in a randomly assigned port\n\tserver := httptest.NewServer(app())\n\tdefer server.Close()\n\n\t\/\/ uuid = curl -XPOST \/streams\n\tresp, err := http.Post(server.URL+\"\/streams\", \"\", nil)\n\tdefer resp.Body.Close()\n\tc.Assert(err, Equals, nil)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, Equals, nil)\n\n\t\/\/ uuid extracted\n\tuuid := string(body)\n\tc.Assert(len(uuid), Equals, 32)\n\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\t\/\/ curl \/streams\/\n\t\t\/\/ -- waiting for publish to arrive\n\t\tresp, err = http.Get(server.URL + \"\/streams\/\" + uuid)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, IsNil)\n\n\t\tbody, _ = ioutil.ReadAll(resp.Body)\n\t\tc.Assert(string(body), Equals, \"Hello\")\n\n\t\tdone <- true\n\t}()\n\n\ttransport := &http.Transport{}\n\tclient := &http.Client{Transport: transport}\n\n\t\/\/ curl -XPOST -H \"Transfer-Encoding: chunked\" -d \"hello\" \/streams\/\n\treq := newRequestFromReader(\"POST\", server.URL+\"\/streams\/\"+uuid, strings.NewReader(\"Hello\"))\n\tr, err := client.Do(req)\n\tr.Body.Close()\n\tc.Assert(err, IsNil)\n\n\t<-done\n}\n\nfunc (s *HttpServerSuite) TestAuthentication(c *C) {\n\t*util.Creds = \"u:pass1|u:pass2\"\n\tdefer func() {\n\t\t*util.Creds = \"\"\n\t}()\n\n\t\/\/ Start the server in a randomly assigned port\n\tserver := httptest.NewServer(app())\n\tdefer server.Close()\n\n\ttransport := &http.Transport{}\n\tclient := &http.Client{Transport: transport}\n\n\t\/\/ Validate that we return 401 for empty and invalid tokens\n\tfor _, token := range []string{\"\", \"invalid\"} {\n\t\trequest := newRequest(\"POST\", server.URL+\"\/streams\", \"\")\n\t\tif token != \"\" {\n\t\t\trequest.SetBasicAuth(\"\", token)\n\t\t}\n\t\tresp, err := client.Do(request)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, Equals, nil)\n\t\tc.Assert(resp.Status, Equals, \"401 Unauthorized\")\n\t}\n\n\t\/\/ Validate that all the colon separated token values are\n\t\/\/ accepted\n\tfor _, token := range []string{\"pass1\", \"pass2\"} {\n\t\trequest := newRequest(\"POST\", server.URL+\"\/streams\", \"\")\n\t\trequest.SetBasicAuth(\"u\", token)\n\t\tresp, err := client.Do(request)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, Equals, nil)\n\t\tc.Assert(resp.Status, Equals, \"200 OK\")\n\t}\n}\n\ntype CloseNotifierRecorder struct {\n\t*httptest.ResponseRecorder\n\tclosed chan bool\n}\n\nfunc (cnr CloseNotifierRecorder) close() {\n\tcnr.closed <- true\n}\n\nfunc (cnr CloseNotifierRecorder) CloseNotify() <-chan bool {\n\treturn cnr.closed\n}\nMake the test less flappypackage server\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/heroku\/busl\/broker\"\n\t\"github.com\/heroku\/busl\/util\"\n\t. \"gopkg.in\/check.v1\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc Test(t *testing.T) { TestingT(t) }\n\ntype HttpServerSuite struct{}\n\nvar _ = Suite(&HttpServerSuite{})\nvar sf = fmt.Sprintf\n\nfunc newRequest(method, url, body string) *http.Request {\n\treturn newRequestFromReader(method, url, bytes.NewBufferString(body))\n}\n\nfunc newRequestFromReader(method, url string, reader io.Reader) *http.Request {\n\trequest, _ := http.NewRequest(method, url, reader)\n\turlParts := strings.Split(url, \"\/\")\n\tif method == \"POST\" {\n\t\trequest.TransferEncoding = []string{\"chunked\"}\n\t\trequest.Header.Add(\"Transfer-Encoding\", \"chunked\")\n\t}\n\tif len(urlParts) == 3 {\n\t\tstreamId := urlParts[2]\n\t\tsetStreamId(request, streamId)\n\t}\n\treturn request\n}\n\nfunc setStreamId(req *http.Request, streamId string) {\n\treq.URL.RawQuery = \"%3Auuid=\" + streamId + \"&\"\n}\n\nfunc (s *HttpServerSuite) TestMkstream(c *C) {\n\trequest := newRequest(\"POST\", \"\/streams\", \"\")\n\tresponse := httptest.NewRecorder()\n\n\tmkstream(response, request)\n\n\tc.Assert(response.Code, Equals, 200)\n\tc.Assert(response.Body.String(), HasLen, 32)\n}\n\nfunc (s *HttpServerSuite) Test410(c *C) {\n\tstreamId, _ := util.NewUUID()\n\trequest := newRequest(\"GET\", \"\/streams\/\"+string(streamId), \"\")\n\tresponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tsub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusNotFound)\n\tc.Assert(response.Body.String(), Equals, \"Channel is not registered.\\n\")\n}\n\nfunc (s *HttpServerSuite) TestPubNotRegistered(c *C) {\n\tstreamId, _ := util.NewUUID()\n\trequest := newRequest(\"POST\", \"\/streams\/\"+string(streamId), \"\")\n\tresponse := httptest.NewRecorder()\n\n\tpub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusNotFound)\n}\n\nfunc (s *HttpServerSuite) TestPubWithoutTransferEncoding(c *C) {\n\trequest, _ := http.NewRequest(\"POST\", \"\/streams\/1234\", nil)\n\tsetStreamId(request, \"1234\")\n\tresponse := httptest.NewRecorder()\n\n\tpub(response, request)\n\n\tc.Assert(response.Code, Equals, http.StatusBadRequest)\n\tc.Assert(response.Body.String(), Equals, \"A chunked Transfer-Encoding header is required.\\n\")\n}\n\nfunc (s *HttpServerSuite) TestSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\twriter, _ := broker.NewWriter(streamId)\n\n\trequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tresponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\twaiter := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tsub(response, request)\n\t})\n\n\twriter.Write([]byte(\"busl1\"))\n\twriter.Close()\n\t<-waiter\n\n\tc.Assert(response.Code, Equals, http.StatusOK)\n\tc.Assert(response.Body.String(), Equals, \"busl1\")\n}\n\nfunc (s *HttpServerSuite) TestPubSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\n\tbody := new(bytes.Buffer)\n\tbodyCloser := ioutil.NopCloser(body)\n\n\tpubRequest := newRequestFromReader(\"POST\", sf(\"\/streams\/%s\", streamId), bodyCloser)\n\tpubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tpubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tpub(pubResponse, pubRequest)\n\t})\n\n\tsubRequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tsubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tsubBlocker := util.TimeoutFunc(time.Millisecond*5, func() {\n\t\tsub(subResponse, subRequest)\n\t})\n\n\tfor _, m := range []string{\"first\", \" \", \"second\", \" \", \"third\"} {\n\t\tbody.Write([]byte(m))\n\t}\n\n\tbodyCloser.Close()\n\t<-pubBlocker\n\t<-subBlocker\n\n\tc.Assert(subResponse.Code, Equals, http.StatusOK)\n\tc.Assert(subResponse.Body.String(), Equals, \"first second third\")\n}\n\nfunc (s *HttpServerSuite) TestBinaryPubSub(c *C) {\n\tstreamId, _ := util.NewUUID()\n\tregistrar := broker.NewRedisRegistrar()\n\tregistrar.Register(streamId)\n\n\tbody := new(bytes.Buffer)\n\tbodyCloser := ioutil.NopCloser(body)\n\n\tpubRequest := newRequestFromReader(\"POST\", sf(\"\/streams\/%s\", streamId), bodyCloser)\n\tpubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tpubDone := make(chan bool)\n\tsubDone := make(chan bool)\n\n\tgo func() {\n\t\tpub(pubResponse, pubRequest)\n\t\tpubDone <- true\n\t}()\n\n\tsubRequest := newRequest(\"GET\", sf(\"\/streams\/%s\", streamId), \"\")\n\tsubResponse := CloseNotifierRecorder{httptest.NewRecorder(), make(chan bool, 1)}\n\n\tgo func() {\n\t\tsub(subResponse, subRequest)\n\t\tsubDone <- true\n\t}()\n\n\texpected := []byte{0x1f, 0x8b, 0x08, 0x00, 0x3f, 0x6b, 0xe1, 0x53, 0x00, 0x03, 0xed, 0xce, 0xb1, 0x0a, 0xc2, 0x30}\n\tfor _, m := range expected {\n\t\tbody.Write([]byte{m})\n\t}\n\n\tbodyCloser.Close()\n\t<-pubDone\n\t<-subDone\n\n\tc.Assert(subResponse.Code, Equals, http.StatusOK)\n\tc.Assert(subResponse.Body.Bytes(), DeepEquals, expected)\n}\n\nfunc (s *HttpServerSuite) TestSubWaitingPub(c *C) {\n\t\/\/ Start the server in a randomly assigned port\n\tserver := httptest.NewServer(app())\n\tdefer server.Close()\n\n\t\/\/ uuid = curl -XPOST \/streams\n\tresp, err := http.Post(server.URL+\"\/streams\", \"\", nil)\n\tdefer resp.Body.Close()\n\tc.Assert(err, Equals, nil)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, Equals, nil)\n\n\t\/\/ uuid extracted\n\tuuid := string(body)\n\tc.Assert(len(uuid), Equals, 32)\n\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\t\/\/ curl \/streams\/\n\t\t\/\/ -- waiting for publish to arrive\n\t\tresp, err = http.Get(server.URL + \"\/streams\/\" + uuid)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, IsNil)\n\n\t\tbody, _ = ioutil.ReadAll(resp.Body)\n\t\tc.Assert(string(body), Equals, \"Hello\")\n\n\t\tdone <- true\n\t}()\n\n\ttransport := &http.Transport{}\n\tclient := &http.Client{Transport: transport}\n\n\t\/\/ curl -XPOST -H \"Transfer-Encoding: chunked\" -d \"hello\" \/streams\/\n\treq := newRequestFromReader(\"POST\", server.URL+\"\/streams\/\"+uuid, strings.NewReader(\"Hello\"))\n\tr, err := client.Do(req)\n\tr.Body.Close()\n\tc.Assert(err, IsNil)\n\n\t<-done\n}\n\nfunc (s *HttpServerSuite) TestAuthentication(c *C) {\n\t*util.Creds = \"u:pass1|u:pass2\"\n\tdefer func() {\n\t\t*util.Creds = \"\"\n\t}()\n\n\t\/\/ Start the server in a randomly assigned port\n\tserver := httptest.NewServer(app())\n\tdefer server.Close()\n\n\ttransport := &http.Transport{}\n\tclient := &http.Client{Transport: transport}\n\n\t\/\/ Validate that we return 401 for empty and invalid tokens\n\tfor _, token := range []string{\"\", \"invalid\"} {\n\t\trequest := newRequest(\"POST\", server.URL+\"\/streams\", \"\")\n\t\tif token != \"\" {\n\t\t\trequest.SetBasicAuth(\"\", token)\n\t\t}\n\t\tresp, err := client.Do(request)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, Equals, nil)\n\t\tc.Assert(resp.Status, Equals, \"401 Unauthorized\")\n\t}\n\n\t\/\/ Validate that all the colon separated token values are\n\t\/\/ accepted\n\tfor _, token := range []string{\"pass1\", \"pass2\"} {\n\t\trequest := newRequest(\"POST\", server.URL+\"\/streams\", \"\")\n\t\trequest.SetBasicAuth(\"u\", token)\n\t\tresp, err := client.Do(request)\n\t\tdefer resp.Body.Close()\n\t\tc.Assert(err, Equals, nil)\n\t\tc.Assert(resp.Status, Equals, \"200 OK\")\n\t}\n}\n\ntype CloseNotifierRecorder struct {\n\t*httptest.ResponseRecorder\n\tclosed chan bool\n}\n\nfunc (cnr CloseNotifierRecorder) close() {\n\tcnr.closed <- true\n}\n\nfunc (cnr CloseNotifierRecorder) CloseNotify() <-chan bool {\n\treturn cnr.closed\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"encoding\/json\"\n)\n\n\ntype domainsResult struct {\n\tResult []string `json:\"result\"`\n\tError error `json:\"error\"`\n}\n\n\nfunc request(s *Server, t *testing.T, method string, domain string, body string) *httptest.ResponseRecorder {\n\treqBody := strings.NewReader(body)\n\treq, err := http.NewRequest(method, \"http:\/\/counters.io\/\" + domain, reqBody)\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\trespw := httptest.NewRecorder()\n\ts.ServeHTTP(respw, req)\n\treturn respw\n}\n\nfunc unmarschal(resp *httptest.ResponseRecorder) domainsResult {\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tvar r domainsResult\n\tjson.Unmarshal(body, &r)\n\treturn r\n}\n\n\nfunc TestDomainsInitiallyEmpty(t *testing.T) {\n\ts := New()\n\tresp := request(s, t, \"GET\", \"\", \"{}\")\n\tif resp.Code != 200 {\n\t\tt.Fatalf(\"Invalid Response Code %d - %s\", resp.Code, resp.Body.String())\t\n\t\treturn\n\t}\n\tresult := unmarschal(resp)\n\tif len(result.Result) != 0 {\n\t\tt.Fatalf(\"Initial resultCount != 0. Got %s\", result)\t\n\t}\n}\n\nfunc TestBadRequest(t *testing.T) {\n\ts := New()\n\tvar resp *httptest.ResponseRecorder\n\tresp = request(s, t, \"GET\", \"\", `{\"invalid\": \"request\"}`)\n\tif resp.Code != 400 {\n\t\tt.Fatalf(\"Invalid Response Code %d - Expected 400\", resp.Code)\t\n\t\treturn\n\t}\n\tresp = request(s, t, \"POST\", \"marvel\", \"{}\")\n\tif resp.Code != 400 {\n\t\tt.Fatalf(\"Invalid Response Code %d - Expected 400\", resp.Code)\t\n\t\treturn\n\t}\n}\n\nfunc TestCreateDomain(t *testing.T) {\n\ts := New()\n\tresp := request(s, t, \"POST\", \"marvel\", `{\n\t\t\"domain\": \"marvel\",\n\t\t\"domainType\": \"mutable\",\n\t\t\"capacity\": 100000,\n\t\t\"values\": []\n\t}`)\n\n\tif resp.Code != 200 {\n\t\tt.Fatalf(\"Invalid Response Code %d - %s\", resp.Code, resp.Body.String())\n\t\treturn\n\t}\n\n\tresult := unmarschal(resp)\n\tif len(result.Result) != 1 {\n\t\tt.Fatalf(\"after add resultCount != 1. Got %s\", result.Result)\t\n\t}\n}\nbugfixpackage server\n\nimport (\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"encoding\/json\"\n)\n\n\ntype domainsResult struct {\n\tResult []string `json:\"result\"`\n\tError error `json:\"error\"`\n}\n\n\nfunc request(s *Server, t *testing.T, method string, domain string, body string) *httptest.ResponseRecorder {\n\treqBody := strings.NewReader(body)\n\treq, err := http.NewRequest(method, \"http:\/\/counters.io\/\" + domain, reqBody)\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\trespw := httptest.NewRecorder()\n\ts.ServeHTTP(respw, req)\n\treturn respw\n}\n\nfunc unmarschal(resp *httptest.ResponseRecorder) domainsResult {\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tvar r domainsResult\n\tjson.Unmarshal(body, &r)\n\treturn r\n}\n\n\nfunc TestDomainsInitiallyEmpty(t *testing.T) {\n\ts := New()\n\tresp := request(s, t, \"GET\", \"\", \"{}\")\n\tif resp.Code != 200 {\n\t\tt.Fatalf(\"Invalid Response Code %d - %s\", resp.Code, resp.Body.String())\t\n\t\treturn\n\t}\n\tresult := unmarschal(resp)\n\tif len(result.Result) != 0 {\n\t\tt.Fatalf(\"Initial resultCount != 0. Got %s\", result)\t\n\t}\n}\n\nfunc TestBadRequest(t *testing.T) {\n\ts := New()\n\tvar resp *httptest.ResponseRecorder\n\tresp = request(s, t, \"GET\", \"\", `{\"invalid\": \"request\"}`)\n\tif resp.Code != 400 {\n\t\tt.Fatalf(\"Invalid Response Code %d - Expected 400\", resp.Code)\t\n\t\treturn\n\t}\n\tresp = request(s, t, \"POST\", \"marvel\", \"{}\")\n\tif resp.Code != 400 {\n\t\tt.Fatalf(\"Invalid Response Code %d - Expected 400\", resp.Code)\t\n\t\treturn\n\t}\n}\n\nfunc TestCreateDomain(t *testing.T) {\n\ts := New()\n\tresp := request(s, t, \"POST\", \"marvel\", `{\n\t\t\"domain\": \"marvel\",\n\t\t\"domainType\": \"mutable\",\n\t\t\"capacity\": 100000,\n\t\t\"values\": []\n\t}`)\n\n\tif resp.Code != 200 {\n\t\tt.Fatalf(\"Invalid Response Code %d - %s\", resp.Code, resp.Body.String())\n\t\treturn\n\t}\n\n\tresult := unmarschal(resp)\n\tif len(result.Result) != 1 {\n\t\tt.Fatalf(\"after add resultCount != 1. Got %s\", len(result.Result))\n\t}\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/deis\/deis\/pkg\/prettyprint\"\n\n\t\"github.com\/deis\/deis\/client\/controller\/api\"\n\t\"github.com\/deis\/deis\/client\/controller\/client\"\n\t\"github.com\/deis\/deis\/client\/controller\/models\/apps\"\n\t\"github.com\/deis\/deis\/client\/controller\/models\/config\"\n\t\"github.com\/deis\/deis\/client\/pkg\/git\"\n\t\"github.com\/deis\/deis\/client\/pkg\/webbrowser\"\n)\n\n\/\/ AppCreate creates an app.\nfunc AppCreate(id string, buildpack string, remote string, noRemote bool) error {\n\tc, err := client.New()\n\n\tfmt.Print(\"Creating Application... \")\n\tquit := progress()\n\tapp, err := apps.New(c, id)\n\n\tquit <- true\n\t<-quit\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"done, created %s\\n\", app.ID)\n\n\tif buildpack != \"\" {\n\t\tconfigValues := api.Config{\n\t\t\tValues: map[string]interface{}{\n\t\t\t\t\"BUILDPACK_URL\": buildpack,\n\t\t\t},\n\t\t}\n\t\tif _, err = config.Set(c, app.ID, configValues); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !noRemote {\n\t\treturn git.CreateRemote(c.ControllerURL.Host, remote, app.ID)\n\t}\n\n\tfmt.Println(\"remote available at\", git.RemoteURL(c.ControllerURL.Host, app.ID))\n\n\treturn nil\n}\n\n\/\/ AppsList lists apps on the Deis controller.\nfunc AppsList(results int) error {\n\tc, err := client.New()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif results == defaultLimit {\n\t\tresults = c.ResponseLimit\n\t}\n\n\tapps, count, err := apps.List(c, results)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"=== Apps%s\", limitCount(len(apps), count))\n\n\tfor _, app := range apps {\n\t\tfmt.Println(app.ID)\n\t}\n\treturn nil\n}\n\n\/\/ AppInfo prints info about app.\nfunc AppInfo(appID string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapp, err := apps.Get(c, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"=== %s Application\\n\", app.ID)\n\tfmt.Println(\"updated: \", app.Updated)\n\tfmt.Println(\"uuid: \", app.UUID)\n\tfmt.Println(\"created: \", app.Created)\n\tfmt.Println(\"url: \", app.URL)\n\tfmt.Println(\"owner: \", app.Owner)\n\tfmt.Println(\"id: \", app.ID)\n\n\tfmt.Println()\n\t\/\/ print the app processes\n\tif err = PsList(app.ID, defaultLimit); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println()\n\t\/\/ print the app domains\n\tif err = DomainsList(app.ID, defaultLimit); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println()\n\n\treturn nil\n}\n\n\/\/ AppOpen opens an app in the default webbrowser.\nfunc AppOpen(appID string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapp, err := apps.Get(c, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.Parse(app.URL)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.Scheme = \"http\"\n\n\treturn webbrowser.Webbrowser(u.String())\n}\n\n\/\/ AppLogs returns the logs from an app.\nfunc AppLogs(appID string, lines int) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogs, err := apps.Logs(c, appID, lines)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn printLogs(logs)\n}\n\n\/\/ printLogs prints each log line with a color matched to its category.\nfunc printLogs(logs string) error {\n\tfor _, log := range strings.Split(strings.Trim(logs, `\\n`), `\\n`) {\n\t\tcategory := \"unknown\"\n\t\tparts := strings.Split(strings.Split(log, \": \")[0], \" \")\n\t\tif len(parts) >= 2 {\n\t\t\tcategory = parts[1]\n\t\t}\n\t\tcolorVars := map[string]string{\n\t\t\t\"Color\": chooseColor(category),\n\t\t\t\"Log\": log,\n\t\t}\n\t\tfmt.Println(prettyprint.ColorizeVars(\"{{.V.Color}}{{.V.Log}}{{.C.Default}}\", colorVars))\n\t}\n\n\treturn nil\n}\n\n\/\/ AppRun runs a one time command in the app.\nfunc AppRun(appID, command string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Running '%s'...\\n\", command)\n\n\tout, err := apps.Run(c, appID, command)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Print(out.Output)\n\tos.Exit(out.ReturnCode)\n\treturn nil\n}\n\n\/\/ AppDestroy destroys an app.\nfunc AppDestroy(appID, confirm string) error {\n\tgitSession := false\n\n\tc, err := client.New()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif appID == \"\" {\n\t\tappID, err = git.DetectAppName(c.ControllerURL.Host)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgitSession = true\n\t}\n\n\tif confirm == \"\" {\n\t\tfmt.Printf(` ! WARNING: Potentially Destructive Action\n ! This command will destroy the application: %s\n ! To proceed, type \"%s\" or re-run this command with --confirm=%s\n\n> `, appID, appID, appID)\n\n\t\tfmt.Scanln(&confirm)\n\t}\n\n\tif confirm != appID {\n\t\treturn fmt.Errorf(\"App %s does not match confirm %s, aborting.\", appID, confirm)\n\t}\n\n\tstartTime := time.Now()\n\tfmt.Printf(\"Destroying %s...\\n\", appID)\n\n\tif err = apps.Delete(c, appID); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"done in %ds\\n\", int(time.Since(startTime).Seconds()))\n\n\tif gitSession {\n\t\treturn git.DeleteRemote(appID)\n\t}\n\n\treturn nil\n}\n\n\/\/ AppTransfer transfers app ownership to another user.\nfunc AppTransfer(appID, username string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Transferring %s to %s... \", appID, username)\n\n\terr = apps.Transfer(c, appID, username)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"done\")\n\n\treturn nil\n}\nfix(client): suggest help when git remote creation failspackage cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/deis\/deis\/pkg\/prettyprint\"\n\n\t\"github.com\/deis\/deis\/client\/controller\/api\"\n\t\"github.com\/deis\/deis\/client\/controller\/client\"\n\t\"github.com\/deis\/deis\/client\/controller\/models\/apps\"\n\t\"github.com\/deis\/deis\/client\/controller\/models\/config\"\n\t\"github.com\/deis\/deis\/client\/pkg\/git\"\n\t\"github.com\/deis\/deis\/client\/pkg\/webbrowser\"\n)\n\n\/\/ AppCreate creates an app.\nfunc AppCreate(id string, buildpack string, remote string, noRemote bool) error {\n\tc, err := client.New()\n\n\tfmt.Print(\"Creating Application... \")\n\tquit := progress()\n\tapp, err := apps.New(c, id)\n\n\tquit <- true\n\t<-quit\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"done, created %s\\n\", app.ID)\n\n\tif buildpack != \"\" {\n\t\tconfigValues := api.Config{\n\t\t\tValues: map[string]interface{}{\n\t\t\t\t\"BUILDPACK_URL\": buildpack,\n\t\t\t},\n\t\t}\n\t\tif _, err = config.Set(c, app.ID, configValues); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !noRemote {\n\t\tif err = git.CreateRemote(c.ControllerURL.Host, remote, app.ID); err != nil {\n\t\t\tif err.Error() == \"exit status 128\" {\n\t\t\t\tfmt.Println(\"To replace the existing git remote entry, run:\")\n\t\t\t\tfmt.Printf(\" git remote rename deis deis.old && deis git:remote -a %s\\n\", app.ID)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Println(\"remote available at\", git.RemoteURL(c.ControllerURL.Host, app.ID))\n\n\treturn nil\n}\n\n\/\/ AppsList lists apps on the Deis controller.\nfunc AppsList(results int) error {\n\tc, err := client.New()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif results == defaultLimit {\n\t\tresults = c.ResponseLimit\n\t}\n\n\tapps, count, err := apps.List(c, results)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"=== Apps%s\", limitCount(len(apps), count))\n\n\tfor _, app := range apps {\n\t\tfmt.Println(app.ID)\n\t}\n\treturn nil\n}\n\n\/\/ AppInfo prints info about app.\nfunc AppInfo(appID string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapp, err := apps.Get(c, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"=== %s Application\\n\", app.ID)\n\tfmt.Println(\"updated: \", app.Updated)\n\tfmt.Println(\"uuid: \", app.UUID)\n\tfmt.Println(\"created: \", app.Created)\n\tfmt.Println(\"url: \", app.URL)\n\tfmt.Println(\"owner: \", app.Owner)\n\tfmt.Println(\"id: \", app.ID)\n\n\tfmt.Println()\n\t\/\/ print the app processes\n\tif err = PsList(app.ID, defaultLimit); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println()\n\t\/\/ print the app domains\n\tif err = DomainsList(app.ID, defaultLimit); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println()\n\n\treturn nil\n}\n\n\/\/ AppOpen opens an app in the default webbrowser.\nfunc AppOpen(appID string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapp, err := apps.Get(c, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.Parse(app.URL)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.Scheme = \"http\"\n\n\treturn webbrowser.Webbrowser(u.String())\n}\n\n\/\/ AppLogs returns the logs from an app.\nfunc AppLogs(appID string, lines int) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogs, err := apps.Logs(c, appID, lines)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn printLogs(logs)\n}\n\n\/\/ printLogs prints each log line with a color matched to its category.\nfunc printLogs(logs string) error {\n\tfor _, log := range strings.Split(strings.Trim(logs, `\\n`), `\\n`) {\n\t\tcategory := \"unknown\"\n\t\tparts := strings.Split(strings.Split(log, \": \")[0], \" \")\n\t\tif len(parts) >= 2 {\n\t\t\tcategory = parts[1]\n\t\t}\n\t\tcolorVars := map[string]string{\n\t\t\t\"Color\": chooseColor(category),\n\t\t\t\"Log\": log,\n\t\t}\n\t\tfmt.Println(prettyprint.ColorizeVars(\"{{.V.Color}}{{.V.Log}}{{.C.Default}}\", colorVars))\n\t}\n\n\treturn nil\n}\n\n\/\/ AppRun runs a one time command in the app.\nfunc AppRun(appID, command string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Running '%s'...\\n\", command)\n\n\tout, err := apps.Run(c, appID, command)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Print(out.Output)\n\tos.Exit(out.ReturnCode)\n\treturn nil\n}\n\n\/\/ AppDestroy destroys an app.\nfunc AppDestroy(appID, confirm string) error {\n\tgitSession := false\n\n\tc, err := client.New()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif appID == \"\" {\n\t\tappID, err = git.DetectAppName(c.ControllerURL.Host)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgitSession = true\n\t}\n\n\tif confirm == \"\" {\n\t\tfmt.Printf(` ! WARNING: Potentially Destructive Action\n ! This command will destroy the application: %s\n ! To proceed, type \"%s\" or re-run this command with --confirm=%s\n\n> `, appID, appID, appID)\n\n\t\tfmt.Scanln(&confirm)\n\t}\n\n\tif confirm != appID {\n\t\treturn fmt.Errorf(\"App %s does not match confirm %s, aborting.\", appID, confirm)\n\t}\n\n\tstartTime := time.Now()\n\tfmt.Printf(\"Destroying %s...\\n\", appID)\n\n\tif err = apps.Delete(c, appID); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"done in %ds\\n\", int(time.Since(startTime).Seconds()))\n\n\tif gitSession {\n\t\treturn git.DeleteRemote(appID)\n\t}\n\n\treturn nil\n}\n\n\/\/ AppTransfer transfers app ownership to another user.\nfunc AppTransfer(appID, username string) error {\n\tc, appID, err := load(appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Transferring %s to %s... \", appID, username)\n\n\terr = apps.Transfer(c, appID, username)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"done\")\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Google LLC. All Rights Reserved.\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 merkle\n\nimport (\n\t\"fmt\"\n\t\"math\/bits\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/trillian\/merkle\/compact\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\n\/\/ Verbosity levels for logging of debug related items\nconst vLevel = 2\nconst vvLevel = 4\n\n\/\/ NodeFetch bundles a nodeID with additional information on how to use the node to construct the\n\/\/ correct proof.\ntype NodeFetch struct {\n\tID compact.NodeID\n\tRehash bool\n}\n\n\/\/ checkSnapshot performs a couple of simple sanity checks on ss and treeSize\n\/\/ and returns an error if there's a problem.\nfunc checkSnapshot(ssDesc string, ss, treeSize int64) error {\n\tif ss < 1 {\n\t\treturn fmt.Errorf(\"%s %d < 1\", ssDesc, ss)\n\t}\n\tif ss > treeSize {\n\t\treturn fmt.Errorf(\"%s %d > treeSize %d\", ssDesc, ss, treeSize)\n\t}\n\treturn nil\n}\n\n\/\/ CalcInclusionProofNodeAddresses returns the tree node IDs needed to build an\n\/\/ inclusion proof for a specified leaf and tree size. The snapshot parameter\n\/\/ is the tree size being queried for, treeSize is the actual size of the tree\n\/\/ at the revision we are using to fetch nodes (this can be > snapshot).\nfunc CalcInclusionProofNodeAddresses(snapshot, index, treeSize int64) ([]NodeFetch, error) {\n\tif err := checkSnapshot(\"snapshot\", snapshot, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: %v\", err)\n\t}\n\tif index >= snapshot {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: index %d is >= snapshot %d\", index, snapshot)\n\t}\n\tif index < 0 {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: index %d is < 0\", index)\n\t}\n\t\/\/ Note: If snapshot < treeSize, the storage might not contain the\n\t\/\/ \"ephemeral\" node of this proof, so rehashing is needed.\n\treturn proofNodes(uint64(index), 0, uint64(snapshot), snapshot < treeSize), nil\n}\n\n\/\/ CalcConsistencyProofNodeAddresses returns the tree node IDs needed to build\n\/\/ a consistency proof between two specified tree sizes. snapshot1 and\n\/\/ snapshot2 represent the two tree sizes for which consistency should be\n\/\/ proved, treeSize is the actual size of the tree at the revision we are using\n\/\/ to fetch nodes (this can be > snapshot2).\n\/\/\n\/\/ The caller is responsible for checking that the input tree sizes correspond\n\/\/ to valid tree heads. All returned NodeIDs are tree coordinates within the\n\/\/ new tree. It is assumed that they will be fetched from storage at a revision\n\/\/ corresponding to the STH associated with the treeSize parameter.\nfunc CalcConsistencyProofNodeAddresses(snapshot1, snapshot2, treeSize int64) ([]NodeFetch, error) {\n\tif err := checkSnapshot(\"snapshot1\", snapshot1, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: %v\", err)\n\t}\n\tif err := checkSnapshot(\"snapshot2\", snapshot2, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: %v\", err)\n\t}\n\tif snapshot1 > snapshot2 {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: snapshot1 %d > snapshot2 %d\", snapshot1, snapshot2)\n\t}\n\n\treturn snapshotConsistency(snapshot1, snapshot2, treeSize)\n}\n\n\/\/ snapshotConsistency does the calculation of consistency proof node addresses between\n\/\/ two snapshots. Based on the C++ code used by CT but adjusted to fit our situation.\nfunc snapshotConsistency(snapshot1, snapshot2, treeSize int64) ([]NodeFetch, error) {\n\tproof := make([]NodeFetch, 0, bits.Len64(uint64(snapshot2))+1)\n\n\tglog.V(vLevel).Infof(\"snapshotConsistency: %d -> %d\", snapshot1, snapshot2)\n\n\tif snapshot1 == snapshot2 {\n\t\treturn proof, nil\n\t}\n\n\tlevel := uint(0)\n\tnode := snapshot1 - 1\n\n\t\/\/ Compute the (compressed) path to the root of snapshot2.\n\t\/\/ Everything left of 'node' is equal in both trees; no need to record.\n\tfor (node & 1) != 0 {\n\t\tglog.V(vvLevel).Infof(\"Move up: l:%d n:%d\", level, node)\n\t\tnode >>= 1\n\t\tlevel++\n\t}\n\n\tif node != 0 {\n\t\tglog.V(vvLevel).Infof(\"Not root snapshot1: %d\", node)\n\t\t\/\/ Not at the root of snapshot 1, record the node\n\t\tn := compact.NewNodeID(level, uint64(node))\n\t\tproof = append(proof, NodeFetch{ID: n})\n\t}\n\n\t\/\/ Now append the path from this node to the root of snapshot2.\n\tp := proofNodes(uint64(node), level, uint64(snapshot2), snapshot2 < treeSize)\n\treturn append(proof, p...), nil\n}\n\n\/\/ proofNodes returns the node IDs necessary to prove that the (level, index)\n\/\/ node is included in the Merkle tree of the given size.\nfunc proofNodes(index uint64, level uint, size uint64, rehash bool) []NodeFetch {\n\t\/\/ [begin, end) is the leaves range covered by the (level, index) node.\n\tbegin, end := index< 1\n\t\t} else {\n\t\t\t\/\/ The parent of the highest node in [end+l, size) is \"ephemeral\".\n\t\t\tlvl := uint(bits.Len64(r))\n\t\t\t\/\/ Except when [end+l, size) is a perfect subtree, in which case we just\n\t\t\t\/\/ take the root node.\n\t\t\tif r&(r-1) == 0 {\n\t\t\t\tlvl--\n\t\t\t}\n\t\t\tright = []compact.NodeID{compact.NewNodeID(lvl, (end+l)>>lvl)}\n\t\t}\n\t}\n\n\t\/\/ The level in the ordered list of nodes where the rehashed nodes appear in\n\t\/\/ lieu of the \"ephemeral\" node. This is equal to the level where the path to\n\t\/\/ the `begin` index diverges from the path to `size`.\n\trehashLevel := uint(bits.Len64(begin^size) - 1)\n\n\t\/\/ Merge the three compact ranges into a single proof ordered by node level\n\t\/\/ from leaves towards the root, i.e. the format specified in RFC 6962.\n\tproof := make([]NodeFetch, 0, len(left)+len(middle)+len(right))\n\ti, j := 0, 0\n\tfor l, levels := level, uint(bits.Len64(size-1)); l < levels; l++ {\n\t\tif i < len(left) && left[i].Level == l {\n\t\t\tproof = append(proof, NodeFetch{ID: left[i]})\n\t\t\ti++\n\t\t} else if j < len(middle) && middle[j].Level == l {\n\t\t\tproof = append(proof, NodeFetch{ID: middle[j]})\n\t\t\tj++\n\t\t}\n\t\tif l == rehashLevel {\n\t\t\tfor _, id := range right {\n\t\t\t\tproof = append(proof, NodeFetch{ID: id, Rehash: rehash})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn proof\n}\n\nfunc reverse(ids []compact.NodeID) []compact.NodeID {\n\tfor i, j := 0, len(ids)-1; i < j; i, j = i+1, j-1 {\n\t\tids[i], ids[j] = ids[j], ids[i]\n\t}\n\treturn ids\n}\nmerkle: Refactor snapshotConsistency function (#2163)\/\/ Copyright 2016 Google LLC. All Rights Reserved.\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 merkle\n\nimport (\n\t\"fmt\"\n\t\"math\/bits\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/trillian\/merkle\/compact\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\n\/\/ Verbosity levels for logging of debug related items\nconst vLevel = 2\nconst vvLevel = 4\n\n\/\/ NodeFetch bundles a nodeID with additional information on how to use the node to construct the\n\/\/ correct proof.\ntype NodeFetch struct {\n\tID compact.NodeID\n\tRehash bool\n}\n\n\/\/ checkSnapshot performs a couple of simple sanity checks on ss and treeSize\n\/\/ and returns an error if there's a problem.\nfunc checkSnapshot(ssDesc string, ss, treeSize int64) error {\n\tif ss < 1 {\n\t\treturn fmt.Errorf(\"%s %d < 1\", ssDesc, ss)\n\t}\n\tif ss > treeSize {\n\t\treturn fmt.Errorf(\"%s %d > treeSize %d\", ssDesc, ss, treeSize)\n\t}\n\treturn nil\n}\n\n\/\/ CalcInclusionProofNodeAddresses returns the tree node IDs needed to build an\n\/\/ inclusion proof for a specified leaf and tree size. The snapshot parameter\n\/\/ is the tree size being queried for, treeSize is the actual size of the tree\n\/\/ at the revision we are using to fetch nodes (this can be > snapshot).\nfunc CalcInclusionProofNodeAddresses(snapshot, index, treeSize int64) ([]NodeFetch, error) {\n\tif err := checkSnapshot(\"snapshot\", snapshot, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: %v\", err)\n\t}\n\tif index >= snapshot {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: index %d is >= snapshot %d\", index, snapshot)\n\t}\n\tif index < 0 {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for inclusion proof: index %d is < 0\", index)\n\t}\n\t\/\/ Note: If snapshot < treeSize, the storage might not contain the\n\t\/\/ \"ephemeral\" node of this proof, so rehashing is needed.\n\treturn proofNodes(uint64(index), 0, uint64(snapshot), snapshot < treeSize), nil\n}\n\n\/\/ CalcConsistencyProofNodeAddresses returns the tree node IDs needed to build\n\/\/ a consistency proof between two specified tree sizes. snapshot1 and\n\/\/ snapshot2 represent the two tree sizes for which consistency should be\n\/\/ proved, treeSize is the actual size of the tree at the revision we are using\n\/\/ to fetch nodes (this can be > snapshot2).\n\/\/\n\/\/ The caller is responsible for checking that the input tree sizes correspond\n\/\/ to valid tree heads. All returned NodeIDs are tree coordinates within the\n\/\/ new tree. It is assumed that they will be fetched from storage at a revision\n\/\/ corresponding to the STH associated with the treeSize parameter.\nfunc CalcConsistencyProofNodeAddresses(snapshot1, snapshot2, treeSize int64) ([]NodeFetch, error) {\n\tif err := checkSnapshot(\"snapshot1\", snapshot1, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: %v\", err)\n\t}\n\tif err := checkSnapshot(\"snapshot2\", snapshot2, treeSize); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: %v\", err)\n\t}\n\tif snapshot1 > snapshot2 {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"invalid parameter for consistency proof: snapshot1 %d > snapshot2 %d\", snapshot1, snapshot2)\n\t}\n\n\treturn snapshotConsistency(snapshot1, snapshot2, treeSize)\n}\n\n\/\/ snapshotConsistency does the calculation of consistency proof node addresses\n\/\/ between two snapshots in a bigger tree of the given size.\nfunc snapshotConsistency(snapshot1, snapshot2, treeSize int64) ([]NodeFetch, error) {\n\tglog.V(vLevel).Infof(\"snapshotConsistency: %d -> %d\", snapshot1, snapshot2)\n\tif snapshot1 == snapshot2 {\n\t\treturn []NodeFetch{}, nil\n\t}\n\n\t\/\/ TODO(pavelkalinnikov): Make the capacity estimate accurate.\n\tproof := make([]NodeFetch, 0, bits.Len64(uint64(snapshot2))+1)\n\n\t\/\/ Find the biggest perfect subtree that ends at snapshot1.\n\tlevel := uint(bits.TrailingZeros64(uint64(snapshot1)))\n\tindex := uint64((snapshot1 - 1)) >> level\n\t\/\/ If it does not cover the whole snapshot1 tree, add this node to the proof.\n\tif index != 0 {\n\t\tglog.V(vvLevel).Infof(\"Not root snapshot1: %d\", index)\n\t\tn := compact.NewNodeID(level, index)\n\t\tproof = append(proof, NodeFetch{ID: n})\n\t}\n\n\t\/\/ Now append the path from this node to the root of snapshot2.\n\tp := proofNodes(index, level, uint64(snapshot2), snapshot2 < treeSize)\n\treturn append(proof, p...), nil\n}\n\n\/\/ proofNodes returns the node IDs necessary to prove that the (level, index)\n\/\/ node is included in the Merkle tree of the given size.\nfunc proofNodes(index uint64, level uint, size uint64, rehash bool) []NodeFetch {\n\t\/\/ [begin, end) is the leaves range covered by the (level, index) node.\n\tbegin, end := index< 1\n\t\t} else {\n\t\t\t\/\/ The parent of the highest node in [end+l, size) is \"ephemeral\".\n\t\t\tlvl := uint(bits.Len64(r))\n\t\t\t\/\/ Except when [end+l, size) is a perfect subtree, in which case we just\n\t\t\t\/\/ take the root node.\n\t\t\tif r&(r-1) == 0 {\n\t\t\t\tlvl--\n\t\t\t}\n\t\t\tright = []compact.NodeID{compact.NewNodeID(lvl, (end+l)>>lvl)}\n\t\t}\n\t}\n\n\t\/\/ The level in the ordered list of nodes where the rehashed nodes appear in\n\t\/\/ lieu of the \"ephemeral\" node. This is equal to the level where the path to\n\t\/\/ the `begin` index diverges from the path to `size`.\n\trehashLevel := uint(bits.Len64(begin^size) - 1)\n\n\t\/\/ Merge the three compact ranges into a single proof ordered by node level\n\t\/\/ from leaves towards the root, i.e. the format specified in RFC 6962.\n\tproof := make([]NodeFetch, 0, len(left)+len(middle)+len(right))\n\ti, j := 0, 0\n\tfor l, levels := level, uint(bits.Len64(size-1)); l < levels; l++ {\n\t\tif i < len(left) && left[i].Level == l {\n\t\t\tproof = append(proof, NodeFetch{ID: left[i]})\n\t\t\ti++\n\t\t} else if j < len(middle) && middle[j].Level == l {\n\t\t\tproof = append(proof, NodeFetch{ID: middle[j]})\n\t\t\tj++\n\t\t}\n\t\tif l == rehashLevel {\n\t\t\tfor _, id := range right {\n\t\t\t\tproof = append(proof, NodeFetch{ID: id, Rehash: rehash})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn proof\n}\n\nfunc reverse(ids []compact.NodeID) []compact.NodeID {\n\tfor i, j := 0, len(ids)-1; i < j; i, j = i+1, j-1 {\n\t\tids[i], ids[j] = ids[j], ids[i]\n\t}\n\treturn ids\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 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\/\/ https:\/\/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 aip0131\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\tdpb \"github.com\/golang\/protobuf\/protoc-gen-go\/descriptor\"\n\t\"github.com\/jhump\/protoreflect\/desc\/builder\"\n\t\"google.golang.org\/genproto\/googleapis\/api\/annotations\"\n)\n\nfunc TestRequestMessageName(t *testing.T) {\n\t\/\/ Set up the testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\tmethodName string\n\t\treqMessageName string\n\t\tproblemCount int\n\t\terrPrefix string\n\t}{\n\t\t{\"Valid\", \"GetBook\", \"GetBookRequest\", 0, \"False positive\"},\n\t\t{\"Invalid\", \"GetBook\", \"Book\", 1, \"False negative\"},\n\t\t{\"GetIamPolicy\", \"GetIamPolicy\", \"GetIamPolicyRequest\", 0, \"False positive\"},\n\t\t{\"Irrelevant\", \"AcquireBook\", \"Book\", 0, \"False positive\"},\n\t}\n\n\t\/\/ Run each test individually.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(test.reqMessageName), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the lint rule, and establish that it returns the correct\n\t\t\t\/\/ number of problems.\n\t\t\tif problems := requestMessageName.Lint(service.GetFile()); len(problems) != test.problemCount {\n\t\t\t\tt.Errorf(\"%s on rule %s: %#v\", test.errPrefix, requestMessageName.Name, problems)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestResponseMessageName(t *testing.T) {\n\t\/\/ Set up the testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\tmethodName string\n\t\trespMessageName string\n\t\tproblemCount int\n\t\terrPrefix string\n\t}{\n\t\t{\"Valid\", \"GetBook\", \"Book\", 0, \"False positive\"},\n\t\t{\"Invalid\", \"GetBook\", \"GetBookResponse\", 1, \"False negative\"},\n\t\t{\"Irrelevant\", \"AcquireBook\", \"AcquireBookResponse\", 0, \"False positive\"},\n\t}\n\n\t\/\/ Run each test individually.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(test.respMessageName), false),\n\t\t\t)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the lint rule, and establish that it returns the correct\n\t\t\t\/\/ number of problems.\n\t\t\tif problems := responseMessageName.Lint(service.GetFile()); len(problems) != test.problemCount {\n\t\t\t\tt.Errorf(\"%s on rule %s: %#v\", test.errPrefix, responseMessageName.Name, problems)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpVerb(t *testing.T) {\n\t\/\/ Set up GET and POST HTTP annotations.\n\thttpGet := &annotations.HttpRule{\n\t\tPattern: &annotations.HttpRule_Get{\n\t\t\tGet: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t},\n\t}\n\thttpPost := &annotations.HttpRule{\n\t\tPattern: &annotations.HttpRule_Post{\n\t\t\tPost: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t},\n\t}\n\n\t\/\/ Set up testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\thttpRule *annotations.HttpRule\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", httpGet, \"GetBook\", \"\"},\n\t\t{\"Invalid\", httpPost, \"GetBook\", \"HTTP GET\"},\n\t\t{\"Irrelevant\", httpPost, \"AcquireBook\", \"\"},\n\t}\n\n\t\/\/ Run each test.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, test.httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpVerb.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpBody(t *testing.T) {\n\ttests := []struct {\n\t\ttestName string\n\t\tbody string\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", \"\", \"GetBook\", \"\"},\n\t\t{\"Invalid\", \"*\", \"GetBook\", \"HTTP body\"},\n\t\t{\"Irrelevant\", \"*\", \"AcquireBook\", \"\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\thttpRule := &annotations.HttpRule{\n\t\t\t\tPattern: &annotations.HttpRule_Get{\n\t\t\t\t\tGet: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t\t\t},\n\t\t\t\tBody: test.body,\n\t\t\t}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpBody.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpNameField(t *testing.T) {\n\ttests := []struct {\n\t\ttestName string\n\t\turi string\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", \"\/v1\/{name=publishers\/*\/books\/*}\", \"GetBook\", \"\"},\n\t\t{\"InvalidVarName\", \"\/v1\/{book=publishers\/*\/books\/*}\", \"GetBook\", \"`name` field\"},\n\t\t{\"NoVarName\", \"\/v1\/publishers\/*\/books\/*\", \"GetBook\", \"`name` field\"},\n\t\t{\"Irrelevant\", \"\/v1\/{book=publishers\/*\/books\/*}\", \"AcquireBook\", \"\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\thttpRule := &annotations.HttpRule{\n\t\t\t\tPattern: &annotations.HttpRule_Get{\n\t\t\t\t\tGet: test.uri,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpNameField.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && len(problems) == 0 {\n\t\t\t\tt.Errorf(\"Got no problems, expected 1.\")\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n[refactor] Make AIP-131 tests use testutils.Problems. (#198)\/\/ Copyright 2019 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\/\/ https:\/\/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 aip0131\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\tdpb \"github.com\/golang\/protobuf\/protoc-gen-go\/descriptor\"\n\t\"github.com\/googleapis\/api-linter\/rules\/internal\/testutils\"\n\t\"github.com\/jhump\/protoreflect\/desc\/builder\"\n\t\"google.golang.org\/genproto\/googleapis\/api\/annotations\"\n)\n\nfunc TestRequestMessageName(t *testing.T) {\n\t\/\/ Set up the testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\tmethodName string\n\t\treqMessageName string\n\t\tproblems testutils.Problems\n\t}{\n\t\t{\"Valid\", \"GetBook\", \"GetBookRequest\", testutils.Problems{}},\n\t\t{\"Invalid\", \"GetBook\", \"Book\", testutils.Problems{{Suggestion: \"GetBookRequest\"}}},\n\t\t{\"GetIamPolicy\", \"GetIamPolicy\", \"GetIamPolicyRequest\", testutils.Problems{}},\n\t\t{\"Irrelevant\", \"AcquireBook\", \"Book\", testutils.Problems{}},\n\t}\n\n\t\/\/ Run each test individually.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(test.reqMessageName), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the lint rule, and establish that it returns the expected problems.\n\t\t\tproblems := requestMessageName.Lint(service.GetFile())\n\t\t\tif diff := test.problems.SetDescriptor(service.GetMethods()[0]).Diff(problems); diff != \"\" {\n\t\t\t\tt.Errorf(diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestResponseMessageName(t *testing.T) {\n\t\/\/ Set up the testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\tmethodName string\n\t\trespMessageName string\n\t\tproblems testutils.Problems\n\t}{\n\t\t{\"Valid\", \"GetBook\", \"Book\", testutils.Problems{}},\n\t\t{\"Invalid\", \"GetBook\", \"GetBookResponse\", testutils.Problems{{Suggestion: \"Book\"}}},\n\t\t{\"Irrelevant\", \"AcquireBook\", \"AcquireBookResponse\", testutils.Problems{}},\n\t}\n\n\t\/\/ Run each test individually.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(test.respMessageName), false),\n\t\t\t)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the lint rule, and establish that it returns the correct\n\t\t\t\/\/ number of problems.\n\t\t\tproblems := responseMessageName.Lint(service.GetFile())\n\t\t\tif diff := test.problems.SetDescriptor(service.GetMethods()[0]).Diff(problems); diff != \"\" {\n\t\t\t\tt.Errorf(diff)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpVerb(t *testing.T) {\n\t\/\/ Set up GET and POST HTTP annotations.\n\thttpGet := &annotations.HttpRule{\n\t\tPattern: &annotations.HttpRule_Get{\n\t\t\tGet: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t},\n\t}\n\thttpPost := &annotations.HttpRule{\n\t\tPattern: &annotations.HttpRule_Post{\n\t\t\tPost: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t},\n\t}\n\n\t\/\/ Set up testing permutations.\n\ttests := []struct {\n\t\ttestName string\n\t\thttpRule *annotations.HttpRule\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", httpGet, \"GetBook\", \"\"},\n\t\t{\"Invalid\", httpPost, \"GetBook\", \"HTTP GET\"},\n\t\t{\"Irrelevant\", httpPost, \"AcquireBook\", \"\"},\n\t}\n\n\t\/\/ Run each test.\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, test.httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpVerb.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpBody(t *testing.T) {\n\ttests := []struct {\n\t\ttestName string\n\t\tbody string\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", \"\", \"GetBook\", \"\"},\n\t\t{\"Invalid\", \"*\", \"GetBook\", \"HTTP body\"},\n\t\t{\"Irrelevant\", \"*\", \"AcquireBook\", \"\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\thttpRule := &annotations.HttpRule{\n\t\t\t\tPattern: &annotations.HttpRule_Get{\n\t\t\t\t\tGet: \"\/v1\/{name=publishers\/*\/books\/*}\",\n\t\t\t\t},\n\t\t\t\tBody: test.body,\n\t\t\t}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpBody.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHttpNameField(t *testing.T) {\n\ttests := []struct {\n\t\ttestName string\n\t\turi string\n\t\tmethodName string\n\t\tmsg string\n\t}{\n\t\t{\"Valid\", \"\/v1\/{name=publishers\/*\/books\/*}\", \"GetBook\", \"\"},\n\t\t{\"InvalidVarName\", \"\/v1\/{book=publishers\/*\/books\/*}\", \"GetBook\", \"`name` field\"},\n\t\t{\"NoVarName\", \"\/v1\/publishers\/*\/books\/*\", \"GetBook\", \"`name` field\"},\n\t\t{\"Irrelevant\", \"\/v1\/{book=publishers\/*\/books\/*}\", \"AcquireBook\", \"\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.testName, func(t *testing.T) {\n\t\t\t\/\/ Create a MethodOptions with the annotation set.\n\t\t\topts := &dpb.MethodOptions{}\n\t\t\thttpRule := &annotations.HttpRule{\n\t\t\t\tPattern: &annotations.HttpRule_Get{\n\t\t\t\t\tGet: test.uri,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif err := proto.SetExtension(opts, annotations.E_Http, httpRule); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to set google.api.http annotation.\")\n\t\t\t}\n\n\t\t\t\/\/ Create a minimal service with a AIP-131 Get method\n\t\t\t\/\/ (or with a different method, in the \"Irrelevant\" case).\n\t\t\tservice, err := builder.NewService(\"Library\").AddMethod(builder.NewMethod(test.methodName,\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"GetBookRequest\"), false),\n\t\t\t\tbuilder.RpcTypeMessage(builder.NewMessage(\"Book\"), false),\n\t\t\t).SetOptions(opts)).Build()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Could not build %s method.\", test.methodName)\n\t\t\t}\n\n\t\t\t\/\/ Run the method, ensure we get what we expect.\n\t\t\tproblems := httpNameField.Lint(service.GetFile())\n\t\t\tif test.msg == \"\" && len(problems) > 0 {\n\t\t\t\tt.Errorf(\"Got %v, expected no problems.\", problems)\n\t\t\t} else if test.msg != \"\" && len(problems) == 0 {\n\t\t\t\tt.Errorf(\"Got no problems, expected 1.\")\n\t\t\t} else if test.msg != \"\" && !strings.Contains(problems[0].Message, test.msg) {\n\t\t\t\tt.Errorf(\"Got %q, expected message containing %q\", problems[0].Message, test.msg)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright ©2017 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 sampleuv\n\nimport (\n\t\"math\/rand\"\n\t\"sort\"\n)\n\n\/\/ WithoutReplacement samples len(idxs) integers from [0, n) without replacement.\n\/\/ That is, upon return the elements of idxs will be unique integers. If source\n\/\/ is non-nil it will be used to generate random numbers, otherwise the default\n\/\/ source from the math\/rand package will be used.\n\/\/\n\/\/ WithoutReplacement will panic if len(idxs) > n.\nfunc WithoutReplacement(idxs []int, n int, src *rand.Rand) {\n\tif len(idxs) == 0 {\n\t\tpanic(\"withoutreplacement: zero length input\")\n\t}\n\tif len(idxs) > n {\n\t\tpanic(\"withoutreplacement: impossible size inputs\")\n\t}\n\n\t\/\/ There are two algorithms. One is to generate a random permutation\n\t\/\/ and take the first len(idxs) elements. The second is to generate\n\t\/\/ individual random numbers for each element and check uniqueness. The first\n\t\/\/ method scales as O(n), and the second scales as O(len(idxs)^2). Choose\n\t\/\/ the algorithm accordingly.\n\tif n < len(idxs)*len(idxs) {\n\t\tvar perm []int\n\t\tif src != nil {\n\t\t\tperm = src.Perm(n)\n\t\t} else {\n\t\t\tperm = rand.Perm(n)\n\t\t}\n\t\tcopy(idxs, perm)\n\t}\n\n\t\/\/ Instead, generate the random numbers directly.\n\tsorted := make([]int, 0, len(idxs))\n\tfor i := range idxs {\n\t\tvar r int\n\t\tif src != nil {\n\t\t\tr = src.Intn(n - i)\n\t\t} else {\n\t\t\tr = rand.Intn(n - i)\n\t\t}\n\t\tfor _, v := range sorted {\n\t\t\tif r >= v {\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\t\tidxs[i] = r\n\t\tsorted = append(sorted, r)\n\t\tsort.Ints(sorted)\n\t}\n}\nstat\/sampleuv: add missing return\/\/ Copyright ©2017 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 sampleuv\n\nimport (\n\t\"math\/rand\"\n\t\"sort\"\n)\n\n\/\/ WithoutReplacement samples len(idxs) integers from [0, n) without replacement.\n\/\/ That is, upon return the elements of idxs will be unique integers. If source\n\/\/ is non-nil it will be used to generate random numbers, otherwise the default\n\/\/ source from the math\/rand package will be used.\n\/\/\n\/\/ WithoutReplacement will panic if len(idxs) > n.\nfunc WithoutReplacement(idxs []int, n int, src *rand.Rand) {\n\tif len(idxs) == 0 {\n\t\tpanic(\"withoutreplacement: zero length input\")\n\t}\n\tif len(idxs) > n {\n\t\tpanic(\"withoutreplacement: impossible size inputs\")\n\t}\n\n\t\/\/ There are two algorithms. One is to generate a random permutation\n\t\/\/ and take the first len(idxs) elements. The second is to generate\n\t\/\/ individual random numbers for each element and check uniqueness. The first\n\t\/\/ method scales as O(n), and the second scales as O(len(idxs)^2). Choose\n\t\/\/ the algorithm accordingly.\n\tif n < len(idxs)*len(idxs) {\n\t\tvar perm []int\n\t\tif src != nil {\n\t\t\tperm = src.Perm(n)\n\t\t} else {\n\t\t\tperm = rand.Perm(n)\n\t\t}\n\t\tcopy(idxs, perm)\n\t\treturn\n\t}\n\n\t\/\/ Instead, generate the random numbers directly.\n\tsorted := make([]int, 0, len(idxs))\n\tfor i := range idxs {\n\t\tvar r int\n\t\tif src != nil {\n\t\t\tr = src.Intn(n - i)\n\t\t} else {\n\t\t\tr = rand.Intn(n - i)\n\t\t}\n\t\tfor _, v := range sorted {\n\t\t\tif r >= v {\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\t\tidxs[i] = r\n\t\tsorted = append(sorted, r)\n\t\tsort.Ints(sorted)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc Test_parseCGIHeaders(t *testing.T) {\n\tdata := []struct {\n\t\tin string\n\t\tout string\n\t\theaders map[string]string\n\t}{\n\t\t{\n\t\t\tin: \"Some text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\n\\nSome text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{\"Location\": \"url\"},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\n\\n\",\n\t\t\tout: \"\",\n\t\t\theaders: map[string]string{\"Location\": \"url\"},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\nX-Name: x-value\\n\\nSome text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{\"Location\": \"url\", \"X-Name\": \"x-value\"},\n\t\t},\n\t}\n\n\tfor i, item := range data {\n\t\tout, headers := parseCGIHeaders(item.in)\n\t\tif !reflect.DeepEqual(item.headers, headers) || item.out != out {\n\t\t\tt.Errorf(\"%d:\\nexpected: %s \/ %#v\\nreal : %s \/ %#v\", i, item.out, item.headers, out, headers)\n\t\t}\n\t}\n}\n\nfunc Test_getShellAndParams(t *testing.T) {\n\tshell, params, err := getShellAndParams(\"ls\", \"sh\", false)\n\tif shell != \"sh\" || !reflect.DeepEqual(params, []string{\"-c\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"1. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls\", \"sh\", true)\n\tif shell != \"cmd\" || !reflect.DeepEqual(params, []string{\"\/C\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"2. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls\", \"bash\", false)\n\tif shell != \"bash\" || !reflect.DeepEqual(params, []string{\"-c\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"3. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls -l -a\", \"\", false)\n\tif shell != \"ls\" || !reflect.DeepEqual(params, []string{\"-l\", \"-a\"}) || err != nil {\n\t\tt.Errorf(\"4. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls -l 'a b'\", \"\", false)\n\tif shell != \"ls\" || !reflect.DeepEqual(params, []string{\"-l\", \"a b\"}) || err != nil {\n\t\tt.Errorf(\"5. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls '-l\", \"\", false)\n\tif err == nil {\n\t\tt.Errorf(\"6. getShellAndParams() failed\")\n\t}\n}\nFirst version of test mainpackage main\n\nimport (\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc Test_parseCGIHeaders(t *testing.T) {\n\tdata := []struct {\n\t\tin string\n\t\tout string\n\t\theaders map[string]string\n\t}{\n\t\t{\n\t\t\tin: \"Some text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\n\\nSome text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{\"Location\": \"url\"},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\n\\n\",\n\t\t\tout: \"\",\n\t\t\theaders: map[string]string{\"Location\": \"url\"},\n\t\t},\n\t\t{\n\t\t\tin: \"Location: url\\nX-Name: x-value\\n\\nSome text\",\n\t\t\tout: \"Some text\",\n\t\t\theaders: map[string]string{\"Location\": \"url\", \"X-Name\": \"x-value\"},\n\t\t},\n\t}\n\n\tfor i, item := range data {\n\t\tout, headers := parseCGIHeaders(item.in)\n\t\tif !reflect.DeepEqual(item.headers, headers) || item.out != out {\n\t\t\tt.Errorf(\"%d:\\nexpected: %s \/ %#v\\nreal : %s \/ %#v\", i, item.out, item.headers, out, headers)\n\t\t}\n\t}\n}\n\nfunc Test_getShellAndParams(t *testing.T) {\n\tshell, params, err := getShellAndParams(\"ls\", \"sh\", false)\n\tif shell != \"sh\" || !reflect.DeepEqual(params, []string{\"-c\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"1. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls\", \"sh\", true)\n\tif shell != \"cmd\" || !reflect.DeepEqual(params, []string{\"\/C\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"2. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls\", \"bash\", false)\n\tif shell != \"bash\" || !reflect.DeepEqual(params, []string{\"-c\", \"ls\"}) || err != nil {\n\t\tt.Errorf(\"3. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls -l -a\", \"\", false)\n\tif shell != \"ls\" || !reflect.DeepEqual(params, []string{\"-l\", \"-a\"}) || err != nil {\n\t\tt.Errorf(\"4. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls -l 'a b'\", \"\", false)\n\tif shell != \"ls\" || !reflect.DeepEqual(params, []string{\"-l\", \"a b\"}) || err != nil {\n\t\tt.Errorf(\"5. getShellAndParams() failed\")\n\t}\n\n\tshell, params, err = getShellAndParams(\"ls '-l\", \"\", false)\n\tif err == nil {\n\t\tt.Errorf(\"6. getShellAndParams() failed\")\n\t}\n}\n\nfunc httpGet(url string) ([]byte, error) {\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tdefer res.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}\n\nfunc getFreePort() string {\n\tlisten, _ := net.Listen(\"tcp\", \":0\")\n\tdefer listen.Close()\n\tparts := strings.Split(listen.Addr().String(), \":\")\n\n\treturn parts[len(parts)-1]\n}\n\nfunc Test_main1(t *testing.T) {\n\tport := getFreePort()\n\tos.Args = []string{\"shell2http\",\n\t\t\"-add-exit\",\n\t\t\"-cache=1\",\n\t\t\"-cgi\",\n\t\t\"-export-all-vars\",\n\t\t\"-form\",\n\t\t\"-one-thread\",\n\t\t\"-shell=bash\",\n\t\t\"-log=\/dev\/null\",\n\t\t\"-port=\" + port,\n\t\t\"\/echo\", \"echo 123\"}\n\tgo main()\n\n\tres, err := httpGet(\"http:\/\/localhost:\" + port + \"\/\")\n\tif err != nil {\n\t\tt.Errorf(\"1. main() failed: %s\", err)\n\t}\n\tif len(res) == 0 || !strings.HasPrefix(string(res), \"\") {\n\t\tt.Errorf(\"1. main() failed: real result: '%s'\", string(res))\n\t}\n\n\tres, err = httpGet(\"http:\/\/localhost:\" + port + \"\/echo\")\n\tif err != nil {\n\t\tt.Errorf(\"2. main() failed: %s\", err)\n\t}\n\tif string(res) != \"123\\n\" {\n\t\tt.Errorf(\"2. main() failed: real result: '%s'\", string(res))\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/google\/go-cmp\/cmp\/cmpopts\"\n\t\"github.com\/influxdata\/flux\"\n\t\"github.com\/influxdata\/flux\/semantic\/semantictest\"\n\tplatform \"github.com\/influxdata\/influxdb\/v2\"\n\t\"github.com\/influxdata\/influxdb\/v2\/mock\"\n\t\"github.com\/influxdata\/influxdb\/v2\/query\/influxql\"\n\tplatformtesting \"github.com\/influxdata\/influxdb\/v2\/testing\"\n)\n\nfunc printUsage() {\n\tfmt.Println(\"usage: prepcsvtests \/path\/to\/testfiles [testname]\")\n}\n\nfunc main() {\n\tfnames := make([]string, 0)\n\tpath := \"\"\n\tvar err error\n\tif len(os.Args) == 3 {\n\t\tpath = os.Args[1]\n\t\tfnames = append(fnames, filepath.Join(path, os.Args[2])+\".flux\")\n\t} else if len(os.Args) == 2 {\n\t\tpath = os.Args[1]\n\t\tfnames, err = filepath.Glob(filepath.Join(path, \"*.flux\"))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tprintUsage()\n\t\treturn\n\t}\n\n\tfor _, fname := range fnames {\n\t\text := \".flux\"\n\t\ttestName := fname[0 : len(fname)-len(ext)]\n\n\t\tfluxText, err := ioutil.ReadFile(fname)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error reading ifq\tl query text: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tinfluxqlText, err := ioutil.ReadFile(testName + \".influxql\")\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error reading influxql query text: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tfluxSpec, err := flux.Compile(context.Background(), string(fluxText), time.Now().UTC())\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error compiling. \\n query: \\n %s \\n err: %s\", string(fluxText), err)\n\t\t\treturn\n\t\t}\n\n\t\ttranspiler := influxql.NewTranspiler(dbrpMappingSvc)\n\t\tinfluxqlSpec, err := transpiler.Transpile(context.Background(), string(influxqlText))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error transpiling. \\n query: \\n %s \\n err: %s\", string(influxqlText), err)\n\t\t\treturn\n\t\t}\n\t\tvar opts = append(\n\t\t\tsemantictest.CmpOptions,\n\t\t\tcmp.AllowUnexported(flux.Spec{}),\n\t\t\tcmpopts.IgnoreUnexported(flux.Spec{}))\n\n\t\tdifference := cmp.Diff(fluxSpec, influxqlSpec, opts...)\n\n\t\tfmt.Printf(\"compiled vs transpiled diff: \\n%s\", difference)\n\t}\n}\n\n\/\/ Setup mock DBRPMappingService to always return `db.rp`.\nvar dbrpMappingSvc = mock.NewDBRPMappingService()\n\nfunc init() {\n\tmapping := platform.DBRPMapping{\n\t\tCluster: \"cluster\",\n\t\tDatabase: \"db\",\n\t\tRetentionPolicy: \"rp\",\n\t\tDefault: true,\n\t\tOrganizationID: platformtesting.MustIDBase16(\"aaaaaaaaaaaaaaaa\"),\n\t\tBucketID: platformtesting.MustIDBase16(\"bbbbbbbbbbbbbbbb\"),\n\t}\n\tdbrpMappingSvc.FindByFn = func(ctx context.Context, cluster string, db string, rp string) (*platform.DBRPMapping, error) {\n\t\treturn &mapping, nil\n\t}\n\tdbrpMappingSvc.FindFn = func(ctx context.Context, filter platform.DBRPMappingFilter) (*platform.DBRPMapping, error) {\n\t\treturn &mapping, nil\n\t}\n\tdbrpMappingSvc.FindManyFn = func(ctx context.Context, filter platform.DBRPMappingFilter, opt ...platform.FindOptions) ([]*platform.DBRPMapping, int, error) {\n\t\treturn []*platform.DBRPMapping{&mapping}, 1, nil\n\t}\n}\nchore: delete unused, broken 'compspecs' testing tool (#22335)<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype SingleRule struct {\n\tcolor string\n\tregex string\n}\n\ntype MultiRule struct {\n\tcolor string\n\tstart string\n\tend string\n}\n\n\/\/ JoinRule takes a syntax rule (which can be multiple regular expressions)\n\/\/ and joins it into one regular expression by ORing everything together\nfunc JoinRule(rule string) string {\n\tsplit := strings.Split(rule, `\" \"`)\n\tjoined := strings.Join(split, \"|\")\n\tjoined = joined\n\treturn joined\n}\n\nfunc parseFile(text, filename string) (filetype, syntax, header string, rules []interface{}) {\n\tlines := strings.Split(text, \"\\n\")\n\n\t\/\/ Regex for parsing syntax statements\n\tsyntaxParser := regexp.MustCompile(`syntax \"(.*?)\"\\s+\"(.*)\"+`)\n\t\/\/ Regex for parsing header statements\n\theaderParser := regexp.MustCompile(`header \"(.*)\"`)\n\n\t\/\/ Regex for parsing standard syntax rules\n\truleParser := regexp.MustCompile(`color (.*?)\\s+(?:\\((.+?)?\\)\\s+)?\"(.*)\"`)\n\t\/\/ Regex for parsing syntax rules with start=\"...\" end=\"...\"\n\truleStartEndParser := regexp.MustCompile(`color (.*?)\\s+(?:\\((.+?)?\\)\\s+)?start=\"(.*)\"\\s+end=\"(.*)\"`)\n\n\tfor lineNum, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, \"syntax\") {\n\t\t\tsyntaxMatches := syntaxParser.FindSubmatch([]byte(line))\n\t\t\tif len(syntaxMatches) == 3 {\n\t\t\t\tfiletype = string(syntaxMatches[1])\n\t\t\t\tsyntax = JoinRule(string(syntaxMatches[2]))\n\t\t\t} else {\n\t\t\t\tfmt.Println(filename, lineNum, \"Syntax statement is not valid: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(line, \"header\") {\n\t\t\t\/\/ Header statement\n\t\t\theaderMatches := headerParser.FindSubmatch([]byte(line))\n\t\t\tif len(headerMatches) == 2 {\n\t\t\t\theader = JoinRule(string(headerMatches[1]))\n\t\t\t} else {\n\t\t\t\tfmt.Println(filename, lineNum, \"Header statement is not valid: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Syntax rule, but it could be standard or start-end\n\t\tif ruleParser.MatchString(line) {\n\t\t\t\/\/ Standard syntax rule\n\t\t\t\/\/ Parse the line\n\t\t\tsubmatch := ruleParser.FindSubmatch([]byte(line))\n\t\t\tvar color string\n\t\t\tvar regexStr string\n\t\t\tvar flags string\n\t\t\tif len(submatch) == 4 {\n\t\t\t\t\/\/ If len is 4 then the user specified some additional flags to use\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tflags = string(submatch[2])\n\t\t\t\tif flags != \"\" {\n\t\t\t\t\tregexStr = \"(?\" + flags + \")\" + JoinRule(string(submatch[3]))\n\t\t\t\t} else {\n\t\t\t\t\tregexStr = JoinRule(string(submatch[3]))\n\t\t\t\t}\n\t\t\t} else if len(submatch) == 3 {\n\t\t\t\t\/\/ If len is 3, no additional flags were given\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tregexStr = JoinRule(string(submatch[2]))\n\t\t\t} else {\n\t\t\t\t\/\/ If len is not 3 or 4 there is a problem\n\t\t\t\tfmt.Println(filename, lineNum, \"Invalid statement: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trules = append(rules, SingleRule{color, regexStr})\n\t\t} else if ruleStartEndParser.MatchString(line) {\n\t\t\t\/\/ Start-end syntax rule\n\t\t\tsubmatch := ruleStartEndParser.FindSubmatch([]byte(line))\n\t\t\tvar color string\n\t\t\tvar start string\n\t\t\tvar end string\n\t\t\t\/\/ Use m and s flags by default\n\t\t\tflags := \"ms\"\n\t\t\tif len(submatch) == 5 {\n\t\t\t\t\/\/ If len is 5 the user provided some additional flags\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tflags += string(submatch[2])\n\t\t\t\tstart = string(submatch[3])\n\t\t\t\tend = string(submatch[4])\n\t\t\t} else if len(submatch) == 4 {\n\t\t\t\t\/\/ If len is 4 the user did not provide additional flags\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tstart = string(submatch[2])\n\t\t\t\tend = string(submatch[3])\n\t\t\t} else {\n\t\t\t\t\/\/ If len is not 4 or 5 there is a problem\n\t\t\t\tfmt.Println(filename, lineNum, \"Invalid statement: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ rules[color] = \"(?\" + flags + \")\" + \"(\" + start + \").*?(\" + end + \")\"\n\t\t\trules = append(rules, MultiRule{color, start, end})\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc generateFile(filetype, syntax, header string, rules []interface{}) string {\n\toutput := \"\"\n\n\toutput += fmt.Sprintf(\"filetype: %s\\n\\n\", filetype)\n\toutput += fmt.Sprintf(\"detect: \\n\\tfilename: \\\"%s\\\"\\n\", strings.Replace(syntax, \"\\\\\", \"\\\\\\\\\", -1))\n\n\tif header != \"\" {\n\t\toutput += fmt.Sprintf(\"\\theader: \\\"%s\\\"\\n\", strings.Replace(header, \"\\\\\", \"\\\\\\\\\", -1))\n\t}\n\n\toutput += \"\\nrules:\\n\"\n\n\tfor _, r := range rules {\n\t\tif rule, ok := r.(SingleRule); ok {\n\t\t\toutput += fmt.Sprintf(\"\\t- %s: \\\"%s\\\"\\n\", rule.color, strings.Replace(strings.Replace(rule.regex, \"\\\\\", \"\\\\\\\\\", -1), \"\\\"\", \"\\\\\\\"\", -1))\n\t\t} else if rule, ok := r.(MultiRule); ok {\n\t\t\toutput += fmt.Sprintf(\"\\t- %s:\\n\", rule.color)\n\t\t\toutput += fmt.Sprintf(\"\\t\\tstart: \\\"%s\\\"\\n\", rule.start)\n\t\t\toutput += fmt.Sprintf(\"\\t\\tend: \\\"%s\\\"\\n\", rule.end)\n\t\t\toutput += fmt.Sprintf(\"\\t\\trules: []\\n\\n\")\n\t\t}\n\t}\n\n\treturn output\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"no args\")\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadFile(os.Args[1])\n\tfmt.Print(generateFile(parseFile(string(data), os.Args[1])))\n}\nNo tabs in yamlpackage main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype SingleRule struct {\n\tcolor string\n\tregex string\n}\n\ntype MultiRule struct {\n\tcolor string\n\tstart string\n\tend string\n}\n\n\/\/ JoinRule takes a syntax rule (which can be multiple regular expressions)\n\/\/ and joins it into one regular expression by ORing everything together\nfunc JoinRule(rule string) string {\n\tsplit := strings.Split(rule, `\" \"`)\n\tjoined := strings.Join(split, \"|\")\n\tjoined = joined\n\treturn joined\n}\n\nfunc parseFile(text, filename string) (filetype, syntax, header string, rules []interface{}) {\n\tlines := strings.Split(text, \"\\n\")\n\n\t\/\/ Regex for parsing syntax statements\n\tsyntaxParser := regexp.MustCompile(`syntax \"(.*?)\"\\s+\"(.*)\"+`)\n\t\/\/ Regex for parsing header statements\n\theaderParser := regexp.MustCompile(`header \"(.*)\"`)\n\n\t\/\/ Regex for parsing standard syntax rules\n\truleParser := regexp.MustCompile(`color (.*?)\\s+(?:\\((.+?)?\\)\\s+)?\"(.*)\"`)\n\t\/\/ Regex for parsing syntax rules with start=\"...\" end=\"...\"\n\truleStartEndParser := regexp.MustCompile(`color (.*?)\\s+(?:\\((.+?)?\\)\\s+)?start=\"(.*)\"\\s+end=\"(.*)\"`)\n\n\tfor lineNum, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, \"syntax\") {\n\t\t\tsyntaxMatches := syntaxParser.FindSubmatch([]byte(line))\n\t\t\tif len(syntaxMatches) == 3 {\n\t\t\t\tfiletype = string(syntaxMatches[1])\n\t\t\t\tsyntax = JoinRule(string(syntaxMatches[2]))\n\t\t\t} else {\n\t\t\t\tfmt.Println(filename, lineNum, \"Syntax statement is not valid: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(line, \"header\") {\n\t\t\t\/\/ Header statement\n\t\t\theaderMatches := headerParser.FindSubmatch([]byte(line))\n\t\t\tif len(headerMatches) == 2 {\n\t\t\t\theader = JoinRule(string(headerMatches[1]))\n\t\t\t} else {\n\t\t\t\tfmt.Println(filename, lineNum, \"Header statement is not valid: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Syntax rule, but it could be standard or start-end\n\t\tif ruleParser.MatchString(line) {\n\t\t\t\/\/ Standard syntax rule\n\t\t\t\/\/ Parse the line\n\t\t\tsubmatch := ruleParser.FindSubmatch([]byte(line))\n\t\t\tvar color string\n\t\t\tvar regexStr string\n\t\t\tvar flags string\n\t\t\tif len(submatch) == 4 {\n\t\t\t\t\/\/ If len is 4 then the user specified some additional flags to use\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tflags = string(submatch[2])\n\t\t\t\tif flags != \"\" {\n\t\t\t\t\tregexStr = \"(?\" + flags + \")\" + JoinRule(string(submatch[3]))\n\t\t\t\t} else {\n\t\t\t\t\tregexStr = JoinRule(string(submatch[3]))\n\t\t\t\t}\n\t\t\t} else if len(submatch) == 3 {\n\t\t\t\t\/\/ If len is 3, no additional flags were given\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tregexStr = JoinRule(string(submatch[2]))\n\t\t\t} else {\n\t\t\t\t\/\/ If len is not 3 or 4 there is a problem\n\t\t\t\tfmt.Println(filename, lineNum, \"Invalid statement: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trules = append(rules, SingleRule{color, regexStr})\n\t\t} else if ruleStartEndParser.MatchString(line) {\n\t\t\t\/\/ Start-end syntax rule\n\t\t\tsubmatch := ruleStartEndParser.FindSubmatch([]byte(line))\n\t\t\tvar color string\n\t\t\tvar start string\n\t\t\tvar end string\n\t\t\t\/\/ Use m and s flags by default\n\t\t\tflags := \"ms\"\n\t\t\tif len(submatch) == 5 {\n\t\t\t\t\/\/ If len is 5 the user provided some additional flags\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tflags += string(submatch[2])\n\t\t\t\tstart = string(submatch[3])\n\t\t\t\tend = string(submatch[4])\n\t\t\t} else if len(submatch) == 4 {\n\t\t\t\t\/\/ If len is 4 the user did not provide additional flags\n\t\t\t\tcolor = string(submatch[1])\n\t\t\t\tstart = string(submatch[2])\n\t\t\t\tend = string(submatch[3])\n\t\t\t} else {\n\t\t\t\t\/\/ If len is not 4 or 5 there is a problem\n\t\t\t\tfmt.Println(filename, lineNum, \"Invalid statement: \"+line)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ rules[color] = \"(?\" + flags + \")\" + \"(\" + start + \").*?(\" + end + \")\"\n\t\t\trules = append(rules, MultiRule{color, start, end})\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc generateFile(filetype, syntax, header string, rules []interface{}) string {\n\toutput := \"\"\n\n\toutput += fmt.Sprintf(\"filetype: %s\\n\\n\", filetype)\n\toutput += fmt.Sprintf(\"detect: \\n filename: \\\"%s\\\"\\n\", strings.Replace(syntax, \"\\\\\", \"\\\\\\\\\", -1))\n\n\tif header != \"\" {\n\t\toutput += fmt.Sprintf(\" header: \\\"%s\\\"\\n\", strings.Replace(header, \"\\\\\", \"\\\\\\\\\", -1))\n\t}\n\n\toutput += \"\\nrules:\\n\"\n\n\tfor _, r := range rules {\n\t\tif rule, ok := r.(SingleRule); ok {\n\t\t\toutput += fmt.Sprintf(\" - %s: \\\"%s\\\"\\n\", rule.color, strings.Replace(strings.Replace(rule.regex, \"\\\\\", \"\\\\\\\\\", -1), \"\\\"\", \"\\\\\\\"\", -1))\n\t\t} else if rule, ok := r.(MultiRule); ok {\n\t\t\toutput += fmt.Sprintf(\" - %s:\\n\", rule.color)\n\t\t\toutput += fmt.Sprintf(\" start: \\\"%s\\\"\\n\", rule.start)\n\t\t\toutput += fmt.Sprintf(\" end: \\\"%s\\\"\\n\", rule.end)\n\t\t\toutput += fmt.Sprintf(\" rules: []\\n\\n\")\n\t\t}\n\t}\n\n\treturn output\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"no args\")\n\t\treturn\n\t}\n\n\tdata, _ := ioutil.ReadFile(os.Args[1])\n\tfmt.Print(generateFile(parseFile(string(data), os.Args[1])))\n}\n<|endoftext|>"} {"text":"package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/workers\/common\/handler\"\n\t\"socialapi\/workers\/common\/response\"\n\t\"socialapi\/workers\/realtime\/models\"\n\t\"time\"\n\n\t\"github.com\/koding\/logging\"\n)\n\ntype Handler struct {\n\tpubnub *models.Pubnub\n\tlogger logging.Logger\n}\n\nfunc NewHandler(p *models.Pubnub, l logging.Logger) *Handler {\n\treturn &Handler{\n\t\tpubnub: p,\n\t\tlogger: l,\n\t}\n}\n\n\/\/ SubscribeChannel checks users channel accessability and regarding to that\n\/\/ grants channel access for them\nfunc (h *Handler) SubscribeChannel(u *url.URL, header http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tres, err := checkParticipation(u, header, req)\n\tif err != nil {\n\t\treturn response.NewAccessDenied(err)\n\t}\n\n\t\/\/ user has access permission, now authenticate user to channel via pubnub\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewPrivateMessageChannel(*res.Channel)\n\ta.Account = res.Account\n\n\terr = h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn responseWithCookie(req, a.Account.Token)\n}\n\n\/\/ SubscribeNotification grants notification channel access for user. User information is\n\/\/ fetched from session\nfunc (h *Handler) SubscribeNotification(u *url.URL, header http.Header, temp *models.Account) (int, http.Header, interface{}, error) {\n\n\t\/\/ fetch account information from session\n\taccount, err := getAccountInfo(u, header)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\t\/\/ authenticate user to their notification channel\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewNotificationChannel(account)\n\ta.Account = account\n\n\terr = h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn responseWithCookie(temp, account.Token)\n}\n\nfunc (h *Handler) SubscribeMessage(u *url.URL, header http.Header, um *models.UpdateInstanceMessage) (int, http.Header, interface{}, error) {\n\tif um.Token == \"\" {\n\t\treturn response.NewBadRequest(models.ErrTokenNotSet)\n\t}\n\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewMessageUpdateChannel(*um)\n\terr := h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(um)\n}\n\nfunc responseWithCookie(req interface{}, token string) (int, http.Header, interface{}, error) {\n\texpires := time.Now().AddDate(5, 0, 0)\n\tcookie := &http.Cookie{\n\t\tName: \"realtimeToken\",\n\t\tValue: token,\n\t\tPath: \"\/\",\n\t\tDomain: \"lvh.me\", \/\/ TODO change this\n\t\tExpires: expires,\n\t\tRawExpires: expires.Format(time.UnixDate),\n\t\tRaw: \"realtimeToken=\" + token,\n\t\tUnparsed: []string{\"realtimeToken=\" + token},\n\t}\n\n\treturn response.NewOKWithCookie(req, []*http.Cookie{cookie})\n}\n\n\/\/ TODO needs a better request handler\nfunc checkParticipation(u *url.URL, header http.Header, cr *models.Channel) (*models.CheckParticipationResponse, error) {\n\t\/\/ relay the cookie to other endpoint\n\tcookie := header.Get(\"Cookie\")\n\trequest := &handler.Request{\n\t\tType: \"GET\",\n\t\tEndpoint: \"\/api\/social\/channel\/checkparticipation\",\n\t\tParams: map[string]string{\n\t\t\t\"name\": cr.Name,\n\t\t\t\"group\": cr.Group,\n\t\t\t\"type\": cr.Type,\n\t\t},\n\t\tCookie: cookie,\n\t}\n\n\t\/\/ TODO update this requester\n\tresp, err := handler.MakeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Need a better response\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cpr models.CheckParticipationResponse\n\terr = json.Unmarshal(body, &cpr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cpr, nil\n}\n\nfunc getAccountInfo(u *url.URL, header http.Header) (*models.Account, error) {\n\tcookie := header.Get(\"Cookie\")\n\trequest := &handler.Request{\n\t\tType: \"GET\",\n\t\tEndpoint: \"\/api\/social\/account\",\n\t\tCookie: cookie,\n\t}\n\n\t\/\/ TODO update this requester\n\tresp, err := handler.MakeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Need a better response\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar a models.Account\n\terr = json.Unmarshal(body, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &a, nil\n}\ngatekeeper: remove domain setter in cookiepackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/workers\/common\/handler\"\n\t\"socialapi\/workers\/common\/response\"\n\t\"socialapi\/workers\/realtime\/models\"\n\t\"time\"\n\n\t\"github.com\/koding\/logging\"\n)\n\ntype Handler struct {\n\tpubnub *models.Pubnub\n\tlogger logging.Logger\n}\n\nfunc NewHandler(p *models.Pubnub, l logging.Logger) *Handler {\n\treturn &Handler{\n\t\tpubnub: p,\n\t\tlogger: l,\n\t}\n}\n\n\/\/ SubscribeChannel checks users channel accessability and regarding to that\n\/\/ grants channel access for them\nfunc (h *Handler) SubscribeChannel(u *url.URL, header http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tres, err := checkParticipation(u, header, req)\n\tif err != nil {\n\t\treturn response.NewAccessDenied(err)\n\t}\n\n\t\/\/ user has access permission, now authenticate user to channel via pubnub\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewPrivateMessageChannel(*res.Channel)\n\ta.Account = res.Account\n\n\terr = h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn responseWithCookie(req, a.Account.Token)\n}\n\n\/\/ SubscribeNotification grants notification channel access for user. User information is\n\/\/ fetched from session\nfunc (h *Handler) SubscribeNotification(u *url.URL, header http.Header, temp *models.Account) (int, http.Header, interface{}, error) {\n\n\t\/\/ fetch account information from session\n\taccount, err := getAccountInfo(u, header)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\t\/\/ authenticate user to their notification channel\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewNotificationChannel(account)\n\ta.Account = account\n\n\terr = h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn responseWithCookie(temp, account.Token)\n}\n\nfunc (h *Handler) SubscribeMessage(u *url.URL, header http.Header, um *models.UpdateInstanceMessage) (int, http.Header, interface{}, error) {\n\tif um.Token == \"\" {\n\t\treturn response.NewBadRequest(models.ErrTokenNotSet)\n\t}\n\n\ta := new(models.Authenticate)\n\ta.Channel = models.NewMessageUpdateChannel(*um)\n\terr := h.pubnub.Authenticate(a)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(um)\n}\n\nfunc responseWithCookie(req interface{}, token string) (int, http.Header, interface{}, error) {\n\texpires := time.Now().AddDate(5, 0, 0)\n\tcookie := &http.Cookie{\n\t\tName: \"realtimeToken\",\n\t\tValue: token,\n\t\tPath: \"\/\",\n\t\tExpires: expires,\n\t\tRawExpires: expires.Format(time.UnixDate),\n\t\tRaw: \"realtimeToken=\" + token,\n\t\tUnparsed: []string{\"realtimeToken=\" + token},\n\t}\n\n\treturn response.NewOKWithCookie(req, []*http.Cookie{cookie})\n}\n\n\/\/ TODO needs a better request handler\nfunc checkParticipation(u *url.URL, header http.Header, cr *models.Channel) (*models.CheckParticipationResponse, error) {\n\t\/\/ relay the cookie to other endpoint\n\tcookie := header.Get(\"Cookie\")\n\trequest := &handler.Request{\n\t\tType: \"GET\",\n\t\tEndpoint: \"\/api\/social\/channel\/checkparticipation\",\n\t\tParams: map[string]string{\n\t\t\t\"name\": cr.Name,\n\t\t\t\"group\": cr.Group,\n\t\t\t\"type\": cr.Type,\n\t\t},\n\t\tCookie: cookie,\n\t}\n\n\t\/\/ TODO update this requester\n\tresp, err := handler.MakeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Need a better response\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cpr models.CheckParticipationResponse\n\terr = json.Unmarshal(body, &cpr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cpr, nil\n}\n\nfunc getAccountInfo(u *url.URL, header http.Header) (*models.Account, error) {\n\tcookie := header.Get(\"Cookie\")\n\trequest := &handler.Request{\n\t\tType: \"GET\",\n\t\tEndpoint: \"\/api\/social\/account\",\n\t\tCookie: cookie,\n\t}\n\n\t\/\/ TODO update this requester\n\tresp, err := handler.MakeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Need a better response\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar a models.Account\n\terr = json.Unmarshal(body, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &a, nil\n}\n<|endoftext|>"} {"text":"package rpm\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n)\n\n\/\/ A Header stores metadata about a rpm package.\ntype Header struct {\n\tVersion int\n\tIndexCount int\n\tLength int\n\tIndexes IndexEntries\n\tStart int\n\tEnd int\n}\n\n\/\/ Headers is an array of Header structs.\ntype Headers []Header\n\n\/\/ Predefined sizing constraints.\nconst (\n\t\/\/ MAX_HEADER_SIZE is the maximum allowable header size in bytes (32 MB).\n\tMAX_HEADER_SIZE = 33554432\n)\n\n\/\/ Predefined header errors.\nvar (\n\t\/\/ ErrBadHeaderLength indicates that the read header section is not the\n\t\/\/ expected length.\n\tErrBadHeaderLength = fmt.Errorf(\"RPM header section is incorrect length\")\n\n\t\/\/ ErrNotHeader indicates that the read header section does start with the\n\t\/\/ expected descriptor.\n\tErrNotHeader = fmt.Errorf(\"invalid RPM header descriptor\")\n\n\t\/\/ ErrBadStoreLength indicates that the read header store section is not the\n\t\/\/ expected length.\n\tErrBadStoreLength = fmt.Errorf(\"header value store is incorrect length\")\n)\n\n\/\/ Predefined header index errors.\nvar (\n\t\/\/ ErrBadIndexCount indicates that number of indexes given in the read\n\t\/\/ header would exceed the actual size of the header.\n\tErrBadIndexCount = fmt.Errorf(\"index count exceeds header size\")\n\n\t\/\/ ErrBadIndexLength indicates that the read header index section is not the\n\t\/\/ expected length.\n\tErrBadIndexLength = fmt.Errorf(\"index section is incorrect length\")\n\n\t\/\/ ErrIndexOutOfRange indicates that the read header index would exceed the\n\t\/\/ range of the header.\n\tErrIndexOutOfRange = fmt.Errorf(\"index is out of range\")\n\n\t\/\/ ErrBadIndexType indicates that the read index contains a value of an\n\t\/\/ unsupported data type.\n\tErrBadIndexType = fmt.Errorf(\"unknown index data type\")\n\n\t\/\/ ErrBadIndexValueCount indicates that the read index value would exceed\n\t\/\/ the range of the header store section.\n\tErrBadIndexValueCount = fmt.Errorf(\"index value count is out of range\")\n)\n\n\/\/ ReadPackageHeader reads an RPM package file header structure from the given\n\/\/ io.Reader.\n\/\/\n\/\/ This function should only be used if you intend to read a package header\n\/\/ structure in isolation.\nfunc ReadPackageHeader(r io.Reader) (*Header, error) {\n\t\/\/ read the \"header structure header\"\n\theader := make([]byte, 16)\n\tn, err := r.Read(header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != 16 {\n\t\treturn nil, ErrBadHeaderLength\n\t}\n\n\t\/\/ check magic number\n\tif 0 != bytes.Compare(header[:3], []byte{0x8E, 0xAD, 0xE8}) {\n\t\treturn nil, ErrNotHeader\n\t}\n\n\t\/\/ translate header\n\th := &Header{\n\t\tVersion: int(header[3]),\n\t\tIndexCount: int(binary.BigEndian.Uint32(header[8:12])),\n\t\tLength: int(binary.BigEndian.Uint32(header[12:16])),\n\t}\n\n\t\/\/ make sure header size is in range\n\tif h.Length > MAX_HEADER_SIZE {\n\t\treturn nil, ErrBadHeaderLength\n\t}\n\n\t\/\/ Ensure index count is in range\n\t\/\/ This test is not entirely precise as h.Length also includes the value\n\t\/\/ store. It should at least help eliminate excessive buffer allocations for\n\t\/\/ corrupted length values in the > h.Length ranges.\n\tif h.IndexCount*16 > h.Length {\n\t\treturn nil, ErrBadIndexCount\n\t}\n\n\th.Indexes = make(IndexEntries, h.IndexCount)\n\n\t\/\/ read indexes\n\tindexLength := 16 * h.IndexCount\n\tindexes := make([]byte, indexLength)\n\tn, err = r.Read(indexes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != indexLength {\n\t\treturn nil, ErrBadIndexLength\n\t}\n\n\tfor x := 0; x < h.IndexCount; x++ {\n\t\to := 16 * x\n\t\tindex := IndexEntry{\n\t\t\tTag: int(binary.BigEndian.Uint32(indexes[o : o+4])),\n\t\t\tType: int(binary.BigEndian.Uint32(indexes[o+4 : o+8])),\n\t\t\tOffset: int(binary.BigEndian.Uint32(indexes[o+8 : o+12])),\n\t\t\tItemCount: int(binary.BigEndian.Uint32(indexes[o+12 : o+16])),\n\t\t}\n\n\t\t\/\/ validate index offset\n\t\tif index.Offset >= h.Length {\n\t\t\treturn nil, ErrIndexOutOfRange\n\t\t}\n\n\t\t\/\/ append\n\t\th.Indexes[x] = index\n\t}\n\n\t\/\/ read the \"store\"\n\tstore := make([]byte, h.Length)\n\tn, err = r.Read(store)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != h.Length {\n\t\treturn nil, ErrBadStoreLength\n\t}\n\n\t\/\/ parse the value of each index from the store\n\tfor x := 0; x < h.IndexCount; x++ {\n\t\tindex := h.Indexes[x]\n\t\to := index.Offset\n\n\t\tif index.ItemCount == 0 {\n\t\t\treturn nil, ErrBadIndexValueCount\n\t\t}\n\n\t\tswitch index.Type {\n\t\tcase IndexDataTypeChar:\n\t\t\tvals := make([]uint8, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o >= len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"uint8 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = uint8(store[o])\n\t\t\t\to += 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt8:\n\t\t\tvals := make([]int8, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o >= len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int8 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int8(store[o])\n\t\t\t\to += 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt16:\n\t\t\tvals := make([]int16, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+2 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int16 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int16(binary.BigEndian.Uint16(store[o : o+2]))\n\t\t\t\to += 2\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt32:\n\t\t\tvals := make([]int32, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+4 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int32 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int32(binary.BigEndian.Uint32(store[o : o+4]))\n\t\t\t\to += 4\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt64:\n\t\t\tvals := make([]int64, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+8 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int64 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int64(binary.BigEndian.Uint64(store[o : o+8]))\n\t\t\t\to += 8\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeBinary:\n\t\t\tif o+index.ItemCount > len(store) {\n\t\t\t\treturn nil, fmt.Errorf(\"[]byte value for index %d is out of range\", x+1)\n\t\t\t}\n\n\t\t\tb := make([]byte, index.ItemCount)\n\t\t\tcopy(b, store[o:o+index.ItemCount])\n\n\t\t\tindex.Value = b\n\n\t\tcase IndexDataTypeString, IndexDataTypeStringArray, IndexDataTypeI8NString:\n\t\t\t\/\/ allow atleast one byte per string\n\t\t\tif o+index.ItemCount > len(store) {\n\t\t\t\treturn nil, fmt.Errorf(\"[]string value for index %d is out of range\", x+1)\n\t\t\t}\n\n\t\t\tvals := make([]string, index.ItemCount)\n\n\t\t\tfor s := 0; s < index.ItemCount; s++ {\n\t\t\t\t\/\/ calculate string length\n\t\t\t\tvar j int\n\t\t\t\tfor j = 0; (o+j) < len(store) && store[o+j] != 0; j++ {\n\t\t\t\t}\n\n\t\t\t\tif j == len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"string value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[s] = string(store[o : o+j])\n\t\t\t\to += j + 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeNull:\n\t\t\t\/\/ nothing to do here\n\n\t\tdefault:\n\t\t\t\/\/ unknown data type\n\t\t\treturn nil, ErrBadIndexType\n\t\t}\n\n\t\t\/\/ save in array\n\t\th.Indexes[x] = index\n\t}\n\n\t\/\/ calculate location of the end of the header by padding to a multiple of 8\n\to := 8 - int(math.Mod(float64(h.Length), 8))\n\n\t\/\/ seek to the end of the header\n\tif o > 0 && o < 8 {\n\t\tpad := make([]byte, o)\n\t\tn, err = r.Read(pad)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error seeking beyond header padding of %d bytes: %v\", o, err)\n\t\t}\n\n\t\tif n != o {\n\t\t\treturn nil, fmt.Errorf(\"Error seeking beyond header padding of %d bytes: only %d bytes returned\", o, n)\n\t\t}\n\t}\n\n\treturn h, nil\n}\nReadall instead of read method. Fix working with some rpms.package rpm\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n)\n\n\/\/ A Header stores metadata about a rpm package.\ntype Header struct {\n\tVersion int\n\tIndexCount int\n\tLength int\n\tIndexes IndexEntries\n\tStart int\n\tEnd int\n}\n\n\/\/ Headers is an array of Header structs.\ntype Headers []Header\n\n\/\/ Predefined sizing constraints.\nconst (\n\t\/\/ MAX_HEADER_SIZE is the maximum allowable header size in bytes (32 MB).\n\tMAX_HEADER_SIZE = 33554432\n)\n\n\/\/ Predefined header errors.\nvar (\n\t\/\/ ErrBadHeaderLength indicates that the read header section is not the\n\t\/\/ expected length.\n\tErrBadHeaderLength = fmt.Errorf(\"RPM header section is incorrect length\")\n\n\t\/\/ ErrNotHeader indicates that the read header section does start with the\n\t\/\/ expected descriptor.\n\tErrNotHeader = fmt.Errorf(\"invalid RPM header descriptor\")\n\n\t\/\/ ErrBadStoreLength indicates that the read header store section is not the\n\t\/\/ expected length.\n\tErrBadStoreLength = fmt.Errorf(\"header value store is incorrect length\")\n)\n\n\/\/ Predefined header index errors.\nvar (\n\t\/\/ ErrBadIndexCount indicates that number of indexes given in the read\n\t\/\/ header would exceed the actual size of the header.\n\tErrBadIndexCount = fmt.Errorf(\"index count exceeds header size\")\n\n\t\/\/ ErrBadIndexLength indicates that the read header index section is not the\n\t\/\/ expected length.\n\tErrBadIndexLength = fmt.Errorf(\"index section is incorrect length\")\n\n\t\/\/ ErrIndexOutOfRange indicates that the read header index would exceed the\n\t\/\/ range of the header.\n\tErrIndexOutOfRange = fmt.Errorf(\"index is out of range\")\n\n\t\/\/ ErrBadIndexType indicates that the read index contains a value of an\n\t\/\/ unsupported data type.\n\tErrBadIndexType = fmt.Errorf(\"unknown index data type\")\n\n\t\/\/ ErrBadIndexValueCount indicates that the read index value would exceed\n\t\/\/ the range of the header store section.\n\tErrBadIndexValueCount = fmt.Errorf(\"index value count is out of range\")\n)\n\n\/\/ ReadPackageHeader reads an RPM package file header structure from the given\n\/\/ io.Reader.\n\/\/\n\/\/ This function should only be used if you intend to read a package header\n\/\/ structure in isolation.\nfunc ReadPackageHeader(r io.Reader) (*Header, error) {\n\t\/\/ read the \"header structure header\"\n\theader := make([]byte, 16)\n\tn, err := r.Read(header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != 16 {\n\t\treturn nil, ErrBadHeaderLength\n\t}\n\n\t\/\/ check magic number\n\tif 0 != bytes.Compare(header[:3], []byte{0x8E, 0xAD, 0xE8}) {\n\t\treturn nil, ErrNotHeader\n\t}\n\n\t\/\/ translate header\n\th := &Header{\n\t\tVersion: int(header[3]),\n\t\tIndexCount: int(binary.BigEndian.Uint32(header[8:12])),\n\t\tLength: int(binary.BigEndian.Uint32(header[12:16])),\n\t}\n\n\t\/\/ make sure header size is in range\n\tif h.Length > MAX_HEADER_SIZE {\n\t\treturn nil, ErrBadHeaderLength\n\t}\n\n\t\/\/ Ensure index count is in range\n\t\/\/ This test is not entirely precise as h.Length also includes the value\n\t\/\/ store. It should at least help eliminate excessive buffer allocations for\n\t\/\/ corrupted length values in the > h.Length ranges.\n\tif h.IndexCount*16 > h.Length {\n\t\treturn nil, ErrBadIndexCount\n\t}\n\n\th.Indexes = make(IndexEntries, h.IndexCount)\n\n\t\/\/ read indexes\n\tindexLength := 16 * h.IndexCount\n\tindexes := make([]byte, indexLength)\n\tn, err = r.Read(indexes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n != indexLength {\n\t\treturn nil, ErrBadIndexLength\n\t}\n\n\tfor x := 0; x < h.IndexCount; x++ {\n\t\to := 16 * x\n\t\tindex := IndexEntry{\n\t\t\tTag: int(binary.BigEndian.Uint32(indexes[o : o+4])),\n\t\t\tType: int(binary.BigEndian.Uint32(indexes[o+4 : o+8])),\n\t\t\tOffset: int(binary.BigEndian.Uint32(indexes[o+8 : o+12])),\n\t\t\tItemCount: int(binary.BigEndian.Uint32(indexes[o+12 : o+16])),\n\t\t}\n\n\t\t\/\/ validate index offset\n\t\tif index.Offset >= h.Length {\n\t\t\treturn nil, ErrIndexOutOfRange\n\t\t}\n\n\t\t\/\/ append\n\t\th.Indexes[x] = index\n\t}\n\n\t\/\/ read the \"store\"\n\tstore, err := ioutil.ReadAll(r)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn = len(store)\n\n\tif n != h.Length {\n\t\treturn nil, ErrBadStoreLength\n\t}\n\n\t\/\/ parse the value of each index from the store\n\tfor x := 0; x < h.IndexCount; x++ {\n\t\tindex := h.Indexes[x]\n\t\to := index.Offset\n\n\t\tif index.ItemCount == 0 {\n\t\t\treturn nil, ErrBadIndexValueCount\n\t\t}\n\n\t\tswitch index.Type {\n\t\tcase IndexDataTypeChar:\n\t\t\tvals := make([]uint8, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o >= len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"uint8 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = uint8(store[o])\n\t\t\t\to += 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt8:\n\t\t\tvals := make([]int8, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o >= len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int8 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int8(store[o])\n\t\t\t\to += 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt16:\n\t\t\tvals := make([]int16, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+2 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int16 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int16(binary.BigEndian.Uint16(store[o : o+2]))\n\t\t\t\to += 2\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt32:\n\t\t\tvals := make([]int32, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+4 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int32 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int32(binary.BigEndian.Uint32(store[o : o+4]))\n\t\t\t\to += 4\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeInt64:\n\t\t\tvals := make([]int64, index.ItemCount)\n\t\t\tfor v := 0; v < index.ItemCount; v++ {\n\t\t\t\tif o+8 > len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"int64 value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[v] = int64(binary.BigEndian.Uint64(store[o : o+8]))\n\t\t\t\to += 8\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeBinary:\n\t\t\tif o+index.ItemCount > len(store) {\n\t\t\t\treturn nil, fmt.Errorf(\"[]byte value for index %d is out of range\", x+1)\n\t\t\t}\n\n\t\t\tb := make([]byte, index.ItemCount)\n\t\t\tcopy(b, store[o:o+index.ItemCount])\n\n\t\t\tindex.Value = b\n\n\t\tcase IndexDataTypeString, IndexDataTypeStringArray, IndexDataTypeI8NString:\n\t\t\t\/\/ allow atleast one byte per string\n\t\t\tif o+index.ItemCount > len(store) {\n\t\t\t\treturn nil, fmt.Errorf(\"[]string value for index %d is out of range\", x+1)\n\t\t\t}\n\n\t\t\tvals := make([]string, index.ItemCount)\n\n\t\t\tfor s := 0; s < index.ItemCount; s++ {\n\t\t\t\t\/\/ calculate string length\n\t\t\t\tvar j int\n\t\t\t\tfor j = 0; (o+j) < len(store) && store[o+j] != 0; j++ {\n\t\t\t\t}\n\n\t\t\t\tif j == len(store) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"string value for index %d is out of range\", x+1)\n\t\t\t\t}\n\n\t\t\t\tvals[s] = string(store[o : o+j])\n\t\t\t\to += j + 1\n\t\t\t}\n\n\t\t\tindex.Value = vals\n\n\t\tcase IndexDataTypeNull:\n\t\t\t\/\/ nothing to do here\n\n\t\tdefault:\n\t\t\t\/\/ unknown data type\n\t\t\treturn nil, ErrBadIndexType\n\t\t}\n\n\t\t\/\/ save in array\n\t\th.Indexes[x] = index\n\t}\n\n\t\/\/ calculate location of the end of the header by padding to a multiple of 8\n\to := 8 - int(math.Mod(float64(h.Length), 8))\n\n\t\/\/ seek to the end of the header\n\tif o > 0 && o < 8 {\n\t\tpad := make([]byte, o)\n\t\tn, err = r.Read(pad)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error seeking beyond header padding of %d bytes: %v\", o, err)\n\t\t}\n\n\t\tif n != o {\n\t\t\treturn nil, fmt.Errorf(\"Error seeking beyond header padding of %d bytes: only %d bytes returned\", o, n)\n\t\t}\n\t}\n\n\treturn h, nil\n}\n<|endoftext|>"} {"text":"package hstspreload\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ 18 weeks\n\thstsMinimumMaxAge = 10886400 \/\/ seconds\n\n\ttenYears = 86400 * 365 * 10 \/\/ seconds\n)\n\n\/\/ MaxAge holds the max-age of an HSTS header in seconds.\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6797#section-6.1.1\ntype MaxAge struct {\n\tSeconds uint64 `json:\"seconds\"`\n}\n\n\/\/ An HSTSHeader stores the semantics of an HSTS header.\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6797#section-6.1\n\/\/\n\/\/ Note that the `preload` directive is not standardized yet: https:\/\/crbug.com\/591212\ntype HSTSHeader struct {\n\t\/\/ A MaxAge of `nil` indicates \"not present\".\n\tMaxAge *MaxAge `json:\"max_age,omitempty\"`\n\tIncludeSubDomains bool `json:\"includeSubDomains\"`\n\tPreload bool `json:\"preload\"`\n}\n\n\/\/ Iff Issues has no errors, the output integer is the max-age in seconds.\nfunc parseMaxAge(directive string) (*MaxAge, Issues) {\n\tissues := Issues{}\n\tmaxAgeNumericalString := directive[8:]\n\n\t\/\/ TODO: Use more concise validation code to parse a digit string to a signed int.\n\tfor i, c := range maxAgeNumericalString {\n\t\tif i == 0 && c == '0' && len(maxAgeNumericalString) > 1 {\n\t\t\tissues = issues.addWarningf(\n\t\t\t\t\"header.parse.max_age.leading_zero\",\n\t\t\t\t\"Unexpected max-age syntax\",\n\t\t\t\t\"The header's max-age value contains a leading 0: `%s`\", directive)\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\treturn nil, issues.addErrorf(\n\t\t\t\t\"header.parse.max_age.non_digit_characters\",\n\t\t\t\t\"Invalid max-age syntax\",\n\t\t\t\t\"The header's max-age value contains characters that are not digits: `%s`\", directive)\n\t\t}\n\t}\n\n\tseconds, err := strconv.ParseUint(maxAgeNumericalString, 10, 64)\n\n\tif err != nil {\n\t\treturn nil, issues.addErrorf(\n\t\t\t\"header.parse.max_age.parse_int_error\",\n\t\t\t\"Invalid max-age syntax\",\n\t\t\t\"We could not parse the header's max-age value `%s`.\", maxAgeNumericalString)\n\t}\n\n\treturn &MaxAge{Seconds: seconds}, issues\n}\n\n\/\/ ParseHeaderString parses an HSTS header. ParseHeaderString will\n\/\/ report syntax errors and warnings, but does NOT calculate whether the\n\/\/ header value is semantically valid. (See PreloadableHeaderString() for\n\/\/ that.)\n\/\/\n\/\/ To interpret the Issues that are returned, see the list of\n\/\/ conventions in the documentation for Issues.\nfunc ParseHeaderString(headerString string) (HSTSHeader, Issues) {\n\thstsHeader := HSTSHeader{}\n\tissues := Issues{}\n\n\tdirectives := strings.Split(headerString, \";\")\n\tfor i, directive := range directives {\n\t\t\/\/ TODO: this trims more than spaces and tabs (LWS). https:\/\/crbug.com\/596561#c10\n\t\tdirectives[i] = strings.TrimSpace(directive)\n\t}\n\n\t\/\/ If strings.Split() is given whitespace, it still returns an (empty) directive.\n\t\/\/ So we handle this case separately.\n\tif len(directives) == 1 && directives[0] == \"\" {\n\t\t\/\/ Return immediately, because all the extra information is redundant.\n\t\treturn hstsHeader, issues.addWarningf(\n\t\t\t\"header.parse.empty\",\n\t\t\t\"Empty Header\",\n\t\t\t\"The HSTS header is empty.\")\n\t}\n\n\tfor _, directive := range directives {\n\t\tdirectiveEqualsIgnoringCase := func(s string) bool {\n\t\t\treturn strings.EqualFold(directive, s)\n\t\t}\n\n\t\tdirectiveHasPrefixIgnoringCase := func(prefix string) bool {\n\t\t\treturn strings.HasPrefix(strings.ToLower(directive), strings.ToLower(prefix))\n\t\t}\n\n\t\tswitch {\n\t\tcase directiveEqualsIgnoringCase(\"preload\"):\n\t\t\tif hstsHeader.Preload {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.preload\",\n\t\t\t\t\t\"Repeated preload directive\",\n\t\t\t\t\t\"Header contains a repeated directive: `preload`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.Preload = true\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"preload\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.invalid.preload\",\n\t\t\t\t\"Invalid preload directive\",\n\t\t\t\t\"Header contains a `preload` directive with extra parts.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"includeSubDomains\"):\n\t\t\tif hstsHeader.IncludeSubDomains {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.include_sub_domains\",\n\t\t\t\t\t\"Repeated includeSubDomains directive\",\n\t\t\t\t\t\"Header contains a repeated directive: `includeSubDomains`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.IncludeSubDomains = true\n\t\t\t\tif directive != \"includeSubDomains\" {\n\t\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\t\"header.parse.spelling.include_sub_domains\",\n\t\t\t\t\t\t\"Non-standard capitalization of includeSubDomains\",\n\t\t\t\t\t\t\"Header contains the token `%s`. The recommended capitalization is `includeSubDomains`.\",\n\t\t\t\t\t\tdirective,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"includeSubDomains\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.invalid.include_sub_domains\",\n\t\t\t\t\"Invalid includeSubDomains directive\",\n\t\t\t\t\"The header contains an `includeSubDomains` directive with extra directives.\")\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age=\"):\n\t\t\tmaxAge, maxAgeIssues := parseMaxAge(directive)\n\t\t\tissues = combineIssues(issues, maxAgeIssues)\n\n\t\t\tif len(maxAgeIssues.Errors) > 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif hstsHeader.MaxAge == nil {\n\t\t\t\thstsHeader.MaxAge = maxAge\n\t\t\t} else {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.max_age\",\n\t\t\t\t\t\"Repeated max-age directive\",\n\t\t\t\t\t\"The header contains a repeated directive: `max-age`\")\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age\"):\n\t\t\tissues = issues.addUniqueErrorf(\n\t\t\t\t\"header.parse.invalid.max_age.no_value\",\n\t\t\t\t\"Max-age drective without a value\",\n\t\t\t\t\"The header contains a max-age directive name without an associated value. Please specify the max-age in seconds.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.empty_directive\",\n\t\t\t\t\"Empty directive or extra semicolon\",\n\t\t\t\t\"The header includes an empty directive or extra semicolon.\")\n\n\t\tdefault:\n\t\t\tissues = issues.addWarningf(\n\t\t\t\t\"header.parse.unknown_directive\",\n\t\t\t\t\"Unknown directive\",\n\t\t\t\t\"The header contains an unknown directive: `%s`\", directive)\n\t\t}\n\t}\n\treturn hstsHeader, issues\n}\n\nfunc preloadableHeaderPreload(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif !hstsHeader.Preload {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.preload.missing\",\n\t\t\t\"No preload directive\",\n\t\t\t\"The header must contain the `preload` directive.\")\n\t}\n\n\treturn issues\n}\n\nfunc preloadableHeaderSubDomains(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif !hstsHeader.IncludeSubDomains {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.include_sub_domains.missing\",\n\t\t\t\"No includeSubDomains directive\",\n\t\t\t\"The header must contain the `includeSubDomains` directive.\")\n\t}\n\n\treturn issues\n}\n\nfunc preloadableHeaderMaxAge(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tswitch {\n\tcase hstsHeader.MaxAge == nil:\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.max_age.missing\",\n\t\t\t\"No max-age directice\",\n\t\t\t\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\n\tcase hstsHeader.MaxAge.Seconds < 0:\n\t\tissues = issues.addErrorf(\n\t\t\t\"internal.header.preloadable.max_age.negative\",\n\t\t\t\"Negative max-age\",\n\t\t\t\"Encountered an HSTSHeader with a negative max-age that does not equal MaxAgeNotPresent: %d\", hstsHeader.MaxAge.Seconds)\n\n\tcase hstsHeader.MaxAge.Seconds < hstsMinimumMaxAge:\n\t\terrorStr := fmt.Sprintf(\n\t\t\t\"The max-age must be at least 10886400 seconds (== 18 weeks), but the header currently only has max-age=%d.\",\n\t\t\thstsHeader.MaxAge.Seconds,\n\t\t)\n\t\tif hstsHeader.MaxAge.Seconds == 0 {\n\t\t\terrorStr += \" If you are trying to remove this domain from the preload list, please contact Lucas Garron at hstspreload@chromium.org\"\n\t\t\tissues = issues.addErrorf(\n\t\t\t\t\"header.preloadable.max_age.zero\",\n\t\t\t\t\"Max-age is 0\",\n\t\t\t\terrorStr,\n\t\t\t)\n\t\t} else {\n\t\t\tissues = issues.addErrorf(\n\t\t\t\t\"header.preloadable.max_age.too_low\",\n\t\t\t\t\"Max-age too low\",\n\t\t\t\terrorStr,\n\t\t\t)\n\t\t}\n\n\tcase hstsHeader.MaxAge.Seconds > tenYears:\n\t\tissues = issues.addWarningf(\n\t\t\t\"header.preloadable.max_age.over_10_years\",\n\t\t\t\"Max-age > 10 years\",\n\t\t\t\"FYI: The max-age (%d seconds) is longer than 10 years, which is an unusually long value.\",\n\t\t\thstsHeader.MaxAge.Seconds,\n\t\t)\n\n\t}\n\n\treturn issues\n}\n\n\/\/ PreloadableHeader checks whether hstsHeader satisfies all requirements\n\/\/ for preloading in Chromium.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\n\/\/\n\/\/ Most of the time, you'll probably want to use PreloadableHeaderString() instead.\nfunc PreloadableHeader(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tissues = combineIssues(issues, preloadableHeaderSubDomains(hstsHeader))\n\tissues = combineIssues(issues, preloadableHeaderPreload(hstsHeader))\n\tissues = combineIssues(issues, preloadableHeaderMaxAge(hstsHeader))\n\treturn issues\n}\n\n\/\/ RemovableHeader checks whether the header satisfies all requirements\n\/\/ for being removed from the Chromium preload list.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\n\/\/\n\/\/ Most of the time, you'll probably want to use RemovableHeaderString() instead.\nfunc RemovableHeader(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif hstsHeader.Preload {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.removable.contains.preload\",\n\t\t\t\"Contains preload directive\",\n\t\t\t\"Header requirement error: For preload list removal, the header must not contain the `preload` directive.\")\n\t}\n\n\tif hstsHeader.MaxAge == nil {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.removable.missing.max_age\",\n\t\t\t\"No max-age directive\",\n\t\t\t\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\t}\n\n\treturn issues\n}\n\n\/\/ PreloadableHeaderString is a convenience function that calls\n\/\/ ParseHeaderString() and then calls on PreloadableHeader() the parsed\n\/\/ header. It returns all issues from both calls, combined.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\nfunc PreloadableHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\treturn combineIssues(issues, PreloadableHeader(hstsHeader))\n}\n\n\/\/ RemovableHeaderString is a convenience function that calls\n\/\/ ParseHeaderString() and then calls on RemovableHeader() the parsed\n\/\/ header. It returns all errors from ParseHeaderString() and all\n\/\/ issues from RemovableHeader(). Note that *warnings* from\n\/\/ ParseHeaderString() are ignored, since domains asking to be removed\n\/\/ will often have minor errors that shouldn't affect removal. It's\n\/\/ better to have a cleaner verdict in this case.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\nfunc RemovableHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\tissues = Issues{\n\t\tErrors: issues.Errors,\n\t\t\/\/ Ignore parse warnings for removal testing.\n\t}\n\treturn combineIssues(issues, RemovableHeader(hstsHeader))\n}\nMake a note about quoted values in parseMaxAge().package hstspreload\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ 18 weeks\n\thstsMinimumMaxAge = 10886400 \/\/ seconds\n\n\ttenYears = 86400 * 365 * 10 \/\/ seconds\n)\n\n\/\/ MaxAge holds the max-age of an HSTS header in seconds.\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6797#section-6.1.1\ntype MaxAge struct {\n\tSeconds uint64 `json:\"seconds\"`\n}\n\n\/\/ An HSTSHeader stores the semantics of an HSTS header.\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6797#section-6.1\n\/\/\n\/\/ Note that the `preload` directive is not standardized yet: https:\/\/crbug.com\/591212\ntype HSTSHeader struct {\n\t\/\/ A MaxAge of `nil` indicates \"not present\".\n\tMaxAge *MaxAge `json:\"max_age,omitempty\"`\n\tIncludeSubDomains bool `json:\"includeSubDomains\"`\n\tPreload bool `json:\"preload\"`\n}\n\n\/\/ Iff Issues has no errors, the output integer is the max-age in seconds.\n\/\/ Note that according to the spec, the max-age value may optionally be quoted:\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6797#section-6.2\n\/\/ However, it seems no one does this in practice, and certainly no one has\n\/\/ asked to be preloaded with a quoted max-age value. So to keep things simple,\n\/\/ we don't support quoted values.\nfunc parseMaxAge(directive string) (*MaxAge, Issues) {\n\tissues := Issues{}\n\tmaxAgeNumericalString := directive[8:]\n\n\t\/\/ TODO: Use more concise validation code to parse a digit string to a signed int.\n\tfor i, c := range maxAgeNumericalString {\n\t\tif i == 0 && c == '0' && len(maxAgeNumericalString) > 1 {\n\t\t\tissues = issues.addWarningf(\n\t\t\t\t\"header.parse.max_age.leading_zero\",\n\t\t\t\t\"Unexpected max-age syntax\",\n\t\t\t\t\"The header's max-age value contains a leading 0: `%s`\", directive)\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\treturn nil, issues.addErrorf(\n\t\t\t\t\"header.parse.max_age.non_digit_characters\",\n\t\t\t\t\"Invalid max-age syntax\",\n\t\t\t\t\"The header's max-age value contains characters that are not digits: `%s`\", directive)\n\t\t}\n\t}\n\n\tseconds, err := strconv.ParseUint(maxAgeNumericalString, 10, 64)\n\n\tif err != nil {\n\t\treturn nil, issues.addErrorf(\n\t\t\t\"header.parse.max_age.parse_int_error\",\n\t\t\t\"Invalid max-age syntax\",\n\t\t\t\"We could not parse the header's max-age value `%s`.\", maxAgeNumericalString)\n\t}\n\n\treturn &MaxAge{Seconds: seconds}, issues\n}\n\n\/\/ ParseHeaderString parses an HSTS header. ParseHeaderString will\n\/\/ report syntax errors and warnings, but does NOT calculate whether the\n\/\/ header value is semantically valid. (See PreloadableHeaderString() for\n\/\/ that.)\n\/\/\n\/\/ To interpret the Issues that are returned, see the list of\n\/\/ conventions in the documentation for Issues.\nfunc ParseHeaderString(headerString string) (HSTSHeader, Issues) {\n\thstsHeader := HSTSHeader{}\n\tissues := Issues{}\n\n\tdirectives := strings.Split(headerString, \";\")\n\tfor i, directive := range directives {\n\t\t\/\/ TODO: this trims more than spaces and tabs (LWS). https:\/\/crbug.com\/596561#c10\n\t\tdirectives[i] = strings.TrimSpace(directive)\n\t}\n\n\t\/\/ If strings.Split() is given whitespace, it still returns an (empty) directive.\n\t\/\/ So we handle this case separately.\n\tif len(directives) == 1 && directives[0] == \"\" {\n\t\t\/\/ Return immediately, because all the extra information is redundant.\n\t\treturn hstsHeader, issues.addWarningf(\n\t\t\t\"header.parse.empty\",\n\t\t\t\"Empty Header\",\n\t\t\t\"The HSTS header is empty.\")\n\t}\n\n\tfor _, directive := range directives {\n\t\tdirectiveEqualsIgnoringCase := func(s string) bool {\n\t\t\treturn strings.EqualFold(directive, s)\n\t\t}\n\n\t\tdirectiveHasPrefixIgnoringCase := func(prefix string) bool {\n\t\t\treturn strings.HasPrefix(strings.ToLower(directive), strings.ToLower(prefix))\n\t\t}\n\n\t\tswitch {\n\t\tcase directiveEqualsIgnoringCase(\"preload\"):\n\t\t\tif hstsHeader.Preload {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.preload\",\n\t\t\t\t\t\"Repeated preload directive\",\n\t\t\t\t\t\"Header contains a repeated directive: `preload`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.Preload = true\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"preload\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.invalid.preload\",\n\t\t\t\t\"Invalid preload directive\",\n\t\t\t\t\"Header contains a `preload` directive with extra parts.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"includeSubDomains\"):\n\t\t\tif hstsHeader.IncludeSubDomains {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.include_sub_domains\",\n\t\t\t\t\t\"Repeated includeSubDomains directive\",\n\t\t\t\t\t\"Header contains a repeated directive: `includeSubDomains`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.IncludeSubDomains = true\n\t\t\t\tif directive != \"includeSubDomains\" {\n\t\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\t\"header.parse.spelling.include_sub_domains\",\n\t\t\t\t\t\t\"Non-standard capitalization of includeSubDomains\",\n\t\t\t\t\t\t\"Header contains the token `%s`. The recommended capitalization is `includeSubDomains`.\",\n\t\t\t\t\t\tdirective,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"includeSubDomains\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.invalid.include_sub_domains\",\n\t\t\t\t\"Invalid includeSubDomains directive\",\n\t\t\t\t\"The header contains an `includeSubDomains` directive with extra directives.\")\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age=\"):\n\t\t\tmaxAge, maxAgeIssues := parseMaxAge(directive)\n\t\t\tissues = combineIssues(issues, maxAgeIssues)\n\n\t\t\tif len(maxAgeIssues.Errors) > 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif hstsHeader.MaxAge == nil {\n\t\t\t\thstsHeader.MaxAge = maxAge\n\t\t\t} else {\n\t\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\t\"header.parse.repeated.max_age\",\n\t\t\t\t\t\"Repeated max-age directive\",\n\t\t\t\t\t\"The header contains a repeated directive: `max-age`\")\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age\"):\n\t\t\tissues = issues.addUniqueErrorf(\n\t\t\t\t\"header.parse.invalid.max_age.no_value\",\n\t\t\t\t\"Max-age drective without a value\",\n\t\t\t\t\"The header contains a max-age directive name without an associated value. Please specify the max-age in seconds.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"\"):\n\t\t\tissues = issues.addUniqueWarningf(\n\t\t\t\t\"header.parse.empty_directive\",\n\t\t\t\t\"Empty directive or extra semicolon\",\n\t\t\t\t\"The header includes an empty directive or extra semicolon.\")\n\n\t\tdefault:\n\t\t\tissues = issues.addWarningf(\n\t\t\t\t\"header.parse.unknown_directive\",\n\t\t\t\t\"Unknown directive\",\n\t\t\t\t\"The header contains an unknown directive: `%s`\", directive)\n\t\t}\n\t}\n\treturn hstsHeader, issues\n}\n\nfunc preloadableHeaderPreload(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif !hstsHeader.Preload {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.preload.missing\",\n\t\t\t\"No preload directive\",\n\t\t\t\"The header must contain the `preload` directive.\")\n\t}\n\n\treturn issues\n}\n\nfunc preloadableHeaderSubDomains(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif !hstsHeader.IncludeSubDomains {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.include_sub_domains.missing\",\n\t\t\t\"No includeSubDomains directive\",\n\t\t\t\"The header must contain the `includeSubDomains` directive.\")\n\t}\n\n\treturn issues\n}\n\nfunc preloadableHeaderMaxAge(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tswitch {\n\tcase hstsHeader.MaxAge == nil:\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.preloadable.max_age.missing\",\n\t\t\t\"No max-age directice\",\n\t\t\t\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\n\tcase hstsHeader.MaxAge.Seconds < 0:\n\t\tissues = issues.addErrorf(\n\t\t\t\"internal.header.preloadable.max_age.negative\",\n\t\t\t\"Negative max-age\",\n\t\t\t\"Encountered an HSTSHeader with a negative max-age that does not equal MaxAgeNotPresent: %d\", hstsHeader.MaxAge.Seconds)\n\n\tcase hstsHeader.MaxAge.Seconds < hstsMinimumMaxAge:\n\t\terrorStr := fmt.Sprintf(\n\t\t\t\"The max-age must be at least 10886400 seconds (== 18 weeks), but the header currently only has max-age=%d.\",\n\t\t\thstsHeader.MaxAge.Seconds,\n\t\t)\n\t\tif hstsHeader.MaxAge.Seconds == 0 {\n\t\t\terrorStr += \" If you are trying to remove this domain from the preload list, please contact Lucas Garron at hstspreload@chromium.org\"\n\t\t\tissues = issues.addErrorf(\n\t\t\t\t\"header.preloadable.max_age.zero\",\n\t\t\t\t\"Max-age is 0\",\n\t\t\t\terrorStr,\n\t\t\t)\n\t\t} else {\n\t\t\tissues = issues.addErrorf(\n\t\t\t\t\"header.preloadable.max_age.too_low\",\n\t\t\t\t\"Max-age too low\",\n\t\t\t\terrorStr,\n\t\t\t)\n\t\t}\n\n\tcase hstsHeader.MaxAge.Seconds > tenYears:\n\t\tissues = issues.addWarningf(\n\t\t\t\"header.preloadable.max_age.over_10_years\",\n\t\t\t\"Max-age > 10 years\",\n\t\t\t\"FYI: The max-age (%d seconds) is longer than 10 years, which is an unusually long value.\",\n\t\t\thstsHeader.MaxAge.Seconds,\n\t\t)\n\n\t}\n\n\treturn issues\n}\n\n\/\/ PreloadableHeader checks whether hstsHeader satisfies all requirements\n\/\/ for preloading in Chromium.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\n\/\/\n\/\/ Most of the time, you'll probably want to use PreloadableHeaderString() instead.\nfunc PreloadableHeader(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tissues = combineIssues(issues, preloadableHeaderSubDomains(hstsHeader))\n\tissues = combineIssues(issues, preloadableHeaderPreload(hstsHeader))\n\tissues = combineIssues(issues, preloadableHeaderMaxAge(hstsHeader))\n\treturn issues\n}\n\n\/\/ RemovableHeader checks whether the header satisfies all requirements\n\/\/ for being removed from the Chromium preload list.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\n\/\/\n\/\/ Most of the time, you'll probably want to use RemovableHeaderString() instead.\nfunc RemovableHeader(hstsHeader HSTSHeader) Issues {\n\tissues := Issues{}\n\n\tif hstsHeader.Preload {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.removable.contains.preload\",\n\t\t\t\"Contains preload directive\",\n\t\t\t\"Header requirement error: For preload list removal, the header must not contain the `preload` directive.\")\n\t}\n\n\tif hstsHeader.MaxAge == nil {\n\t\tissues = issues.addErrorf(\n\t\t\t\"header.removable.missing.max_age\",\n\t\t\t\"No max-age directive\",\n\t\t\t\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\t}\n\n\treturn issues\n}\n\n\/\/ PreloadableHeaderString is a convenience function that calls\n\/\/ ParseHeaderString() and then calls on PreloadableHeader() the parsed\n\/\/ header. It returns all issues from both calls, combined.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\nfunc PreloadableHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\treturn combineIssues(issues, PreloadableHeader(hstsHeader))\n}\n\n\/\/ RemovableHeaderString is a convenience function that calls\n\/\/ ParseHeaderString() and then calls on RemovableHeader() the parsed\n\/\/ header. It returns all errors from ParseHeaderString() and all\n\/\/ issues from RemovableHeader(). Note that *warnings* from\n\/\/ ParseHeaderString() are ignored, since domains asking to be removed\n\/\/ will often have minor errors that shouldn't affect removal. It's\n\/\/ better to have a cleaner verdict in this case.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for Issues.\nfunc RemovableHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\tissues = Issues{\n\t\tErrors: issues.Errors,\n\t\t\/\/ Ignore parse warnings for removal testing.\n\t}\n\treturn combineIssues(issues, RemovableHeader(hstsHeader))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\/\/import libraries\n\t\"fmt\"\n\t\"net\/http\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\t\"bufio\"\n\t\"os\"\n)\n\ntype Server struct {\n\thealth bool\n\tservice string\n}\n\ntype Servers map[string]*Server\n\nfunc main() {\n\tservers := make(Servers)\n\n\taddserver(servers, \"http:\/\/cheesy-fries.mit.edu\/health\", \"service\")\n\taddserver(servers, \"http:\/\/strawberry-habanero.mit.edu\/health\", \"service\")\n\n\tloopservers(servers, 100, 500)\n\n\t\/\/takes user input command to add or remove server\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tvar input = scanner.Text()\n \tfmt.Println(\"Executing: \",input)\n \twords := strings.Fields(input)\n\n\t if strings.Contains(input, \"rmserver\"){\n\t \trmserver(servers, words[1])\n\t \tfmt.Println(servers)\n\t }\n\n\t if strings.Contains(input, \"addserver\"){\n\t \taddserver(servers, words[1], words[2])\n\t \tfmt.Println(servers)\n \t}\n\t}\n}\n\n\n\/\/adds server to servers hash table\nfunc addserver(servers map[string]*Server, url string, service string) {\n\tservers[url] = &Server{false, service}\n}\n\n\/\/removes server from servers hash table\nfunc rmserver(servers map[string]*Server, url string){\n\tdelete(servers, url)\n}\n\n\/\/runs health checks on all servers\nfunc loopservers(servers map[string]*Server, num float64, timeout int){\n\tfor k:= range servers{\n\t\tgo loop(servers, k, num, timeout)\n\t}\n}\n\n\/\/runs health check on a single server\nfunc loop(servers map[string]*Server, url string, num float64, timeout int) {\n\tcount := 0\n\tboo := true\n\n\tfor boo{\n\t\tnum := time.Duration(num)\n\n\t\ttime.Sleep(num * time.Millisecond)\n\t\t\/\/fmt.Println(url, health(url), \"\\n\", count, servers)\n\n\t\tif health(url) != true{\n\t\t\tcount += 1\n\t\t\tfmt.Println(count)\n\t\t}\n\n\t\tif health(url) == true {\n\t\t\tcount = 0\n\t\t\tservers[url].health = true\n\t\t}\n\n\t\tif count >= timeout{ \/\/change this later\n\t\t\tservers[url].health = false\n\t\t}\n\n\t}\n}\n\n\/\/checks health of server\nfunc health(url string) bool{\n\tresp, _ := http.Get(url)\n\tbytes, _ := ioutil.ReadAll(resp.Body)\n\n\tresp.Body.Close()\n\n\tif resp == nil {\n\t\treturn false\n\t}\n\n\tif strings.Contains(string(bytes),\"healthy\") {\n\t\treturn true\n\t}\n\n\treturn false\n}converted spaces to tabspackage main\n\nimport (\n\t\/\/import libraries\n\t\"fmt\"\n\t\"net\/http\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\t\"bufio\"\n\t\"os\"\n)\n\ntype Server struct {\n\thealth bool\n\tservice string\n}\n\ntype Servers map[string]*Server\n\nfunc main() {\n\tservers := make(Servers)\n\n\taddserver(servers, \"http:\/\/cheesy-fries.mit.edu\/health\", \"service\")\n\taddserver(servers, \"http:\/\/strawberry-habanero.mit.edu\/health\", \"service\")\n\n\tloopservers(servers, 100, 500)\n\n\t\/\/takes user input command to add or remove server\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tvar input = scanner.Text()\n\t\tfmt.Println(\"Executing: \",input)\n\t\twords := strings.Fields(input)\n\n\t\tif strings.Contains(input, \"rmserver\"){\n\t\t\trmserver(servers, words[1])\n\t\t\tfmt.Println(servers)\n\t\t}\n\n\t\tif strings.Contains(input, \"addserver\"){\n\t\t\taddserver(servers, words[1], words[2])\n\t\t\tfmt.Println(servers)\n\t\t}\n\t}\n}\n\n\n\/\/adds server to servers hash table\nfunc addserver(servers map[string]*Server, url string, service string) {\n\tservers[url] = &Server{false, service}\n}\n\n\/\/removes server from servers hash table\nfunc rmserver(servers map[string]*Server, url string){\n\tdelete(servers, url)\n}\n\n\/\/runs health checks on all servers\nfunc loopservers(servers map[string]*Server, num float64, timeout int){\n\tfor k:= range servers{\n\t\tgo loop(servers, k, num, timeout)\n\t}\n}\n\n\/\/runs health check on a single server\nfunc loop(servers map[string]*Server, url string, num float64, timeout int) {\n\tcount := 0\n\tboo := true\n\n\tfor boo{\n\t\tnum := time.Duration(num)\n\n\t\ttime.Sleep(num * time.Millisecond)\n\t\t\/\/fmt.Println(url, health(url), \"\\n\", count, servers)\n\n\t\tif health(url) != true{\n\t\t\tcount += 1\n\t\t\tfmt.Println(count)\n\t\t}\n\n\t\tif health(url) == true {\n\t\t\tcount = 0\n\t\t\tservers[url].health = true\n\t\t}\n\n\t\tif count >= timeout{ \/\/change this later\n\t\t\tservers[url].health = false\n\t\t}\n\n\t}\n}\n\n\/\/checks health of server\nfunc health(url string) bool{\n\tresp, _ := http.Get(url)\n\tbytes, _ := ioutil.ReadAll(resp.Body)\n\n\tresp.Body.Close()\n\n\tif resp == nil {\n\t\treturn false\n\t}\n\n\tif strings.Contains(string(bytes),\"healthy\") {\n\t\treturn true\n\t}\n\n\treturn false\n}<|endoftext|>"} {"text":"package gogadgets\n\nimport (\n\t\"time\"\n)\n\n\/\/Heater represents an electic heating element. It\n\/\/provides a way to heat up something to a target\n\/\/temperature. In order to use this there must be\n\/\/a thermometer in the same Location.\ntype Heater struct {\n\tonTime time.Duration\n\toffTime time.Duration\n\ttoggleTime time.Duration\n\twaitTime time.Duration\n\tt1 time.Time\n\ttarget float64\n\tcurrentTemp float64\n\tduration time.Duration\n\tstatus bool\n\tgpioStatus bool\n\tdoPWM bool\n\tgpio OutputDevice\n\tio chan *Value\n\tupdate chan *Message\n\tstarted bool\n}\n\nfunc NewHeater(pin *Pin) (OutputDevice, error) {\n\tvar h *Heater\n\tvar err error\n\tvar dev OutputDevice\n\tdoPWM := pin.Args[\"pwm\"] == true\n\tif pin.Frequency == 0 {\n\t\tpin.Frequency = 1\n\t}\n\tdev, err = newGPIO(pin)\n\tif err == nil {\n\t\th = &Heater{\n\t\t\ttoggleTime: 100 * time.Hour,\n\t\t\tgpio: dev,\n\t\t\ttarget: 100.0,\n\t\t\tdoPWM: doPWM,\n\t\t\tio: make(chan *Value),\n\t\t\tupdate: make(chan *Message),\n\t\t}\n\t}\n\treturn h, err\n}\n\nfunc (h *Heater) Commands(location, name string) *Commands {\n\treturn nil\n}\n\nfunc (h *Heater) Update(msg *Message) bool {\n\tvar ret bool\n\tif h.status && msg.Name == \"temperature\" {\n\t\tret = true\n\t\th.update <- msg\n\t} else {\n\t\th.readTemperature(msg)\n\t}\n\treturn ret\n}\n\nfunc (h *Heater) On(val *Value) error {\n\th.status = true\n\tif !h.started {\n\t\th.started = true\n\t\tgo h.toggle(h.io, h.update)\n\t}\n\tif val == nil {\n\t\tval = &Value{Value: true}\n\t}\n\th.io <- val\n\treturn nil\n}\n\nfunc (h *Heater) Status() map[string]bool {\n\treturn h.gpio.Status()\n}\n\nfunc (h *Heater) Off() error {\n\tif h.started {\n\t\th.target = 0.0\n\t\th.status = false\n\t\th.io <- &Value{Value: false}\n\t}\n\treturn nil\n}\n\n\/*\nThe pwm drivers on beaglebone black seem to be\nbroken. This function brings the same functionality\nusing gpio.\n*\/\nfunc (h *Heater) toggle(value chan *Value, update chan *Message) {\n\tfor {\n\t\tselect {\n\t\tcase val := <-value:\n\t\t\tswitch v := val.Value.(type) {\n\t\t\tcase float64:\n\t\t\t\th.waitTime = 100 * time.Millisecond\n\t\t\t\th.getTarget(val)\n\t\t\t\th.setDuty()\n\t\t\t\th.status = true\n\t\t\t\th.gpioStatus = true\n\t\t\t\th.gpio.On(nil)\n\t\t\t\th.t1 = time.Now()\n\t\t\tcase bool:\n\t\t\t\th.waitTime = 100 * time.Hour\n\t\t\t\tif v == true {\n\t\t\t\t\th.status = true\n\t\t\t\t\th.gpio.On(nil)\n\t\t\t\t} else {\n\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.target = 1000.0\n\t\t\t\t\th.status = false\n\t\t\t\t}\n\t\t\t}\n\t\tcase m := <-update:\n\t\t\th.readTemperature(m)\n\t\tcase _ = <-time.After(h.waitTime):\n\t\t\tn := time.Now()\n\t\t\tdiff := n.Sub(h.t1)\n\t\t\tif h.doPWM && diff > h.toggleTime {\n\t\t\t\th.t1 = n\n\t\t\t\tif h.gpioStatus && h.offTime > 0.0 {\n\t\t\t\t\th.toggleTime = h.offTime\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.gpioStatus = false\n\t\t\t\t} else if !h.gpioStatus && h.onTime > 0.0 {\n\t\t\t\t\th.toggleTime = h.onTime\n\t\t\t\t\th.gpio.On(nil)\n\t\t\t\t\th.gpioStatus = true\n\t\t\t\t} else {\n\t\t\t\t\th.toggleTime = h.offTime\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.gpioStatus = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *Heater) getTarget(val *Value) {\n\tif val != nil {\n\t\tt, ok := val.ToFloat()\n\t\tif ok {\n\t\t\th.target = t\n\t\t}\n\t}\n}\n\nfunc (h *Heater) readTemperature(msg *Message) {\n\tif msg.Name != \"temperature\" {\n\t\treturn\n\t}\n\ttemp, ok := msg.Value.ToFloat()\n\tif ok {\n\t\th.currentTemp = temp\n\t\tif h.status {\n\t\t\th.setDuty()\n\t\t}\n\t}\n}\n\n\/\/Once the heater approaches the target temperature the electricity\n\/\/is applied PWM style so the target temperature isn't overshot.\n\/\/This functionality is geared towards heating up a tank of water\n\/\/and can be disabled if you are using this component to heat something\n\/\/else, like a house.\nfunc (h *Heater) setDuty() {\n\tdiff := h.target - h.currentTemp\n\tif diff <= 0.0 {\n\t\th.onTime = 0\n\t\th.offTime = 1 * time.Second\n\t} else if diff <= 1.0 {\n\t\th.onTime = 1 * time.Second\n\t\th.offTime = 3 * time.Second\n\t} else if diff <= 2.0 {\n\t\th.onTime = 2 * time.Second\n\t\th.offTime = 2 * time.Second\n\t} else {\n\t\th.onTime = 4 * time.Second\n\t\th.offTime = 0 * time.Second\n\t}\n\tif h.gpioStatus {\n\t\th.toggleTime = h.onTime\n\t} else {\n\t\th.toggleTime = h.offTime\n\t}\n}\nheater can be turned on with '%' as unitspackage gogadgets\n\nimport (\n\t\"time\"\n)\n\n\/\/Heater represents an electic heating element. It\n\/\/provides a way to heat up something to a target\n\/\/temperature. In order to use this there must be\n\/\/a thermometer in the same Location.\ntype Heater struct {\n\tonTime time.Duration\n\toffTime time.Duration\n\ttoggleTime time.Duration\n\twaitTime time.Duration\n\tt1 time.Time\n\ttarget float64\n\tpercentage bool\n\tcurrentTemp float64\n\tduration time.Duration\n\tstatus bool\n\tgpioStatus bool\n\tdoPWM bool\n\tgpio OutputDevice\n\tio chan *Value\n\tupdate chan *Message\n\tstarted bool\n}\n\nfunc NewHeater(pin *Pin) (OutputDevice, error) {\n\tvar h *Heater\n\tvar err error\n\tvar dev OutputDevice\n\tdoPWM := pin.Args[\"pwm\"] == true\n\tif pin.Frequency == 0 {\n\t\tpin.Frequency = 1\n\t}\n\tdev, err = newGPIO(pin)\n\tif err == nil {\n\t\th = &Heater{\n\t\t\ttoggleTime: 100 * time.Hour,\n\t\t\tgpio: dev,\n\t\t\ttarget: 100.0,\n\t\t\tdoPWM: doPWM,\n\t\t\tio: make(chan *Value),\n\t\t\tupdate: make(chan *Message),\n\t\t}\n\t}\n\treturn h, err\n}\n\nfunc (h *Heater) Commands(location, name string) *Commands {\n\treturn nil\n}\n\nfunc (h *Heater) Update(msg *Message) bool {\n\tvar ret bool\n\tif h.status && msg.Name == \"temperature\" {\n\t\tret = true\n\t\th.update <- msg\n\t} else {\n\t\th.readTemperature(msg)\n\t}\n\treturn ret\n}\n\nfunc (h *Heater) On(val *Value) error {\n\th.status = true\n\tif !h.started {\n\t\th.started = true\n\t\tgo h.toggle(h.io, h.update)\n\t}\n\tif val == nil {\n\t\tval = &Value{Value: true}\n\t}\n\th.io <- val\n\treturn nil\n}\n\nfunc (h *Heater) Status() map[string]bool {\n\treturn h.gpio.Status()\n}\n\nfunc (h *Heater) Off() error {\n\tif h.started {\n\t\th.target = 0.0\n\t\th.percentage = false\n\t\th.status = false\n\t\th.io <- &Value{Value: false}\n\t}\n\treturn nil\n}\n\n\/*\nThe pwm drivers on beaglebone black seem to be\nbroken. This function brings the same functionality\nusing gpio.\n*\/\nfunc (h *Heater) toggle(value chan *Value, update chan *Message) {\n\tfor {\n\t\tselect {\n\t\tcase val := <-value:\n\t\t\tswitch v := val.Value.(type) {\n\t\t\tcase float64:\n\t\t\t\tif val.Units == \"%\" {\n\t\t\t\t\th.target = 1000.0\n\t\t\t\t\th.percentage = true\n\t\t\t\t\td := time.Duration(v) * time.Millisecond * 10\n\t\t\t\t\th.onTime = d * 4\n\t\t\t\t\th.offTime = (4 * time.Second) - h.onTime\n\t\t\t\t} else {\n\t\t\t\t\th.percentage = false\n\t\t\t\t\th.getTarget(val)\n\t\t\t\t\th.setDuty()\n\t\t\t\t\th.t1 = time.Now()\n\t\t\t\t}\n\n\t\t\t\th.waitTime = 100 * time.Millisecond\n\t\t\t\th.status = true\n\t\t\t\th.gpioStatus = true\n\t\t\t\th.gpio.On(nil)\n\t\t\tcase bool:\n\t\t\t\th.waitTime = 100 * time.Hour\n\t\t\t\tif v == true {\n\t\t\t\t\th.status = true\n\t\t\t\t\th.gpio.On(nil)\n\t\t\t\t} else {\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.target = 1000.0\n\t\t\t\t\th.percentage = false\n\t\t\t\t\th.status = false\n\t\t\t\t}\n\t\t\t}\n\t\tcase m := <-update:\n\t\t\th.readTemperature(m)\n\t\tcase _ = <-time.After(h.waitTime):\n\t\t\tn := time.Now()\n\t\t\tdiff := n.Sub(h.t1)\n\t\t\tif h.doPWM && diff > h.toggleTime {\n\t\t\t\th.t1 = n\n\t\t\t\tif h.gpioStatus && h.offTime > 0.0 {\n\t\t\t\t\th.toggleTime = h.offTime\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.gpioStatus = false\n\t\t\t\t} else if !h.gpioStatus && h.onTime > 0.0 {\n\t\t\t\t\th.toggleTime = h.onTime\n\t\t\t\t\th.gpio.On(nil)\n\t\t\t\t\th.gpioStatus = true\n\t\t\t\t} else {\n\t\t\t\t\th.toggleTime = h.offTime\n\t\t\t\t\th.gpio.Off()\n\t\t\t\t\th.gpioStatus = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *Heater) getTarget(val *Value) {\n\tif val != nil {\n\t\tt, ok := val.ToFloat()\n\t\tif ok {\n\t\t\th.target = t\n\t\t\th.percentage = false\n\t\t}\n\t}\n}\n\nfunc (h *Heater) readTemperature(msg *Message) {\n\tif msg.Name != \"temperature\" {\n\t\treturn\n\t}\n\ttemp, ok := msg.Value.ToFloat()\n\tif ok {\n\t\th.currentTemp = temp\n\t\tif h.status {\n\t\t\th.setDuty()\n\t\t}\n\t}\n}\n\n\/\/Once the heater approaches the target temperature the electricity\n\/\/is applied PWM style so the target temperature isn't overshot.\n\/\/This functionality is geared towards heating up a tank of water\n\/\/and can be disabled if you are using this component to heat something\n\/\/else, like a house.\nfunc (h *Heater) setDuty() {\n\tif h.percentage {\n\t\treturn\n\t}\n\n\tdiff := h.target - h.currentTemp\n\tif diff <= 0.0 {\n\t\th.onTime = 0\n\t\th.offTime = 1 * time.Second\n\t} else if diff <= 1.0 {\n\t\th.onTime = 1 * time.Second\n\t\th.offTime = 3 * time.Second\n\t} else if diff <= 2.0 {\n\t\th.onTime = 2 * time.Second\n\t\th.offTime = 2 * time.Second\n\t} else {\n\t\th.onTime = 4 * time.Second\n\t\th.offTime = 0 * time.Second\n\t}\n\tif h.gpioStatus {\n\t\th.toggleTime = h.onTime\n\t} else {\n\t\th.toggleTime = h.offTime\n\t}\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 xsrf\n\nimport (\n\t\"context\"\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/google\/go-safeweb\/safehttp\"\n\t\"github.com\/google\/go-safeweb\/safehttp\/safehttptest\"\n\t\"golang.org\/x\/net\/xsrftoken\"\n\t\"strings\"\n\t\"testing\"\n)\n\ntype userIdentifier struct{}\n\nfunc (userIdentifier) UserID(r *safehttp.IncomingRequest) (string, error) {\n\treturn \"1234\", nil\n}\n\nvar (\n\tformTokenTests = []struct {\n\t\tname, userID, actionID, wantBody string\n\t\twantStatus safehttp.StatusCode\n\t\twantHeader map[string][]string\n\t}{\n\t\t{\n\t\t\tname: \"Valid token\",\n\t\t\tuserID: \"1234\",\n\t\t\tactionID: \"POST \/pizza\",\n\t\t\twantStatus: safehttp.StatusOK,\n\t\t\twantHeader: map[string][]string{},\n\t\t\twantBody: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid actionID in token generation\",\n\t\t\tuserID: \"1234\",\n\t\t\tactionID: \"HEAD \/pizza\",\n\t\t\twantStatus: safehttp.StatusForbidden,\n\t\t\twantHeader: map[string][]string{\n\t\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t\t},\n\t\t\twantBody: \"Forbidden\\n\",\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid userID in token generation\",\n\t\t\tuserID: \"5678\",\n\t\t\tactionID: \"POST \/pizza\",\n\t\t\twantStatus: safehttp.StatusForbidden,\n\t\t\twantHeader: map[string][]string{\n\t\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t\t},\n\t\t\twantBody: \"Forbidden\\n\",\n\t\t},\n\t}\n)\n\nfunc TestTokenPost(t *testing.T) {\n\tfor _, test := range formTokenTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trec := safehttptest.NewResponseRecorder()\n\t\t\ttok := xsrftoken.Generate(\"xsrf\", test.userID, test.actionID)\n\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"https:\/\/foo.com\/pizza\", strings.NewReader(TokenKey+\"=\"+tok))\n\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\t\t\ti := Interceptor{AppKey: \"xsrf\", Identifier: userIdentifier{}}\n\t\t\ti.Before(rec.ResponseWriter, req, nil)\n\n\t\t\tif got := rec.Status(); got != test.wantStatus {\n\t\t\t\tt.Errorf(\"response status: got %v, want %v\", got, test.wantStatus)\n\t\t\t}\n\t\t\tif diff := cmp.Diff(test.wantHeader, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\t\tt.Errorf(\"rec.Header() mismatch (-want +got):\\n%s\", diff)\n\t\t\t}\n\t\t\tif got := rec.Body(); got != test.wantBody {\n\t\t\t\tt.Errorf(\"response body: got %q want %q\", got, test.wantBody)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTokenMultipart(t *testing.T) {\n\tfor _, test := range formTokenTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trec := safehttptest.NewResponseRecorder()\n\t\t\ttok := xsrftoken.Generate(\"xsrf\", test.userID, test.actionID)\n\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\"Content-Disposition: form-data; name=\\\"xsrf-token\\\"\\r\\n\" +\n\t\t\t\t\"\\r\\n\" +\n\t\t\t\ttok + \"\\r\\n\" +\n\t\t\t\t\"--123--\\r\\n\"\n\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"https:\/\/foo.com\/pizza\", strings.NewReader(b))\n\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\n\t\t\ti := Interceptor{AppKey: \"xsrf\", Identifier: userIdentifier{}}\n\t\t\ti.Before(rec.ResponseWriter, req, nil)\n\n\t\t\tif got := rec.Status(); got != test.wantStatus {\n\t\t\t\tt.Errorf(\"response status: got %v, want %v\", got, test.wantStatus)\n\t\t\t}\n\t\t\tif diff := cmp.Diff(test.wantHeader, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\t\tt.Errorf(\"rw.header mismatch (-want +got):\\n%s\", diff)\n\t\t\t}\n\t\t\tif got := rec.Body(); got != test.wantBody {\n\t\t\t\tt.Errorf(\"response body: got %q want %q\", got, test.wantBody)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMissingTokenInBody(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\treq *safehttp.IncomingRequest\n\t}{\n\t\t{\n\t\t\tname: \"Missing token in POST request with form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"\/\", strings.NewReader(\"foo=bar\"))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in PATCH request with form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPatch, \"\/\", strings.NewReader(\"foo=bar\"))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in POST request with multipart form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\t\"Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\" +\n\t\t\t\t\t\"\\r\\n\" +\n\t\t\t\t\t\"bar\\r\\n\" +\n\t\t\t\t\t\"--123--\\r\\n\"\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"\/\", strings.NewReader(b))\n\t\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in PATCH request with multipart form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\t\"Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\" +\n\t\t\t\t\t\"\\r\\n\" +\n\t\t\t\t\t\"bar\\r\\n\" +\n\t\t\t\t\t\"--123--\\r\\n\"\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPatch, \"\/\", strings.NewReader(b))\n\t\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\trec := safehttptest.NewResponseRecorder()\n\n\t\ti := Interceptor{AppKey: \"xsrf\", Identifier: userIdentifier{}}\n\t\ti.Before(rec.ResponseWriter, test.req, nil)\n\n\t\tif want, got := safehttp.StatusUnauthorized, rec.Status(); got != want {\n\t\t\tt.Errorf(\"response status: got %v, want %v\", got, want)\n\t\t}\n\t\twantHeaders := map[string][]string{\n\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t}\n\t\tif diff := cmp.Diff(wantHeaders, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\tt.Errorf(\"rw.header mismatch (-want +got):\\n%s\", diff)\n\t\t}\n\t\tif want, got := \"Unauthorized\\n\", rec.Body(); got != want {\n\t\t\tt.Errorf(\"response body: got %q want %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestBeforeTokenInRequestContext(t *testing.T) {\n\trec := safehttptest.NewResponseRecorder()\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"https:\/\/foo.com\/pizza\", nil)\n\n\ti := Interceptor{AppKey: \"xsrf\", Identifier: userIdentifier{}}\n\ti.Before(rec.ResponseWriter, req, nil)\n\n\ttok, err := Token(req)\n\tif tok == \"\" {\n\t\tt.Error(`Token(req): got \"\", want token`)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Token(req): got %v, want nil\", err)\n\t}\n\n\tif want, got := safehttp.StatusOK, safehttp.StatusCode(rec.Status()); want != got {\n\t\tt.Errorf(\"response status: got %v, want %v\", got, want)\n\t}\n\tif diff := cmp.Diff(map[string][]string{}, map[string][]string(rec.Header())); diff != \"\" {\n\t\tt.Errorf(\"rec.Header() mismatch (-want +got):\\n%s\", diff)\n\t}\n\tif want, got := \"\", rec.Body(); got != want {\n\t\tt.Errorf(\"response body: got %q want %q\", got, want)\n\t}\n\n}\n\nfunc TestTokenInRequestContext(t *testing.T) {\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"\/\", nil)\n\treq.SetContext(context.WithValue(req.Context(), tokenCtxKey{}, \"pizza\"))\n\n\tgot, err := Token(req)\n\tif want := \"pizza\"; want != got {\n\t\tt.Errorf(\"Token(req): got %v, want %v\", got, want)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Token(req): got %v, want nil\", err)\n\t}\n}\n\nfunc TestMissingTokenInRequestContext(t *testing.T) {\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"\/\", nil)\n\treq.SetContext(context.Background())\n\n\tgot, err := Token(req)\n\tif want := \"\"; want != got {\n\t\tt.Errorf(\"Token(req): got %v, want %v\", got, want)\n\t}\n\tif err == nil {\n\t\tt.Error(\"Token(req): got nil, want error\")\n\t}\n}\nRename AppKey in tests\/\/ 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 xsrf\n\nimport (\n\t\"context\"\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/google\/go-safeweb\/safehttp\"\n\t\"github.com\/google\/go-safeweb\/safehttp\/safehttptest\"\n\t\"golang.org\/x\/net\/xsrftoken\"\n\t\"strings\"\n\t\"testing\"\n)\n\ntype userIdentifier struct{}\n\nfunc (userIdentifier) UserID(r *safehttp.IncomingRequest) (string, error) {\n\treturn \"1234\", nil\n}\n\nvar (\n\tformTokenTests = []struct {\n\t\tname, userID, actionID, wantBody string\n\t\twantStatus safehttp.StatusCode\n\t\twantHeader map[string][]string\n\t}{\n\t\t{\n\t\t\tname: \"Valid token\",\n\t\t\tuserID: \"1234\",\n\t\t\tactionID: \"POST \/pizza\",\n\t\t\twantStatus: safehttp.StatusOK,\n\t\t\twantHeader: map[string][]string{},\n\t\t\twantBody: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid actionID in token generation\",\n\t\t\tuserID: \"1234\",\n\t\t\tactionID: \"HEAD \/pizza\",\n\t\t\twantStatus: safehttp.StatusForbidden,\n\t\t\twantHeader: map[string][]string{\n\t\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t\t},\n\t\t\twantBody: \"Forbidden\\n\",\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid userID in token generation\",\n\t\t\tuserID: \"5678\",\n\t\t\tactionID: \"POST \/pizza\",\n\t\t\twantStatus: safehttp.StatusForbidden,\n\t\t\twantHeader: map[string][]string{\n\t\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t\t},\n\t\t\twantBody: \"Forbidden\\n\",\n\t\t},\n\t}\n)\n\nfunc TestTokenPost(t *testing.T) {\n\tfor _, test := range formTokenTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trec := safehttptest.NewResponseRecorder()\n\t\t\ttok := xsrftoken.Generate(\"testAppKey\", test.userID, test.actionID)\n\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"https:\/\/foo.com\/pizza\", strings.NewReader(TokenKey+\"=\"+tok))\n\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\t\t\ti := Interceptor{AppKey: \"testAppKey\", Identifier: userIdentifier{}}\n\t\t\ti.Before(rec.ResponseWriter, req, nil)\n\n\t\t\tif got := rec.Status(); got != test.wantStatus {\n\t\t\t\tt.Errorf(\"response status: got %v, want %v\", got, test.wantStatus)\n\t\t\t}\n\t\t\tif diff := cmp.Diff(test.wantHeader, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\t\tt.Errorf(\"rec.Header() mismatch (-want +got):\\n%s\", diff)\n\t\t\t}\n\t\t\tif got := rec.Body(); got != test.wantBody {\n\t\t\t\tt.Errorf(\"response body: got %q want %q\", got, test.wantBody)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTokenMultipart(t *testing.T) {\n\tfor _, test := range formTokenTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trec := safehttptest.NewResponseRecorder()\n\t\t\ttok := xsrftoken.Generate(\"testAppKey\", test.userID, test.actionID)\n\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\"Content-Disposition: form-data; name=\\\"xsrf-token\\\"\\r\\n\" +\n\t\t\t\t\"\\r\\n\" +\n\t\t\t\ttok + \"\\r\\n\" +\n\t\t\t\t\"--123--\\r\\n\"\n\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"https:\/\/foo.com\/pizza\", strings.NewReader(b))\n\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\n\t\t\ti := Interceptor{AppKey: \"testAppKey\", Identifier: userIdentifier{}}\n\t\t\ti.Before(rec.ResponseWriter, req, nil)\n\n\t\t\tif got := rec.Status(); got != test.wantStatus {\n\t\t\t\tt.Errorf(\"response status: got %v, want %v\", got, test.wantStatus)\n\t\t\t}\n\t\t\tif diff := cmp.Diff(test.wantHeader, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\t\tt.Errorf(\"rw.header mismatch (-want +got):\\n%s\", diff)\n\t\t\t}\n\t\t\tif got := rec.Body(); got != test.wantBody {\n\t\t\t\tt.Errorf(\"response body: got %q want %q\", got, test.wantBody)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMissingTokenInBody(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\treq *safehttp.IncomingRequest\n\t}{\n\t\t{\n\t\t\tname: \"Missing token in POST request with form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"\/\", strings.NewReader(\"foo=bar\"))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in PATCH request with form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPatch, \"\/\", strings.NewReader(\"foo=bar\"))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in POST request with multipart form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\t\"Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\" +\n\t\t\t\t\t\"\\r\\n\" +\n\t\t\t\t\t\"bar\\r\\n\" +\n\t\t\t\t\t\"--123--\\r\\n\"\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPost, \"\/\", strings.NewReader(b))\n\t\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Missing token in PATCH request with multipart form\",\n\t\t\treq: func() *safehttp.IncomingRequest {\n\t\t\t\tb := \"--123\\r\\n\" +\n\t\t\t\t\t\"Content-Disposition: form-data; name=\\\"foo\\\"\\r\\n\" +\n\t\t\t\t\t\"\\r\\n\" +\n\t\t\t\t\t\"bar\\r\\n\" +\n\t\t\t\t\t\"--123--\\r\\n\"\n\t\t\t\treq := safehttptest.NewRequest(safehttp.MethodPatch, \"\/\", strings.NewReader(b))\n\t\t\t\treq.Header.Set(\"Content-Type\", `multipart\/form-data; boundary=\"123\"`)\n\t\t\t\treturn req\n\t\t\t}(),\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\trec := safehttptest.NewResponseRecorder()\n\n\t\ti := Interceptor{AppKey: \"testAppKey\", Identifier: userIdentifier{}}\n\t\ti.Before(rec.ResponseWriter, test.req, nil)\n\n\t\tif want, got := safehttp.StatusUnauthorized, rec.Status(); got != want {\n\t\t\tt.Errorf(\"response status: got %v, want %v\", got, want)\n\t\t}\n\t\twantHeaders := map[string][]string{\n\t\t\t\"Content-Type\": {\"text\/plain; charset=utf-8\"},\n\t\t\t\"X-Content-Type-Options\": {\"nosniff\"},\n\t\t}\n\t\tif diff := cmp.Diff(wantHeaders, map[string][]string(rec.Header())); diff != \"\" {\n\t\t\tt.Errorf(\"rw.header mismatch (-want +got):\\n%s\", diff)\n\t\t}\n\t\tif want, got := \"Unauthorized\\n\", rec.Body(); got != want {\n\t\t\tt.Errorf(\"response body: got %q want %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestBeforeTokenInRequestContext(t *testing.T) {\n\trec := safehttptest.NewResponseRecorder()\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"https:\/\/foo.com\/pizza\", nil)\n\n\ti := Interceptor{AppKey: \"testAppKey\", Identifier: userIdentifier{}}\n\ti.Before(rec.ResponseWriter, req, nil)\n\n\ttok, err := Token(req)\n\tif tok == \"\" {\n\t\tt.Error(`Token(req): got \"\", want token`)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Token(req): got %v, want nil\", err)\n\t}\n\n\tif want, got := safehttp.StatusOK, safehttp.StatusCode(rec.Status()); want != got {\n\t\tt.Errorf(\"response status: got %v, want %v\", got, want)\n\t}\n\tif diff := cmp.Diff(map[string][]string{}, map[string][]string(rec.Header())); diff != \"\" {\n\t\tt.Errorf(\"rec.Header() mismatch (-want +got):\\n%s\", diff)\n\t}\n\tif want, got := \"\", rec.Body(); got != want {\n\t\tt.Errorf(\"response body: got %q want %q\", got, want)\n\t}\n\n}\n\nfunc TestTokenInRequestContext(t *testing.T) {\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"\/\", nil)\n\treq.SetContext(context.WithValue(req.Context(), tokenCtxKey{}, \"pizza\"))\n\n\tgot, err := Token(req)\n\tif want := \"pizza\"; want != got {\n\t\tt.Errorf(\"Token(req): got %v, want %v\", got, want)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Token(req): got %v, want nil\", err)\n\t}\n}\n\nfunc TestMissingTokenInRequestContext(t *testing.T) {\n\treq := safehttptest.NewRequest(safehttp.MethodGet, \"\/\", nil)\n\treq.SetContext(context.Background())\n\n\tgot, err := Token(req)\n\tif want := \"\"; want != got {\n\t\tt.Errorf(\"Token(req): got %v, want %v\", got, want)\n\t}\n\tif err == nil {\n\t\tt.Error(\"Token(req): got nil, want error\")\n\t}\n}\n<|endoftext|>"} {"text":"package metainfo\n\nimport (\n\t\"crypto\/sha1\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com\/anacrolix\/libtorgo\/bencode\"\n)\n\n\/\/ Information specific to a single file inside the MetaInfo structure.\ntype FileInfo struct {\n\tLength int64 `bencode:\"length\"`\n\tPath []string `bencode:\"path\"`\n}\n\n\/\/ Load a MetaInfo from an io.Reader. Returns a non-nil error in case of\n\/\/ failure.\nfunc Load(r io.Reader) (*MetaInfo, error) {\n\tvar mi MetaInfo\n\td := bencode.NewDecoder(r)\n\terr := d.Decode(&mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mi, nil\n}\n\n\/\/ Convenience function for loading a MetaInfo from a file.\nfunc LoadFromFile(filename string) (*MetaInfo, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn Load(f)\n}\n\n\/\/ The info dictionary.\ntype Info struct {\n\tPieceLength int64 `bencode:\"piece length\"`\n\tPieces []byte `bencode:\"pieces\"`\n\tName string `bencode:\"name\"`\n\tLength int64 `bencode:\"length,omitempty\"`\n\tPrivate bool `bencode:\"private,omitempty\"`\n\tFiles []FileInfo `bencode:\"files,omitempty\"`\n}\n\n\/\/ The info dictionary with its hash and raw bytes exposed, as these are\n\/\/ important to Bittorrent.\ntype InfoEx struct {\n\tInfo\n\tHash []byte\n\tBytes []byte\n}\n\nvar (\n\t_ bencode.Marshaler = InfoEx{}\n\t_ bencode.Unmarshaler = &InfoEx{}\n)\n\nfunc (this *InfoEx) UnmarshalBencode(data []byte) error {\n\tthis.Bytes = make([]byte, 0, len(data))\n\tthis.Bytes = append(this.Bytes, data...)\n\th := sha1.New()\n\t_, err := h.Write(this.Bytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tthis.Hash = h.Sum(nil)\n\treturn bencode.Unmarshal(data, &this.Info)\n}\n\nfunc (this InfoEx) MarshalBencode() ([]byte, error) {\n\tif this.Bytes != nil {\n\t\treturn this.Bytes, nil\n\t}\n\treturn bencode.Marshal(&this.Info)\n}\n\ntype MetaInfo struct {\n\tInfo InfoEx `bencode:\"info\"`\n\tAnnounce string `bencode:\"announce\"`\n\tAnnounceList [][]string `bencode:\"announce-list,omitempty\"`\n\tCreationDate int64 `bencode:\"creation date,omitempty\"`\n\tComment string `bencode:\"comment,omitempty\"`\n\tCreatedBy string `bencode:\"created by,omitempty\"`\n\tEncoding string `bencode:\"encoding,omitempty\"`\n\tURLList interface{} `bencode:\"url-list,omitempty\"`\n}\nAdd UpvertedFiles() to Info to make single-file torrents usable like multi-file torrents.package metainfo\n\nimport (\n\t\"crypto\/sha1\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com\/anacrolix\/libtorgo\/bencode\"\n)\n\n\/\/ Information specific to a single file inside the MetaInfo structure.\ntype FileInfo struct {\n\tLength int64 `bencode:\"length\"`\n\tPath []string `bencode:\"path\"`\n}\n\n\/\/ Load a MetaInfo from an io.Reader. Returns a non-nil error in case of\n\/\/ failure.\nfunc Load(r io.Reader) (*MetaInfo, error) {\n\tvar mi MetaInfo\n\td := bencode.NewDecoder(r)\n\terr := d.Decode(&mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mi, nil\n}\n\n\/\/ Convenience function for loading a MetaInfo from a file.\nfunc LoadFromFile(filename string) (*MetaInfo, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn Load(f)\n}\n\n\/\/ The info dictionary.\ntype Info struct {\n\tPieceLength int64 `bencode:\"piece length\"`\n\tPieces []byte `bencode:\"pieces\"`\n\tName string `bencode:\"name\"`\n\tLength int64 `bencode:\"length,omitempty\"`\n\tPrivate bool `bencode:\"private,omitempty\"`\n\tFiles []FileInfo `bencode:\"files,omitempty\"`\n}\n\n\/\/ The files field, converted up from the old single-file in the parent info\n\/\/ dict if necessary. This is a helper to avoid having to conditionally handle\n\/\/ single and multi-file torrent infos.\nfunc (i *Info) UpvertedFiles() []FileInfo {\n\tif len(i.Files) == 0 {\n\t\treturn []FileInfo{{\n\t\t\tLength: i.Length,\n\t\t\tPath: []string{i.Name},\n\t\t}}\n\t}\n\treturn i.Files\n}\n\n\/\/ The info dictionary with its hash and raw bytes exposed, as these are\n\/\/ important to Bittorrent.\ntype InfoEx struct {\n\tInfo\n\tHash []byte\n\tBytes []byte\n}\n\nvar (\n\t_ bencode.Marshaler = InfoEx{}\n\t_ bencode.Unmarshaler = &InfoEx{}\n)\n\nfunc (this *InfoEx) UnmarshalBencode(data []byte) error {\n\tthis.Bytes = make([]byte, 0, len(data))\n\tthis.Bytes = append(this.Bytes, data...)\n\th := sha1.New()\n\t_, err := h.Write(this.Bytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tthis.Hash = h.Sum(nil)\n\treturn bencode.Unmarshal(data, &this.Info)\n}\n\nfunc (this InfoEx) MarshalBencode() ([]byte, error) {\n\tif this.Bytes != nil {\n\t\treturn this.Bytes, nil\n\t}\n\treturn bencode.Marshal(&this.Info)\n}\n\ntype MetaInfo struct {\n\tInfo InfoEx `bencode:\"info\"`\n\tAnnounce string `bencode:\"announce\"`\n\tAnnounceList [][]string `bencode:\"announce-list,omitempty\"`\n\tCreationDate int64 `bencode:\"creation date,omitempty\"`\n\tComment string `bencode:\"comment,omitempty\"`\n\tCreatedBy string `bencode:\"created by,omitempty\"`\n\tEncoding string `bencode:\"encoding,omitempty\"`\n\tURLList interface{} `bencode:\"url-list,omitempty\"`\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2014 Ashley Jeffs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\npackage input\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jeffail\/benthos\/types\"\n\t\"github.com\/pebbe\/zmq4\"\n)\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ ZMQ4Config - Configuration for the ZMQ4 input type.\ntype ZMQ4Config struct {\n\tAddresses []string `json:\"addresses\"`\n\tSocketType string `json:\"socket_type\"`\n\tPollTimeoutMS int `json:\"poll_timeout_ms\"`\n}\n\n\/\/ NewZMQ4Config - Creates a new ZMQ4Config with default values.\nfunc NewZMQ4Config() ZMQ4Config {\n\treturn ZMQ4Config{\n\t\tAddresses: []string{\"localhost:1234\"},\n\t\tSocketType: \"PULL\",\n\t\tPollTimeoutMS: 5000,\n\t}\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ ZMQ4 - An input type that serves ZMQ4 POST requests.\ntype ZMQ4 struct {\n\tconf Config\n\n\tsocket *zmq4.Socket\n\tpoller *zmq4.Poller\n\n\tmessages chan types.Message\n\tresponses <-chan types.Response\n\n\tnewResponsesChan chan (<-chan types.Response)\n\n\tclosedChan chan struct{}\n\tcloseChan chan struct{}\n}\n\n\/\/ NewZMQ4 - Create a new ZMQ4 input type.\nfunc NewZMQ4(conf Config) (*ZMQ4, error) {\n\tz := ZMQ4{\n\t\tconf: conf,\n\t\tmessages: make(chan types.Message),\n\t\tresponses: nil,\n\t\tnewResponsesChan: make(chan (<-chan types.Response)),\n\t\tclosedChan: make(chan struct{}),\n\t\tcloseChan: make(chan struct{}),\n\t}\n\n\tt, err := getZMQType(conf.ZMQ4.SocketType)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tctx, err := zmq4.NewContext()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tif z.socket, err = ctx.NewSocket(t); nil != err {\n\t\treturn nil, err\n\t}\n\n\tfor _, address := range conf.ZMQ4.Addresses {\n\t\tif strings.Contains(address, \"*\") {\n\t\t\terr = z.socket.Bind(address)\n\t\t} else {\n\t\t\terr = z.socket.Connect(address)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tz.poller = zmq4.NewPoller()\n\tz.poller.Add(z.socket, zmq4.POLLIN)\n\n\tgo z.loop()\n\n\treturn &z, nil\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\nfunc getZMQType(t string) (zmq4.Type, error) {\n\tswitch t {\n\tcase \"REQ\":\n\t\treturn zmq4.REQ, nil\n\tcase \"REP\":\n\t\treturn zmq4.REP, nil\n\tcase \"DEALER\":\n\t\treturn zmq4.DEALER, nil\n\tcase \"ROUTER\":\n\t\treturn zmq4.ROUTER, nil\n\tcase \"PUB\":\n\t\treturn zmq4.PUB, nil\n\tcase \"SUB\":\n\t\treturn zmq4.SUB, nil\n\tcase \"XPUB\":\n\t\treturn zmq4.XPUB, nil\n\tcase \"XSUB\":\n\t\treturn zmq4.XSUB, nil\n\tcase \"PUSH\":\n\t\treturn zmq4.PUSH, nil\n\tcase \"PULL\":\n\t\treturn zmq4.PULL, nil\n\tcase \"PAIR\":\n\t\treturn zmq4.PAIR, nil\n\tcase \"STREAM\":\n\t\treturn zmq4.STREAM, nil\n\t}\n\treturn zmq4.PULL, types.ErrInvalidZMQType\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ loop - Internal loop brokers incoming messages to output pipe.\nfunc (z *ZMQ4) loop() {\n\tvar bytes [][]byte\n\tvar msgChan chan<- types.Message\n\n\tpollTimeout := time.Millisecond * time.Duration(z.conf.ZMQ4.PollTimeoutMS)\n\n\trunning, responsePending := true, false\n\tfor running {\n\t\t\/\/ If no bytes then read a message\n\t\tif bytes == nil {\n\t\t\tpolled, err := z.poller.Poll(pollTimeout)\n\t\t\tif err == nil && len(polled) == 1 {\n\t\t\t\tbytes, err = z.socket.RecvMessageBytes(0)\n\t\t\t\tif err != nil {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have a line to push out\n\t\tif bytes != nil && !responsePending {\n\t\t\tmsgChan = z.messages\n\t\t} else {\n\t\t\tmsgChan = nil\n\t\t}\n\n\t\tif running {\n\t\t\tselect {\n\t\t\tcase msgChan <- types.Message{Parts: bytes}:\n\t\t\t\tresponsePending = true\n\t\t\tcase err, open := <-z.responses:\n\t\t\t\tif !open {\n\t\t\t\t\tz.responses = nil\n\t\t\t\t} else if err == nil {\n\t\t\t\t\tresponsePending = false\n\t\t\t\t\tbytes = nil\n\t\t\t\t}\n\t\t\tcase newResChan, open := <-z.newResponsesChan:\n\t\t\t\tif running = open; open {\n\t\t\t\t\tz.responses = newResChan\n\t\t\t\t}\n\t\t\tcase _, running = <-z.closeChan:\n\t\t\t}\n\t\t}\n\t}\n\n\tclose(z.messages)\n\tclose(z.newResponsesChan)\n\tclose(z.closedChan)\n}\n\n\/\/ SetResponseChan - Sets the channel used by the input to validate message receipt.\nfunc (z *ZMQ4) SetResponseChan(responses <-chan types.Response) {\n\tz.newResponsesChan <- responses\n}\n\n\/\/ ConsumerChan - Returns the messages channel.\nfunc (z *ZMQ4) ConsumerChan() <-chan types.Message {\n\treturn z.messages\n}\n\n\/\/ CloseAsync - Shuts down the ZMQ4 input and stops processing requests.\nfunc (z *ZMQ4) CloseAsync() {\n\tclose(z.closeChan)\n}\n\n\/\/ WaitForClose - Blocks until the ZMQ4 input has closed down.\nfunc (z *ZMQ4) WaitForClose(timeout time.Duration) error {\n\tselect {\n\tcase <-z.closedChan:\n\tcase <-time.After(timeout):\n\t\treturn types.ErrTimeout\n\t}\n\treturn nil\n}\n\n\/\/--------------------------------------------------------------------------------------------------\nRefactor zmq input\/*\nCopyright (c) 2014 Ashley Jeffs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\npackage input\n\nimport (\n\t\"strings\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/jeffail\/benthos\/types\"\n\t\"github.com\/pebbe\/zmq4\"\n)\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ ZMQ4Config - Configuration for the ZMQ4 input type.\ntype ZMQ4Config struct {\n\tAddresses []string `json:\"addresses\"`\n\tSocketType string `json:\"socket_type\"`\n\tPollTimeoutMS int `json:\"poll_timeout_ms\"`\n}\n\n\/\/ NewZMQ4Config - Creates a new ZMQ4Config with default values.\nfunc NewZMQ4Config() ZMQ4Config {\n\treturn ZMQ4Config{\n\t\tAddresses: []string{\"localhost:1234\"},\n\t\tSocketType: \"PULL\",\n\t\tPollTimeoutMS: 5000,\n\t}\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ ZMQ4 - An input type that serves ZMQ4 POST requests.\ntype ZMQ4 struct {\n\trunning int32\n\n\tconf Config\n\n\tsocket *zmq4.Socket\n\n\tinternalMessages chan [][]byte\n\n\tmessages chan types.Message\n\tresponses <-chan types.Response\n\n\tnewResponsesChan chan (<-chan types.Response)\n\n\tclosedChan chan struct{}\n\tcloseChan chan struct{}\n}\n\n\/\/ NewZMQ4 - Create a new ZMQ4 input type.\nfunc NewZMQ4(conf Config) (*ZMQ4, error) {\n\tz := ZMQ4{\n\t\trunning: 1,\n\t\tconf: conf,\n\t\tinternalMessages: make(chan [][]byte),\n\t\tmessages: make(chan types.Message),\n\t\tresponses: nil,\n\t\tnewResponsesChan: make(chan (<-chan types.Response)),\n\t\tclosedChan: make(chan struct{}),\n\t\tcloseChan: make(chan struct{}),\n\t}\n\n\tt, err := getZMQType(conf.ZMQ4.SocketType)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tctx, err := zmq4.NewContext()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tif z.socket, err = ctx.NewSocket(t); nil != err {\n\t\treturn nil, err\n\t}\n\n\tfor _, address := range conf.ZMQ4.Addresses {\n\t\tif strings.Contains(address, \"*\") {\n\t\t\terr = z.socket.Bind(address)\n\t\t} else {\n\t\t\terr = z.socket.Connect(address)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tgo z.readerLoop()\n\tgo z.loop()\n\n\treturn &z, nil\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\nfunc getZMQType(t string) (zmq4.Type, error) {\n\tswitch t {\n\tcase \"REQ\":\n\t\treturn zmq4.REQ, nil\n\tcase \"REP\":\n\t\treturn zmq4.REP, nil\n\tcase \"DEALER\":\n\t\treturn zmq4.DEALER, nil\n\tcase \"ROUTER\":\n\t\treturn zmq4.ROUTER, nil\n\tcase \"PUB\":\n\t\treturn zmq4.PUB, nil\n\tcase \"SUB\":\n\t\treturn zmq4.SUB, nil\n\tcase \"XPUB\":\n\t\treturn zmq4.XPUB, nil\n\tcase \"XSUB\":\n\t\treturn zmq4.XSUB, nil\n\tcase \"PUSH\":\n\t\treturn zmq4.PUSH, nil\n\tcase \"PULL\":\n\t\treturn zmq4.PULL, nil\n\tcase \"PAIR\":\n\t\treturn zmq4.PAIR, nil\n\tcase \"STREAM\":\n\t\treturn zmq4.STREAM, nil\n\t}\n\treturn zmq4.PULL, types.ErrInvalidZMQType\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n\n\/\/ readerLoop - Internal loop for polling new messages.\nfunc (z *ZMQ4) readerLoop() {\n\tpollTimeout := time.Millisecond * time.Duration(z.conf.ZMQ4.PollTimeoutMS)\n\tpoller := zmq4.NewPoller()\n\tpoller.Add(z.socket, zmq4.POLLIN)\n\n\tfor atomic.LoadInt32(&z.running) == 1 {\n\t\t\/\/ If no bytes then read a message\n\t\tpolled, err := poller.Poll(pollTimeout)\n\t\tif err == nil && len(polled) == 1 {\n\t\t\tif bytes, err := z.socket.RecvMessageBytes(0); err == nil {\n\t\t\t\tz.internalMessages <- bytes\n\t\t\t} else {\n\t\t\t\t_ = err\n\t\t\t\t\/\/ TODO: propagate errors, input type should have error channel.\n\t\t\t}\n\t\t}\n\t}\n\tclose(z.internalMessages)\n}\n\n\/\/ loop - Internal loop brokers incoming messages to output pipe.\nfunc (z *ZMQ4) loop() {\n\tvar bytes [][]byte\n\n\tvar msgChan chan<- types.Message\n\tvar internalChan <-chan [][]byte\n\n\trunning, responsePending := true, false\n\tfor running {\n\t\t\/\/ If we have a line to push out\n\t\tif responsePending {\n\t\t\tmsgChan = nil\n\t\t\tinternalChan = nil\n\t\t} else {\n\t\t\tif bytes == nil {\n\t\t\t\tmsgChan = nil\n\t\t\t\tinternalChan = z.internalMessages\n\t\t\t} else {\n\t\t\t\tmsgChan = z.messages\n\t\t\t\tinternalChan = nil\n\t\t\t}\n\t\t}\n\n\t\tselect {\n\t\tcase bytes, running = <-internalChan:\n\t\tcase msgChan <- types.Message{Parts: bytes}:\n\t\t\tresponsePending = true\n\t\tcase err, open := <-z.responses:\n\t\t\tresponsePending = false\n\t\t\tif !open {\n\t\t\t\tz.responses = nil\n\t\t\t} else if err == nil {\n\t\t\t\tbytes = nil\n\t\t\t}\n\t\tcase newResChan, open := <-z.newResponsesChan:\n\t\t\tif running = open; open {\n\t\t\t\tz.responses = newResChan\n\t\t\t}\n\t\tcase _, running = <-z.closeChan:\n\t\t}\n\t}\n\n\tclose(z.messages)\n\tclose(z.newResponsesChan)\n\tclose(z.closedChan)\n}\n\n\/\/ SetResponseChan - Sets the channel used by the input to validate message receipt.\nfunc (z *ZMQ4) SetResponseChan(responses <-chan types.Response) {\n\tz.newResponsesChan <- responses\n}\n\n\/\/ ConsumerChan - Returns the messages channel.\nfunc (z *ZMQ4) ConsumerChan() <-chan types.Message {\n\treturn z.messages\n}\n\n\/\/ CloseAsync - Shuts down the ZMQ4 input and stops processing requests.\nfunc (z *ZMQ4) CloseAsync() {\n\tatomic.StoreInt32(&z.running, 0)\n}\n\n\/\/ WaitForClose - Blocks until the ZMQ4 input has closed down.\nfunc (z *ZMQ4) WaitForClose(timeout time.Duration) error {\n\tselect {\n\tcase <-z.closedChan:\n\tcase <-time.After(timeout):\n\t\treturn types.ErrTimeout\n\t}\n\treturn nil\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n<|endoftext|>"} {"text":"\/\/ Copyright 2012-present Oliver Eilhard. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-license.\n\/\/ See http:\/\/olivere.mit-license.org\/license.txt for details.\n\npackage elastic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"github.com\/olivere\/elastic\/uritemplates\"\n)\n\n\/\/ See the documentation at\n\/\/ https:\/\/www.elastic.co\/guide\/en\/elasticsearch\/reference\/6.7\/ilm-get-lifecycle.html.\ntype XPackIlmDeleteLifecycleService struct {\n\tclient *Client\n\tpolicy string\n\tpretty bool\n\ttimeout string\n\tmasterTimeout string\n\tflatSettings *bool\n\tlocal *bool\n}\n\n\/\/ NewXPackIlmDeleteLifecycleService creates a new XPackIlmDeleteLifecycleService.\nfunc NewXPackIlmDeleteLifecycleService(client *Client) *XPackIlmDeleteLifecycleService {\n\treturn &XPackIlmDeleteLifecycleService{\n\t\tclient: client,\n\t}\n}\n\n\/\/ Policy is the name of the index lifecycle policy.\nfunc (s *XPackIlmDeleteLifecycleService) Policy(policy string) *XPackIlmDeleteLifecycleService {\n\ts.policy = policy\n\treturn s\n}\n\n\/\/ Timeout is an explicit operation timeout.\nfunc (s *XPackIlmDeleteLifecycleService) Timeout(timeout string) *XPackIlmDeleteLifecycleService {\n\ts.timeout = timeout\n\treturn s\n}\n\n\/\/ MasterTimeout specifies the timeout for connection to master.\nfunc (s *XPackIlmDeleteLifecycleService) MasterTimeout(masterTimeout string) *XPackIlmDeleteLifecycleService {\n\ts.masterTimeout = masterTimeout\n\treturn s\n}\n\n\/\/ FlatSettings is returns settings in flat format (default: false).\nfunc (s *XPackIlmDeleteLifecycleService) FlatSettings(flatSettings bool) *XPackIlmDeleteLifecycleService {\n\ts.flatSettings = &flatSettings\n\treturn s\n}\n\n\/\/ Pretty indicates that the JSON response be indented and human readable.\nfunc (s *XPackIlmDeleteLifecycleService) Pretty(pretty bool) *XPackIlmDeleteLifecycleService {\n\ts.pretty = pretty\n\treturn s\n}\n\n\/\/ buildURL builds the URL for the operation.\nfunc (s *XPackIlmDeleteLifecycleService) buildURL() (string, url.Values, error) {\n\t\/\/ Build URL\n\tvar err error\n\tvar path string\n\tif s.policy != \"\" {\n\t\tpath, err = uritemplates.Expand(\"\/_ilm\/policy\/{policy}\", map[string]string{\n\t\t\t\"policy\": s.policy,\n\t\t})\n\t} else {\n\t\tpath = \"\/_template\"\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t\/\/ Add query string parameters\n\tparams := url.Values{}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", \"true\")\n\t}\n\tif s.flatSettings != nil {\n\t\tparams.Set(\"flat_settings\", fmt.Sprintf(\"%v\", *s.flatSettings))\n\t}\n\tif s.timeout != \"\" {\n\t\tparams.Set(\"timeout\", s.timeout)\n\t}\n\tif s.masterTimeout != \"\" {\n\t\tparams.Set(\"master_timeout\", s.masterTimeout)\n\t}\n\tif s.local != nil {\n\t\tparams.Set(\"local\", fmt.Sprintf(\"%v\", *s.local))\n\t}\n\treturn path, params, nil\n}\n\n\/\/ Validate checks if the operation is valid.\nfunc (s *XPackIlmDeleteLifecycleService) Validate() error {\n\tvar invalid []string\n\tif s.policy == \"\" {\n\t\tinvalid = append(invalid, \"Policy\")\n\t}\n\tif len(invalid) > 0 {\n\t\treturn fmt.Errorf(\"missing required fields: %v\", invalid)\n\t}\n\treturn nil\n}\n\n\/\/ Do executes the operation.\nfunc (s *XPackIlmDeleteLifecycleService) Do(ctx context.Context) (*XPackIlmDeleteLifecycleResponse, error) {\n\t\/\/ Check pre-conditions\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Delete URL for request\n\tpath, params, err := s.buildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Delete HTTP response\n\tres, err := s.client.PerformRequest(ctx, PerformRequestOptions{\n\t\tMethod: \"DELETE\",\n\t\tPath: path,\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Return operation response\n\tret := new(XPackIlmDeleteLifecycleResponse)\n\tif err := s.client.decoder.Decode(res.Body, ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}\n\n\/\/ XPackIlmDeleteLifecycleResponse is the response of XPackIlmDeleteLifecycleService.Do.\ntype XPackIlmDeleteLifecycleResponse struct {\n\tAcknowledged bool `json:\"acknowledged\"`\n}\nsmall fix in delete from copy paste error\/\/ Copyright 2012-present Oliver Eilhard. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-license.\n\/\/ See http:\/\/olivere.mit-license.org\/license.txt for details.\n\npackage elastic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"github.com\/olivere\/elastic\/uritemplates\"\n)\n\n\/\/ See the documentation at\n\/\/ https:\/\/www.elastic.co\/guide\/en\/elasticsearch\/reference\/6.7\/ilm-get-lifecycle.html.\ntype XPackIlmDeleteLifecycleService struct {\n\tclient *Client\n\tpolicy string\n\tpretty bool\n\ttimeout string\n\tmasterTimeout string\n\tflatSettings *bool\n\tlocal *bool\n}\n\n\/\/ NewXPackIlmDeleteLifecycleService creates a new XPackIlmDeleteLifecycleService.\nfunc NewXPackIlmDeleteLifecycleService(client *Client) *XPackIlmDeleteLifecycleService {\n\treturn &XPackIlmDeleteLifecycleService{\n\t\tclient: client,\n\t}\n}\n\n\/\/ Policy is the name of the index lifecycle policy.\nfunc (s *XPackIlmDeleteLifecycleService) Policy(policy string) *XPackIlmDeleteLifecycleService {\n\ts.policy = policy\n\treturn s\n}\n\n\/\/ Timeout is an explicit operation timeout.\nfunc (s *XPackIlmDeleteLifecycleService) Timeout(timeout string) *XPackIlmDeleteLifecycleService {\n\ts.timeout = timeout\n\treturn s\n}\n\n\/\/ MasterTimeout specifies the timeout for connection to master.\nfunc (s *XPackIlmDeleteLifecycleService) MasterTimeout(masterTimeout string) *XPackIlmDeleteLifecycleService {\n\ts.masterTimeout = masterTimeout\n\treturn s\n}\n\n\/\/ FlatSettings is returns settings in flat format (default: false).\nfunc (s *XPackIlmDeleteLifecycleService) FlatSettings(flatSettings bool) *XPackIlmDeleteLifecycleService {\n\ts.flatSettings = &flatSettings\n\treturn s\n}\n\n\/\/ Pretty indicates that the JSON response be indented and human readable.\nfunc (s *XPackIlmDeleteLifecycleService) Pretty(pretty bool) *XPackIlmDeleteLifecycleService {\n\ts.pretty = pretty\n\treturn s\n}\n\n\/\/ buildURL builds the URL for the operation.\nfunc (s *XPackIlmDeleteLifecycleService) buildURL() (string, url.Values, error) {\n\t\/\/ Build URL\n\tvar err error\n\tvar path string\n\tpath, err = uritemplates.Expand(\"\/_ilm\/policy\/{policy}\", map[string]string{\n\t\t\"policy\": s.policy,\n\t})\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t\/\/ Add query string parameters\n\tparams := url.Values{}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", \"true\")\n\t}\n\tif s.flatSettings != nil {\n\t\tparams.Set(\"flat_settings\", fmt.Sprintf(\"%v\", *s.flatSettings))\n\t}\n\tif s.timeout != \"\" {\n\t\tparams.Set(\"timeout\", s.timeout)\n\t}\n\tif s.masterTimeout != \"\" {\n\t\tparams.Set(\"master_timeout\", s.masterTimeout)\n\t}\n\tif s.local != nil {\n\t\tparams.Set(\"local\", fmt.Sprintf(\"%v\", *s.local))\n\t}\n\treturn path, params, nil\n}\n\n\/\/ Validate checks if the operation is valid.\nfunc (s *XPackIlmDeleteLifecycleService) Validate() error {\n\tvar invalid []string\n\tif s.policy == \"\" {\n\t\tinvalid = append(invalid, \"Policy\")\n\t}\n\tif len(invalid) > 0 {\n\t\treturn fmt.Errorf(\"missing required fields: %v\", invalid)\n\t}\n\treturn nil\n}\n\n\/\/ Do executes the operation.\nfunc (s *XPackIlmDeleteLifecycleService) Do(ctx context.Context) (*XPackIlmDeleteLifecycleResponse, error) {\n\t\/\/ Check pre-conditions\n\tif err := s.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Delete URL for request\n\tpath, params, err := s.buildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Delete HTTP response\n\tres, err := s.client.PerformRequest(ctx, PerformRequestOptions{\n\t\tMethod: \"DELETE\",\n\t\tPath: path,\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Return operation response\n\tret := new(XPackIlmDeleteLifecycleResponse)\n\tif err := s.client.decoder.Decode(res.Body, ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}\n\n\/\/ XPackIlmDeleteLifecycleResponse is the response of XPackIlmDeleteLifecycleService.Do.\ntype XPackIlmDeleteLifecycleResponse struct {\n\tAcknowledged bool `json:\"acknowledged\"`\n}\n<|endoftext|>"} {"text":"package cloudwatch\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Pallinder\/go-randomdata\"\n\t\"github.com\/gliderlabs\/logspout\/router\"\n)\n\nconst NumMessages = 2000000\n\nfunc TestCloudWatchAdapter(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration test in short mode.\")\n\t}\n\n\troute := &router.Route{Address: \"logspout-cloudwatch\"}\n\tmessages := make(chan *router.Message)\n\n\tadapter, err := NewAdapter(route)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tgo adapter.Stream(messages)\n\tfor i := 0; i < NumMessages; i++ {\n\t\tmessages <- &router.Message{Data: randomdata.Paragraph(), Time: time.Now()}\n\t}\n\n\tclose(messages)\n}\nReduce number of messages inserted during integration test.package cloudwatch\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Pallinder\/go-randomdata\"\n\t\"github.com\/gliderlabs\/logspout\/router\"\n)\n\nconst NumMessages = 250000\n\nfunc TestCloudWatchAdapter(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration test in short mode.\")\n\t}\n\n\troute := &router.Route{Address: \"logspout-cloudwatch\"}\n\tmessages := make(chan *router.Message)\n\n\tadapter, err := NewAdapter(route)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tgo adapter.Stream(messages)\n\tfor i := 0; i < NumMessages; i++ {\n\t\tmessages <- &router.Message{Data: randomdata.Paragraph(), Time: time.Now()}\n\t}\n\n\tclose(messages)\n}\n<|endoftext|>"} {"text":"package cluster\n\nimport (\n\t\"time\"\n\n\t\"github.com\/AsynkronIT\/gonet\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/log\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/remote\"\n)\n\nvar cfg *ClusterConfig\n\nfunc Start(clusterName, address string, provider ClusterProvider) {\n\tStartWithConfig(NewClusterConfig(clusterName, address, provider))\n}\n\nfunc StartWithConfig(config *ClusterConfig) {\n\tcfg = config\n\n\t\/\/TODO: make it possible to become a cluster even if remoting is already started\n\tremote.Start(cfg.Address, cfg.RemotingOption...)\n\n\taddress := actor.ProcessRegistry.Address\n\th, p := gonet.GetAddress(address)\n\tplog.Info(\"Starting Proto.Actor cluster\", log.String(\"address\", address))\n\tkinds := remote.GetKnownKinds()\n\n\t\/\/for each known kind, spin up a partition-kind actor to handle all requests for that kind\n\tsetupPartition(kinds)\n\tsetupPidCache()\n\tsetupMemberList()\n\n\tcfg.ClusterProvider.RegisterMember(cfg.Name, h, p, kinds, cfg.InitialMemberStatusValue, cfg.MemberStatusValueSerializer)\n\tcfg.ClusterProvider.MonitorMemberStatusChanges()\n}\n\nfunc Shutdown(graceful bool) {\n\tif graceful {\n\t\tcfg.ClusterProvider.Shutdown()\n\t\t\/\/This is to wait ownership transfering complete.\n\t\ttime.Sleep(time.Millisecond * 2000)\n\t\tstopMemberList()\n\t\tstopPidCache()\n\t\tstopPartition()\n\t}\n\n\tremote.Shutdown(graceful)\n\n\taddress := actor.ProcessRegistry.Address\n\tplog.Info(\"Stopped Proto.Actor cluster\", log.String(\"address\", address))\n}\n\n\/\/Get a PID to a virtual actor\nfunc Get(name string, kind string) (*actor.PID, remote.ResponseStatusCode) {\n\t\/\/Check Cache\n\tif pid, ok := pidCache.getCache(name); ok {\n\t\treturn pid, remote.ResponseStatusCodeOK\n\t}\n\n\t\/\/Get Pid\n\taddress := memberList.getPartitionMember(name, kind)\n\tif address == \"\" {\n\t\t\/\/No available member found\n\t\treturn nil, remote.ResponseStatusCodeUNAVAILABLE\n\t}\n\n\t\/\/package the request as a remote.ActorPidRequest\n\treq := &remote.ActorPidRequest{\n\t\tKind: kind,\n\t\tName: name,\n\t}\n\n\t\/\/ask the DHT partition for this name to give us a PID\n\tremotePartition := partition.partitionForKind(address, kind)\n\tf := remotePartition.RequestFuture(req, cfg.TimeoutTime)\n\terr := f.Wait()\n\tif err == actor.ErrTimeout {\n\t\tplog.Error(\"PidCache Pid request timeout\")\n\t\treturn nil, remote.ResponseStatusCodeTIMEOUT\n\t} else if err != nil {\n\t\tplog.Error(\"PidCache Pid request error\", log.Error(err))\n\t\treturn nil, remote.ResponseStatusCodeERROR\n\t}\n\n\tr, _ := f.Result()\n\tresponse, ok := r.(*remote.ActorPidResponse)\n\tif !ok {\n\t\treturn nil, remote.ResponseStatusCodeERROR\n\t}\n\n\tstatusCode := remote.ResponseStatusCode(response.StatusCode)\n\tswitch statusCode {\n\tcase remote.ResponseStatusCodeOK:\n\t\t\/\/save cache\n\t\tpidCache.addCache(name, response.Pid)\n\t\t\/\/tell the original requester that we have a response\n\t\treturn response.Pid, statusCode\n\tdefault:\n\t\t\/\/forward to requester\n\t\treturn response.Pid, statusCode\n\t}\n}\n\n\/\/RemoveCache at PidCache\nfunc RemoveCache(name string) {\n\tpidCache.removeCacheByName(name)\n}\nSimplify cluster GetPid code.package cluster\n\nimport (\n\t\"time\"\n\n\t\"github.com\/AsynkronIT\/gonet\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/log\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/remote\"\n)\n\nvar cfg *ClusterConfig\n\nfunc Start(clusterName, address string, provider ClusterProvider) {\n\tStartWithConfig(NewClusterConfig(clusterName, address, provider))\n}\n\nfunc StartWithConfig(config *ClusterConfig) {\n\tcfg = config\n\n\t\/\/TODO: make it possible to become a cluster even if remoting is already started\n\tremote.Start(cfg.Address, cfg.RemotingOption...)\n\n\taddress := actor.ProcessRegistry.Address\n\th, p := gonet.GetAddress(address)\n\tplog.Info(\"Starting Proto.Actor cluster\", log.String(\"address\", address))\n\tkinds := remote.GetKnownKinds()\n\n\t\/\/for each known kind, spin up a partition-kind actor to handle all requests for that kind\n\tsetupPartition(kinds)\n\tsetupPidCache()\n\tsetupMemberList()\n\n\tcfg.ClusterProvider.RegisterMember(cfg.Name, h, p, kinds, cfg.InitialMemberStatusValue, cfg.MemberStatusValueSerializer)\n\tcfg.ClusterProvider.MonitorMemberStatusChanges()\n}\n\nfunc Shutdown(graceful bool) {\n\tif graceful {\n\t\tcfg.ClusterProvider.Shutdown()\n\t\t\/\/This is to wait ownership transfering complete.\n\t\ttime.Sleep(time.Millisecond * 2000)\n\t\tstopMemberList()\n\t\tstopPidCache()\n\t\tstopPartition()\n\t}\n\n\tremote.Shutdown(graceful)\n\n\taddress := actor.ProcessRegistry.Address\n\tplog.Info(\"Stopped Proto.Actor cluster\", log.String(\"address\", address))\n}\n\n\/\/Get a PID to a virtual actor\nfunc Get(name string, kind string) (*actor.PID, remote.ResponseStatusCode) {\n\t\/\/Check Cache\n\tif pid, ok := pidCache.getCache(name); ok {\n\t\treturn pid, remote.ResponseStatusCodeOK\n\t}\n\n\t\/\/Get Pid\n\taddress := memberList.getPartitionMember(name, kind)\n\tif address == \"\" {\n\t\t\/\/No available member found\n\t\treturn nil, remote.ResponseStatusCodeUNAVAILABLE\n\t}\n\n\t\/\/package the request as a remote.ActorPidRequest\n\treq := &remote.ActorPidRequest{\n\t\tKind: kind,\n\t\tName: name,\n\t}\n\n\t\/\/ask the DHT partition for this name to give us a PID\n\tremotePartition := partition.partitionForKind(address, kind)\n\tr, err := remotePartition.RequestFuture(req, cfg.TimeoutTime).Result()\n\tif err == actor.ErrTimeout {\n\t\tplog.Error(\"PidCache Pid request timeout\")\n\t\treturn nil, remote.ResponseStatusCodeTIMEOUT\n\t} else if err != nil {\n\t\tplog.Error(\"PidCache Pid request error\", log.Error(err))\n\t\treturn nil, remote.ResponseStatusCodeERROR\n\t}\n\n\tresponse, ok := r.(*remote.ActorPidResponse)\n\tif !ok {\n\t\treturn nil, remote.ResponseStatusCodeERROR\n\t}\n\n\tstatusCode := remote.ResponseStatusCode(response.StatusCode)\n\tswitch statusCode {\n\tcase remote.ResponseStatusCodeOK:\n\t\t\/\/save cache\n\t\tpidCache.addCache(name, response.Pid)\n\t\t\/\/tell the original requester that we have a response\n\t\treturn response.Pid, statusCode\n\tdefault:\n\t\t\/\/forward to requester\n\t\treturn response.Pid, statusCode\n\t}\n}\n\n\/\/RemoveCache at PidCache\nfunc RemoveCache(name string) {\n\tpidCache.removeCacheByName(name)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Reed O'Brien. 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 rescat\n\nimport (\n\t\"io\"\n)\n\n\/\/ Fetcher interface to be provided for FS, HTTP etc...\ntype Fetcher interface {\n\tFetch(n string) (b []byte, err error)\n}\n\n\/\/ Maybe doesn't need to be an interface?\ntype Provider interface {\n\t\/\/ return the concatinated string as a ??? ready to write to\n\t\/\/ and HTTP Response\n\tProvide(names []string) (r io.Reader, err error)\n\tFetcher\n}\nadd doc string\/\/ Copyright 2013 Reed O'Brien. 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 rescat\n\nimport (\n\t\"io\"\n)\n\n\/\/ Fetcher interface to be provided for FS, HTTP etc...\ntype Fetcher interface {\n\t\/\/ Fetch the resource n and return it as a byte array.\n\tFetch(n string) (b []byte, err error)\n}\n\n\/\/ Maybe doesn't need to be an interface?\ntype Provider interface {\n\t\/\/ return the concatinated string as a ??? ready to write to\n\t\/\/ and HTTP Response\n\tProvide(names []string) (r io.Reader, err error)\n\tFetcher\n}\n<|endoftext|>"} {"text":"package main\r\n\r\nimport (\r\n\t\"compress\/gzip\"\r\n\t\"crypto\/sha256\"\r\n\t\"encoding\/hex\"\r\n\t\"io\"\r\n\t\"net\/http\"\r\n\t\"strings\"\r\n\t\"sync\"\r\n\t\"time\"\r\n\r\n\t\"github.com\/superp00t\/etc\"\r\n\t\"github.com\/superp00t\/etc\/yo\"\r\n)\r\n\r\ntype diskStatus struct {\r\n\tAll uint64 `json:\"all\"`\r\n\tUsed uint64 `json:\"used\"`\r\n\tFree uint64 `json:\"free\"`\r\n}\r\n\r\ntype cacher struct {\r\n\tHandler http.Handler\r\n\r\n\tsync.Mutex\r\n}\r\n\r\nfunc hashString(name string) string {\r\n\ts := sha256.New()\r\n\ts.Write([]byte(name))\r\n\treturn strings.ToUpper(hex.EncodeToString(s.Sum(nil)))\r\n}\r\n\r\nfunc (c *cacher) Available() uint64 {\r\n\treturn directory.Concat(\"c\").Free()\r\n}\r\n\r\nfunc (c *cacher) serveContent(rw http.ResponseWriter, r *http.Request, path string) {\r\n\tif strings.Contains(r.Header.Get(\"Accept-Ranges\"), \"-\") {\r\n\t\t\/\/ Cannot serve compressed in this fashion\r\n\t\thttp.ServeFile(rw, r, path)\r\n\t\treturn\r\n\t}\r\n\r\n\tif strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\r\n\t\trw.Header().Set(\"Content-Encoding\", \"gzip\")\r\n\r\n\t\tfile, err := etc.FileController(path, true)\r\n\t\tif err != nil {\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\ttp := http.DetectContentType(file.ReadBytes(512))\r\n\r\n\t\trw.Header().Set(\"Content-Type\", tp)\r\n\r\n\t\tfile.SeekR(0)\r\n\r\n\t\tgz := gzip.NewWriter(rw)\r\n\t\tio.Copy(gz, file)\r\n\t\tgz.Close()\r\n\t\tfile.Close()\r\n\t\treturn\r\n\t}\r\n\r\n\thttp.ServeFile(rw, r, path)\r\n}\r\n\r\nfunc (c *cacher) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\r\n\tpth := r.URL.Path[1:]\r\n\thash := hashString(pth)\r\n\tpCachePath := directory.Concat(\"c\").Concat(hash)\r\n\tpSrcPath := directory.Concat(\"i\").GetSub(etc.ParseUnixPath(pth))\r\n\r\n\tif pCachePath.IsExtant() && time.Since(pCachePath.Time()) < Config.CacheDuration.Duration {\r\n\t\t\/\/ cached file exists.\r\n\t\tc.serveContent(rw, r, pCachePath.Render())\r\n\t\treturn\r\n\t}\r\n\r\n\t\/\/ Backend may be down. serve cached file in its place.\r\n\tif !pSrcPath.IsExtant() && pCachePath.IsExtant() {\r\n\t\tc.serveContent(rw, r, pCachePath.Render())\r\n\t\treturn\r\n\t}\r\n\r\n\tif pSrcPath.IsExtant() == false {\r\n\t\thttp.Error(rw, \"file not found\", 404)\r\n\t\treturn\r\n\t}\r\n\r\n\tcacheDir := directory.Concat(\"c\")\r\n\r\n\t\/\/ delete oldest item in cache if we have not enough space.\r\n\tfor cacheDir.Free() < pSrcPath.Size() || cacheDir.Size() > Config.MaxCacheBytes {\r\n\t\tyo.Ok(\"erasing until bytes free are more than\", cacheDir.Free())\r\n\r\n\t\tlru, err := cacheDir.LRU()\r\n\t\tif err != nil {\r\n\t\t\tyo.Warn(err)\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tcacheDir.Concat(lru).Remove()\r\n\t}\r\n\r\n\tpCachePath.Remove()\r\n\r\n\tf, err := etc.FileController(pCachePath.Render())\r\n\tif err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tif err = f.Flush(); err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\ts, err := etc.FileController(pSrcPath.Render(), true)\r\n\tif err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tif _, err = io.Copy(f, s); err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tf.Close()\r\n\ts.Close()\r\n\r\n\tc.serveContent(rw, r, pCachePath.Render())\r\n}\r\ndont gzip textpackage main\r\n\r\nimport (\r\n\t\"compress\/gzip\"\r\n\t\"crypto\/sha256\"\r\n\t\"encoding\/hex\"\r\n\t\"io\"\r\n\t\"net\/http\"\r\n\t\"strings\"\r\n\t\"sync\"\r\n\t\"time\"\r\n\r\n\t\"github.com\/superp00t\/etc\"\r\n\t\"github.com\/superp00t\/etc\/yo\"\r\n)\r\n\r\ntype diskStatus struct {\r\n\tAll uint64 `json:\"all\"`\r\n\tUsed uint64 `json:\"used\"`\r\n\tFree uint64 `json:\"free\"`\r\n}\r\n\r\ntype cacher struct {\r\n\tHandler http.Handler\r\n\r\n\tsync.Mutex\r\n}\r\n\r\nfunc hashString(name string) string {\r\n\ts := sha256.New()\r\n\ts.Write([]byte(name))\r\n\treturn strings.ToUpper(hex.EncodeToString(s.Sum(nil)))\r\n}\r\n\r\nfunc (c *cacher) Available() uint64 {\r\n\treturn directory.Concat(\"c\").Free()\r\n}\r\n\r\nfunc (c *cacher) serveContent(rw http.ResponseWriter, r *http.Request, path string) {\r\n\tif strings.Contains(r.Header.Get(\"Accept-Ranges\"), \"-\") {\r\n\t\t\/\/ Cannot serve compressed in this fashion\r\n\t\thttp.ServeFile(rw, r, path)\r\n\t\treturn\r\n\t}\r\n\r\n\tif strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\r\n\r\n\t\tfile, err := etc.FileController(path, true)\r\n\t\tif err != nil {\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\ttp := http.DetectContentType(file.ReadBytes(512))\r\n\r\n\t\tif strings.HasPrefix(tp, \"text\/\") {\r\n\t\t\thttp.ServeFile(rw, r, path)\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\trw.Header().Set(\"Content-Encoding\", \"gzip\")\r\n\t\trw.Header().Set(\"Content-Type\", tp)\r\n\r\n\t\tfile.SeekR(0)\r\n\r\n\t\tgz := gzip.NewWriter(rw)\r\n\t\tio.Copy(gz, file)\r\n\t\tgz.Close()\r\n\t\tfile.Close()\r\n\t\treturn\r\n\t}\r\n\r\n\thttp.ServeFile(rw, r, path)\r\n}\r\n\r\nfunc (c *cacher) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\r\n\tpth := r.URL.Path[1:]\r\n\thash := hashString(pth)\r\n\tpCachePath := directory.Concat(\"c\").Concat(hash)\r\n\tpSrcPath := directory.Concat(\"i\").GetSub(etc.ParseUnixPath(pth))\r\n\r\n\tif pCachePath.IsExtant() && time.Since(pCachePath.Time()) < Config.CacheDuration.Duration {\r\n\t\t\/\/ cached file exists.\r\n\t\tc.serveContent(rw, r, pCachePath.Render())\r\n\t\treturn\r\n\t}\r\n\r\n\t\/\/ Backend may be down. serve cached file in its place.\r\n\tif !pSrcPath.IsExtant() && pCachePath.IsExtant() {\r\n\t\tc.serveContent(rw, r, pCachePath.Render())\r\n\t\treturn\r\n\t}\r\n\r\n\tif pSrcPath.IsExtant() == false {\r\n\t\thttp.Error(rw, \"file not found\", 404)\r\n\t\treturn\r\n\t}\r\n\r\n\tcacheDir := directory.Concat(\"c\")\r\n\r\n\t\/\/ delete oldest item in cache if we have not enough space.\r\n\tfor cacheDir.Free() < pSrcPath.Size() || cacheDir.Size() > Config.MaxCacheBytes {\r\n\t\tyo.Ok(\"erasing until bytes free are more than\", cacheDir.Free())\r\n\r\n\t\tlru, err := cacheDir.LRU()\r\n\t\tif err != nil {\r\n\t\t\tyo.Warn(err)\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tcacheDir.Concat(lru).Remove()\r\n\t}\r\n\r\n\tpCachePath.Remove()\r\n\r\n\tf, err := etc.FileController(pCachePath.Render())\r\n\tif err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tif err = f.Flush(); err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\ts, err := etc.FileController(pSrcPath.Render(), true)\r\n\tif err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tif _, err = io.Copy(f, s); err != nil {\r\n\t\tyo.Fatal(err)\r\n\t}\r\n\r\n\tf.Close()\r\n\ts.Close()\r\n\r\n\tc.serveContent(rw, r, pCachePath.Render())\r\n}\r\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\/net\"\n\n\tcmds \"github.com\/jbenet\/go-ipfs\/commands\"\n\tcmdsHttp \"github.com\/jbenet\/go-ipfs\/commands\/http\"\n\t\"github.com\/jbenet\/go-ipfs\/daemon\"\n)\n\nvar Daemon = &cmds.Command{\n\tOptions: []cmds.Option{},\n\tHelp: \"TODO\",\n\tSubcommands: map[string]*cmds.Command{},\n\tRun: daemonFunc,\n}\n\nfunc daemonFunc(req cmds.Request, res cmds.Response) {\n\t\/\/ TODO: spin up a core.IpfsNode\n\n\tctx := req.Context()\n\n\tlk, err := daemon.Lock(ctx.ConfigRoot)\n\tif err != nil {\n\t\tres.SetError(fmt.Errorf(\"Couldn't obtain lock. Is another daemon already running?\"), cmds.ErrNormal)\n\t\treturn\n\t}\n\tdefer lk.Close()\n\n\taddr, err := ma.NewMultiaddr(ctx.Config.Addresses.API)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n\n\t_, host, err := manet.DialArgs(addr)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n\n\thandler := cmdsHttp.Handler{*ctx}\n\thttp.Handle(cmdsHttp.ApiPath+\"\/\", handler)\n\terr = http.ListenAndServe(host, nil)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n\t\/\/ TODO: log to indicate that we are now listening\n\n}\ncmd\/ipfs: Log to show API server is listeningpackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\/net\"\n\n\tcmds \"github.com\/jbenet\/go-ipfs\/commands\"\n\tcmdsHttp \"github.com\/jbenet\/go-ipfs\/commands\/http\"\n\t\"github.com\/jbenet\/go-ipfs\/daemon\"\n)\n\nvar Daemon = &cmds.Command{\n\tOptions: []cmds.Option{},\n\tHelp: \"TODO\",\n\tSubcommands: map[string]*cmds.Command{},\n\tRun: daemonFunc,\n}\n\nfunc daemonFunc(req cmds.Request, res cmds.Response) {\n\t\/\/ TODO: spin up a core.IpfsNode\n\n\tctx := req.Context()\n\n\tlk, err := daemon.Lock(ctx.ConfigRoot)\n\tif err != nil {\n\t\tres.SetError(fmt.Errorf(\"Couldn't obtain lock. Is another daemon already running?\"), cmds.ErrNormal)\n\t\treturn\n\t}\n\tdefer lk.Close()\n\n\taddr, err := ma.NewMultiaddr(ctx.Config.Addresses.API)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n\n\t_, host, err := manet.DialArgs(addr)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n\n\thandler := cmdsHttp.Handler{*ctx}\n\thttp.Handle(cmdsHttp.ApiPath+\"\/\", handler)\n\n\tfmt.Printf(\"API server listening on '%s'\\n\", host)\n\n\terr = http.ListenAndServe(host, nil)\n\tif err != nil {\n\t\tres.SetError(err, cmds.ErrNormal)\n\t\treturn\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/umbel\/pilosa\"\n)\n\n\/\/ Build holds the build information passed in at compile time.\nvar Build string\n\nfunc init() {\n\tif Build == \"\" {\n\t\tBuild = \"v0.0.0\"\n\t}\n\n\trand.Seed(time.Now().UTC().UnixNano())\n}\n\nconst (\n\t\/\/ DefaultDataDir is the default data directory.\n\tDefaultDataDir = \"~\/.pilosa\"\n\n\t\/\/ DefaultHost is the default hostname and port to use.\n\tDefaultHost = \"localhost:15000\"\n)\n\nfunc main() {\n\tm := NewMain()\n\tfmt.Fprintf(m.Stderr, \"Pilosa %s\\n\", Build)\n\n\t\/\/ Parse command line arguments.\n\tif err := m.ParseFlags(os.Args[1:]); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\t\/\/ Execute the program.\n\tif err := m.Run(); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ First SIGKILL causes server to shut down gracefully.\n\t\/\/ Second signal causes a hard shutdown.\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, os.Interrupt)\n\tsig := <-c\n\tfmt.Fprintf(m.Stderr, \"Received %s; gracefully shutting down...\\n\", sig.String())\n\tgo func() { <-c; os.Exit(1) }()\n\n\tif err := m.Close(); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ Main represents the main program execution.\ntype Main struct {\n\tServer *pilosa.Server\n\n\t\/\/ Configuration options.\n\tConfigPath string\n\tConfig *Config\n\n\t\/\/ Standard input\/output\n\tStdin io.Reader\n\tStdout io.Writer\n\tStderr io.Writer\n}\n\n\/\/ NewMain returns a new instance of Main.\nfunc NewMain() *Main {\n\treturn &Main{\n\t\tServer: pilosa.NewServer(),\n\t\tConfig: NewConfig(),\n\n\t\tStdin: os.Stdin,\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t}\n}\n\n\/\/ Run executes the main program execution.\nfunc (m *Main) Run(args ...string) error {\n\t\/\/ Notify user of config file.\n\tif m.ConfigPath != \"\" {\n\t\tfmt.Fprintf(m.Stdout, \"Using config: %s\\n\", m.ConfigPath)\n\t}\n\n\t\/\/ Setup logging output.\n\tm.Server.LogOutput = m.Stderr\n\n\t\/\/ Configure index.\n\tfmt.Fprintf(m.Stderr, \"Using data from: %s\\n\", m.Config.DataDir)\n\tm.Server.Index.Path = m.Config.DataDir\n\n\t\/\/ Build cluster from config file.\n\tm.Server.Host = m.Config.Host\n\tm.Server.Cluster = m.Config.PilosaCluster()\n\n\t\/\/ Initialize server.\n\tif err := m.Server.Open(); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(m.Stderr, \"Listening as http:\/\/%s\\n\", m.Server.Host)\n\n\treturn nil\n}\n\n\/\/ Close shuts down the server.\nfunc (m *Main) Close() error {\n\treturn m.Server.Close()\n}\n\n\/\/ ParseFlags parses command line flags from args.\nfunc (m *Main) ParseFlags(args []string) error {\n\tfs := flag.NewFlagSet(\"pilosa\", flag.ContinueOnError)\n\tfs.SetOutput(m.Stderr)\n\tfs.StringVar(&m.ConfigPath, \"config\", \"\", \"config path\")\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Load config, if specified.\n\tif m.ConfigPath != \"\" {\n\t\tif _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Use default data directory if one is not specified.\n\tif m.Config.DataDir == \"\" {\n\t\tm.Config.DataDir = DefaultDataDir\n\t}\n\n\t\/\/ Expand home directory.\n\tprefix := \"~\" + string(filepath.Separator)\n\tif strings.HasPrefix(m.Config.DataDir, prefix) {\n\t\t\/\/\tu, err := user.Current()\n\t\tHomeDir := os.Getenv(\"HOME\")\n\t\t\/*if err != nil {\n\t\t\treturn err\n\t\t} else*\/if HomeDir == \"\" {\n\t\t\treturn errors.New(\"data directory not specified and no home dir available\")\n\t\t}\n\t\tm.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix))\n\t}\n\n\treturn nil\n}\n\n\/\/ Config represents the configuration for the command.\ntype Config struct {\n\tDataDir string `toml:\"data-dir\"`\n\tHost string `toml:\"host\"`\n\n\tCluster struct {\n\t\tReplicaN int `toml:\"replicas\"`\n\t\tNodes []*ConfigNode `toml:\"node\"`\n\t\tPollingInterval Duration `toml:\"polling-interval\"`\n\t} `toml:\"cluster\"`\n\n\tPlugins struct {\n\t\tPath string `toml:\"path\"`\n\t} `toml:\"plugins\"`\n\n\tAntiEntropy struct {\n\t\tInterval Duration `toml:\"interval\"`\n\t} `toml:\"anti-entropy\"`\n}\n\ntype ConfigNode struct {\n\tHost string `toml:\"host\"`\n}\n\n\/\/ NewConfig returns an instance of Config with default options.\nfunc NewConfig() *Config {\n\tc := &Config{\n\t\tHost: DefaultHost,\n\t}\n\tc.Cluster.ReplicaN = pilosa.DefaultReplicaN\n\tc.Cluster.PollingInterval = Duration(pilosa.DefaultPollingInterval)\n\tc.AntiEntropy.Interval = Duration(pilosa.DefaultAntiEntropyInterval)\n\treturn c\n}\n\n\/\/ PilosaCluster returns a new instance of pilosa.Cluster based on the config.\nfunc (c *Config) PilosaCluster() *pilosa.Cluster {\n\tcluster := pilosa.NewCluster()\n\tcluster.ReplicaN = c.Cluster.ReplicaN\n\n\tfor _, n := range c.Cluster.Nodes {\n\t\tcluster.Nodes = append(cluster.Nodes, &pilosa.Node{Host: n.Host})\n\t}\n\n\treturn cluster\n}\n\n\/\/ Duration is a TOML wrapper type for time.Duration.\ntype Duration time.Duration\n\n\/\/ String returns the string representation of the duration.\nfunc (d Duration) String() string { return time.Duration(d).String() }\n\n\/\/ UnmarshalText parses a TOML value into a duration value.\nfunc (d *Duration) UnmarshalText(text []byte) error {\n\tv, err := time.ParseDuration(string(text))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*d = Duration(v)\n\treturn nil\n}\nadd CLI profilingpackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/umbel\/pilosa\"\n)\n\n\/\/ Build holds the build information passed in at compile time.\nvar Build string\n\nfunc init() {\n\tif Build == \"\" {\n\t\tBuild = \"v0.0.0\"\n\t}\n\n\trand.Seed(time.Now().UTC().UnixNano())\n}\n\nconst (\n\t\/\/ DefaultDataDir is the default data directory.\n\tDefaultDataDir = \"~\/.pilosa\"\n\n\t\/\/ DefaultHost is the default hostname and port to use.\n\tDefaultHost = \"localhost:15000\"\n)\n\nfunc main() {\n\tm := NewMain()\n\tfmt.Fprintf(m.Stderr, \"Pilosa %s\\n\", Build)\n\n\t\/\/ Parse command line arguments.\n\tif err := m.ParseFlags(os.Args[1:]); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tos.Exit(2)\n\t}\n\n\t\/\/ Start CPU profiling.\n\tif m.CPUProfile != \"\" {\n\t\tf, err := os.Create(m.CPUProfile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(m.Stderr, \"create cpu profile: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tfmt.Fprintln(m.Stderr, \"Starting cpu profile\")\n\t\tpprof.StartCPUProfile(f)\n\t\ttime.AfterFunc(m.CPUTime, func() {\n\t\t\tfmt.Fprintln(m.Stderr, \"Stopping cpu profile\")\n\t\t\tpprof.StopCPUProfile()\n\t\t\tf.Close()\n\t\t})\n\t}\n\n\t\/\/ Execute the program.\n\tif err := m.Run(); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tfmt.Fprintln(m.Stderr, \"stopping profile\")\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ First SIGKILL causes server to shut down gracefully.\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, os.Interrupt)\n\tsig := <-c\n\tfmt.Fprintf(m.Stderr, \"Received %s; gracefully shutting down...\\n\", sig.String())\n\n\t\/\/ Second signal causes a hard shutdown.\n\tgo func() { <-c; os.Exit(1) }()\n\n\tif err := m.Close(); err != nil {\n\t\tfmt.Fprintln(m.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ Main represents the main program execution.\ntype Main struct {\n\tServer *pilosa.Server\n\n\t\/\/ Configuration options.\n\tConfigPath string\n\tConfig *Config\n\n\t\/\/ Profiling options.\n\tCPUProfile string\n\tCPUTime time.Duration\n\n\t\/\/ Standard input\/output\n\tStdin io.Reader\n\tStdout io.Writer\n\tStderr io.Writer\n}\n\n\/\/ NewMain returns a new instance of Main.\nfunc NewMain() *Main {\n\treturn &Main{\n\t\tServer: pilosa.NewServer(),\n\t\tConfig: NewConfig(),\n\n\t\tStdin: os.Stdin,\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t}\n}\n\n\/\/ Run executes the main program execution.\nfunc (m *Main) Run(args ...string) error {\n\t\/\/ Notify user of config file.\n\tif m.ConfigPath != \"\" {\n\t\tfmt.Fprintf(m.Stdout, \"Using config: %s\\n\", m.ConfigPath)\n\t}\n\n\t\/\/ Setup logging output.\n\tm.Server.LogOutput = m.Stderr\n\n\t\/\/ Configure index.\n\tfmt.Fprintf(m.Stderr, \"Using data from: %s\\n\", m.Config.DataDir)\n\tm.Server.Index.Path = m.Config.DataDir\n\n\t\/\/ Build cluster from config file.\n\tm.Server.Host = m.Config.Host\n\tm.Server.Cluster = m.Config.PilosaCluster()\n\n\t\/\/ Initialize server.\n\tif err := m.Server.Open(); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(m.Stderr, \"Listening as http:\/\/%s\\n\", m.Server.Host)\n\n\treturn nil\n}\n\n\/\/ Close shuts down the server.\nfunc (m *Main) Close() error {\n\treturn m.Server.Close()\n}\n\n\/\/ ParseFlags parses command line flags from args.\nfunc (m *Main) ParseFlags(args []string) error {\n\tfs := flag.NewFlagSet(\"pilosa\", flag.ContinueOnError)\n\tfs.StringVar(&m.CPUProfile, \"cpuprofile\", \"\", \"cpu profile\")\n\tfs.DurationVar(&m.CPUTime, \"cputime\", 30*time.Second, \"cpu profile duration\")\n\tfs.StringVar(&m.ConfigPath, \"config\", \"\", \"config path\")\n\tfs.SetOutput(m.Stderr)\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Load config, if specified.\n\tif m.ConfigPath != \"\" {\n\t\tif _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Use default data directory if one is not specified.\n\tif m.Config.DataDir == \"\" {\n\t\tm.Config.DataDir = DefaultDataDir\n\t}\n\n\t\/\/ Expand home directory.\n\tprefix := \"~\" + string(filepath.Separator)\n\tif strings.HasPrefix(m.Config.DataDir, prefix) {\n\t\t\/\/\tu, err := user.Current()\n\t\tHomeDir := os.Getenv(\"HOME\")\n\t\t\/*if err != nil {\n\t\t\treturn err\n\t\t} else*\/if HomeDir == \"\" {\n\t\t\treturn errors.New(\"data directory not specified and no home dir available\")\n\t\t}\n\t\tm.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix))\n\t}\n\n\treturn nil\n}\n\n\/\/ Config represents the configuration for the command.\ntype Config struct {\n\tDataDir string `toml:\"data-dir\"`\n\tHost string `toml:\"host\"`\n\n\tCluster struct {\n\t\tReplicaN int `toml:\"replicas\"`\n\t\tNodes []*ConfigNode `toml:\"node\"`\n\t\tPollingInterval Duration `toml:\"polling-interval\"`\n\t} `toml:\"cluster\"`\n\n\tPlugins struct {\n\t\tPath string `toml:\"path\"`\n\t} `toml:\"plugins\"`\n\n\tAntiEntropy struct {\n\t\tInterval Duration `toml:\"interval\"`\n\t} `toml:\"anti-entropy\"`\n}\n\ntype ConfigNode struct {\n\tHost string `toml:\"host\"`\n}\n\n\/\/ NewConfig returns an instance of Config with default options.\nfunc NewConfig() *Config {\n\tc := &Config{\n\t\tHost: DefaultHost,\n\t}\n\tc.Cluster.ReplicaN = pilosa.DefaultReplicaN\n\tc.Cluster.PollingInterval = Duration(pilosa.DefaultPollingInterval)\n\tc.AntiEntropy.Interval = Duration(pilosa.DefaultAntiEntropyInterval)\n\treturn c\n}\n\n\/\/ PilosaCluster returns a new instance of pilosa.Cluster based on the config.\nfunc (c *Config) PilosaCluster() *pilosa.Cluster {\n\tcluster := pilosa.NewCluster()\n\tcluster.ReplicaN = c.Cluster.ReplicaN\n\n\tfor _, n := range c.Cluster.Nodes {\n\t\tcluster.Nodes = append(cluster.Nodes, &pilosa.Node{Host: n.Host})\n\t}\n\n\treturn cluster\n}\n\n\/\/ Duration is a TOML wrapper type for time.Duration.\ntype Duration time.Duration\n\n\/\/ String returns the string representation of the duration.\nfunc (d Duration) String() string { return time.Duration(d).String() }\n\n\/\/ UnmarshalText parses a TOML value into a duration value.\nfunc (d *Duration) UnmarshalText(text []byte) error {\n\tv, err := time.ParseDuration(string(text))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*d = Duration(v)\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/GeertJohan\/go.rice\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cswank\/quimby\"\n\t\"github.com\/cswank\/quimby\/cmd\/quimby\/handlers\"\n\t\"github.com\/cswank\/quimby\/cmd\/quimby\/utils\"\n\t\"github.com\/cswank\/rex\"\n\t\"github.com\/justinas\/alice\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst (\n\tversion = \"0.6.0\"\n)\n\nvar (\n\tusers = kingpin.Command(\"users\", \"User management\")\n\tuserAdd = users.Command(\"add\", \"Add a new user.\")\n\tuserName = users.Flag(\"username\", \"Username for a new user\").String()\n\tuserPW = users.Flag(\"password\", \"Password for a new user\").String()\n\tuserPerm = users.Flag(\"permission\", \"Permission (read, write, or admin\").String()\n\tuserList = users.Command(\"list\", \"List users.\")\n\tuserEdit = users.Command(\"edit\", \"Update a user.\")\n\tcert = kingpin.Command(\"cert\", \"Make an tls cert.\")\n\tdomain = cert.Flag(\"domain\", \"The domain for the tls cert.\").Required().Short('d').String()\n\tpth = cert.Flag(\"path\", \"The directory where the cert files will be written\").Required().Short('p').String()\n\tserve = kingpin.Command(\"serve\", \"Start the server.\")\n\tsetup = kingpin.Command(\"setup\", \"Set up the the server (keys and init scripts and what not.\")\n\tnet = setup.Flag(\"net\", \"network interface\").Short('n').Default(\"eth0\").String()\n\tsetupDomain = setup.Flag(\"domain\", \"network interface\").Required().Short('d').String()\n\tcommand = kingpin.Command(\"command\", \"Send a command.\")\n\tmethod = kingpin.Command(\"method\", \"Send a method.\")\n\tgadgets = kingpin.Command(\"gadgets\", \"Commands for managing gadgets\")\n\tgadgetAdd = gadgets.Command(\"add\", \"Add a gadget.\")\n\tgadgetName = gadgets.Flag(\"name\", \"Name of the gadget.\").String()\n\tgadgetHost = gadgets.Flag(\"host\", \"ip address of gadget (id http:\/\/:6111)\").String()\n\tgadgetList = gadgets.Command(\"list\", \"List the gadgets.\")\n\tgadgetEdit = gadgets.Command(\"edit\", \"List the gadgets.\")\n\tgadgetDelete = gadgets.Command(\"delete\", \"Delete a gadget.\")\n\ttoken = kingpin.Command(\"token\", \"Generate a jwt token\")\n\tbootstrap = kingpin.Command(\"bootstrap\", \"Set up a bunch of stuff\")\n\n\tkeyPath = os.Getenv(\"QUIMBY_TLS_KEY\")\n\tcertPath = os.Getenv(\"QUIMBY_TLS_CERT\")\n\tiface = os.Getenv(\"QUIMBY_INTERFACE\")\n)\n\nfunc main() {\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(version).Author(\"Craig Swank\")\n\tswitch kingpin.Parse() {\n\tcase \"cert\":\n\t\tutils.GenerateCert(*domain, *pth)\n\tcase \"users add\":\n\t\tdoUser(utils.AddUser)\n\tcase \"users list\":\n\t\taddDB(utils.ListUsers)\n\tcase \"users edit\":\n\t\taddDB(utils.EditUser)\n\tcase \"gadgets add\":\n\t\tdoGadget(utils.AddGadget)\n\tcase \"gadgets list\":\n\t\taddDB(utils.ListGadgets)\n\tcase \"gadgets edit\":\n\t\taddDB(utils.EditGadget)\n\tcase \"gadgets delete\":\n\t\taddDB(utils.DeleteGadget)\n\tcase \"command\":\n\t\taddDB(utils.SendCommand)\n\tcase \"token\":\n\t\tutils.GetToken()\n\tcase \"bootstrap\":\n\t\tutils.Bootstrap()\n\tcase \"serve\":\n\t\taddDB(startServer)\n\tcase \"setup\":\n\t\tutils.SetupServer(*setupDomain, *net)\n\t}\n}\n\ntype dbNeeder func(*bolt.DB)\ntype userNeeder func(*quimby.User)\ntype gadgetNeeder func(*quimby.Gadget)\n\nfunc getDB() *bolt.DB {\n\tpth := os.Getenv(\"QUIMBY_DB\")\n\tif pth == \"\" {\n\t\tlog.Fatal(\"you must specify a db location with QUIMBY_DB\")\n\t}\n\tdb, err := quimby.GetDB(pth)\n\tif err != nil {\n\t\tlog.Fatalf(\"could not open db at %s - %v\", pth, err)\n\t}\n\treturn db\n}\n\nfunc doUser(f userNeeder) {\n\tdb := getDB()\n\tu := quimby.NewUser(\n\t\t*userName,\n\t\tquimby.UserDB(db),\n\t\tquimby.UserPassword(*userPW),\n\t\tquimby.UserPermission(*userPerm),\n\t)\n\tf(u)\n\tdefer db.Close()\n}\n\nfunc doGadget(f gadgetNeeder) {\n\tdb := getDB()\n\tg := &quimby.Gadget{\n\t\tDB: db,\n\t\tName: *gadgetName,\n\t\tHost: *gadgetHost,\n\t}\n\tf(g)\n\tdb.Close()\n}\n\nfunc addDB(f dbNeeder) {\n\tdb := getDB()\n\tf(db)\n\tdefer db.Close()\n}\n\nfunc startServer(db *bolt.DB) {\n\tport := os.Getenv(\"QUIMBY_PORT\")\n\tif port == \"\" {\n\t\tlog.Fatal(\"you must specify a port with QUIMBY_PORT\")\n\t}\n\n\tdomain := os.Getenv(\"QUIMBY_DOMAIN\")\n\tif domain == \"\" {\n\t\tlog.Fatal(\"you must specify a domain with QUIMBY_DOMAIN\")\n\t}\n\n\tinternalPort := os.Getenv(\"QUIMBY_INTERNAL_PORT\")\n\tif port == \"\" {\n\t\tlog.Fatal(\"you must specify a port with QUIMBY_INTERNAL_PORT\")\n\t}\n\n\tvar lg *log.Logger\n\tif os.Getenv(\"QUIMBY_NULLLOG\") != \"\" {\n\t\tlg = log.New(ioutil.Discard, \"quimby \", log.Ltime)\n\t} else {\n\t\tlg = log.New(os.Stdout, \"quimby \", log.Ltime)\n\t}\n\tclients := quimby.NewClientHolder()\n\ttfa := quimby.NewTFA(domain)\n\tstart(db, port, internalPort, \"\/\", \"\/api\", lg, clients, tfa)\n}\n\nfunc getMiddleware(perm handlers.ACL, f http.HandlerFunc) http.Handler {\n\treturn alice.New(handlers.Perm(perm)).Then(http.HandlerFunc(f))\n}\n\nfunc start(db *bolt.DB, port, internalPort, root string, iRoot string, lg quimby.Logger, clients *quimby.ClientHolder, tfa quimby.TFAer) {\n\tquimby.Clients = clients\n\tquimby.DB = db\n\tquimby.LG = lg\n\thandlers.DB = db\n\thandlers.LG = lg\n\thandlers.TFA = tfa\n\n\tgo startInternal(iRoot, db, lg, internalPort)\n\tgo startHomeKit(db, lg)\n\n\tr := rex.New(\"main\")\n\tr.Post(\"\/api\/login\", http.HandlerFunc(handlers.Login))\n\tr.Post(\"\/api\/logout\", http.HandlerFunc(handlers.Logout))\n\tr.Get(\"\/api\/ping\", getMiddleware(handlers.Read, handlers.Ping))\n\tr.Get(\"\/api\/currentuser\", getMiddleware(handlers.Read, handlers.GetCurrentUser))\n\tr.Get(\"\/api\/users\", getMiddleware(handlers.Admin, handlers.GetUsers))\n\tr.Post(\"\/api\/users\", getMiddleware(handlers.Admin, handlers.AddUser))\n\tr.Delete(\"\/api\/users\/{username}\", getMiddleware(handlers.Admin, handlers.DeleteUser))\n\tr.Post(\"\/api\/users\/{username}\/permission\", getMiddleware(handlers.Admin, handlers.UpdateUserPermission))\n\tr.Post(\"\/api\/users\/{username}\/password\", getMiddleware(handlers.Admin, handlers.UpdateUserPassword))\n\tr.Get(\"\/api\/users\/{username}\", getMiddleware(handlers.Admin, handlers.GetUser))\n\tr.Get(\"\/api\/gadgets\", getMiddleware(handlers.Read, handlers.GetGadgets))\n\tr.Post(\"\/api\/gadgets\", getMiddleware(handlers.Read, handlers.AddGadget))\n\tr.Get(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Read, handlers.GetGadget))\n\tr.Post(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Write, handlers.UpdateGadget))\n\tr.Delete(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Write, handlers.DeleteGadget))\n\tr.Post(\"\/api\/gadgets\/{id}\/command\", getMiddleware(handlers.Write, handlers.SendCommand))\n\tr.Post(\"\/api\/gadgets\/{id}\/method\", getMiddleware(handlers.Write, handlers.SendMethod))\n\tr.Get(\"\/api\/gadgets\/{id}\/websocket\", getMiddleware(handlers.Write, handlers.Connect))\n\tr.Get(\"\/api\/gadgets\/{id}\/values\", getMiddleware(handlers.Read, handlers.GetUpdates))\n\tr.Get(\"\/api\/gadgets\/{id}\/status\", getMiddleware(handlers.Read, handlers.GetStatus))\n\tr.Post(\"\/api\/gadgets\/{id}\/notes\", getMiddleware(handlers.Write, handlers.AddNote))\n\tr.Get(\"\/api\/gadgets\/{id}\/notes\", getMiddleware(handlers.Read, handlers.GetNotes))\n\tr.Get(\"\/api\/gadgets\/{id}\/locations\/{location}\/devices\/{device}\/status\", getMiddleware(handlers.Read, handlers.GetDevice))\n\tr.Post(\"\/api\/gadgets\/{id}\/locations\/{location}\/devices\/{device}\/status\", getMiddleware(handlers.Write, handlers.UpdateDevice))\n\tr.Get(\"\/api\/gadgets\/{id}\/sources\/{name}\", getMiddleware(handlers.Read, handlers.GetDataPoints))\n\tr.Get(\"\/api\/gadgets\/{id}\/sources\/{name}\/csv\", getMiddleware(handlers.Read, handlers.GetDataPointsCSV))\n\tr.Get(\"\/api\/beer\/{name}\", getMiddleware(handlers.Read, handlers.GetRecipe))\n\tr.Get(\"\/api\/admin\/clients\", getMiddleware(handlers.Admin, handlers.GetClients))\n\n\tr.ServeFiles(http.FileServer(rice.MustFindBox(\"www\/dist\").HTTPBox()))\n\n\tchain := alice.New(handlers.Auth(db, lg, \"main\"), handlers.FetchGadget(), handlers.Error(lg)).Then(r)\n\n\thttp.Handle(root, chain)\n\n\taddr := fmt.Sprintf(\"%s:%s\", iface, port)\n\tlg.Printf(\"listening on %s\\n\", addr)\n\tif keyPath == \"\" {\n\t\tlg.Println(http.ListenAndServe(addr, chain))\n\t} else {\n\t\tlg.Println(http.ListenAndServeTLS(fmt.Sprintf(\"%s:443\", iface), certPath, keyPath, chain))\n\t}\n}\n\nfunc startHomeKit(db *bolt.DB, lg quimby.Logger) {\n\tkey := os.Getenv(\"QUIMBY_HOMEKIT\")\n\tif key == \"\" {\n\t\tlg.Println(\"QUIMBY_HOMEKIT not set, not starting homekit\")\n\t\treturn\n\t}\n\thk := quimby.NewHomeKit(key, db)\n\thk.Start()\n}\n\n\/\/This is the endpoint that the gadgets report to. It is\n\/\/served on a separate port so it doesn't have to be exposed\n\/\/publicly if the main port is exposed.\nfunc startInternal(iRoot string, db *bolt.DB, lg quimby.Logger, port string) {\n\tr := rex.New(\"internal\")\n\tr.Post(\"\/internal\/updates\", getMiddleware(handlers.Write, handlers.RelayMessage))\n\tr.Post(\"\/internal\/gadgets\/{id}\/sources\/{name}\", getMiddleware(handlers.Write, handlers.AddDataPoint))\n\n\tchain := alice.New(handlers.Auth(db, lg, \"internal\"), handlers.FetchGadget()).Then(r)\n\n\thttp.Handle(iRoot, chain)\n\ta := fmt.Sprintf(\":%s\", port)\n\tlg.Printf(\"listening on %s\", a)\n\terr := http.ListenAndServe(a, chain)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\nBump version to 0.7.0package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/GeertJohan\/go.rice\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cswank\/quimby\"\n\t\"github.com\/cswank\/quimby\/cmd\/quimby\/handlers\"\n\t\"github.com\/cswank\/quimby\/cmd\/quimby\/utils\"\n\t\"github.com\/cswank\/rex\"\n\t\"github.com\/justinas\/alice\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst (\n\tversion = \"0.7.0\"\n)\n\nvar (\n\tusers = kingpin.Command(\"users\", \"User management\")\n\tuserAdd = users.Command(\"add\", \"Add a new user.\")\n\tuserName = users.Flag(\"username\", \"Username for a new user\").String()\n\tuserPW = users.Flag(\"password\", \"Password for a new user\").String()\n\tuserPerm = users.Flag(\"permission\", \"Permission (read, write, or admin\").String()\n\tuserList = users.Command(\"list\", \"List users.\")\n\tuserEdit = users.Command(\"edit\", \"Update a user.\")\n\tcert = kingpin.Command(\"cert\", \"Make an tls cert.\")\n\tdomain = cert.Flag(\"domain\", \"The domain for the tls cert.\").Required().Short('d').String()\n\tpth = cert.Flag(\"path\", \"The directory where the cert files will be written\").Required().Short('p').String()\n\tserve = kingpin.Command(\"serve\", \"Start the server.\")\n\tsetup = kingpin.Command(\"setup\", \"Set up the the server (keys and init scripts and what not.\")\n\tnet = setup.Flag(\"net\", \"network interface\").Short('n').Default(\"eth0\").String()\n\tsetupDomain = setup.Flag(\"domain\", \"network interface\").Required().Short('d').String()\n\tcommand = kingpin.Command(\"command\", \"Send a command.\")\n\tmethod = kingpin.Command(\"method\", \"Send a method.\")\n\tgadgets = kingpin.Command(\"gadgets\", \"Commands for managing gadgets\")\n\tgadgetAdd = gadgets.Command(\"add\", \"Add a gadget.\")\n\tgadgetName = gadgets.Flag(\"name\", \"Name of the gadget.\").String()\n\tgadgetHost = gadgets.Flag(\"host\", \"ip address of gadget (id http:\/\/:6111)\").String()\n\tgadgetList = gadgets.Command(\"list\", \"List the gadgets.\")\n\tgadgetEdit = gadgets.Command(\"edit\", \"List the gadgets.\")\n\tgadgetDelete = gadgets.Command(\"delete\", \"Delete a gadget.\")\n\ttoken = kingpin.Command(\"token\", \"Generate a jwt token\")\n\tbootstrap = kingpin.Command(\"bootstrap\", \"Set up a bunch of stuff\")\n\n\tkeyPath = os.Getenv(\"QUIMBY_TLS_KEY\")\n\tcertPath = os.Getenv(\"QUIMBY_TLS_CERT\")\n\tiface = os.Getenv(\"QUIMBY_INTERFACE\")\n)\n\nfunc main() {\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(version).Author(\"Craig Swank\")\n\tswitch kingpin.Parse() {\n\tcase \"cert\":\n\t\tutils.GenerateCert(*domain, *pth)\n\tcase \"users add\":\n\t\tdoUser(utils.AddUser)\n\tcase \"users list\":\n\t\taddDB(utils.ListUsers)\n\tcase \"users edit\":\n\t\taddDB(utils.EditUser)\n\tcase \"gadgets add\":\n\t\tdoGadget(utils.AddGadget)\n\tcase \"gadgets list\":\n\t\taddDB(utils.ListGadgets)\n\tcase \"gadgets edit\":\n\t\taddDB(utils.EditGadget)\n\tcase \"gadgets delete\":\n\t\taddDB(utils.DeleteGadget)\n\tcase \"command\":\n\t\taddDB(utils.SendCommand)\n\tcase \"token\":\n\t\tutils.GetToken()\n\tcase \"bootstrap\":\n\t\tutils.Bootstrap()\n\tcase \"serve\":\n\t\taddDB(startServer)\n\tcase \"setup\":\n\t\tutils.SetupServer(*setupDomain, *net)\n\t}\n}\n\ntype dbNeeder func(*bolt.DB)\ntype userNeeder func(*quimby.User)\ntype gadgetNeeder func(*quimby.Gadget)\n\nfunc getDB() *bolt.DB {\n\tpth := os.Getenv(\"QUIMBY_DB\")\n\tif pth == \"\" {\n\t\tlog.Fatal(\"you must specify a db location with QUIMBY_DB\")\n\t}\n\tdb, err := quimby.GetDB(pth)\n\tif err != nil {\n\t\tlog.Fatalf(\"could not open db at %s - %v\", pth, err)\n\t}\n\treturn db\n}\n\nfunc doUser(f userNeeder) {\n\tdb := getDB()\n\tu := quimby.NewUser(\n\t\t*userName,\n\t\tquimby.UserDB(db),\n\t\tquimby.UserPassword(*userPW),\n\t\tquimby.UserPermission(*userPerm),\n\t)\n\tf(u)\n\tdefer db.Close()\n}\n\nfunc doGadget(f gadgetNeeder) {\n\tdb := getDB()\n\tg := &quimby.Gadget{\n\t\tDB: db,\n\t\tName: *gadgetName,\n\t\tHost: *gadgetHost,\n\t}\n\tf(g)\n\tdb.Close()\n}\n\nfunc addDB(f dbNeeder) {\n\tdb := getDB()\n\tf(db)\n\tdefer db.Close()\n}\n\nfunc startServer(db *bolt.DB) {\n\tport := os.Getenv(\"QUIMBY_PORT\")\n\tif port == \"\" {\n\t\tlog.Fatal(\"you must specify a port with QUIMBY_PORT\")\n\t}\n\n\tdomain := os.Getenv(\"QUIMBY_DOMAIN\")\n\tif domain == \"\" {\n\t\tlog.Fatal(\"you must specify a domain with QUIMBY_DOMAIN\")\n\t}\n\n\tinternalPort := os.Getenv(\"QUIMBY_INTERNAL_PORT\")\n\tif port == \"\" {\n\t\tlog.Fatal(\"you must specify a port with QUIMBY_INTERNAL_PORT\")\n\t}\n\n\tvar lg *log.Logger\n\tif os.Getenv(\"QUIMBY_NULLLOG\") != \"\" {\n\t\tlg = log.New(ioutil.Discard, \"quimby \", log.Ltime)\n\t} else {\n\t\tlg = log.New(os.Stdout, \"quimby \", log.Ltime)\n\t}\n\tclients := quimby.NewClientHolder()\n\ttfa := quimby.NewTFA(domain)\n\tstart(db, port, internalPort, \"\/\", \"\/api\", lg, clients, tfa)\n}\n\nfunc getMiddleware(perm handlers.ACL, f http.HandlerFunc) http.Handler {\n\treturn alice.New(handlers.Perm(perm)).Then(http.HandlerFunc(f))\n}\n\nfunc start(db *bolt.DB, port, internalPort, root string, iRoot string, lg quimby.Logger, clients *quimby.ClientHolder, tfa quimby.TFAer) {\n\tquimby.Clients = clients\n\tquimby.DB = db\n\tquimby.LG = lg\n\thandlers.DB = db\n\thandlers.LG = lg\n\thandlers.TFA = tfa\n\n\tgo startInternal(iRoot, db, lg, internalPort)\n\tgo startHomeKit(db, lg)\n\n\tr := rex.New(\"main\")\n\tr.Post(\"\/api\/login\", http.HandlerFunc(handlers.Login))\n\tr.Post(\"\/api\/logout\", http.HandlerFunc(handlers.Logout))\n\tr.Get(\"\/api\/ping\", getMiddleware(handlers.Read, handlers.Ping))\n\tr.Get(\"\/api\/currentuser\", getMiddleware(handlers.Read, handlers.GetCurrentUser))\n\tr.Get(\"\/api\/users\", getMiddleware(handlers.Admin, handlers.GetUsers))\n\tr.Post(\"\/api\/users\", getMiddleware(handlers.Admin, handlers.AddUser))\n\tr.Delete(\"\/api\/users\/{username}\", getMiddleware(handlers.Admin, handlers.DeleteUser))\n\tr.Post(\"\/api\/users\/{username}\/permission\", getMiddleware(handlers.Admin, handlers.UpdateUserPermission))\n\tr.Post(\"\/api\/users\/{username}\/password\", getMiddleware(handlers.Admin, handlers.UpdateUserPassword))\n\tr.Get(\"\/api\/users\/{username}\", getMiddleware(handlers.Admin, handlers.GetUser))\n\tr.Get(\"\/api\/gadgets\", getMiddleware(handlers.Read, handlers.GetGadgets))\n\tr.Post(\"\/api\/gadgets\", getMiddleware(handlers.Read, handlers.AddGadget))\n\tr.Get(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Read, handlers.GetGadget))\n\tr.Post(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Write, handlers.UpdateGadget))\n\tr.Delete(\"\/api\/gadgets\/{id}\", getMiddleware(handlers.Write, handlers.DeleteGadget))\n\tr.Post(\"\/api\/gadgets\/{id}\/command\", getMiddleware(handlers.Write, handlers.SendCommand))\n\tr.Post(\"\/api\/gadgets\/{id}\/method\", getMiddleware(handlers.Write, handlers.SendMethod))\n\tr.Get(\"\/api\/gadgets\/{id}\/websocket\", getMiddleware(handlers.Write, handlers.Connect))\n\tr.Get(\"\/api\/gadgets\/{id}\/values\", getMiddleware(handlers.Read, handlers.GetUpdates))\n\tr.Get(\"\/api\/gadgets\/{id}\/status\", getMiddleware(handlers.Read, handlers.GetStatus))\n\tr.Post(\"\/api\/gadgets\/{id}\/notes\", getMiddleware(handlers.Write, handlers.AddNote))\n\tr.Get(\"\/api\/gadgets\/{id}\/notes\", getMiddleware(handlers.Read, handlers.GetNotes))\n\tr.Get(\"\/api\/gadgets\/{id}\/locations\/{location}\/devices\/{device}\/status\", getMiddleware(handlers.Read, handlers.GetDevice))\n\tr.Post(\"\/api\/gadgets\/{id}\/locations\/{location}\/devices\/{device}\/status\", getMiddleware(handlers.Write, handlers.UpdateDevice))\n\tr.Get(\"\/api\/gadgets\/{id}\/sources\/{name}\", getMiddleware(handlers.Read, handlers.GetDataPoints))\n\tr.Get(\"\/api\/gadgets\/{id}\/sources\/{name}\/csv\", getMiddleware(handlers.Read, handlers.GetDataPointsCSV))\n\tr.Get(\"\/api\/beer\/{name}\", getMiddleware(handlers.Read, handlers.GetRecipe))\n\tr.Get(\"\/api\/admin\/clients\", getMiddleware(handlers.Admin, handlers.GetClients))\n\n\tr.ServeFiles(http.FileServer(rice.MustFindBox(\"www\/dist\").HTTPBox()))\n\n\tchain := alice.New(handlers.Auth(db, lg, \"main\"), handlers.FetchGadget(), handlers.Error(lg)).Then(r)\n\n\thttp.Handle(root, chain)\n\n\taddr := fmt.Sprintf(\"%s:%s\", iface, port)\n\tlg.Printf(\"listening on %s\\n\", addr)\n\tif keyPath == \"\" {\n\t\tlg.Println(http.ListenAndServe(addr, chain))\n\t} else {\n\t\tlg.Println(http.ListenAndServeTLS(fmt.Sprintf(\"%s:443\", iface), certPath, keyPath, chain))\n\t}\n}\n\nfunc startHomeKit(db *bolt.DB, lg quimby.Logger) {\n\tkey := os.Getenv(\"QUIMBY_HOMEKIT\")\n\tif key == \"\" {\n\t\tlg.Println(\"QUIMBY_HOMEKIT not set, not starting homekit\")\n\t\treturn\n\t}\n\thk := quimby.NewHomeKit(key, db)\n\thk.Start()\n}\n\n\/\/This is the endpoint that the gadgets report to. It is\n\/\/served on a separate port so it doesn't have to be exposed\n\/\/publicly if the main port is exposed.\nfunc startInternal(iRoot string, db *bolt.DB, lg quimby.Logger, port string) {\n\tr := rex.New(\"internal\")\n\tr.Post(\"\/internal\/updates\", getMiddleware(handlers.Write, handlers.RelayMessage))\n\tr.Post(\"\/internal\/gadgets\/{id}\/sources\/{name}\", getMiddleware(handlers.Write, handlers.AddDataPoint))\n\n\tchain := alice.New(handlers.Auth(db, lg, \"internal\"), handlers.FetchGadget()).Then(r)\n\n\thttp.Handle(iRoot, chain)\n\ta := fmt.Sprintf(\":%s\", port)\n\tlg.Printf(\"listening on %s\", a)\n\terr := http.ListenAndServe(a, chain)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\tgorums \"github.com\/relab\/raft\/raftgorums\/gorumspb\"\n\tpb \"github.com\/relab\/raft\/raftgorums\/raftpb\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n)\n\nvar client gorums.RaftClient\n\nvar counter chan interface{}\nvar seq chan uint64\n\nvar leader = flag.String(\"leader\", \"\", \"Leader server address\")\nvar clients = flag.Int(\"clients\", 1, \"Number of clients\")\nvar rate = flag.Int(\"rate\", 40, \"How often each client sends a request in microseconds\")\nvar timeout = flag.Duration(\"time\", time.Second*30, \"How long to measure in `seconds`\\n\\ttime\/2 seconds will be spent to saturate the cluster\")\n\nfunc main() {\n\tflag.Parse()\n\n\tif *leader == \"\" {\n\t\tfmt.Print(\"-leader argument is required\\n\\n\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tt := *timeout\n\n\tcounter = make(chan interface{})\n\tseq = make(chan uint64)\n\tstop := make(chan interface{})\n\treset := make(chan interface{})\n\n\tgo func() {\n\t\ti := uint64(1)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase seq <- i:\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ti++\n\t\t}\n\t}()\n\n\tmgr, err := gorums.NewManager([]string{*leader},\n\t\tgorums.WithGrpcDialOptions(\n\t\t\tgrpc.WithInsecure(),\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpc.WithTimeout(time.Second),\n\t\t))\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient = mgr.Nodes()[0].RaftClient\n\n\tcount := 0\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-reset:\n\t\t\t\tlog.Println(\"Beginning count after:\", t\/2)\n\t\t\t\tcount = 0\n\t\t\tcase <-counter:\n\t\t\t\tcount++\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tn := *clients\n\twait := time.Duration(*rate) * time.Microsecond\n\n\tvar wg sync.WaitGroup\n\twg.Add(n)\n\n\tgo func() {\n\t\twg.Wait()\n\n\t\tlog.Println(\"Waiting:\", t\/2)\n\t\t<-time.After(t \/ 2)\n\n\t\treset <- struct{}{}\n\t\treset <- struct{}{}\n\t}()\n\n\tfor i := 0; i < n; i++ {\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\n\t\treply, err := client.ClientCommand(ctx, &pb.ClientCommandRequest{Command: \"REGISTER\", SequenceNumber: 0})\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif reply.Status != pb.OK {\n\t\t\tlog.Fatal(\"Not leader!\")\n\t\t}\n\n\t\tgo func(clientID uint32) {\n\t\t\twg.Done()\n\t\t\twg.Wait()\n\n\t\t\tfor {\n\t\t\t\tgo sendCommand(clientID)\n\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(wait):\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}(reply.ClientID)\n\t}\n\n\twg.Wait()\n\n\t<-reset\n\n\ttime.AfterFunc(t, func() {\n\t\tlog.Println(\"Throughput over:\", t)\n\t\tlog.Println(count, float64(count)\/(t.Seconds()))\n\n\t\tclose(stop)\n\t})\n\n\t<-stop\n\tlog.Println(\"Waiting:\", t\/2)\n\t<-time.After(t \/ 2)\n}\n\nfunc sendCommand(clientID uint32) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\treply, err := client.ClientCommand(ctx, &pb.ClientCommandRequest{Command: \"xxxxxxxxxxxxxxxx\", SequenceNumber: <-seq, ClientID: clientID})\n\n\tif err == nil && reply.Status == pb.OK {\n\t\tcounter <- struct{}{}\n\t}\n}\ncmd\/rkvctl: Delete deprecated client<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/Microsoft\/go-winio\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/regstate\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/runhcs\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ Add a manifest to get proper Windows version detection.\n\/\/\n\/\/ goversioninfo can be installed with \"go get github.com\/josephspurrier\/goversioninfo\/cmd\/goversioninfo\"\n\n\/\/go:generate goversioninfo -platform-specific\n\n\/\/ version will be populated by the Makefile, read from\n\/\/ VERSION file of the source code.\nvar version = \"\"\n\n\/\/ gitCommit will be the hash that the binary was built from\n\/\/ and will be populated by the Makefile\nvar gitCommit = \"\"\n\nvar stateKey *regstate.Key\n\nvar logFormat string\n\nconst (\n\tspecConfig = \"config.json\"\n\tusage = `Open Container Initiative runtime for Windows\n\nrunhcs is a fork of runc, modified to run containers on Windows with or without Hyper-V isolation. Like runc, it is a command line client for running applications packaged according to the Open Container Initiative (OCI) format.\n\nrunhcs integrates with existing process supervisors to provide a production container runtime environment for applications. It can be used with your existing process monitoring tools and the container will be spawned as a direct child of the process supervisor.\n\nContainers are configured using bundles. A bundle for a container is a directory that includes a specification file named \"` + specConfig + `\". Bundle contents will depend on the container type.\n\nTo start a new instance of a container:\n\n # runhcs run [ -b bundle ] \n\nWhere \"\" is your name for the instance of the container that you are starting. The name you provide for the container instance must be unique on your host. Providing the bundle directory using \"-b\" is optional. The default value for \"bundle\" is the current directory.`\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"runhcs\"\n\tapp.Usage = usage\n\n\tvar v []string\n\tif version != \"\" {\n\t\tv = append(v, version)\n\t}\n\tif gitCommit != \"\" {\n\t\tv = append(v, fmt.Sprintf(\"commit: %s\", gitCommit))\n\t}\n\tv = append(v, fmt.Sprintf(\"spec: %s\", specs.Version))\n\tapp.Version = strings.Join(v, \"\\n\")\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"debug\",\n\t\t\tUsage: \"enable debug output for logging\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"log\",\n\t\t\tValue: \"nul\",\n\t\t\tUsage: `set the log file path or named pipe (e.g. \\\\.\\pipe\\ProtectedPrefix\\Administrators\\runhcs-log) where internal debug information is written`,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"log-format\",\n\t\t\tValue: \"text\",\n\t\t\tUsage: \"set the format used by logs ('text' (default), or 'json')\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"owner\",\n\t\t\tValue: \"runhcs\",\n\t\t\tUsage: \"compute system owner\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"root\",\n\t\t\tValue: \"default\",\n\t\t\tUsage: \"registry key for storage of container state\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\tcreateCommand,\n\t\tcreateScratchCommand,\n\t\tdeleteCommand,\n\t\t\/\/ eventsCommand,\n\t\texecCommand,\n\t\tkillCommand,\n\t\tlistCommand,\n\t\tpauseCommand,\n\t\tpsCommand,\n\t\tresizeTtyCommand,\n\t\tresumeCommand,\n\t\trunCommand,\n\t\tshimCommand,\n\t\tstartCommand,\n\t\tstateCommand,\n\t\t\/\/ updateCommand,\n\t\tvmshimCommand,\n\t}\n\tapp.Before = func(context *cli.Context) error {\n\t\tif context.GlobalBool(\"debug\") {\n\t\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t\t}\n\t\tif path := context.GlobalString(\"log\"); path != \"\" {\n\t\t\tvar f io.Writer\n\t\t\tvar err error\n\t\t\tif strings.HasPrefix(path, runhcs.SafePipePrefix) {\n\t\t\t\tf, err = winio.DialPipe(path, nil)\n\t\t\t} else {\n\t\t\t\tf, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0666)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlogrus.SetOutput(f)\n\t\t}\n\t\tswitch logFormat = context.GlobalString(\"log-format\"); logFormat {\n\t\tcase \"text\":\n\t\t\t\/\/ retain logrus's default.\n\t\tcase \"json\":\n\t\t\tlogrus.SetFormatter(new(logrus.JSONFormatter))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown log-format %q\", logFormat)\n\t\t}\n\n\t\tvar err error\n\t\tstateKey, err = regstate.Open(context.GlobalString(\"root\"), false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\t\/\/ If the command returns an error, cli takes upon itself to print\n\t\/\/ the error on cli.ErrWriter and exit.\n\t\/\/ Use our own writer here to ensure the log gets sent to the right location.\n\tfatalWriter.Writer = cli.ErrWriter\n\tcli.ErrWriter = &fatalWriter\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Fprintln(cli.ErrWriter, err)\n\t\tos.Exit(1)\n\t}\n}\n\ntype logErrorWriter struct {\n\tWriter io.Writer\n}\n\nvar fatalWriter logErrorWriter\n\nfunc (f *logErrorWriter) Write(p []byte) (n int, err error) {\n\tlogrus.Error(string(p))\n\treturn f.Writer.Write(p)\n}\nUse ETW Logrus hook in RunHCSpackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/Microsoft\/go-winio\"\n\t\"github.com\/Microsoft\/go-winio\/pkg\/etwlogrus\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/regstate\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/runhcs\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ Add a manifest to get proper Windows version detection.\n\/\/\n\/\/ goversioninfo can be installed with \"go get github.com\/josephspurrier\/goversioninfo\/cmd\/goversioninfo\"\n\n\/\/go:generate goversioninfo -platform-specific\n\n\/\/ version will be populated by the Makefile, read from\n\/\/ VERSION file of the source code.\nvar version = \"\"\n\n\/\/ gitCommit will be the hash that the binary was built from\n\/\/ and will be populated by the Makefile\nvar gitCommit = \"\"\n\nvar stateKey *regstate.Key\n\nvar logFormat string\n\nconst (\n\tspecConfig = \"config.json\"\n\tusage = `Open Container Initiative runtime for Windows\n\nrunhcs is a fork of runc, modified to run containers on Windows with or without Hyper-V isolation. Like runc, it is a command line client for running applications packaged according to the Open Container Initiative (OCI) format.\n\nrunhcs integrates with existing process supervisors to provide a production container runtime environment for applications. It can be used with your existing process monitoring tools and the container will be spawned as a direct child of the process supervisor.\n\nContainers are configured using bundles. A bundle for a container is a directory that includes a specification file named \"` + specConfig + `\". Bundle contents will depend on the container type.\n\nTo start a new instance of a container:\n\n # runhcs run [ -b bundle ] \n\nWhere \"\" is your name for the instance of the container that you are starting. The name you provide for the container instance must be unique on your host. Providing the bundle directory using \"-b\" is optional. The default value for \"bundle\" is the current directory.`\n)\n\nfunc main() {\n\thook, err := etwlogrus.NewHook(\"Microsoft-Virtualization-RunHCS\")\n\tif err == nil {\n\t\tlogrus.AddHook(hook)\n\t} else {\n\t\tlogrus.Error(err)\n\t}\n\tdefer func() {\n\t\tif hook != nil {\n\t\t\tif err := hook.Close(); err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tapp := cli.NewApp()\n\tapp.Name = \"runhcs\"\n\tapp.Usage = usage\n\n\tvar v []string\n\tif version != \"\" {\n\t\tv = append(v, version)\n\t}\n\tif gitCommit != \"\" {\n\t\tv = append(v, fmt.Sprintf(\"commit: %s\", gitCommit))\n\t}\n\tv = append(v, fmt.Sprintf(\"spec: %s\", specs.Version))\n\tapp.Version = strings.Join(v, \"\\n\")\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"debug\",\n\t\t\tUsage: \"enable debug output for logging\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"log\",\n\t\t\tValue: \"nul\",\n\t\t\tUsage: `set the log file path or named pipe (e.g. \\\\.\\pipe\\ProtectedPrefix\\Administrators\\runhcs-log) where internal debug information is written`,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"log-format\",\n\t\t\tValue: \"text\",\n\t\t\tUsage: \"set the format used by logs ('text' (default), or 'json')\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"owner\",\n\t\t\tValue: \"runhcs\",\n\t\t\tUsage: \"compute system owner\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"root\",\n\t\t\tValue: \"default\",\n\t\t\tUsage: \"registry key for storage of container state\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\tcreateCommand,\n\t\tcreateScratchCommand,\n\t\tdeleteCommand,\n\t\t\/\/ eventsCommand,\n\t\texecCommand,\n\t\tkillCommand,\n\t\tlistCommand,\n\t\tpauseCommand,\n\t\tpsCommand,\n\t\tresizeTtyCommand,\n\t\tresumeCommand,\n\t\trunCommand,\n\t\tshimCommand,\n\t\tstartCommand,\n\t\tstateCommand,\n\t\t\/\/ updateCommand,\n\t\tvmshimCommand,\n\t}\n\tapp.Before = func(context *cli.Context) error {\n\t\tif context.GlobalBool(\"debug\") {\n\t\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t\t}\n\t\tif path := context.GlobalString(\"log\"); path != \"\" {\n\t\t\tvar f io.Writer\n\t\t\tvar err error\n\t\t\tif strings.HasPrefix(path, runhcs.SafePipePrefix) {\n\t\t\t\tf, err = winio.DialPipe(path, nil)\n\t\t\t} else {\n\t\t\t\tf, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0666)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlogrus.SetOutput(f)\n\t\t}\n\t\tswitch logFormat = context.GlobalString(\"log-format\"); logFormat {\n\t\tcase \"text\":\n\t\t\t\/\/ retain logrus's default.\n\t\tcase \"json\":\n\t\t\tlogrus.SetFormatter(new(logrus.JSONFormatter))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown log-format %q\", logFormat)\n\t\t}\n\n\t\tvar err error\n\t\tstateKey, err = regstate.Open(context.GlobalString(\"root\"), false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\t\/\/ If the command returns an error, cli takes upon itself to print\n\t\/\/ the error on cli.ErrWriter and exit.\n\t\/\/ Use our own writer here to ensure the log gets sent to the right location.\n\tfatalWriter.Writer = cli.ErrWriter\n\tcli.ErrWriter = &fatalWriter\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Fprintln(cli.ErrWriter, err)\n\t\tos.Exit(1)\n\t}\n}\n\ntype logErrorWriter struct {\n\tWriter io.Writer\n}\n\nvar fatalWriter logErrorWriter\n\nfunc (f *logErrorWriter) Write(p []byte) (n int, err error) {\n\tlogrus.Error(string(p))\n\treturn f.Writer.Write(p)\n}\n<|endoftext|>"} {"text":"package server\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ikawaha\/kagome\/v2\/tokenizer\"\n)\n\n\/\/ TokenizeDemoHandler represents the tokenizer demo server struct.\ntype TokenizeDemoHandler struct {\n\ttokenizer *tokenizer.Tokenizer\n}\n\n\/\/ ServeHTTP serves a tokenize demo server.\nfunc (h *TokenizeDemoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttype record struct {\n\t\tSurface string\n\t\tPOS string\n\t\tBaseform string\n\t\tReading string\n\t\tPronunciation string\n\t}\n\tsen := r.FormValue(\"s\")\n\tmode := r.FormValue(\"r\")\n\tlattice := r.FormValue(\"lattice\")\n\n\tif lattice == \"\" {\n\t\td := struct {\n\t\t\tSentence string\n\t\t\tRadioOpt string\n\t\t}{Sentence: sen, RadioOpt: mode}\n\t\tt := template.Must(template.New(\"top\").Parse(demoHTML))\n\t\tif err := t.Execute(w, d); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tconst (\n\t\tgraphvizCmd = \"circo\" \/\/ \"dot\"\n\t\tcmdTimeout = 25 * time.Second\n\t)\n\tvar (\n\t\trecords []record\n\t\ttokens []tokenizer.Token\n\t\tsvg string\n\t\tcmdErr string\n\t)\n\n\tm := tokenizer.Normal\n\tswitch mode {\n\tcase \"Search\", \"Extended\": \/\/ Extended uses search mode\n\t\tm = tokenizer.Search\n\t}\n\tif _, err := exec.LookPath(graphvizCmd); err != nil {\n\t\tcmdErr = \"Error: circo\/graphviz is not installed in your $PATH\"\n\t\tlog.Print(\"Error: circo\/graphviz is not installed in your $PATH\\n\")\n\t} else {\n\t\tctx, cancel := context.WithTimeout(context.Background(), cmdTimeout)\n\t\tdefer cancel()\n\t\tvar buf bytes.Buffer\n\t\tcmd := exec.CommandContext(ctx, \"dot\", \"-Tsvg\")\n\t\tr0, w0 := io.Pipe()\n\t\tcmd.Stdin = r0\n\t\tcmd.Stdout = &buf\n\t\tcmd.Stderr = ErrorWriter\n\t\tif err := cmd.Start(); err != nil {\n\t\t\tcmdErr = \"Error\"\n\t\t\tlog.Printf(\"process done with error = %v\", err)\n\t\t}\n\t\ttokens = h.tokenizer.AnalyzeGraph(w0, sen, m)\n\t\tif err := w0.Close(); err != nil {\n\t\t\tlog.Printf(\"pipe close error, %v\", err)\n\t\t}\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tcmdErr = fmt.Sprintf(\"Error: process done with error, %v\", err)\n\t\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\t\tcmdErr = \"Error: Graphviz time out\"\n\t\t\t}\n\t\t}\n\t\tsvg = buf.String()\n\t\tif pos := strings.Index(svg, \" 0 {\n\t\t\tsvg = svg[pos:]\n\t\t}\n\t\tfor _, tok := range tokens {\n\t\t\tif tok.ID == tokenizer.BosEosID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm := record{\n\t\t\t\tSurface: tok.Surface,\n\t\t\t}\n\t\t\tif m.POS = strings.Join(tok.POS(), \",\"); m.POS == \"\" {\n\t\t\t\tm.POS = \"*\"\n\t\t\t}\n\t\t\tvar ok bool\n\t\t\tif m.Baseform, ok = tok.BaseForm(); !ok {\n\t\t\t\tm.Baseform = \"*\"\n\t\t\t}\n\t\t\tif m.Reading, ok = tok.Reading(); !ok {\n\t\t\t\tm.Reading = \"*\"\n\t\t\t}\n\t\t\tif m.Pronunciation, ok = tok.Pronunciation(); !ok {\n\t\t\t\tm.Pronunciation = \"*\"\n\t\t\t}\n\t\t\trecords = append(records, m)\n\t\t}\n\t}\n\td := struct {\n\t\tSentence string\n\t\tTokens []record\n\t\tCmdErr string\n\t\tGraphSvg template.HTML\n\t\tMode string\n\t}{Sentence: sen, Tokens: records, CmdErr: cmdErr, GraphSvg: template.HTML(svg), Mode: mode}\n\tt := template.Must(template.New(\"top\").Parse(graphHTML))\n\tif err := t.Execute(w, d); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nvar graphHTML = `\n\n\n\n