author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
748,234 | 01.06.2019 10:28:39 | 25,200 | 50352c139137980ddf165aa3835091056491f1bf | fix: Remove authorization from static files
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -6,16 +6,12 @@ module.exports = function(RED) {\nconst HomeAssistant = require('../../lib/node-home-assistant');\n// Handle static files\n- RED.httpAdmin.get(\n- '/homeassistant/static/*',\n- RED.auth.needsPermission('server.read'),\n- function(req, res, next) {\n+ RED.httpAdmin.get('/homeassistant/static/*', function(req, res, next) {\nres.sendFile(req.params[0], {\nroot: require('path').join(__dirname, '..', '/_static'),\ndotfiles: 'deny'\n});\n- }\n- );\n+ });\nconst httpHandlers = {\ngetEntities: function(req, res, next) {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: Remove authorization from static files
Closes #125 |
748,234 | 01.06.2019 19:31:44 | 25,200 | 4231717fd4344b5b6c839f6aa73448ea3bd69585 | fix(wait-until): removed leftover code that was breaking events | [
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.js",
"new_path": "nodes/wait-until/wait-until.js",
"diff": "@@ -93,11 +93,6 @@ module.exports = function(RED) {\nreturn null;\n}\n- if (this.websocketClient) {\n- Object.entries(this.listeners).forEach(([event, handler]) => {\n- this.websocketClient.removeListener(event, handler);\n- });\n- }\nnode.savedMessage = message;\nnode.active = true;\nlet statusText = 'waiting';\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(wait-until): removed leftover code that was breaking events |
748,234 | 04.06.2019 23:22:27 | 25,200 | 79fcf29e9c49b7f56e09fedc7dbc2b72a23c2446 | fix(current-state): fix for none type for state and data location
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/current-state/current-state.js",
"new_path": "nodes/current-state/current-state.js",
"diff": "@@ -12,12 +12,20 @@ module.exports = function(RED) {\nstate_type: nodeDef => nodeDef.state_type || 'str',\nstate_location: nodeDef => nodeDef.state_location || 'payload',\n// state location type\n- override_payload: nodeDef =>\n- nodeDef.override_payload !== false ? 'msg' : 'none',\n+ override_payload: nodeDef => {\n+ if (nodeDef.state_location === undefined) {\n+ return nodeDef.override_payload !== false ? 'msg' : 'none';\n+ }\n+ return nodeDef.override_payload;\n+ },\nentity_location: nodeDef => nodeDef.entity_location || 'data',\n// entity location type\n- override_data: nodeDef =>\n- nodeDef.override_data !== false ? 'msg' : 'none',\n+ override_data: nodeDef => {\n+ if (nodeDef.entity_location === undefined) {\n+ return nodeDef.override_data !== false ? 'msg' : 'none';\n+ }\n+ return nodeDef.override_data;\n+ },\nblockInputOverrides: {}\n},\ninput: {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(current-state): fix for none type for state and data location
Closes #126 |
748,234 | 04.06.2019 23:26:21 | 25,200 | ea82e09d913370daff93f7ee4935699c6626ab25 | style: Changed if state icon | [
{
"change_type": "MODIFY",
"old_path": "nodes/current-state/current-state.html",
"new_path": "nodes/current-state/current-state.html",
"diff": "</div>\n<div class=\"form-row\">\n- <label for=\"node-input-halt_if_compare\"><i class=\"fa fa-random\"></i> If State</label>\n+ <label for=\"node-input-halt_if_compare\"><i class=\"fa fa-check-square\"></i> If State</label>\n<div style=\"width: 70%;display: inline-block;\">\n<select type=\"text\" id=\"node-input-halt_if_compare\" style=\"width: auto;\">\n<option value=\"is\">is</option>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.html",
"new_path": "nodes/events-state-changed/events-state-changed.html",
"diff": "<div class=\"form-row\">\n- <label for=\"node-input-haltifstate\"><i class=\"fa fa-random\"></i> If State</label>\n+ <label for=\"node-input-haltifstate\"><i class=\"fa fa-check-square\"></i> If State</label>\n<div style=\"width: 70%;display: inline-block;\">\n<select type=\"text\" id=\"node-input-halt_if_compare\" style=\"width: auto;\">\n<option value=\"is\">is</option>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/poll-state/poll-state.html",
"new_path": "nodes/poll-state/poll-state.html",
"diff": "</div>\n<div class=\"form-row\">\n- <label for=\"node-input-halt_if_compare\"><i class=\"fa fa-random\"></i> If State</label>\n+ <label for=\"node-input-halt_if_compare\"><i class=\"fa fa-check-square\"></i> If State</label>\n<div style=\"width: 70%;display: inline-block;\">\n<select type=\"text\" id=\"node-input-halt_if_compare\" style=\"width: auto;\">\n<option value=\"is\">is</option>\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | style: Changed if state icon |
748,234 | 23.06.2019 06:05:29 | 25,200 | c4d308196f4f34d369b451b376a507b30508cc75 | feat(wait-until): Allow overriding of config value | [
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -40,7 +40,7 @@ class EventsNode extends BaseNode {\nthis.websocketClient.addListener(event, handler);\n}\n- onClose(nodeRemoved) {\n+ removeEventClientListeners() {\nif (this.websocketClient) {\nObject.entries(this.listeners).forEach(([event, handler]) => {\nthis.websocketClient.removeListener(event, handler);\n@@ -48,6 +48,10 @@ class EventsNode extends BaseNode {\n}\n}\n+ onClose(nodeRemoved) {\n+ this.removeEventClientListeners();\n+ }\n+\nonHaEventsClose() {\nthis.updateConnectionStatus();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.html",
"new_path": "nodes/wait-until/wait-until.html",
"diff": "name: { value: \"\" },\nserver: { value: \"\", type: \"server\", required: true },\noutputs: { value: 1 },\n- entityId: { value: \"\", required: true },\n- property: { value: \"\", required: true },\n+ entityId: { value: \"\" },\n+ property: { value: \"\" },\ncomparator: { value: \"is\" },\nvalue: { value: \"\" },\nvalueType: { value: \"str\" },\ntimeoutUnits: { value: \"seconds\" },\nentityLocation: { value: \"data\" },\nentityLocationType: { value: \"none\" },\n- checkCurrentState: { value: true }\n+ checkCurrentState: { value: true },\n+ blockInputOverrides: { value: false }\n},\noneditprepare: function() {\nconst node = this;\n<input type=\"checkbox\" id=\"node-input-checkCurrentState\" checked style=\"margin-left:105px;display:inline-block; width:auto; vertical-align:baseline;\"> \n<label for=\"node-input-checkCurrentState\" style=\"width: auto;margin-right: 20px;\">Check against current state</label>\n</div>\n+\n+ <div class=\"form-row checkboxOption\">\n+ <input type=\"checkbox\" id=\"node-input-blockInputOverrides\"> \n+ <label for=\"node-input-blockInputOverrides\">Block Input Overrides</label>\n+ </div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"ha-wait-until\">\n<dl class=\"message-properties\">\n<dt class=\"optional\">reset <span class=\"property-type\"></span> </dt>\n<dd>If the received message has this property set to any value the node will be set to inactive and the timeout cleared.</dd>\n+\n+ <dt class=\"optional\">payload <span class=\"property-type\">object</span> </dt>\n+ <dd>\n+ Override config values by passing in a property with a valid value.\n+ <ul>\n+ <li>entityId</li>\n+ <li>property</li>\n+ <li>comparator</li>\n+ <li>value</li>\n+ <li>valueType</li>\n+ <li>timeout</li>\n+ <li>timeoutUnits</li>\n+ <li>entityLocation</li>\n+ <li>entityLocationType</li>\n+ <li>checkCurrentState</li>\n+ </ul>\n+ </dd>\n+\n</dl>\n<h3>Configuration</h3>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.js",
"new_path": "nodes/wait-until/wait-until.js",
"diff": "module.exports = function(RED) {\n+ const Joi = require('@hapi/joi');\nconst EventsNode = require('../../lib/events-node');\nconst nodeOptions = {\n@@ -15,7 +16,104 @@ module.exports = function(RED) {\ntimeoutUnits: {},\nentityLocation: {},\nentityLocationType: {},\n- checkCurrentState: {}\n+ checkCurrentState: {},\n+ blockInputOverrides: {}\n+ },\n+ input: {\n+ entityId: {\n+ messageProp: 'payload.entityId',\n+ configProp: 'entityId',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string().label('entityId')\n+ }\n+ },\n+ property: {\n+ messageProp: 'payload.property',\n+ configProp: 'property',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string().label('property')\n+ }\n+ },\n+ comparator: {\n+ messageProp: 'payload.comparator',\n+ configProp: 'comparator',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid(\n+ 'is',\n+ 'is_not',\n+ 'lt',\n+ 'lte',\n+ 'gt',\n+ 'gte',\n+ 'includes',\n+ 'does_not_include'\n+ )\n+ .label('comparator')\n+ }\n+ },\n+ value: {\n+ messageProp: 'payload.value',\n+ configProp: 'value',\n+ validation: {\n+ schema: Joi.string().label('value')\n+ }\n+ },\n+ valueType: {\n+ messageProp: 'payload.valueType',\n+ configProp: 'valueType',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string().label('valueType')\n+ }\n+ },\n+ timeout: {\n+ messageProp: 'payload.timeout',\n+ configProp: 'timeout',\n+ validation: {\n+ schema: Joi.number().label('timeout')\n+ }\n+ },\n+ timeoutUnits: {\n+ messageProp: 'payload.timeoutUnits',\n+ configProp: 'timeoutUnits',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid(\n+ 'milliseconds',\n+ 'seconds',\n+ 'minutes',\n+ 'hours',\n+ 'days'\n+ )\n+ .label('timeoutUnits')\n+ }\n+ },\n+ entityLocation: {\n+ messageProp: 'payload.entityLocation',\n+ configProp: 'entityLocation',\n+ validation: {\n+ schema: Joi.string().label('entityLocation')\n+ }\n+ },\n+ entityLocationType: {\n+ messageProp: 'payload.entityLocationType',\n+ configProp: 'entityLocationType',\n+ validation: {\n+ schema: Joi.string().label('entityLocationType')\n+ }\n+ },\n+ checkCurrentState: {\n+ messageProp: 'payload.checkCurrentState',\n+ configProp: 'checkCurrentState',\n+ validation: {\n+ schema: Joi.boolean().label('checkCurrentState')\n+ }\n+ }\n}\n};\n@@ -25,16 +123,10 @@ module.exports = function(RED) {\nthis.active = false;\nthis.savedMessage = {};\nthis.timeoutId = -1;\n-\n- this.addEventClientListener({\n- event: `ha_events:state_changed:${this.nodeConfig.entityId}`,\n- handler: this.onEntityChange.bind(this)\n- });\n}\nasync onEntityChange(evt) {\ntry {\n- const config = this.nodeConfig;\nconst event = Object.assign({}, evt.event);\nif (!this.active) {\n@@ -42,10 +134,13 @@ module.exports = function(RED) {\n}\nconst result = await this.getComparatorResult(\n- config.comparator,\n- config.value,\n- this.utils.selectn(config.property, event.new_state),\n- config.valueType,\n+ this.savedConfig.comparator,\n+ this.savedConfig.value,\n+ this.utils.selectn(\n+ this.savedConfig.property,\n+ event.new_state\n+ ),\n+ this.savedConfig.valueType,\n{\nmessage: this.savedMessage,\nentity: event.new_state\n@@ -61,8 +156,8 @@ module.exports = function(RED) {\nthis.setStatusSuccess('true');\nif (\n- config.entityLocationType !== 'none' &&\n- config.entityLocation\n+ this.savedConfig.entityLocationType !== 'none' &&\n+ this.savedConfig.entityLocation\n) {\nevent.new_state.timeSinceChangedMs =\nDate.now() -\n@@ -70,8 +165,8 @@ module.exports = function(RED) {\nthis.setContextValue(\nevent.new_state,\n- config.entityLocationType,\n- config.entityLocation,\n+ this.savedConfig.entityLocationType,\n+ this.savedConfig.entityLocation,\nthis.savedMessage\n);\n}\n@@ -82,44 +177,74 @@ module.exports = function(RED) {\n}\n}\n- async onInput({ message }) {\n+ async onInput({ message, parsedMessage }) {\nconst node = this;\n- const config = node.nodeConfig;\n-\nclearTimeout(node.timeoutId);\n+\nif (message.hasOwnProperty('reset')) {\nnode.status({ text: 'reset' });\nnode.active = false;\nreturn null;\n}\n+ node.savedConfig = {\n+ entityId: parsedMessage.entityId.value,\n+ property: parsedMessage.property.value,\n+ comparator: parsedMessage.comparator.value,\n+ value: parsedMessage.value.value,\n+ valueType: parsedMessage.valueType.value,\n+ timeout: parsedMessage.timeout.value,\n+ timeoutUnits: parsedMessage.timeoutUnits.value,\n+ entityLocation: parsedMessage.entityLocation.value,\n+ entityLocationType: parsedMessage.entityLocationType.value,\n+ checkCurrentState: parsedMessage.checkCurrentState.value\n+ };\n+\n+ // If blocking input overrides reset values to nodeConfig\n+ if (node.nodeConfig.blockInputOverrides === true) {\n+ Object.keys(node.savedConfig).forEach(\n+ key =>\n+ (node.savedConfig[key] = (key in node.nodeConfig\n+ ? node.nodeConfig\n+ : node.savedConfig)[key])\n+ );\n+ }\n+\n+ node.removeEventClientListeners();\n+ node.addEventClientListener({\n+ event: `ha_events:state_changed:${node.savedConfig.entityId}`,\n+ handler: node.onEntityChange.bind(node)\n+ });\n+\nnode.savedMessage = message;\nnode.active = true;\nlet statusText = 'waiting';\n- if (config.timeout > 0) {\n- if (config.timeoutUnits === 'milliseconds') {\n- node.timeout = config.timeout;\n- statusText = `waiting for ${config.timeout} milliseconds`;\n- } else if (config.timeoutUnits === 'minutes') {\n- node.timeout = config.timeout * (60 * 1000);\n- statusText = `waiting for ${config.timeout} minutes`;\n- } else if (config.timeoutUnits === 'hours') {\n- node.timeout = config.timeout * (60 * 60 * 1000);\n+ const timeout = node.savedConfig.timeout;\n+ if (timeout > 0) {\n+ const timeoutUnits = node.savedConfig.timeoutUnits;\n+ if (timeoutUnits === 'milliseconds') {\n+ node.timeout = timeout;\n+ statusText = `waiting for ${timeout} milliseconds`;\n+ } else if (timeoutUnits === 'minutes') {\n+ node.timeout = timeout * (60 * 1000);\n+ statusText = `waiting for ${timeout} minutes`;\n+ } else if (timeoutUnits === 'hours') {\n+ node.timeout = timeout * (60 * 60 * 1000);\nstatusText = node.timeoutStatus(node.timeout);\n- } else if (config.timeoutUnits === 'days') {\n- node.timeout = config.timeout * (24 * 60 * 60 * 1000);\n+ } else if (timeoutUnits === 'days') {\n+ node.timeout = timeout * (24 * 60 * 60 * 1000);\nstatusText = node.timeoutStatus(node.timeout);\n} else {\n- node.timeout = config.timeout * 1000;\n- statusText = `waiting for ${config.timeout} seconds`;\n+ node.timeout = timeout * 1000;\n+ statusText = `waiting for ${timeout} seconds`;\n}\n- node.timeoutId = setTimeout(async function() {\n+ node.timeoutId = setTimeout(async () => {\nconst state = Object.assign(\n{},\n- await config.server.homeAssistant.getStates(\n- config.entityId\n+ await node.nodeConfig.server.homeAssistant.getStates(\n+ node.savedConfig.entityId\n)\n);\n@@ -128,8 +253,8 @@ module.exports = function(RED) {\nnode.setContextValue(\nstate,\n- config.entityLocationType,\n- config.entityLocation,\n+ node.savedConfig.entityLocationType,\n+ node.savedConfig.entityLocation,\nmessage\n);\n@@ -140,9 +265,9 @@ module.exports = function(RED) {\n}\nnode.setStatus({ text: statusText });\n- if (config.checkCurrentState === true) {\n- const currentState = await this.nodeConfig.server.homeAssistant.getStates(\n- config.entityId\n+ if (node.nodeConfig.checkCurrentState === true) {\n+ const currentState = await node.nodeConfig.server.homeAssistant.getStates(\n+ node.savedConfig.entityId\n);\nnode.onEntityChange({ event: { new_state: currentState } });\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(wait-until): Allow overriding of config value |
748,234 | 01.07.2019 16:52:41 | 25,200 | 4c37f61b9bd0a29423389cf47689de25b42d5247 | refactor(wait-until): set default to block input overrides of config | [
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.html",
"new_path": "nodes/wait-until/wait-until.html",
"diff": "entityLocation: { value: \"data\" },\nentityLocationType: { value: \"none\" },\ncheckCurrentState: { value: true },\n- blockInputOverrides: { value: false }\n+ blockInputOverrides: { value: true }\n},\noneditprepare: function() {\nconst node = this;\ntypeField: \"#node-input-entityLocationType\"\n})\n.typedInput(\"width\", \"68%\");\n+\n+ if (node.blockInputOverrides === undefined) {\n+ $(\"#node-input-blockInputOverrides\").prop(\"checked\", true);\n+ }\n},\noneditsave: function() {\nconst outputs = $(\"#node-input-timeout\").val() > 0 ? 2 : 1;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.js",
"new_path": "nodes/wait-until/wait-until.js",
"diff": "@@ -17,7 +17,10 @@ module.exports = function(RED) {\nentityLocation: {},\nentityLocationType: {},\ncheckCurrentState: {},\n- blockInputOverrides: {}\n+ blockInputOverrides: nodeDef =>\n+ nodeDef.blockInputOverrides === undefined\n+ ? true\n+ : nodeDef.blockInputOverrides\n},\ninput: {\nentityId: {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor(wait-until): set default to block input overrides of config |
748,234 | 01.07.2019 17:42:56 | 25,200 | aed45795c4220866edfde84adf879dfcf9d1f5f4 | feat(current-state): Templates are processed in the entity id field | [
{
"change_type": "MODIFY",
"old_path": "nodes/current-state/current-state.js",
"new_path": "nodes/current-state/current-state.js",
"diff": "+const RenderTemplate = require('../../lib/mustache-context');\nconst BaseNode = require('../../lib/base-node');\nconst Joi = require('@hapi/joi');\n@@ -48,10 +49,14 @@ module.exports = function(RED) {\n/* eslint-disable camelcase */\nasync onInput({ parsedMessage, message }) {\nconst config = this.nodeConfig;\n- const entityId =\n+ const entityId = RenderTemplate(\nconfig.blockInputOverrides === true\n? config.entity_id\n- : parsedMessage.entity_id.value;\n+ : parsedMessage.entity_id.value,\n+ message,\n+ this.node.context(),\n+ this.utils.toCamelCase(config.server.name)\n+ );\nif (config.server === null) {\nthis.node.error('No valid server selected.', message);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(current-state): Templates are processed in the entity id field |
748,234 | 06.07.2019 15:10:00 | 25,200 | e0f52e0b8722a3d9ce269f7abd3cf0283860fb6b | fix: Load external js,css for all nodes not only config
Load external js and css files for all nodes just not server-config
nodes. Fixes NodeVersion error when no config has been defined yet. | [
{
"change_type": "MODIFY",
"old_path": "nodes/api/api.html",
"new_path": "nodes/api/api.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"ha-api\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.html",
"new_path": "nodes/call-service/call-service.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"api-call-service\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/current-state/current-state.html",
"new_path": "nodes/current-state/current-state.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script src=\"homeassistant/static/ifstate.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"api-current-state\", {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.html",
"new_path": "nodes/events-all/events-all.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"server-events\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.html",
"new_path": "nodes/events-state-changed/events-state-changed.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script src=\"homeassistant/static/ifstate.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"server-state-changed\", {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/fire-event/fire-event.html",
"new_path": "nodes/fire-event/fire-event.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"ha-fire-event\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.html",
"new_path": "nodes/get-entities/get-entities.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"ha-get-entities\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/get-history/get-history.html",
"new_path": "nodes/get-history/get-history.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"api-get-history\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/poll-state/poll-state.html",
"new_path": "nodes/poll-state/poll-state.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script src=\"homeassistant/static/ifstate.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"poll-state\", {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/render-template/render-template.html",
"new_path": "nodes/render-template/render-template.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\n(function() {\nRED.nodes.registerType(\"api-render-template\", {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.html",
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"trigger-state\", {\ncategory: \"home_assistant\",\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/wait-until/wait-until.html",
"new_path": "nodes/wait-until/wait-until.html",
"diff": "+<link rel=\"stylesheet\" type=\"text/css\" href=\"homeassistant/static/common.css\" />\n+<script src=\"homeassistant/static/common.js\"></script>\n<script type=\"text/javascript\">\nRED.nodes.registerType(\"ha-wait-until\", {\ncategory: \"home_assistant\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: Load external js,css for all nodes not only config
Load external js and css files for all nodes just not server-config
nodes. Fixes NodeVersion error when no config has been defined yet. |
748,234 | 07.07.2019 20:10:14 | 25,200 | 5f437d4e4e055239d20e6cc4ba91e3fd396162da | docs: Info about docker on rpi needing node.js upgraded | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -12,9 +12,9 @@ Project is going through active development and as such will probably have a few\n## Getting Started\n-This assumes you have [Node-RED](https://nodered.org) already installed and working, if you need to install Node-RED see [here](https://nodered.org/docs/getting-started/installation)\n+This assumes you have [Node-RED](https://nodered.org) already installed and working, if you need to install Node-RED see [here](https://nodered.org/docs/getting-started/installation).\n-**NOTE:** This requires [Node.js](https://nodejs.org) v8.12+ and [Node-RED](https://nodered.org/) v0.19+.\n+**NOTE:** This requires at least [Node.js](https://nodejs.org) v8.12.x and [Node-RED](https://nodered.org/) v0.19.x.\nInstall via Node-RED Manage Palette\n@@ -30,6 +30,8 @@ $ npm install node-red-contrib-home-assistant-websocket\n# then restart node-red\n```\n+**Docker users on Rpi** will need to upgrade Node.js inside the [official Node-RED container](https://hub.docker.com/r/nodered/node-red-docker/) or can use the [raymondmm/node-red container](https://hub.docker.com/r/raymondmm/node-red) which comes with Node.js 8.16.0 installed.\n+\nFor [Hass.io](https://hass.io/) add-on users:\nThe Community Hass.io add-on ships with this node right out of the box.\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Info about docker on rpi needing node.js upgraded |
748,234 | 20.07.2019 05:48:58 | 25,200 | a0fdb963b0a1ac598773dfc3e7ea8848ae054bef | feat(get-entities): Allow overriding of config values from payload
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.css",
"new_path": "nodes/_static/common.css",
"diff": "-ms-user-select: none;\nuser-select: none;\n}\n+\n+li span.property-type {\n+ font-family: \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n+ color: #666;\n+ font-style: italic;\n+ font-size: 11px;\n+ float: right;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.html",
"new_path": "nodes/get-entities/get-entities.html",
"diff": "<dd>Has autocomplete with all properties currently set on all loaded entities.</dd>\n</dl>\n+ <h3>Inputs</h3>\n+\n+ <dl class=\"message-properties\">\n+ <dt class=\"optional\">payload <span class=\"property-type\">object</span> </dt>\n+ <dd>\n+ Override config values by passing in a property with a valid value.\n+ <ul>\n+ <li>rules <span class=\"property-type\">array</span>\n+ <ul>\n+ <li>property <span class=\"property-type\">string</span></li>\n+ <li>logic <span class=\"property-type\">string</span></li>\n+ <li>value <span class=\"property-type\">string</span></li>\n+ <li>valueType <span class=\"property-type\">string</span></li>\n+ </ul>\n+ </li>\n+ <li>outputType <span class=\"property-type\">string</span></li>\n+ <li>outputEmptyResults <span class=\"property-type\">boolean</span></li>\n+ <li>outputLocationType <span class=\"property-type\">string</span></li>\n+ <li>outputLocation <span class=\"property-type\">string</span></li>\n+ <li>outputResultscount <span class=\"property-type\">number</span></li>\n+ </ul>\n+ </dd>\n+ </dl>\n+\n<h3>Outputs</h3>\n<dl class=\"message-properties\">\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.js",
"new_path": "nodes/get-entities/get-entities.js",
"diff": "const BaseNode = require('../../lib/base-node');\nconst { shuffle } = require('lodash');\nconst { filter } = require('p-iteration');\n+const Joi = require('@hapi/joi');\nmodule.exports = function(RED) {\nconst nodeOptions = {\n@@ -14,6 +15,97 @@ module.exports = function(RED) {\noutput_location_type: {},\noutput_location: {},\noutput_results_count: {}\n+ },\n+ input: {\n+ outputType: {\n+ messageProp: 'payload.outputType',\n+ configProp: 'output_type',\n+ default: 'array',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid('array', 'count', 'random', 'split')\n+ .label('OutputType')\n+ }\n+ },\n+ outputEmptyResults: {\n+ messageProp: 'payload.outputEmptyResults',\n+ configProp: 'output_empty_results',\n+ default: false,\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.boolean().label('outputEmptyResults')\n+ }\n+ },\n+ outputLocationType: {\n+ messageProp: 'payload.outputLocationType',\n+ configProp: 'output_location_type',\n+ default: 'msg',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid('array', 'msg', 'flow', 'global')\n+ .label('outputLocationType')\n+ }\n+ },\n+ outputLocation: {\n+ messageProp: 'payload.outputLocation',\n+ configProp: 'output_location',\n+ default: 'payload',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string().label('outputLocation')\n+ }\n+ },\n+ outputResultsCount: {\n+ messageProp: 'payload.outputResultsCount',\n+ configProp: 'output_results_count',\n+ default: 1,\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.number().label('outputResultsCount')\n+ }\n+ },\n+ rules: {\n+ messageProp: 'payload.rules',\n+ configProp: 'rules',\n+ default: [],\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.array()\n+ .items(\n+ Joi.object({\n+ property: Joi.string(),\n+ logic: Joi.string().valid(\n+ 'is',\n+ 'is_not',\n+ 'lt',\n+ 'lte',\n+ 'gt',\n+ 'gte',\n+ 'includes',\n+ 'does_not_include',\n+ 'starts_with',\n+ 'in_group',\n+ 'jsonata'\n+ ),\n+ value: Joi.string(),\n+ valueType: Joi.string().valid(\n+ 'str',\n+ 'num',\n+ 'bool',\n+ 're',\n+ 'jsonata',\n+ 'msg',\n+ 'flow',\n+ 'global',\n+ 'entity'\n+ )\n+ })\n+ )\n+ .label('rules')\n+ }\n+ }\n}\n};\n@@ -23,16 +115,15 @@ module.exports = function(RED) {\n}\n/* eslint-disable camelcase */\n- async onInput({ message }) {\n- const config = this.nodeConfig;\n+ async onInput({ message, parsedMessage }) {\nlet noPayload = false;\n- if (config.server === null) {\n+ if (this.nodeConfig.server === null) {\nthis.node.error('No valid server selected.', message);\nreturn;\n}\n- const states = await config.server.homeAssistant.getStates();\n+ const states = await this.nodeConfig.server.homeAssistant.getStates();\nif (!states) {\nthis.node.warn(\n'local state cache missing sending empty payload'\n@@ -43,7 +134,7 @@ module.exports = function(RED) {\nlet entities;\ntry {\nentities = await filter(Object.values(states), async entity => {\n- const rules = config.rules;\n+ const rules = parsedMessage.rules.value;\nfor (const rule of rules) {\nconst value = this.utils.selectn(rule.property, entity);\n@@ -78,7 +169,7 @@ module.exports = function(RED) {\nlet statusText = `${entities.length} entities`;\nlet payload = {};\n- switch (config.output_type) {\n+ switch (parsedMessage.outputType.value) {\ncase 'count':\npayload = entities.length;\nbreak;\n@@ -96,7 +187,8 @@ module.exports = function(RED) {\nnoPayload = true;\nbreak;\n}\n- let maxReturned = Number(config.output_results_count) || 1;\n+ let maxReturned =\n+ Number(parsedMessage.outputResultsCount.value) || 1;\nconst max =\nentities.length <= maxReturned\n@@ -113,7 +205,10 @@ module.exports = function(RED) {\nbreak;\ncase 'array':\ndefault:\n- if (entities.length === 0 && !config.output_empty_results) {\n+ if (\n+ entities.length === 0 &&\n+ !parsedMessage.outputEmptyResults.value\n+ ) {\nnoPayload = true;\n}\n@@ -130,8 +225,8 @@ module.exports = function(RED) {\nthis.setContextValue(\npayload,\n- config.output_location_type,\n- config.output_location,\n+ parsedMessage.outputLocationType.value,\n+ parsedMessage.outputLocation.value,\nmessage\n);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(get-entities): Allow overriding of config values from payload
Closes #133 |
748,234 | 21.07.2019 06:31:00 | 25,200 | 37b54ce910875e748e49427664d4235ca9891410 | feat(api): Add option for data field to be a JSONata Expr | [
{
"change_type": "MODIFY",
"old_path": "nodes/api/api.html",
"new_path": "nodes/api/api.html",
"diff": "method: { value: \"get\" },\npath: { value: \"\" },\ndata: { value: \"\" },\n+ dataType: { value: \"json\" },\nlocation: { value: \"payload\" },\nlocationType: { value: \"msg\" },\nresponseType: { value: \"json\" }\n$(\"#node-input-data\")\n.typedInput({\n- types: [\"json\"]\n+ types: [\"json\", \"jsonata\"],\n+ typeField: \"#node-input-dataType\"\n})\n.typedInput(\"width\", \"68%\");\n<div class=\"form-row\">\n<label id=\"data-label\" for=\"node-input-data\">Data</label>\n<input type=\"text\" id=\"node-input-data\">\n+ <input type=\"hidden\" id=\"node-input-dataType\">\n</div>\n<div class=\"form-row\">\n<p>Will output the results received from the API call to the location defined in the config.</p>\n<h3>Templates</h3>\n- <p>Templates can be used in path, params and data fields. When using templates the top level is a property of the message object: <code>msg.payload</code> would be <code>{{payload}}</code>.</p>\n+ <p>Templates can be used in path, params and data fields. When using templates the top level is a property of the message object: <code>msg.payload</code> would be <code>{{payload}}</code>. Templates will only work in the data field when the data type is JSON.</p>\n<h3>References</h3>\n<p>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api/api.js",
"new_path": "nodes/api/api.js",
"diff": "@@ -11,6 +11,7 @@ module.exports = function(RED) {\nmethod: {},\npath: {},\ndata: {},\n+ dataType: nodeDef => nodeDef.dataType || 'json',\nlocation: {},\nlocationType: {},\nresponseType: {}\n@@ -51,6 +52,17 @@ module.exports = function(RED) {\nmessageProp: 'payload.data',\nconfigProp: 'data'\n},\n+ dataType: {\n+ messageProp: 'payload.dataType',\n+ configProp: 'dataType',\n+ default: 'json',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid('json', 'jsonata')\n+ .label('dataType')\n+ }\n+ },\nlocation: {\nmessageProp: 'payload.location',\nconfigProp: 'location',\n@@ -103,7 +115,19 @@ module.exports = function(RED) {\n}\nconst serverName = node.utils.toCamelCase(config.server.name);\n- const data = RenderTemplate(\n+ let data;\n+ if (parsedMessage.dataType.value === 'jsonata') {\n+ try {\n+ data = JSON.stringify(\n+ this.evaluateJSONata(parsedMessage.data.value, message)\n+ );\n+ } catch (e) {\n+ this.setStatusFailed('Error');\n+ this.node.error(e.message, message);\n+ return;\n+ }\n+ } else {\n+ data = RenderTemplate(\ntypeof parsedMessage.data.value === 'object'\n? JSON.stringify(parsedMessage.data.value)\n: parsedMessage.data.value,\n@@ -111,6 +135,8 @@ module.exports = function(RED) {\nnode.node.context(),\nserverName\n);\n+ }\n+\nconst method = parsedMessage.method.value;\nlet apiCall;\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(api): Add option for data field to be a JSONata Expr |
748,234 | 21.07.2019 07:52:12 | 25,200 | 526d0836ab8660c3369b37af97ca15cfeb668ad3 | feat(fire-event): Add option for data field to be a JSONata Expr
Add option for data field to be a JSONata Exprression.
Removed merge context | [
{
"change_type": "MODIFY",
"old_path": "nodes/fire-event/fire-event.html",
"new_path": "nodes/fire-event/fire-event.html",
"diff": "name: { value: \"\" },\nserver: { value: \"\", type: \"server\", required: true },\nevent: { value: \"\" },\n- data: {\n- value: \"\",\n- validate: function(v) {\n- // data isn't required since it could be either not needed or provided via payload\n- if (!v) {\n- return true;\n- }\n- try {\n- JSON.parse(v);\n- return true;\n- } catch (e) {\n- return false;\n- }\n- }\n- },\n- mergecontext: { value: null }\n+ data: { value: \"\" },\n+ dataType: { value: \"json\" }\n},\noneditprepare: function() {\n- const NODE = this;\n- const $server = $(\"#node-input-server\");\n-\nconst node = this;\n+ haServer.init(node, \"#node-input-server\");\n+\n$(\"#node-input-data\")\n.typedInput({\n- types: [\"json\"]\n+ types: [\"json\", \"jsonata\"],\n+ typeField: \"#node-input-dataType\"\n})\n.typedInput(\"width\", \"68%\");\n-\n- const utils = {\n- setDefaultServerSelection: function() {\n- let defaultServer;\n- RED.nodes.eachConfig(n => {\n- if (n.type === \"server\" && !defaultServer) defaultServer = n.id;\n- });\n- if (defaultServer) $server.val(defaultServer);\n- }\n- };\n-\n- if (!NODE.server) {\n- utils.setDefaultServerSelection();\n- }\n}\n});\n</script>\n<div class=\"form-row\">\n<label for=\"node-input-data\"><i class=\"fa fa-dot-circle-o\"></i> Data</label>\n- <input type=\"text\" id=\"node-input-data\" placeholder=\"{ }\"/>\n- </div>\n-\n- <div class=\"form-row\">\n- <label for=\"node-input-mergecontext\"><i class=\"fa fa-dot-circle-o\"></i> Merge Context</label>\n- <input type=\"text\" id=\"node-input-mergecontext\" placeholder=\"lightOptions\"/>\n+ <input type=\"text\" id=\"node-input-data\" />\n+ <input type=\"hidden\" id=\"node-input-dataType\" />\n</div>\n</script>\n<h3>Details</h3>\n<p>If the incoming message has a <code>payload</code> property with <code>event</code> set it will override any config values if set.</p>\n- <p>If the incoming message has a <code>payload.data</code> that is an object or parseable into an object these properties will be <strong>merged</strong> with any config values set.<p>\n+ <p>If the incoming message has a <code>payload.data</code> that is an object or parsable into an object these properties will be <strong>merged</strong> with any config values set.<p>\n<p>If the node has a property value in it's config for <code>Merge Context</code> then the <code>flow</code> and <code>global</code> contexts will be checked for this property which should be an object that will also be merged into the data payload.<p>\n- <h3>Merge Resolution</h3>\n- <p>As seen above the <code>data</code> property has a lot going on in the way of data merging, in the end all of these are optional and the right most will win in the event that a property exists in multiple objects<p>\n- <p>Config Data, Global Data, Flow Data, Payload Data ( payload data property always wins if provided )<p>\n-\n<h3>References</h3>\n<ul>\n<li><a href=\"https://developers.home-assistant.io/docs/en/dev_101_events.html#firing-events\">HA Events</a></li>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/fire-event/fire-event.js",
"new_path": "nodes/fire-event/fire-event.js",
"diff": "@@ -9,7 +9,7 @@ module.exports = function(RED) {\nserver: { isNode: true },\nevent: {},\ndata: {},\n- mergecontext: {}\n+ dataType: nodeDef => nodeDef.dataType || 'json'\n},\ninput: {\nevent: {\n@@ -27,6 +27,17 @@ module.exports = function(RED) {\nhaltOnFail: false,\nschema: Joi.string().label('data')\n}\n+ },\n+ dataType: {\n+ messageProp: 'payload.dataType',\n+ configProp: 'dataType',\n+ default: 'json',\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string()\n+ .valid('json', 'jsonata')\n+ .label('dataType')\n+ }\n}\n}\n};\n@@ -54,7 +65,19 @@ module.exports = function(RED) {\nthis.node.context(),\nthis.utils.toCamelCase(this.nodeConfig.server.name)\n);\n- const configData = RenderTemplate(\n+ let eventData;\n+ if (parsedMessage.dataType.value === 'jsonata') {\n+ try {\n+ eventData = JSON.stringify(\n+ this.evaluateJSONata(parsedMessage.data.value, message)\n+ );\n+ } catch (e) {\n+ this.setStatusFailed('Error');\n+ this.node.error(e.message, message);\n+ return;\n+ }\n+ } else {\n+ eventData = RenderTemplate(\ntypeof parsedMessage.data.value === 'object'\n? JSON.stringify(parsedMessage.data.value)\n: parsedMessage.data.value,\n@@ -62,14 +85,6 @@ module.exports = function(RED) {\nthis.node.context(),\nthis.utils.toCamelCase(this.nodeConfig.server.name)\n);\n- const eventData = this.getEventData(message.payload, configData);\n-\n- if (!eventType) {\n- this.node.error(\n- 'Fire event node is missing \"event\" property, not found in config or payload',\n- message\n- );\n- return;\n}\nthis.debug(`Fire Event: ${eventType} -- ${JSON.stringify({})}`);\n@@ -97,35 +112,6 @@ module.exports = function(RED) {\nthis.setStatusFailed('API Error');\n});\n}\n-\n- getEventData(payload, data) {\n- let eventData;\n- let contextData = {};\n-\n- let payloadData = this.utils.selectn('data', payload);\n- let configData = this.tryToObject(data);\n- payloadData = payloadData || {};\n- configData = configData || {};\n-\n- // Calculate payload to send end priority ends up being 'Config, Global Ctx, Flow Ctx, Payload' with right most winning\n- if (this.nodeConfig.mergecontext) {\n- const ctx = this.node.context();\n- let flowVal = ctx.flow.get(this.nodeConfig.mergecontext);\n- let globalVal = ctx.global.get(this.nodeConfig.mergecontext);\n- flowVal = flowVal || {};\n- globalVal = globalVal || {};\n- contextData = this.utils.merge({}, globalVal, flowVal);\n- }\n-\n- eventData = this.utils.merge(\n- {},\n- configData,\n- contextData,\n- payloadData\n- );\n-\n- return eventData;\n- }\n}\nRED.nodes.registerType('ha-fire-event', FireEventNode);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(fire-event): Add option for data field to be a JSONata Expr
Add option for data field to be a JSONata Exprression.
Removed merge context |
748,234 | 23.07.2019 21:37:32 | 25,200 | 8e91f42d21b2f95391268fb0a9a4c7e943a5f3ea | feat(call-service): Add JSONata option to data field | [
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.js",
"new_path": "nodes/_static/common.js",
"diff": "@@ -7,6 +7,9 @@ var nodeVersion = (function($) {\ncase 'api-current-state':\nname = 'current-state';\nbreak;\n+ case 'api-call-service':\n+ name = 'call-service';\n+ break;\ncase 'poll-state':\nname = 'poll-state';\nbreak;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.html",
"new_path": "nodes/call-service/call-service.html",
"diff": "defaults: {\nname: { value: \"\" },\nserver: { value: \"\", type: \"server\", required: true },\n+ version: { value: 1 },\nservice_domain: { value: \"\" },\nservice: { value: \"\" },\n+ entityId: { value: \"\" },\ndata: {\nvalue: \"\",\nvalidate: function(v) {\n// data isn't required since it could be either not needed or provided via payload\n- if (!v) {\n+ if (\n+ !v ||\n+ $(\"#node-input-dataType\").val() === \"jsonata\" ||\n+ template.indexOf(\"{{\") !== -1\n+ ) {\nreturn true;\n}\ntry {\n}\n}\n},\n+ dataType: { value: \"json\" },\nmergecontext: { value: null },\noutput_location: { value: \"payload\" },\noutput_location_type: { value: \"none\" },\nmustacheAltTags: { value: false }\n},\noneditprepare: function() {\n+ nodeVersion.check(this);\nconst node = this;\nconst $domainField = $(\"#service_domain\");\nconst $serviceField = $(\"#service\");\n- const $entityIdField = $(\"#entity_id\");\n+ const $entityIdField = $(\"#node-input-entityId\");\nconst $data = $(\"#node-input-data\");\n+ const $dataType = $(\"#node-input-dataType\");\nconst $serviceDataDiv = $(\"#service-data-desc\");\nconst $serviceDescDiv = $(\".service-description\", $serviceDataDiv);\n$domainField.val(node.service_domain);\n$serviceField.val(node.service);\n- $entityIdField.val(node.entity_id);\n+ if (!node.version) {\n// Extract entity_id from data and fill in the entity_id input\ntry {\nconst data = JSON.parse(node.data);\n$data.val(!Object.keys(data).length ? \"\" : JSON.stringify(data));\n}\n} catch (e) {}\n+ }\n$data\n.typedInput({\n- types: [\"json\"]\n+ types: [\"json\", \"jsonata\"],\n+ typeField: \"#node-input-dataType\"\n})\n.typedInput(\"width\", \"68%\");\n+ $data.on(\"change\", function() {\n+ $(\"#mustacheAltTags\").toggle($dataType.val() === \"json\");\n+ });\n+\nhaServer.init(node, \"#node-input-server\");\nhaServer.autocomplete(\"entities\", entities => {\nnode.availableEntities = entities;\n.typedInput(\"width\", \"68%\");\n},\noneditsave: function() {\n- let entityId = $(\"#entity_id\").val();\n+ let entityId = $(\"#node-input-entityId\").val();\nthis.service_domain = $(\"#service_domain\").val();\nthis.service = $(\"#service\").val();\n} else {\nentityId = entityId.replace(/\\s*,\\s*$/, \"\"); // remove trailing comma\n}\n-\n- try {\n- const data = JSON.parse(dataString);\n- const mergedData = Object.assign({ entity_id: entityId }, data);\n- $nodeInputData.val(JSON.stringify(mergedData));\n- } catch (e) {\n- RED.notify(\"Error merging Entity Id into data.\", \"error\");\n- }\n+ $(\"#node-input-entityId\").val(entityId);\n}\n+\n+ nodeVersion.update(this);\n}\n});\n</script>\n<script type=\"text/x-red\" data-template-name=\"api-call-service\">\n+ <input type=\"hidden\" id=\"node-input-version\" />\n+\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n<div class=\"form-row\">\n- <label for=\"entity_id\"><i class=\"fa fa-cube\"></i> Entity Id</label>\n- <input type=\"text\" id=\"entity_id\">\n+ <label for=\"node-input-entityId\"><i class=\"fa fa-cube\"></i> Entity Id</label>\n+ <input type=\"text\" id=\"node-input-entityId\">\n</div>\n<div class=\"form-row\">\n<label for=\"node-input-data\"><i class=\"fa fa-dot-circle-o\"></i> Data</label>\n<input type=\"text\" id=\"node-input-data\" />\n+ <input type=\"hidden\" id=\"node-input-dataType\" />\n</div>\n- <div class=\"form-row checkboxOption\">\n+ <div class=\"form-row checkboxOption\" id=\"mustacheAltTags\">\n<input type=\"checkbox\" id=\"node-input-mustacheAltTags\"> \n- <label for=\"node-input-mustacheAltTags\">Use alternative Mustache tags for the Data field</label>\n+ <label for=\"node-input-mustacheAltTags\">Use alternative template tags for the Data field</label>\n</div>\n<div class=\"form-row\">\n<h3>Config</h3>\n<dl class=\"message-properties\">\n- <dt>Entity Id <span class=\"property-type\">string</span></dt>\n+ <dt>Domain <span class=\"property-type\">string</span></dt>\n+ <dd>Service domain to call</dd>\n+\n+ <dt>Service <span class=\"property-type\">string</span></dt>\n+ <dd>Service service to call</dd>\n+\n+ <dt class=\"optional\">Entity Id <span class=\"property-type\">string</span></dt>\n<dd>A comma delimited list of entity ids</dd>\n- <dt class=\"optional\">data <span class=\"property-type\">JSON</span></dt>\n+ <dt class=\"optional\">Data <span class=\"property-type\">JSON</span></dt>\n<dd>JSON object to pass along.</dd>\n<dt class=\"optional\">Merge Context <span class=\"property-type\">string</span></dt>\n<dd>If defined will attempt to merge the global and flow context variable into the config</dd>\n- <dt class=\"optional\">Alternative Mustache tags <span class=\"property-type\">boolean</span></dt>\n+ <dt class=\"optional\">Alternative template tags <span class=\"property-type\">boolean</span></dt>\n<dd>Will change the tags used for mustache template to <code><%</code> and <code>%></code></dd>\n</dl>\n</dl>\n<h3>Templates</h3>\n- <p>You can use templates in the <code>Domain</code>, <code>Service</code>, <code>Entity Id</code>, and <code>data</code> fields. When using templates the top level is a property of the message object: <code>msg.payload</code> would be <code>{{payload}}</code>. You can also access the <code>flow, global and states</code> contexts <code>{{flow.foobar}}</code> <code>{{global.something}}</code>. For the <code>states</code> context you can use the <code>{{entity.domain.entity_id}}</code> to just get the state or drill further down like <code>{{entity.light.kitchen.attributes.friendly_name}}</code>. <code>{{entity.light.kitchen}}</code> and <code>{{entity.light.kitchen.state}}</code> are equivalent.</p>\n+ <p>You can use templates in the <code>Domain</code>, <code>Service</code>, <code>Entity Id</code>, and <code>data</code> fields. When using templates the top level is a property of the message object: <code>msg.payload</code> would be <code>{{payload}}</code>. You can also access the <code>flow, global and states</code> contexts <code>{{flow.foobar}}</code> <code>{{global.something}}</code>. For the <code>states</code> context you can use the <code>{{entity.domain.entity_id}}</code> to just get the state or drill further down like <code>{{entity.light.kitchen.attributes.friendly_name}}</code>. <code>{{entity.light.kitchen}}</code> and <code>{{entity.light.kitchen.state}}</code> are equivalent.</p><p>Templates only work in the data field when the data type is JSON.</p>\n<h3>Details</h3>\n<p>If the incoming message has a <code>payload</code> property with <code>domain</code>, <code>service</code> set it will override any config values if set.</p>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.js",
"new_path": "nodes/call-service/call-service.js",
"diff": "@@ -8,7 +8,9 @@ module.exports = function(RED) {\nconfig: {\nservice_domain: {},\nservice: {},\n+ entityId: {},\ndata: {},\n+ dataType: nodeDef => nodeDef.dataType || 'json',\nmergecontext: {},\nname: {},\nserver: { isNode: true },\n@@ -70,13 +72,27 @@ module.exports = function(RED) {\ncontext,\nserverName\n);\n- const configData = RenderTemplate(\n+ let configData;\n+ if (config.dataType === 'jsonata' && config.data.length) {\n+ try {\n+ configData = JSON.stringify(\n+ this.evaluateJSONata(config.data, message)\n+ );\n+ } catch (e) {\n+ this.setStatusFailed('Error');\n+ this.node.error(e.message, message);\n+ return;\n+ }\n+ } else {\n+ configData = RenderTemplate(\nconfig.data,\nmessage,\ncontext,\nserverName,\nconfig.mustacheAltTags\n);\n+ }\n+\nconst apiData = this.getApiData(payload, configData);\nif (!apiDomain || !apiService) {\n@@ -96,6 +112,10 @@ module.exports = function(RED) {\n)}`\n);\n+ // Merge entity id field into data property if it doesn't exist\n+ if (config.entityId.length && !apiData.hasOwnProperty('entity_id'))\n+ apiData.entity_id = config.entityId;\n+\nconst msgPayload = {\ndomain: apiDomain,\nservice: apiService,\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(call-service): Add JSONata option to data field |
748,234 | 23.07.2019 23:42:42 | 25,200 | cb4771b3f5866d88395d961117d73dec546caf2f | refactor(call-service): check for valid data and entity_id before acting | [
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.js",
"new_path": "nodes/call-service/call-service.js",
"diff": "@@ -73,7 +73,7 @@ module.exports = function(RED) {\nserverName\n);\nlet configData;\n- if (config.dataType === 'jsonata' && config.data.length) {\n+ if (config.dataType === 'jsonata' && config.data) {\ntry {\nconfigData = JSON.stringify(\nthis.evaluateJSONata(config.data, message)\n@@ -113,7 +113,7 @@ module.exports = function(RED) {\n);\n// Merge entity id field into data property if it doesn't exist\n- if (config.entityId.length && !apiData.hasOwnProperty('entity_id'))\n+ if (config.entityId && !apiData.hasOwnProperty('entity_id'))\napiData.entity_id = config.entityId;\nconst msgPayload = {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor(call-service): check for valid data and entity_id before acting |
748,234 | 27.07.2019 17:23:08 | 25,200 | b1180098b75e7f714667537d183153e1d04c3023 | fix(call-service): homeassistant domain ids needing to be an array
Moved the coverting of homeassistant domainids to an array to the
backend
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.html",
"new_path": "nodes/call-service/call-service.html",
"diff": "this.service_domain = $(\"#service_domain\").val();\nthis.service = $(\"#service\").val();\n- // Insert entity id into data object\nif (entityId.length) {\n- const $nodeInputData = $(\"#node-input-data\");\n- const dataString = $nodeInputData.val() || \"{}\";\n-\n- if (\n- this.service_domain === \"homeassistant\" &&\n- entityId.indexOf(\",\") !== -1\n- ) {\n- entityId = entityId\n- .replace(/\\s/g, \"\") // remove spaces\n- .replace(/\\s*,\\s*$/, \"\") // remove trailing comma\n- .split(\",\");\n- } else {\n- entityId = entityId.replace(/\\s*,\\s*$/, \"\"); // remove trailing comma\n- }\n- $(\"#node-input-entityId\").val(entityId);\n+ // remove trailing comma\n+ $(\"#node-input-entityId\").val(entityId.replace(/\\s*,\\s*$/, \"\"));\n}\nnodeVersion.update(this);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.js",
"new_path": "nodes/call-service/call-service.js",
"diff": "@@ -120,8 +120,17 @@ module.exports = function(RED) {\nif (\nconfig.entityId &&\n!Object.prototype.hasOwnProperty.call(apiData, 'entity_id')\n- )\n+ ) {\n+ // homeassistant domain requires entity_id to be an array for multiple ids\n+ if (\n+ apiDomain === 'homeassistant' &&\n+ config.entityId.indexOf(',') !== -1\n+ ) {\n+ apiData.entity_id = config.entityId.split(',');\n+ } else {\napiData.entity_id = config.entityId;\n+ }\n+ }\nconst msgPayload = {\ndomain: apiDomain,\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(call-service): homeassistant domain ids needing to be an array
Moved the coverting of homeassistant domainids to an array to the
backend
Closes #136 |
748,234 | 27.07.2019 17:23:42 | 25,200 | 09021621855c6877d6a44658ac0405533abb0bc0 | fix(call-service): fix for validation of data field | [
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.html",
"new_path": "nodes/call-service/call-service.html",
"diff": "service_domain: { value: \"\" },\nservice: { value: \"\" },\nentityId: { value: \"\" },\n- data: {\n- value: \"\",\n- validate: function(v) {\n- // data isn't required since it could be either not needed or provided via payload\n- if (\n- !v ||\n- $(\"#node-input-dataType\").val() === \"jsonata\" ||\n- template.indexOf(\"{{\") !== -1\n- ) {\n- return true;\n- }\n- try {\n- JSON.parse(v);\n- return true;\n- } catch (e) {\n- return false;\n- }\n- }\n- },\n+ data: { value: \"\" },\ndataType: { value: \"json\" },\nmergecontext: { value: null },\noutput_location: { value: \"payload\" },\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(call-service): fix for validation of data field |
748,234 | 01.08.2019 10:23:50 | 25,200 | 888935512ac7f9bf56c8f6611c28b90cb282b2ca | fix(call-service): render mustache templates for entity id field | [
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.js",
"new_path": "nodes/call-service/call-service.js",
"diff": "@@ -121,14 +121,21 @@ module.exports = function(RED) {\nconfig.entityId &&\n!Object.prototype.hasOwnProperty.call(apiData, 'entity_id')\n) {\n+ const entityId = RenderTemplate(\n+ config.entityId,\n+ message,\n+ context,\n+ serverName,\n+ config.mustacheAltTags\n+ );\n// homeassistant domain requires entity_id to be an array for multiple ids\nif (\napiDomain === 'homeassistant' &&\n- config.entityId.indexOf(',') !== -1\n+ entityId.indexOf(',') !== -1\n) {\n- apiData.entity_id = config.entityId.split(',');\n+ apiData.entity_id = entityId.split(',');\n} else {\n- apiData.entity_id = config.entityId;\n+ apiData.entity_id = entityId;\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(call-service): render mustache templates for entity id field |
748,234 | 08.08.2019 19:52:55 | 25,200 | 34a268b3d12493e41d7796b15d7d2f6ff58055c8 | ci: add linting to travis ci | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "language: node_js\nnode_js:\n- \"8\"\n-script: \"npm run-script test-travis\"\n+script:\n+ - npm run lint\n+ - npm run-script test-travis\n# Send coverage data to Coveralls\nafter_script: \"cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | ci: add linting to travis ci |
748,234 | 13.08.2019 00:40:00 | 25,200 | 47727727dbfe6d63b19be61d3812ced4309e9702 | ci: removed test-travis script | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "language: node_js\nnode_js:\n- - \"8\"\n+ - 8\n+ - 10\nscript:\n- npm run lint\n- - npm run-script test-travis\n+ - npm run test\nafter_success:\n# Send coverage data to Coveralls\n- nyc npm test && nyc report --reporter=text-lcov | coveralls\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | ci: removed test-travis script |
748,234 | 14.08.2019 21:30:28 | 25,200 | 5125821b56cbb9e24f898e1c71eedcc886d46f47 | fix(get-entities): error when property value was not set for jsonata | [
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.js",
"new_path": "nodes/get-entities/get-entities.js",
"diff": "@@ -75,7 +75,11 @@ module.exports = function(RED) {\nschema: Joi.array()\n.items(\nJoi.object({\n- property: Joi.string(),\n+ property: Joi.when('logic', {\n+ is: 'jsonata',\n+ then: Joi.any(),\n+ otherwise: Joi.string()\n+ }),\nlogic: Joi.string().valid(\n'is',\n'is_not',\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(get-entities): error when property value was not set for jsonata |
748,234 | 17.08.2019 03:25:35 | 25,200 | a45366f4fad7c9bc783a197f9497b079065d718b | fix(trigger-state): Attribute of other entity undefined in trigger
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -324,14 +324,23 @@ module.exports = function(RED) {\n? this.nodeConfig.entityid\n: constraint.targetValue;\n- if (isTargetThisEntity) {\n- targetData.state = triggerEvent;\n- } else {\n- const state = await this.nodeConfig.server.homeAssistant.getStates(\n+ targetData.state = isTargetThisEntity\n+ ? triggerEvent\n+ : await this.nodeConfig.server.homeAssistant.getStates(\ntargetData.entityid\n);\n+\n+ // TODO: Deprecated, remove at a later date\n+ if (\n+ !isTargetThisEntity &&\n+ constraint.propertyValue.startsWith('new_state.')\n+ ) {\n+ this.warn(\n+ 'DEPRECATED: new_state is no longer needed to access properties of this entity. The ability to do so will be removed in the future',\n+ {}\n+ );\ntargetData.state = {\n- new_state: state\n+ new_state: targetData.state\n};\n}\n} catch (e) {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix(trigger-state): Attribute of other entity undefined in trigger
Closes #148 |
748,234 | 17.08.2019 04:03:04 | 25,200 | c7529a6c1099c241e7307ad74497cecc1adf866a | refactor(trigger-state): remove deprecation warning | [
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -217,10 +217,13 @@ module.exports = function(RED) {\nconstraint,\neventMessage.event\n);\n+\nconst actualValue = this.utils.selectn(\nconstraint.propertyValue,\nconstraintTarget.state\n);\n+ console.log(constraint.propertyValue, actualValue);\n+\nconst comparatorResult = await this.getComparatorResult(\ncomparatorType,\ncomparatorValue,\n@@ -330,15 +333,10 @@ module.exports = function(RED) {\ntargetData.entityid\n);\n- // TODO: Deprecated, remove at a later date\nif (\n!isTargetThisEntity &&\n- constraint.propertyValue.startsWith('new_state.')\n+ constraint.propertyType === 'current_state'\n) {\n- this.warn(\n- 'DEPRECATED: new_state is no longer needed to access properties of this entity. The ability to do so will be removed in the future',\n- {}\n- );\ntargetData.state = {\nnew_state: targetData.state\n};\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor(trigger-state): remove deprecation warning |
748,234 | 17.08.2019 11:03:04 | 25,200 | 545643c8556cf98e825ef94522f955848aed30f2 | refactor(trigger-state): remove console.log | [
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -222,7 +222,6 @@ module.exports = function(RED) {\nconstraint.propertyValue,\nconstraintTarget.state\n);\n- console.log(constraint.propertyValue, actualValue);\nconst comparatorResult = await this.getComparatorResult(\ncomparatorType,\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor(trigger-state): remove console.log |
748,234 | 17.08.2019 11:06:45 | 25,200 | adfd0dc46fbd4285732d953893bba9c4dbfb4da3 | feat(get-entities): timeSinceChangedMs is not a filterable property
Closes | [
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.js",
"new_path": "nodes/get-entities/get-entities.js",
"diff": "@@ -140,6 +140,9 @@ module.exports = function(RED) {\nentities = await filter(Object.values(states), async entity => {\nconst rules = parsedMessage.rules.value;\n+ entity.timeSinceChangedMs =\n+ Date.now() - new Date(entity.last_changed).getTime();\n+\nfor (const rule of rules) {\nconst value = this.utils.selectn(rule.property, entity);\nconst result = await this.getComparatorResult(\n@@ -160,8 +163,6 @@ module.exports = function(RED) {\n}\n}\n- entity.timeSinceChangedMs =\n- Date.now() - new Date(entity.last_changed).getTime();\nreturn true;\n});\n} catch (e) {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(get-entities): timeSinceChangedMs is not a filterable property
Closes #147 |
748,234 | 22.08.2019 08:39:47 | 25,200 | 91203409707842454d330a45d6979a32933d2149 | ci: Add npm release to master tagged pushes | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -2,9 +2,25 @@ language: node_js\nnode_js:\n- 8\n- 10\n+\n+stages:\n+ - name: test\n+ - name: release\n+ if: (branch = master AND type = push) OR (tag IS present)\n+\n+jobs:\n+ include:\n+ - stage: test\nscript:\n- npm run lint\n- npm run test\nafter_success:\n# Send coverage data to Coveralls\n- nyc npm test && nyc report --reporter=text-lcov | coveralls\n+ - stage: release\n+ node_js: 10\n+ deploy: npm\n+ email: \"$NPM_EMAIL\"\n+ api_key: \"$NPM_TOKEN\"\n+ on:\n+ tags: true\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | ci: Add npm release to master tagged pushes |
748,234 | 22.08.2019 09:02:27 | 25,200 | de1333bcb0076411674cc29b608946ab8eeaeaee | ci: fix travis-ci yaml | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -19,7 +19,8 @@ jobs:\n- nyc npm test && nyc report --reporter=text-lcov | coveralls\n- stage: release\nnode_js: 10\n- deploy: npm\n+ deploy:\n+ provider: npm\nemail: \"$NPM_EMAIL\"\napi_key: \"$NPM_TOKEN\"\non:\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | ci: fix travis-ci yaml |
748,234 | 30.09.2019 18:49:50 | 25,200 | 2990dcb8ed8300d7d312aef0c0ac23ee033dc94b | docs: Removed docker info as no longer needed for NR 1.0 | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -30,8 +30,6 @@ $ npm install node-red-contrib-home-assistant-websocket\n# then restart node-red\n```\n-**Docker users on Rpi** will need to upgrade Node.js inside the [official Node-RED container](https://hub.docker.com/r/nodered/node-red-docker/) or can use the [raymondmm/node-red container](https://hub.docker.com/r/raymondmm/node-red) which comes with Node.js 8.16.0 installed.\n-\nFor [Hass.io](https://hass.io/) add-on users:\nThe Community Hass.io add-on ships with this node right out of the box.\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Removed docker info as no longer needed for NR 1.0 |
748,234 | 10.10.2019 18:31:06 | 25,200 | 989dfb5b03f2fc626012b55f3b99ada731152414 | refactor: Only subscribe to needed events not all
No longer subscribe to all events from HA and only subscribe to
state_changed and events define in events: all nodes.
All events can still be subscribed to but doing so may overload the send
queue in HA.
Closes | [
{
"change_type": "MODIFY",
"old_path": "lib/ha-websocket.js",
"new_path": "lib/ha-websocket.js",
"diff": "@@ -18,6 +18,9 @@ class HaWebsocket extends EventEmitter {\nthis.states = {};\nthis.services = {};\nthis.statesLoaded = false;\n+ this.client = null;\n+ this.subscribedEvents = new Set();\n+ this.unsubEvents = {};\nthis.setMaxListeners(0);\n}\n@@ -49,6 +52,7 @@ class HaWebsocket extends EventEmitter {\nself: this,\ncreateSocket: this.createSocket\n});\n+ this.emit('ha_events:connected');\n} catch (e) {\nthis.connectionState = HaWebsocket.DISCONNECTED;\nthis.emit('ha_events:close');\n@@ -64,8 +68,6 @@ class HaWebsocket extends EventEmitter {\nthis.onClientError.bind(this)\n);\n- this.client.subscribeEvents(ent => this.onClientEvents(ent));\n-\nhomeassistant.subscribeEntities(this.client, ent =>\nthis.onClientStates(ent)\n);\n@@ -76,6 +78,68 @@ class HaWebsocket extends EventEmitter {\nreturn true;\n}\n+ async subscribeEvents(events) {\n+ const currentEvents = new Set(Object.values(events));\n+\n+ if (\n+ currentEvents.has('__ALL__') &&\n+ this.subscribedEvents.has('__ALL__')\n+ ) {\n+ return;\n+ }\n+\n+ // If events contains '__ALL__' register all events and skip individual ones\n+ if (\n+ currentEvents.has('__ALL__') &&\n+ !this.subscribedEvents.has('__ALL__')\n+ ) {\n+ this.subscribedEvents.forEach(e => {\n+ if (e !== '__ALL__') {\n+ this.unsubEvents[e]();\n+ delete this.unsubEvents[e];\n+ }\n+ });\n+\n+ // subscribe to all event and save unsubscribe callback\n+ this.unsubEvents.__ALL__ = await this.client.subscribeEvents(ent =>\n+ this.onClientEvents(ent)\n+ );\n+\n+ this.subscribedEvents.clear();\n+ this.subscribedEvents.add('__ALL__');\n+ return;\n+ }\n+\n+ // Always need the state_changed event\n+ currentEvents.add('state_changed');\n+\n+ const add = new Set(\n+ [...currentEvents].filter(x => !this.subscribedEvents.has(x))\n+ );\n+ const remove = new Set(\n+ [...this.subscribedEvents].filter(x => !currentEvents.has(x))\n+ );\n+ const same = new Set(\n+ [...currentEvents].filter(x => this.subscribedEvents.has(x))\n+ );\n+ // Create new subscribed list\n+ this.subscribedEvents = new Set([...same, ...add]);\n+\n+ // Remove unused subscriptions\n+ remove.forEach(e => {\n+ this.unsubEvents[e]();\n+ delete this.unsubEvents[e];\n+ });\n+\n+ // Subscribe to each selected event type and save each unsubscribe callback\n+ for (const type of add) {\n+ this.unsubEvents[type] = await this.client.subscribeEvents(\n+ ent => this.onClientEvents(ent),\n+ type\n+ );\n+ }\n+ }\n+\nonClientStates(msg) {\nif (!msg || Object.keys(msg).length === 0) {\nreturn;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/node-home-assistant.js",
"new_path": "lib/node-home-assistant.js",
"diff": "@@ -25,6 +25,7 @@ class HomeAssistant {\nthis.config = Object.assign({}, DEFAULTS, config);\nthis.http = new HaHttp(this.config);\nthis.websocket = new HaWebsocket(this.config);\n+ this.registeredEvents = {};\n}\nasync startListening({ includeRegex, excludeRegex } = {}) {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -191,6 +191,10 @@ module.exports = function(RED) {\n'ha_events:services_loaded',\nthis.onHaServicesLoaded.bind(this)\n);\n+ this.websocket.once(\n+ 'ha_events:connected',\n+ this.registerEvents.bind(this)\n+ );\n}\n}\n@@ -269,12 +273,22 @@ module.exports = function(RED) {\nwebSocketClient.close();\n}\n}\n+\n+ registerEvents() {\n+ this.homeAssistant.websocket.subscribeEvents(\n+ this.homeAssistant.registeredEvents\n+ );\n+ }\n}\nRED.nodes.registerType('server', ConfigServerNode, {\ncredentials: {\n- host: { type: 'text' },\n- access_token: { type: 'text' }\n+ host: {\n+ type: 'text'\n+ },\n+ access_token: {\n+ type: 'text'\n+ }\n}\n});\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.html",
"new_path": "nodes/events-all/events-all.html",
"diff": "category: \"home_assistant\",\ncolor: \"#038FC7\",\ndefaults: {\n- name: { value: \"\" },\n- server: { value: \"\", type: \"server\", required: true },\n- event_type: { value: \"\", required: false }\n+ name: {\n+ value: \"\"\n+ },\n+ server: {\n+ value: \"\",\n+ type: \"server\",\n+ required: true\n+ },\n+ event_type: {\n+ value: \"\",\n+ required: false\n+ }\n},\ninputs: 0,\noutputs: 1,\nif (!NODE.server) {\nutils.setDefaultServerSelection();\n}\n+\n+ $(\"#node-input-event_type\").on(\"change paste keyup\", function (e) {\n+ $(\"#eventAlert\").toggle(this.value.length === 0)\n+ }).trigger();\n}\n});\n</script>\n<label for=\"node-input-event_type\"><i class=\"fa fa-tag\"></i> Event Type</label>\n<input type=\"text\" id=\"node-input-event_type\" placeholder=\"leave empty for all events\" />\n</div>\n+\n+ <div id=\"eventAlert\" class=\"ui-state-error\"><p><strong>Alert:</strong> Leaving Event Type empty and listening for all events may overload the websocket message queue.</p></div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-events\">\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.js",
"new_path": "nodes/events-all/events-all.js",
"diff": "@@ -27,6 +27,11 @@ module.exports = function(RED) {\nhandler: this.onClientServicesLoaded.bind(this)\n});\n}\n+\n+ // Registering only needed event types\n+ this.nodeConfig.server.homeAssistant.registeredEvents[this.id] =\n+ this.nodeConfig.event_type || '__ALL__';\n+ this.updateEventList();\n}\nonHaEventsAll(evt) {\n@@ -64,6 +69,17 @@ module.exports = function(RED) {\nthis.clientEvent('services_loaded');\n}\n+ onClose(nodeRemoved) {\n+ super.onClose();\n+\n+ if (nodeRemoved) {\n+ delete this.nodeConfig.server.homeAssistant.registeredEvents[\n+ this.id\n+ ];\n+ this.updateEventList();\n+ }\n+ }\n+\nonHaEventsClose() {\nsuper.onHaEventsClose();\nthis.clientEvent('disconnected');\n@@ -85,6 +101,14 @@ module.exports = function(RED) {\nthis.clientEvent('error', err.message);\n}\n}\n+\n+ updateEventList() {\n+ if (this.isConnected) {\n+ this.websocketClient.subscribeEvents(\n+ this.nodeConfig.server.homeAssistant.registeredEvents\n+ );\n+ }\n+ }\n}\nRED.nodes.registerType('server-events', ServerEventsNode);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.js",
"new_path": "nodes/events-state-changed/events-state-changed.js",
"diff": "@@ -87,6 +87,7 @@ module.exports = function(RED) {\nif (\nrunAll === undefined &&\nthis.nodeConfig.output_only_on_state_change === true &&\n+ event.old_state &&\nevent.old_state.state === event.new_state.state\n) {\nreturn null;\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor: Only subscribe to needed events not all
No longer subscribe to all events from HA and only subscribe to
state_changed and events define in events: all nodes.
All events can still be subscribed to but doing so may overload the send
queue in HA.
Closes #153 |
748,234 | 10.10.2019 19:08:02 | 25,200 | 321561d324c8f460fc81b1093f3a1859013d9d04 | fix: Remove event type from sub list when unsubscribing | [
{
"change_type": "MODIFY",
"old_path": "lib/ha-websocket.js",
"new_path": "lib/ha-websocket.js",
"diff": "@@ -97,6 +97,7 @@ class HaWebsocket extends EventEmitter {\nif (e !== '__ALL__') {\nthis.unsubEvents[e]();\ndelete this.unsubEvents[e];\n+ this.subscribedEvents.delete(e);\n}\n});\n@@ -105,7 +106,6 @@ class HaWebsocket extends EventEmitter {\nthis.onClientEvents(ent)\n);\n- this.subscribedEvents.clear();\nthis.subscribedEvents.add('__ALL__');\nreturn;\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: Remove event type from sub list when unsubscribing |
748,234 | 10.10.2019 19:18:49 | 25,200 | 93615712339822b91b0c973e3657e9b028cd2863 | refactor: eslint fixes/changes | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -23,12 +23,18 @@ const DEFAULT_OPTIONS = {\nconfig: {\ndebugenabled: {},\nname: {},\n- server: { isNode: true },\n+ server: {\n+ isNode: true\n+ },\nversion: nodeDef => nodeDef.version || 0\n},\ninput: {\n- topic: { messageProp: 'topic' },\n- payload: { messageProp: 'payload' }\n+ topic: {\n+ messageProp: 'topic'\n+ },\n+ payload: {\n+ messageProp: 'payload'\n+ }\n}\n};\n@@ -78,7 +84,9 @@ class BaseNode {\nconst adapter = new FileAsync(dbLocation);\nDB = await low(adapter);\n- DB.defaults({ nodes: {} });\n+ DB.defaults({\n+ nodes: {}\n+ });\nreturn DB;\n}\n@@ -139,7 +147,13 @@ class BaseNode {\n}\n}\n- setStatus(opts = { shape: 'dot', fill: 'blue', text: '' }) {\n+ setStatus(\n+ opts = {\n+ shape: 'dot',\n+ fill: 'blue',\n+ text: ''\n+ }\n+ ) {\nthis.node.status(opts);\n}\n@@ -260,12 +274,13 @@ class BaseNode {\nreturn value + '';\ncase 'bool':\nreturn !!value;\n- case 'habool':\n+ case 'habool': {\nconst haBoolean =\nthis.nodeConfig.server.nodeConfig.ha_boolean === undefined\n? `^(y|yes|true|on|home|open)$`\n: `^(${this.nodeConfig.server.nodeConfig.ha_boolean})$`;\nreturn new RegExp(haBoolean, 'i').test(value);\n+ }\ncase 're':\nreturn new RegExp(value);\ncase 'list':\n@@ -357,17 +372,19 @@ class BaseNode {\nswitch (comparatorType) {\ncase 'is':\n- case 'is_not':\n+ case 'is_not': {\n// Datatype might be num, bool, str, re (regular expression)\nconst isMatch =\ncomparatorValueDatatype === 're'\n? cValue.test(actualValue)\n: cValue === actualValue;\nreturn comparatorType === 'is' ? isMatch : !isMatch;\n+ }\ncase 'includes':\n- case 'does_not_include':\n+ case 'does_not_include': {\nconst isIncluded = cValue.includes(actualValue);\nreturn comparatorType === 'includes' ? isIncluded : !isIncluded;\n+ }\ncase 'cont':\nreturn (actualValue + '').indexOf(cValue) !== -1;\ncase 'greater_than': // here for backwards compatibility\n@@ -386,13 +403,14 @@ class BaseNode {\nreturn actualValue <= cValue;\ncase 'starts_with':\nreturn actualValue.startsWith(cValue);\n- case 'in_group':\n+ case 'in_group': {\nconst ent = await this.nodeConfig.server.homeAssistant.getStates(\ncValue\n);\nconst groupEntities =\nselectn('attributes.entity_id', ent) || [];\nreturn groupEntities.includes(actualValue);\n+ }\ncase 'jsonata':\nif (!cValue) return true;\n@@ -470,10 +488,15 @@ const _internals = {\nconst { error, value } = Joi.validate(\nresult.value,\nfieldConfig.validation.schema,\n- { convert: true }\n+ {\n+ convert: true\n+ }\n);\nif (error && fieldConfig.validation.haltOnFail) throw error;\n- result.validation = { error, value };\n+ result.validation = {\n+ error,\n+ value\n+ };\n}\n// Assign result to config key value\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/get-entities/get-entities.js",
"new_path": "nodes/get-entities/get-entities.js",
"diff": "@@ -7,7 +7,9 @@ module.exports = function(RED) {\nconst nodeOptions = {\ndebug: true,\nconfig: {\n- server: { isNode: true },\n+ server: {\n+ isNode: true\n+ },\nname: {},\nrules: {},\noutput_type: {},\n@@ -132,7 +134,9 @@ module.exports = function(RED) {\nthis.node.warn(\n'local state cache missing sending empty payload'\n);\n- return { payload: {} };\n+ return {\n+ payload: {}\n+ };\n}\nlet entities;\n@@ -187,7 +191,7 @@ module.exports = function(RED) {\nthis.setStatusSuccess(statusText);\nthis.sendSplit(message, entities);\nreturn;\n- case 'random':\n+ case 'random': {\nif (entities.length === 0) {\nnoPayload = true;\nbreak;\n@@ -208,6 +212,7 @@ module.exports = function(RED) {\nmaxReturned === 1 ? 1 : payload.length\n} Random`;\nbreak;\n+ }\ncase 'array':\ndefault:\nif (\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor: eslint fixes/changes |
748,234 | 14.10.2019 16:57:07 | 25,200 | d7d1b8c4b45efe3050009e75e70305468e35408f | refactor: Cleaned up event subscribing | [
{
"change_type": "MODIFY",
"old_path": "lib/ha-websocket.js",
"new_path": "lib/ha-websocket.js",
"diff": "@@ -20,7 +20,7 @@ class HaWebsocket extends EventEmitter {\nthis.statesLoaded = false;\nthis.client = null;\nthis.subscribedEvents = new Set();\n- this.unsubEvents = {};\n+ this.unsubCallback = {};\nthis.setMaxListeners(0);\n}\n@@ -81,29 +81,24 @@ class HaWebsocket extends EventEmitter {\nasync subscribeEvents(events) {\nconst currentEvents = new Set(Object.values(events));\n- if (\n- currentEvents.has('__ALL__') &&\n- this.subscribedEvents.has('__ALL__')\n- ) {\n+ // If events contains '__ALL__' register all events and skip individual ones\n+ if (currentEvents.has('__ALL__')) {\n+ if (this.subscribedEvents.has('__ALL__')) {\n+ // Nothing to do\nreturn;\n}\n- // If events contains '__ALL__' register all events and skip individual ones\n- if (\n- currentEvents.has('__ALL__') &&\n- !this.subscribedEvents.has('__ALL__')\n- ) {\nthis.subscribedEvents.forEach(e => {\nif (e !== '__ALL__') {\n- this.unsubEvents[e]();\n- delete this.unsubEvents[e];\n+ this.unsubCallback[e]();\n+ delete this.unsubCallback[e];\nthis.subscribedEvents.delete(e);\n}\n});\n// subscribe to all event and save unsubscribe callback\n- this.unsubEvents.__ALL__ = await this.client.subscribeEvents(ent =>\n- this.onClientEvents(ent)\n+ this.unsubCallback.__ALL__ = await this.client.subscribeEvents(\n+ ent => this.onClientEvents(ent)\n);\nthis.subscribedEvents.add('__ALL__');\n@@ -119,21 +114,22 @@ class HaWebsocket extends EventEmitter {\nconst remove = new Set(\n[...this.subscribedEvents].filter(x => !currentEvents.has(x))\n);\n- const same = new Set(\n- [...currentEvents].filter(x => this.subscribedEvents.has(x))\n- );\n- // Create new subscribed list\n- this.subscribedEvents = new Set([...same, ...add]);\n+\n+ // Create new subscription list\n+ this.subscribedEvents = new Set([\n+ ...[...currentEvents].filter(x => this.subscribedEvents.has(x)),\n+ ...add\n+ ]);\n// Remove unused subscriptions\nremove.forEach(e => {\n- this.unsubEvents[e]();\n- delete this.unsubEvents[e];\n+ this.unsubCallback[e]();\n+ delete this.unsubCallback[e];\n});\n- // Subscribe to each selected event type and save each unsubscribe callback\n+ // Subscribe to each event type and save each unsubscribe callback\nfor (const type of add) {\n- this.unsubEvents[type] = await this.client.subscribeEvents(\n+ this.unsubCallback[type] = await this.client.subscribeEvents(\nent => this.onClientEvents(ent),\ntype\n);\n"
},
{
"change_type": "RENAME",
"old_path": "lib/node-home-assistant.js",
"new_path": "lib/home-assistant.js",
"diff": "@@ -25,7 +25,7 @@ class HomeAssistant {\nthis.config = Object.assign({}, DEFAULTS, config);\nthis.http = new HaHttp(this.config);\nthis.websocket = new HaWebsocket(this.config);\n- this.registeredEvents = {};\n+ this.eventsList = {};\n}\nasync startListening({ includeRegex, excludeRegex } = {}) {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.css",
"new_path": "nodes/_static/common.css",
"diff": "@@ -49,3 +49,8 @@ li span.property-type {\nfont-size: 11px;\nfloat: right;\n}\n+\n+.ha-alertbox {\n+ padding: 10px;\n+ margin-bottom: 10px;\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.js",
"new_path": "nodes/_static/common.js",
"diff": "@@ -22,7 +22,7 @@ var nodeVersion = (function($) {\nfunction check(node) {\nnode.version = node.version === undefined ? 0 : Number(node.version);\n- const versionAlert = `<div id=\"versionUpdate\" class=\"ui-state-error\"><p><strong>Alert:</strong>This node will be updated to version ${\n+ const versionAlert = `<div id=\"versionUpdate\" class=\"ui-state-error ha-alertbox\"><p><strong>Alert:</strong>This node will be updated to version ${\nnode._def.defaults.version.value\n} from ${node.version} (<a href=\"${wikiLink(\nnode.type\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -3,7 +3,7 @@ const flatten = require('flat');\nconst uniq = require('lodash.uniq');\nmodule.exports = function(RED) {\n- const HomeAssistant = require('../../lib/node-home-assistant');\n+ const HomeAssistant = require('../../lib/home-assistant');\n// Handle static files\nRED.httpAdmin.get('/homeassistant/static/*', function(req, res, next) {\n@@ -276,7 +276,7 @@ module.exports = function(RED) {\nregisterEvents() {\nthis.homeAssistant.websocket.subscribeEvents(\n- this.homeAssistant.registeredEvents\n+ this.homeAssistant.eventsList\n);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.html",
"new_path": "nodes/events-all/events-all.html",
"diff": "<input type=\"text\" id=\"node-input-event_type\" placeholder=\"leave empty for all events\" />\n</div>\n- <div id=\"eventAlert\" class=\"ui-state-error\"><p><strong>Alert:</strong> Leaving Event Type empty and listening for all events may overload the websocket message queue.</p></div>\n+ <div id=\"eventAlert\" class=\"ui-state-error ha-alertbox\"><strong>Alert:</strong> Leaving Event Type empty and listening for all events may overload the websocket message queue.</div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-events\">\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.js",
"new_path": "nodes/events-all/events-all.js",
"diff": "@@ -29,7 +29,7 @@ module.exports = function(RED) {\n}\n// Registering only needed event types\n- this.nodeConfig.server.homeAssistant.registeredEvents[this.id] =\n+ this.nodeConfig.server.homeAssistant.eventsList[this.id] =\nthis.nodeConfig.event_type || '__ALL__';\nthis.updateEventList();\n}\n@@ -73,9 +73,7 @@ module.exports = function(RED) {\nsuper.onClose();\nif (nodeRemoved) {\n- delete this.nodeConfig.server.homeAssistant.registeredEvents[\n- this.id\n- ];\n+ delete this.nodeConfig.server.homeAssistant.eventsList[this.id];\nthis.updateEventList();\n}\n}\n@@ -105,7 +103,7 @@ module.exports = function(RED) {\nupdateEventList() {\nif (this.isConnected) {\nthis.websocketClient.subscribeEvents(\n- this.nodeConfig.server.homeAssistant.registeredEvents\n+ this.nodeConfig.server.homeAssistant.eventsList\n);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor: Cleaned up event subscribing |
748,234 | 14.10.2019 22:12:40 | 25,200 | 41539d7df918f8e7356fa6e6a248ffe255137a46 | fix: css changed for NR v1.0 | [
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.css",
"new_path": "nodes/_static/common.css",
"diff": "margin-top: 5px;\n}\n-.checkboxOption input {\n+.form-row.checkboxOption input {\nmargin-left: 105px;\ndisplay: inline-block;\nwidth: auto;\nvertical-align: baseline;\n}\n-.checkboxOption label {\n+.form-row.checkboxOption label {\nwidth: auto;\nmargin-right: 20px;\n}\n-.node_label_legacy {\n+.ha-nodeLabelLegacy {\nfill: #fdfd96;\nstroke-width: 0;\nfont-size: 14px;\n@@ -50,7 +50,7 @@ li span.property-type {\nfloat: right;\n}\n-.ha-alertbox {\n+.ha-alertBox {\npadding: 10px;\nmargin-bottom: 10px;\n}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/_static/common.js",
"new_path": "nodes/_static/common.js",
"diff": "@@ -22,7 +22,7 @@ var nodeVersion = (function($) {\nfunction check(node) {\nnode.version = node.version === undefined ? 0 : Number(node.version);\n- const versionAlert = `<div id=\"versionUpdate\" class=\"ui-state-error ha-alertbox\"><p><strong>Alert:</strong>This node will be updated to version ${\n+ const versionAlert = `<div id=\"versionUpdate\" class=\"ui-state-error ha-alertBox\"><p><strong>Alert:</strong>This node will be updated to version ${\nnode._def.defaults.version.value\n} from ${node.version} (<a href=\"${wikiLink(\nnode.type\n@@ -55,7 +55,7 @@ var nodeVersion = (function($) {\nreturn `${\nthis._def.defaults.version &&\nNumber(this.version) !== this._def.defaults.version.value\n- ? 'node_label_legacy '\n+ ? 'ha-nodeLabelLegacy '\n: ''\n}${this.name ? 'node_label_italic' : ''}`;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.html",
"new_path": "nodes/events-all/events-all.html",
"diff": "<input type=\"text\" id=\"node-input-event_type\" placeholder=\"leave empty for all events\" />\n</div>\n- <div id=\"eventAlert\" class=\"ui-state-error ha-alertbox\"><strong>Alert:</strong> Leaving Event Type empty and listening for all events may overload the websocket message queue.</div>\n+ <div id=\"eventAlert\" class=\"ui-state-error ha-alertBox\"><strong>Alert:</strong> Leaving Event Type empty and listening for all events may overload the websocket message queue.</div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-events\">\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: css changed for NR v1.0 |
748,234 | 15.10.2019 03:22:15 | 25,200 | 6b687bb96c1c173433f5e3e66637c8fc015b0c79 | refactor: Changed prefix of client event to 'ha_client' | [
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -5,7 +5,9 @@ const DEFAULT_NODE_OPTIONS = {\ndebug: false,\nconfig: {\nname: {},\n- server: { isNode: true }\n+ server: {\n+ isNode: true\n+ }\n}\n};\n@@ -16,19 +18,19 @@ class EventsNode extends BaseNode {\nthis.listeners = {};\nthis.addEventClientListener({\n- event: 'ha_events:close',\n+ event: 'ha_client:close',\nhandler: this.onHaEventsClose.bind(this)\n});\nthis.addEventClientListener({\n- event: 'ha_events:open',\n+ event: 'ha_client:open',\nhandler: this.onHaEventsOpen.bind(this)\n});\nthis.addEventClientListener({\n- event: 'ha_events:error',\n+ event: 'ha_client:error',\nhandler: this.onHaEventsError.bind(this)\n});\nthis.addEventClientListener({\n- event: 'ha_events:connecting',\n+ event: 'ha_client:connecting',\nhandler: this.onHaEventsConnecting.bind(this)\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/ha-websocket.js",
"new_path": "lib/ha-websocket.js",
"diff": "@@ -52,10 +52,10 @@ class HaWebsocket extends EventEmitter {\nself: this,\ncreateSocket: this.createSocket\n});\n- this.emit('ha_events:connected');\n+ this.emit('ha_client:connected');\n} catch (e) {\nthis.connectionState = HaWebsocket.DISCONNECTED;\n- this.emit('ha_events:close');\n+ this.emit('ha_client:close');\nreturn false;\n}\n@@ -145,7 +145,7 @@ class HaWebsocket extends EventEmitter {\nif (!this.statesLoaded) {\nthis.statesLoaded = true;\n- this.emit('ha_events:states_loaded', this.states);\n+ this.emit('ha_client:states_loaded', this.states);\n}\n}\n@@ -158,7 +158,7 @@ class HaWebsocket extends EventEmitter {\nif (!this.servicesLoaded) {\nthis.servicesLoaded = true;\n- this.emit('ha_events:services_loaded', this.services);\n+ this.emit('ha_client:services_loaded', this.services);\n}\n}\n@@ -236,7 +236,7 @@ class HaWebsocket extends EventEmitter {\n}\nif (err) {\ndebug(err);\n- this.emit('ha_events:error', err);\n+ this.emit('ha_client:error', err);\n}\nthis.servicesLoaded = false;\n@@ -244,7 +244,7 @@ class HaWebsocket extends EventEmitter {\nif (this.client && this.client.readyState === this.client.CLOSED) {\nthis.connectionState = HaWebsocket.DISCONNECTED;\n- this.emit('ha_events:close');\n+ this.emit('ha_client:close');\n}\n}\n@@ -308,7 +308,7 @@ class HaWebsocket extends EventEmitter {\nfunction connect(promResolve, promReject) {\ndebug('[Auth Phase] New connection', url);\nself.connectionState = self.CONNECTING;\n- self.emit('ha_events:connecting');\n+ self.emit('ha_client:connecting');\nconst socket = new WebSocket(url, {\nrejectUnauthorized: self.config.rejectUnauthorizedCerts\n@@ -339,7 +339,7 @@ class HaWebsocket extends EventEmitter {\ncase MSG_TYPE_AUTH_OK:\nself.connectionState = self.CONNECTED;\n- self.emit('ha_events:open');\n+ self.emit('ha_client:open');\nsocket.removeEventListener('open', onOpen);\nsocket.removeEventListener('message', onMessage);\n@@ -357,7 +357,7 @@ class HaWebsocket extends EventEmitter {\nconst onClose = () => {\nself.connectionState = self.DISCONNECTED;\n- self.emit('ha_events:close');\n+ self.emit('ha_client:close');\n// If we are in error handler make sure close handler doesn't also fire.\nsocket.removeEventListener('close', onClose);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -164,35 +164,35 @@ module.exports = function(RED) {\n.catch(err => this.node.error(err));\nthis.websocket.addListener(\n- 'ha_events:close',\n+ 'ha_client:close',\nthis.onHaEventsClose.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:open',\n+ 'ha_client:open',\nthis.onHaEventsOpen.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:connecting',\n+ 'ha_client:connecting',\nthis.onHaEventsConnecting.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:error',\n+ 'ha_client:error',\nthis.onHaEventsError.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:state_changed',\n+ 'ha_client:state_changed',\nthis.onHaStateChanged.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:states_loaded',\n+ 'ha_client:states_loaded',\nthis.onHaStatesLoaded.bind(this)\n);\nthis.websocket.addListener(\n- 'ha_events:services_loaded',\n+ 'ha_client:services_loaded',\nthis.onHaServicesLoaded.bind(this)\n);\nthis.websocket.once(\n- 'ha_events:connected',\n+ 'ha_client:connected',\nthis.registerEvents.bind(this)\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-all/events-all.js",
"new_path": "nodes/events-all/events-all.js",
"diff": "@@ -19,11 +19,11 @@ module.exports = function(RED) {\nthis.nodeConfig.event_type === 'home_assistant_client'\n) {\nthis.addEventClientListener({\n- event: 'ha_events:states_loaded',\n+ event: 'ha_client:states_loaded',\nhandler: this.onClientStatesLoaded.bind(this)\n});\nthis.addEventClientListener({\n- event: 'ha_events:services_loaded',\n+ event: 'ha_client:services_loaded',\nhandler: this.onClientServicesLoaded.bind(this)\n});\n}\n@@ -61,14 +61,6 @@ module.exports = function(RED) {\n}\n}\n- onClientStatesLoaded() {\n- this.clientEvent('states_loaded');\n- }\n-\n- onClientServicesLoaded() {\n- this.clientEvent('services_loaded');\n- }\n-\nonClose(nodeRemoved) {\nsuper.onClose();\n@@ -100,6 +92,14 @@ module.exports = function(RED) {\n}\n}\n+ onClientStatesLoaded() {\n+ this.clientEvent('states_loaded');\n+ }\n+\n+ onClientServicesLoaded() {\n+ this.clientEvent('services_loaded');\n+ }\n+\nupdateEventList() {\nif (this.isConnected) {\nthis.websocketClient.subscribeEvents(\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.js",
"new_path": "nodes/events-state-changed/events-state-changed.js",
"diff": "@@ -45,7 +45,7 @@ module.exports = function(RED) {\nthis.onDeploy();\n} else {\nthis.addEventClientListener({\n- event: 'ha_events:states_loaded',\n+ event: 'ha_client:states_loaded',\nhandler: this.onStatesLoaded.bind(this)\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/poll-state/poll-state.js",
"new_path": "nodes/poll-state/poll-state.js",
"diff": "@@ -59,7 +59,7 @@ module.exports = function(RED) {\nif (this.nodeConfig.outputinitially) {\nthis.addEventClientListener({\n- event: 'ha_events:states_loaded',\n+ event: 'ha_client:states_loaded',\nhandler: this.onTimer.bind(this)\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -22,7 +22,9 @@ module.exports = function(RED) {\nconstraints: {},\ncustomoutputs: {},\noutputinitially: {},\n- state_type: { value: 'str' }\n+ state_type: {\n+ value: 'str'\n+ }\n}\n};\n@@ -51,7 +53,7 @@ module.exports = function(RED) {\nthis.onDeploy();\n} else {\nthis.addEventClientListener({\n- event: 'ha_events:states_loaded',\n+ event: 'ha_client:states_loaded',\nhandler: this.onStatesLoaded.bind(this)\n});\n}\n@@ -318,7 +320,10 @@ module.exports = function(RED) {\n}\nasync getConstraintTargetData(constraint, triggerEvent) {\n- const targetData = { entityid: null, state: null };\n+ const targetData = {\n+ entityid: null,\n+ state: null\n+ };\ntry {\nconst isTargetThisEntity =\nconstraint.targetType === 'this_entity';\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor: Changed prefix of client event to 'ha_client' |
748,234 | 17.10.2019 04:20:21 | 25,200 | 873603b29778c824bd3f8b2c72b80964efd440bf | feat(call-service): Add debug flag for more information | [
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.html",
"new_path": "nodes/call-service/call-service.html",
"diff": "},\nlabelStyle: nodeVersion.labelStyle,\ndefaults: {\n- name: { value: \"\" },\n- server: { value: \"\", type: \"server\", required: true },\n- version: { value: 1 },\n- service_domain: { value: \"\" },\n- service: { value: \"\" },\n- entityId: { value: \"\" },\n- data: { value: \"\" },\n- dataType: { value: \"json\" },\n- mergecontext: { value: null },\n- output_location: { value: \"payload\" },\n- output_location_type: { value: \"none\" },\n- mustacheAltTags: { value: false }\n+ name: {\n+ value: \"\"\n+ },\n+ server: {\n+ value: \"\",\n+ type: \"server\",\n+ required: true\n+ },\n+ version: {\n+ value: 1\n+ },\n+ debugenabled: {\n+ value: false\n+ },\n+ service_domain: {\n+ value: \"\"\n+ },\n+ service: {\n+ value: \"\"\n+ },\n+ entityId: {\n+ value: \"\"\n+ },\n+ data: {\n+ value: \"\"\n+ },\n+ dataType: {\n+ value: \"json\"\n+ },\n+ mergecontext: {\n+ value: null\n+ },\n+ output_location: {\n+ value: \"payload\"\n+ },\n+ output_location_type: {\n+ value: \"none\"\n+ },\n+ mustacheAltTags: {\n+ value: false\n+ }\n},\noneditprepare: function () {\nnodeVersion.check(this);\nfunction split(val) {\nreturn val.split(/,\\s*/);\n}\n+\nfunction extractLast(term) {\nreturn split(term).pop();\n}\n$domainField\n.autocomplete({\nsource: node.allDomains,\n- create: (evt, ui) => updateDomainSelection({ event: evt }),\n- change: (evt, ui) => updateDomainSelection({ event: evt }),\n- select: (evt, ui) => updateDomainSelection({ event: evt }),\n+ create: (evt, ui) => updateDomainSelection({\n+ event: evt\n+ }),\n+ change: (evt, ui) => updateDomainSelection({\n+ event: evt\n+ }),\n+ select: (evt, ui) => updateDomainSelection({\n+ event: evt\n+ }),\nminLength: 0\n})\n.focus(function () {\n$domainField.autocomplete(\"search\");\n});\n- updateDomainSelection({ domainText: node.service_domain || \"\" });\n- updateServiceSelection({ serviceText: node.service || \"\" });\n+ updateDomainSelection({\n+ domainText: node.service_domain || \"\"\n+ });\n+ updateServiceSelection({\n+ serviceText: node.service || \"\"\n+ });\nreturn node;\n});\n- function updateServiceSelection({ event, serviceText }) {\n+ function updateServiceSelection({\n+ event,\n+ serviceText\n+ }) {\nlet selectedServiceText = serviceText;\nif (!selectedServiceText && event) {\nselectedServiceText = $(event.target).val();\nnode.selectedDomain.services[selectedServiceText];\n// If a known service\nif (node.selectedService) {\n- const serviceDesc = node.selectedService.description\n- ? node.selectedService.description\n- : \"No description provided by home assistant\";\n+ const serviceDesc = node.selectedService.description ?\n+ node.selectedService.description :\n+ \"No description provided by home assistant\";\nconst fields = node.selectedService.fields;\nlet tableRows = Object.keys(fields).reduce((tRows, k) => {\n}\n}\n- function updateDomainSelection({ event, domainText }) {\n+ function updateDomainSelection({\n+ event,\n+ domainText\n+ }) {\nlet selectedDomainText = domainText;\nif (!selectedDomainText && event) {\nselectedDomainText = $(event.target).val();\n}\nconst knownDomain = node.allDomains.indexOf(selectedDomainText) > -1;\n- node.selectedDomain = knownDomain\n- ? {\n+ node.selectedDomain = knownDomain ? {\nservices: node.allServices[selectedDomainText],\nname: selectedDomainText\n- }\n- : (node.selectedDomain = { services: {} });\n+ } :\n+ (node.selectedDomain = {\n+ services: {}\n+ });\n$serviceField\n.autocomplete({\nsource: Object.keys(node.selectedDomain.services).sort(),\n- create: (evt, ui) => updateServiceSelection({ event: evt }),\n- change: (evt, ui) => updateServiceSelection({ event: evt }),\n- select: (evt, ui) => updateServiceSelection({ event: evt }),\n- focus: (evt, ui) => updateServiceSelection({ event: evt }),\n+ create: (evt, ui) => updateServiceSelection({\n+ event: evt\n+ }),\n+ change: (evt, ui) => updateServiceSelection({\n+ event: evt\n+ }),\n+ select: (evt, ui) => updateServiceSelection({\n+ event: evt\n+ }),\n+ focus: (evt, ui) => updateServiceSelection({\n+ event: evt\n+ }),\nminLength: 0\n})\n.focus(function () {\n\"msg\",\n\"flow\",\n\"global\",\n- { value: \"none\", label: \"None\", hasValue: false }\n+ {\n+ value: \"none\",\n+ label: \"None\",\n+ hasValue: false\n+ }\n],\ntypeField: \"#node-input-output_location_type\"\n})\n</table>\n</div>\n</div>\n+\n+ <div class=\"form-row\">\n+ <input type=\"checkbox\" id=\"node-input-debugenabled\" style=\"display: inline-block; width: auto; vertical-align: top;\" />\n+ <label for=\"node-input-debugenabled\" style=\"width: auto;\">Show Debug Information</label>\n+ </div>\n+\n</script>\n<script type=\"text/x-red\" data-help-name=\"api-call-service\">\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/call-service/call-service.js",
"new_path": "nodes/call-service/call-service.js",
"diff": "@@ -13,7 +13,9 @@ module.exports = function(RED) {\ndataType: nodeDef => nodeDef.dataType || 'json',\nmergecontext: {},\nname: {},\n- server: { isNode: true },\n+ server: {\n+ isNode: true\n+ },\noutput_location: {},\noutput_location_type: {},\nmustacheAltTags: {}\n@@ -147,6 +149,12 @@ module.exports = function(RED) {\nthis.setStatusSending();\n+ this.debugToClient({\n+ domain: apiDomain,\n+ service: apiService,\n+ data: apiData\n+ });\n+\nreturn this.websocketClient\n.callService(apiDomain, apiService, apiData)\n.then(() => {\n@@ -167,7 +175,6 @@ module.exports = function(RED) {\n}`,\nmessage\n);\n-\nthis.setStatusFailed('API Error');\n});\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | feat(call-service): Add debug flag for more information |
748,261 | 21.11.2019 23:22:10 | 18,000 | a5a5e62e1e2caf7603cd4da473f76ece8159421c | docs: Update events-state-changed.html
Previous help included "Output Initially" which is no longer available. This update reflect current options. I also removed the language "on each interval" which does not seem applicable, but please check.
Cheers, Richard | [
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.html",
"new_path": "nodes/events-state-changed/events-state-changed.html",
"diff": "<dt>State Type<span class=\"property-type\">string</span></dt>\n<dd>Convert the state of the entity to the selected type. Boolean will be convert to true based on if the string is equal by default to (y|yes|true|on|home|open). Original value stored in msg.data.original_state</dd>\n- <dt>Output Initially<span class=\"property-type\">boolean</span></dt>\n- <dd>Output once on startup/deploy then on each interval</dd>\n+ <dt>Output only on state change<span class=\"property-type\">boolean</span></dt>\n+ <dd>Output only when state has changed and not on startup/deploy</dd>\n+\n+ <dt>Output on Connect<span class=\"property-type\">boolean</span></dt>\n+ <dd>Output once on startup/deploy</dd>\n+\n</dl>\n<h3>Output Object:</h3>\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Update events-state-changed.html (#166)
Previous help included "Output Initially" which is no longer available. This update reflect current options. I also removed the language "on each interval" which does not seem applicable, but please check.
Cheers, Richard |
748,242 | 02.01.2020 02:44:19 | 0 | b7047192703de707e8b5c2f4782abcd872059697 | docs: [Auto Commit] Convert markdown docs to Node-RED help files | [
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.html",
"new_path": "nodes/config-server/config-server.html",
"diff": "<p>Home Assistant connection configuration</p>\n<h3>Config</h3>\n<dl class=\"message-properties\">\n- <dt>Name<span class=\"property-type\"></span></dt>\n+ <dt>Name<span class=\"property-type\">string</span></dt>\n<dd>Label for this configuration, see details below for implications</dd>\n- <dt>Hass.io<span class=\"property-type\"></span></dt>\n+ <dt>Hass.io<span class=\"property-type\">boolean</span></dt>\n<dd>\nIf you're running Node-RED as a Hass.io Add-on check this. No other\ninformation is needed.\n</dd>\n- <dt>Base URL<span class=\"property-type\"></span></dt>\n+ <dt>Base URL<span class=\"property-type\">string</span></dt>\n<dd>\nThe base URL and port the home assistant instance can be reached at, for\nexample: <code>http://192.168.0.100:8123</code> or\n<code>https://homeassistant.mysite.com</code>\n</dd>\n- <dt>Access Token / Password<span class=\"property-type\"></span></dt>\n+ <dt>Access Token / Password<span class=\"property-type\">string</span></dt>\n<dd>Long-lived Access Token or Password used to contact the API</dd>\n- <dt>Legacy Password<span class=\"property-type\"></span></dt>\n+ <dt>Legacy Password<span class=\"property-type\">boolean</span></dt>\n<dd>\nIf you're using the legacy password to log into Home Assistant\ncheck this and enter your password in the password text box.\n</dd>\n- <dt>Unauthorized SSL Certificates<span class=\"property-type\"></span></dt>\n+ <dt>\n+ Unauthorized SSL Certificates<span class=\"property-type\">boolean</span>\n+ </dt>\n<dd>\nThis will allow you to use self-signed certificates. Only use this if\nyou know what you're doing.\n</dd>\n- <dt>State Boolean<span class=\"property-type\"></span></dt>\n+ <dt>\n+ State Boolean<span class=\"property-type\">string | delimited</span>\n+ </dt>\n<dd>\nA list of strings, not case sensitive, delimited by vertical pipe, |,\nthat will return true for State Type Boolean.\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: [Auto Commit] Convert markdown docs to Node-RED help files |
748,233 | 02.04.2020 16:42:40 | 21,600 | 5aa5b71e945ba6e3fd16063511d47e2fcbc31b7e | fix: "NaN" for events-state-changed | [
{
"change_type": "MODIFY",
"old_path": "nodes/events-state-changed/events-state-changed.js",
"new_path": "nodes/events-state-changed/events-state-changed.js",
"diff": "@@ -49,7 +49,7 @@ module.exports = function (RED) {\nif (this.isEnabled === false) {\nreturn;\n}\n- const { entity_id, event } = { ...evt };\n+ const { entity_id, event } = JSON.parse(JSON.stringify(evt));\nif (!event.new_state) {\nreturn null;\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: "NaN" for events-state-changed |
748,249 | 17.10.2020 12:49:20 | 18,000 | cf9d858ed0e4fd8ecb895d579e4c7b0fdf82a100 | docs: Correct REST and Websocket API links | [
{
"change_type": "MODIFY",
"old_path": "docs/node/API.md",
"new_path": "docs/node/API.md",
"diff": "@@ -94,5 +94,5 @@ Will output the results received from the API call to the location defined in th\n## References\n-- [http api](https://developers.home-assistant.io/docs/en/external_api_rest.html)\n-- [websocket api](https://developers.home-assistant.io/docs/en/external_api_websocket.html)\n+- [http api](https://developers.home-assistant.io/docs/api/rest)\n+- [websocket api](https://developers.home-assistant.io/docs/api/websocket)\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Correct REST and Websocket API links (#280) |
748,236 | 04.01.2021 11:42:32 | 25,200 | 9fe6023e4babd2f7d5761b3df3178604f62f28c8 | docs: Update README.md
Fixed minor spelling error | [
{
"change_type": "MODIFY",
"old_path": "docs/cookbook/README.md",
"new_path": "docs/cookbook/README.md",
"diff": "@@ -13,7 +13,7 @@ further educate yourself in the world of Home Automation with Node-RED.\n- [Expiration Date Monitor](./expiration-date-monitor.md)\n- [Using date and time entities to trigger flows](./using-date-and-time-entities-to-trigger-flows.md)\n- [Check if an entity was a certain state in the last 24 hours](./check-if-an-entity-was-turned-on-in-the-last-24-hours.md)\n-- [Starting flow after Home Assistant reestart](./starting-flow-after-home-assistant-restart.md)\n+- [Starting flow after Home Assistant restart](./starting-flow-after-home-assistant-restart.md)\n- [Holiday lights scheduler and demo mode for WLED](./holiday-lights-scheduler-and-demo-mode-for-wled.md)\n- [Actionable Notifications Subflow for Android](./actionable-notifications-subflow-for-android.md)\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Update README.md (#325)
Fixed minor spelling error |
748,237 | 21.09.2022 22:34:46 | -3,600 | 7e22233b01dfed5c35ed6008f4711754752ab4a7 | fix: Trigger Node Custom Output Comparators
* fix: Trigger Node Custom Output Comparators
Updates the select_option values to match the labels, aligns the lists
with 'Conditions' options
* formatting | [
{
"change_type": "MODIFY",
"old_path": "src/nodes/trigger-state/editor.html",
"new_path": "src/nodes/trigger-state/editor.html",
"diff": "<option\nvalue=\">\"\n- data-i18n=\"home-assistant.label.select_option.less_than\"\n+ data-i18n=\"home-assistant.label.select_option.greater_than\"\n></option>\n<option\nvalue=\">=\"\n- data-i18n=\"home-assistant.label.select_option.less_than_equal\"\n+ data-i18n=\"home-assistant.label.select_option.greater_than_equal\"\n></option>\n<option\nvalue=\"<\"\n- data-i18n=\"home-assistant.label.select_option.greater_than\"\n+ data-i18n=\"home-assistant.label.select_option.less_than\"\n></option>\n<option\nvalue=\"<=\"\n- data-i18n=\"home-assistant.label.select_option.greater_than_equal\"\n+ data-i18n=\"home-assistant.label.select_option.less_than_equal\"\n></option>\n<option\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix: Trigger Node Custom Output Comparators #580 (#665)
* fix: Trigger Node Custom Output Comparators #580
Updates the select_option values to match the labels, aligns the lists
with 'Conditions' options
* formatting
Co-authored-by: Jason <[email protected]> |
748,252 | 11.10.2022 03:48:22 | -7,200 | 60a9bb9d6862b58f7c73b8cf296ad18dc22092a7 | docs: change url for device-config.md | [
{
"change_type": "MODIFY",
"old_path": "docs/node/entity-config.md",
"new_path": "docs/node/entity-config.md",
"diff": "@@ -13,7 +13,7 @@ The name of the entity that will show in Node-RED\n### Device\n- Type: `string`\n-- [device config documentation](./device-config.md)\n+- [device config documentation](/node/device-config.md)\nA list of devices the entity can be associated with. This is used to group entities together in the UI.\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: change url for device-config.md (#697) |
748,254 | 12.10.2022 06:25:41 | -7,200 | 46ee50fd16de171247d8ca69dd44d696365d0269 | docs: Fix JSONata Example links
* Removal of Example links
Example links point to not existing sites
* fix links | [
{
"change_type": "MODIFY",
"old_path": "docs/guide/jsonata.md",
"new_path": "docs/guide/jsonata.md",
"diff": "@@ -25,11 +25,9 @@ When it is chosen with a conditional, not JSONata it will return a value of the\n\n-## Examples\n-\n-- [Increase lights brightness with remote](/cookbook/jsonata.html#increase-lights-brightness-with-remote)\n-- [Notification of lights left on when leaving home](/cookbook/jsonata.html#notification-of-lights-left-on-when-leaving-home)\n-- [OR conditional for the events: state node](/cookbook/jsonata.html#or-conditional-for-the-events-state-node)\n+- [Increase lights brightness with remote](../cookbook/jsonata.html#increase-lights-brightness-with-remote)\n+- [Notification of lights left on when leaving home](../cookbook/jsonata.html#notification-of-lights-left-on-when-leaving-home)\n+- [OR conditional for the events: state node](../cookbook/jsonata.html#or-conditional-for-the-events-state-node)\n**Also see:**\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | docs: Fix JSONata Example links (#666)
* Removal of Example links
Example links point to not existing sites
* fix links
Co-authored-by: Jason <[email protected]> |
748,253 | 25.01.2023 07:24:25 | -36,000 | 3e5a25d55566b58b217d82102aa9b61ffd354e9e | Push nodered json/jsonata params to Http Api as an object instead of a string. | [
{
"change_type": "MODIFY",
"old_path": "src/nodes/api/controller.js",
"new_path": "src/nodes/api/controller.js",
"diff": "@@ -109,22 +109,24 @@ class Api extends BaseNode {\nlet data;\nif (parsedMessage.dataType.value === 'jsonata') {\ntry {\n- data = JSON.stringify(\n- this.evaluateJSONata(parsedMessage.data.value, { message })\n- );\n+ data = this.evaluateJSONata(parsedMessage.data.value, {\n+ message,\n+ });\n} catch (e) {\nthis.status.setFailed('Error');\ndone(e.message);\nreturn;\n}\n} else {\n- data = renderTemplate(\n+ data = JSON.parse(\n+ renderTemplate(\ntypeof parsedMessage.data.value === 'object'\n? JSON.stringify(parsedMessage.data.value)\n: parsedMessage.data.value,\nmessage,\nthis.node.context(),\nthis.homeAssistant.getStates()\n+ )\n);\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Push nodered json/jsonata params to Http Api as an object instead of a string. (#828) |
259,992 | 28.04.2018 11:12:01 | 25,200 | 54a20025b15795bf3d6bd2435b8e83dbbca55a64 | Fix center alignment
github markdown doesn't like {style} tags. Also moved the image after their respective section. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -35,9 +35,6 @@ made available to a container.\nTwo other approaches are commonly taken to provide stronger isolation than\nnative containers.\n-{style=\"display:block;margin:auto\"}\n-\n**Machine-level virtualization**, such as [KVM][kvm] and [Xen][xen], exposes\nvirtualized hardware to a guest kernel via a Virtual Machine Monitor (VMM). This\nvirtualized hardware is generally enlightened (paravirtualized) and additional\n@@ -48,7 +45,7 @@ performance (though nested virtualization may bring challenges in this area),\nbut for containers it often requires additional proxies and agents, and may\nrequire a larger resource footprint and slower start-up times.\n-{style=\"display:block;margin:auto\"}\n+<p align=\"center\"><img src=\"g3doc/Machine-Virtualization.png\"></p>\n**Rule-based execution**, such as [seccomp][seccomp], [SELinux][selinux] and\n[AppArmor][apparmor], allows the specification of a fine-grained security policy\n@@ -63,7 +60,7 @@ making this approach challenging to apply universally.\nRule-based execution is often combined with additional layers for\ndefense-in-depth.\n-{style=\"display:block;margin:auto\"}\n+<p align=\"center\"><img src=\"g3doc/Rule-Based-Execution.png\"></p>\n**gVisor** provides a third isolation mechanism, distinct from those mentioned\nabove.\n@@ -79,6 +76,8 @@ reduced application compatibility and higher per-system call overhead.\nOn top of this, gVisor employs rule-based execution to provide defense-in-depth\n(details below).\n+<p align=\"center\"><img src=\"g3doc/Layers.png\"></p>\n+\ngVisor's approach is similar to [User Mode Linux (UML)][uml], although UML\nvirtualizes hardware internally and thus provides a fixed resource footprint.\n@@ -107,8 +106,6 @@ application to directly control the system calls it makes.\n### File System Access\n-{style=\"display:block;margin:auto\"}\n-\nIn order to provide defense-in-depth and limit the host system surface, the\ngVisor container runtime is normally split into two separate processes. First,\nthe *Sentry* process includes the kernel and is responsible for executing user\n@@ -122,6 +119,8 @@ access itself. Furthermore, the Sentry runs in an empty user namespace, and the\nsystem calls made by gVisor to the host are restricted using seccomp filters in\norder to provide defense-in-depth.\n+<p align=\"center\"><img src=\"g3doc/Sentry-Gofer.png\"></p>\n+\n### Network Access\nThe Sentry implements its own network stack (also written in Go) called\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix center alignment
github markdown doesn't like {style} tags. Also moved the image after their respective section.
PiperOrigin-RevId: 194663070
Change-Id: I7a7b97c1bc6f2b368837a3aa936f8bd3c00469fd |
259,858 | 28.04.2018 18:05:12 | 25,200 | 913aa0a24dc3ed6cb71971e56c6ae363e8d0113d | Restore markdown images that work universally | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -45,7 +45,7 @@ performance (though nested virtualization may bring challenges in this area),\nbut for containers it often requires additional proxies and agents, and may\nrequire a larger resource footprint and slower start-up times.\n-<p align=\"center\"><img src=\"g3doc/Machine-Virtualization.png\"></p>\n+\n**Rule-based execution**, such as [seccomp][seccomp], [SELinux][selinux] and\n[AppArmor][apparmor], allows the specification of a fine-grained security policy\n@@ -57,14 +57,16 @@ However, in practice it can be extremely difficult (if not impossible) to\nreliably define a policy for arbitrary, previously unknown applications,\nmaking this approach challenging to apply universally.\n+\n+\nRule-based execution is often combined with additional layers for\ndefense-in-depth.\n-<p align=\"center\"><img src=\"g3doc/Rule-Based-Execution.png\"></p>\n-\n**gVisor** provides a third isolation mechanism, distinct from those mentioned\nabove.\n+\n+\ngVisor intercepts application system calls and acts as the guest kernel, without\nthe need for translation through virtualized hardware. gVisor may be thought of\nas either a merged guest kernel and VMM, or as seccomp on steroids. This\n@@ -76,8 +78,6 @@ reduced application compatibility and higher per-system call overhead.\nOn top of this, gVisor employs rule-based execution to provide defense-in-depth\n(details below).\n-<p align=\"center\"><img src=\"g3doc/Layers.png\"></p>\n-\ngVisor's approach is similar to [User Mode Linux (UML)][uml], although UML\nvirtualizes hardware internally and thus provides a fixed resource footprint.\n@@ -106,6 +106,8 @@ application to directly control the system calls it makes.\n### File System Access\n+\n+\nIn order to provide defense-in-depth and limit the host system surface, the\ngVisor container runtime is normally split into two separate processes. First,\nthe *Sentry* process includes the kernel and is responsible for executing user\n@@ -119,8 +121,6 @@ access itself. Furthermore, the Sentry runs in an empty user namespace, and the\nsystem calls made by gVisor to the host are restricted using seccomp filters in\norder to provide defense-in-depth.\n-<p align=\"center\"><img src=\"g3doc/Sentry-Gofer.png\"></p>\n-\n### Network Access\nThe Sentry implements its own network stack (also written in Go) called\n"
}
] | Go | Apache License 2.0 | google/gvisor | Restore markdown images that work universally
PiperOrigin-RevId: 194676199
Change-Id: Ibb9257a5504b10c4469a57ba27cd866f2d660fd8 |
259,858 | 01.05.2018 07:47:48 | 25,200 | 8a17bd183e0f7528c03c5445de4d74bf72e068f1 | Make images consistent. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -65,8 +65,6 @@ defense-in-depth.\n**gVisor** provides a third isolation mechanism, distinct from those mentioned\nabove.\n-\n-\ngVisor intercepts application system calls and acts as the guest kernel, without\nthe need for translation through virtualized hardware. gVisor may be thought of\nas either a merged guest kernel and VMM, or as seccomp on steroids. This\n@@ -75,6 +73,8 @@ on threads and memory mappings, not fixed guest physical resources) while also\nlowering the fixed costs of virtualization. However, this comes at the price of\nreduced application compatibility and higher per-system call overhead.\n+\n+\nOn top of this, gVisor employs rule-based execution to provide defense-in-depth\n(details below).\n@@ -106,8 +106,6 @@ application to directly control the system calls it makes.\n### File System Access\n-\n-\nIn order to provide defense-in-depth and limit the host system surface, the\ngVisor container runtime is normally split into two separate processes. First,\nthe *Sentry* process includes the kernel and is responsible for executing user\n@@ -115,6 +113,8 @@ code and handling system calls. Second, file system operations that extend beyon\nthe sandbox (not internal proc or tmp files, pipes, etc.) are sent to a proxy,\ncalled a *Gofer*, via a 9P connection.\n+\n+\nThe Gofer acts as a file system proxy by opening host files on behalf of the\napplication, and passing them to the Sentry process, which has no host file\naccess itself. Furthermore, the Sentry runs in an empty user namespace, and the\n@@ -228,7 +228,6 @@ Terminal support works too:\ndocker run --runtime=runsc -it ubuntu /bin/bash\n```\n-\n### Kubernetes Support (Experimental)\ngVisor can run sandboxed containers in a Kubernetes cluster with cri-o, although\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make images consistent.
PiperOrigin-RevId: 194936276
Change-Id: I01f840f573c206e865de8e5e2dd4304dcb5e3621 |
259,854 | 01.05.2018 08:06:11 | 25,200 | b701ee221434572881b9b3b0164d5a5b54714fa9 | Fix SO_RCVTIMEOUT for recvmsg | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -610,7 +610,14 @@ func RecvMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\nflags |= linux.MSG_DONTWAIT\n}\n- n, err := recvSingleMsg(t, s, msgPtr, flags, false, ktime.Time{})\n+ var haveDeadline bool\n+ var deadline ktime.Time\n+ if dl := s.RecvTimeout(); dl != 0 {\n+ deadline = t.Kernel().MonotonicClock().Now().Add(time.Duration(dl) * time.Nanosecond)\n+ haveDeadline = true\n+ }\n+\n+ n, err := recvSingleMsg(t, s, msgPtr, flags, haveDeadline, deadline)\nreturn n, nil, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix SO_RCVTIMEOUT for recvmsg
PiperOrigin-RevId: 194938091
Change-Id: Id17f26df13a915ec0c388aad3198207ea1c28d53 |
259,962 | 01.05.2018 19:11:10 | 25,200 | 43256efb080915d92a17549d86ef4eaff9ab8ef8 | Write either packet logs or pcap file. But not both. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -86,8 +86,9 @@ func writePCAPHeader(w io.Writer, maxLen uint32) error {\n// NewWithFile creates a new sniffer link-layer endpoint. It wraps around\n// another endpoint and logs packets and they traverse the endpoint.\n//\n-// Packets can be logged to file in the pcap format in addition to the standard\n-// human-readable logs.\n+// Packets can be logged to file in the pcap format. A sniffer created\n+// with this function will not emit packets using the standard log\n+// package.\n//\n// snapLen is the maximum amount of a packet to be saved. Packets with a length\n// less than or equal too snapLen will be saved in their entirety. Longer\n@@ -107,7 +108,7 @@ func NewWithFile(lower tcpip.LinkEndpointID, file *os.File, snapLen uint32) (tcp\n// called by the link-layer endpoint being wrapped when a packet arrives, and\n// logs the packet before forwarding to the actual dispatcher.\nfunc (e *endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remoteLinkAddr tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv *buffer.VectorisedView) {\n- if atomic.LoadUint32(&LogPackets) == 1 {\n+ if atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {\nLogPacket(\"recv\", protocol, vv.First(), nil)\n}\nif e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {\n@@ -168,7 +169,7 @@ func (e *endpoint) LinkAddress() tcpip.LinkAddress {\n// higher-level protocols to write packets; it just logs the packet and forwards\n// the request to the lower endpoint.\nfunc (e *endpoint) WritePacket(r *stack.Route, hdr *buffer.Prependable, payload buffer.View, protocol tcpip.NetworkProtocolNumber) *tcpip.Error {\n- if atomic.LoadUint32(&LogPackets) == 1 {\n+ if atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {\nLogPacket(\"send\", protocol, hdr.UsedBytes(), payload)\n}\nif e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Write either packet logs or pcap file. But not both.
PiperOrigin-RevId: 195035056
Change-Id: Ib32188b62188ddc2059debd52610e7904e1438c6 |
259,881 | 01.05.2018 21:14:24 | 25,200 | 185233427b3834086a9050336113f9e22176fa3b | Note that the KVM platform is experimental | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -142,12 +142,13 @@ mapping functionality. Today, gVisor supports two platforms:\nexecuting host system calls. This platform can run anywhere that `ptrace`\nworks (even VMs without nested virtualization).\n-* The **KVM** platform allows the Sentry to act as both guest OS and VMM,\n- switching back and forth between the two worlds seamlessly. The KVM platform\n- can run on bare-metal or on a VM with nested virtualization enabled. While\n- there is no virtualized hardware layer -- the sandbox retains a process model\n- -- gVisor leverages virtualization extensions available on modern processors\n- in order to improve isolation and performance of address space switches.\n+* The **KVM** platform (experimental) allows the Sentry to act as both guest OS\n+ and VMM, switching back and forth between the two worlds seamlessly. The KVM\n+ platform can run on bare-metal or on a VM with nested virtualization enabled.\n+ While there is no virtualized hardware layer -- the sandbox retains a process\n+ model -- gVisor leverages virtualization extensions available on modern\n+ processors in order to improve isolation and performance of address space\n+ switches.\n### Performance\n"
}
] | Go | Apache License 2.0 | google/gvisor | Note that the KVM platform is experimental
PiperOrigin-RevId: 195043285
Change-Id: Ie76112eff61062e1a54894b3707201fd284be377 |
259,881 | 01.05.2018 22:17:13 | 25,200 | 65df95516898f077cda44ace15e45e4c777fdaf3 | Set LMA in EFER
As of Linux 4.15 (f29810335965ac1f7bcb501ee2af5f039f792416
KVM/x86: Check input paging mode when cs.l is set), KVM validates that
LMA is set along with LME. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"diff": "@@ -149,7 +149,7 @@ func (c *CPU) CR4() uint64 {\n//\n//go:nosplit\nfunc (c *CPU) EFER() uint64 {\n- return _EFER_LME | _EFER_SCE | _EFER_NX\n+ return _EFER_LME | _EFER_LMA | _EFER_SCE | _EFER_NX\n}\n// IsCanonical indicates whether addr is canonical per the amd64 spec.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/x86.go",
"new_path": "pkg/sentry/platform/ring0/x86.go",
"diff": "@@ -46,6 +46,7 @@ const (\n_EFER_SCE = 0x001\n_EFER_LME = 0x100\n+ _EFER_LMA = 0x400\n_EFER_NX = 0x800\n_MSR_STAR = 0xc0000081\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set LMA in EFER
As of Linux 4.15 (f29810335965ac1f7bcb501ee2af5f039f792416
KVM/x86: Check input paging mode when cs.l is set), KVM validates that
LMA is set along with LME.
PiperOrigin-RevId: 195047401
Change-Id: I8b43d8f758a85b1f58ccbd747dcacd4056ef3f66 |
259,926 | 02.05.2018 03:42:54 | 25,200 | 2264ce7f62994fa0476f8e1eb9fe497d60547bda | Use png for the run states diagram | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/README.md",
"new_path": "pkg/sentry/kernel/README.md",
"diff": "@@ -87,7 +87,7 @@ kept separate from the main \"app\" state to reduce the size of the latter.\n4. `SyscallReinvoke`, which does not correspond to anything in Linux, and exists\nsolely to serve the autosave feature.\n-\n+\nStates before which a stop may occur are represented as implementations of the\n`taskRunState` interface named `run(state)`, allowing them to be saved and\n"
},
{
"change_type": "ADD",
"old_path": "pkg/sentry/kernel/g3doc/run_states.png",
"new_path": "pkg/sentry/kernel/g3doc/run_states.png",
"diff": "Binary files /dev/null and b/pkg/sentry/kernel/g3doc/run_states.png differ\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use png for the run states diagram
PiperOrigin-RevId: 195071508
Change-Id: I63314bf7529560e4c779ef07cc9399ad8d53f0a2 |
259,881 | 02.05.2018 11:20:43 | 25,200 | 6c061ad913fce6fbfe9a98c0fc1f5b67fad1b9b0 | Note that build requires Python 2.7
Updates | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -168,6 +168,8 @@ and Docker.\n* [git][git]\n* [Bazel][bazel]\n+* [Python 2.7][python] (See [bug #8](https://github.com/google/gvisor/issues/8)\n+ for Python 3 support updates)\n* [Docker version 17.09.0 or greater][docker]\n### Getting the source\n@@ -417,6 +419,7 @@ See [Contributing.md](CONTRIBUTING.md).\n[kvm]: https://www.linux-kvm.org\n[netstack]: https://github.com/google/netstack\n[oci]: https://www.opencontainers.org\n+[python]: https://python.org\n[sandbox]: https://en.wikipedia.org/wiki/Sandbox_(computer_security)\n[seccomp]: https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt\n[selinux]: https://selinuxproject.org\n"
}
] | Go | Apache License 2.0 | google/gvisor | Note that build requires Python 2.7
Updates #8
PiperOrigin-RevId: 195122103
Change-Id: Iff190283961b8ab99ad4f3e47ffeb9ab491d0eb3 |
259,992 | 02.05.2018 17:39:12 | 25,200 | a61def1b368a9042e346787008e12770e4e67b35 | Remove detach for exec options
Detachable exec commands are handled in the client entirely and the detach option is not used anymore. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/proc.go",
"new_path": "pkg/sentry/control/proc.go",
"diff": "@@ -72,9 +72,6 @@ type ExecArgs struct {\n// Capabilities is the list of capabilities to give to the process.\nCapabilities *auth.TaskCapabilities\n- // Detach indicates whether Exec should detach once the process starts.\n- Detach bool\n-\n// FilePayload determines the files to give to the new process.\nurpc.FilePayload\n}\n@@ -135,12 +132,6 @@ func (proc *Proc) Exec(args *ExecArgs, waitStatus *uint32) error {\nreturn err\n}\n- // If we're supposed to detach, don't wait for the process to exit.\n- if args.Detach {\n- *waitStatus = 0\n- return nil\n- }\n-\n// Wait for completion.\nnewTG.WaitExited()\n*waitStatus = newTG.ExitStatus().Status()\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/exec.go",
"new_path": "runsc/cmd/exec.go",
"diff": "@@ -99,7 +99,6 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif err != nil {\nFatalf(\"error parsing process spec: %v\", err)\n}\n- e.Detach = ex.detach\nconf := args[0].(*boot.Config)\nwaitStatus := args[1].(*syscall.WaitStatus)\n@@ -123,7 +122,7 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// executed. If detach was specified, starts a child in non-detach mode,\n// write the child's PID to the pid file. So when the container returns, the\n// child process will also return and signal containerd.\n- if e.Detach {\n+ if ex.detach {\nbinPath, err := specutils.BinPath()\nif err != nil {\nFatalf(\"error getting bin path: %v\", err)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox_test.go",
"new_path": "runsc/sandbox/sandbox_test.go",
"diff": "@@ -365,7 +365,6 @@ func TestExec(t *testing.T) {\nEnvv: []string{\"PATH=\" + os.Getenv(\"PATH\")},\nWorkingDirectory: \"/\",\nKUID: uid,\n- Detach: false,\n}\n// Verify that \"sleep 100\" and \"sleep 5\" are running after exec.\n@@ -472,7 +471,6 @@ func TestCapabilities(t *testing.T) {\nKUID: uid,\nKGID: gid,\nCapabilities: &auth.TaskCapabilities{},\n- Detach: true,\n}\n// \"exe\" should fail because we don't have the necessary permissions.\n@@ -484,14 +482,10 @@ func TestCapabilities(t *testing.T) {\nexecArgs.Capabilities = &auth.TaskCapabilities{\nEffectiveCaps: auth.CapabilitySetOf(linux.CAP_DAC_OVERRIDE),\n}\n- // First, start running exec.\n+ // \"exe\" should not fail this time.\nif _, err := s.Execute(&execArgs); err != nil {\nt.Fatalf(\"sandbox failed to exec %v: %v\", execArgs, err)\n}\n-\n- if err := waitForProcessList(s, expectedPL); err != nil {\n- t.Error(err)\n- }\n}\n// Test that an tty FD is sent over the console socket if one is provided.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove detach for exec options
Detachable exec commands are handled in the client entirely and the detach option is not used anymore.
PiperOrigin-RevId: 195181272
Change-Id: I6e82a2876d2c173709c099be59670f71702e5bf0 |
259,956 | 03.05.2018 09:59:32 | 25,200 | 9739b8c21cd1716c4c1c81a27121c50e63fcf906 | Don't prematurely remove MountSource from parent's children.
Otherwise, mounts that fail to be unmounted (EBUSY) will be removed
from the children list anyway.
At this point, this just affects /proc/pid/mounts and /proc/pid/mountinfo. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/mounts.go",
"new_path": "pkg/sentry/fs/mounts.go",
"diff": "@@ -272,8 +272,25 @@ func (mns *MountNamespace) Unmount(ctx context.Context, node *Dirent, detachOnly\npanic(\"cannot unmount initial dirent\")\n}\n- if !detachOnly {\nm := node.Inode.MountSource\n+ if !detachOnly {\n+ // Flush all references on the mounted node.\n+ m.FlushDirentRefs()\n+\n+ // At this point, exactly two references must be held\n+ // to mount: one mount reference on node, and one due\n+ // to walking to node.\n+ //\n+ // We must also be guaranteed that no more references\n+ // can be taken on mount. This is why withMountLocked\n+ // must be held at this point to prevent any walks to\n+ // and from node.\n+ if refs := m.DirentRefs(); refs < 2 {\n+ panic(fmt.Sprintf(\"have %d refs on unmount, expect 2 or more\", refs))\n+ } else if refs != 2 {\n+ return syserror.EBUSY\n+ }\n+ }\n// Lock the parent MountSource first, if it exists. We are\n// holding mns.Lock, so the parent can not change out\n@@ -294,25 +311,6 @@ func (mns *MountNamespace) Unmount(ctx context.Context, node *Dirent, detachOnly\npanic(fmt.Sprintf(\"mount %+v is not a child of parent %+v\", m, m.parent))\n}\ndelete(m.parent.children, m)\n- m.parent = nil\n- }\n-\n- // Flush all references on the mounted node.\n- m.FlushDirentRefs()\n-\n- // At this point, exactly two references must be held\n- // to mount: one mount reference on node, and one due\n- // to walking to node.\n- //\n- // We must also be guaranteed that no more references\n- // can be taken on mount. This is why withMountLocked\n- // must be held at this point to prevent any walks to\n- // and from node.\n- if refs := m.DirentRefs(); refs < 2 {\n- panic(fmt.Sprintf(\"have %d refs on unmount, expect 2 or more\", refs))\n- } else if refs != 2 {\n- return syserror.EBUSY\n- }\n}\noriginal := origs[len(origs)-1]\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't prematurely remove MountSource from parent's children.
Otherwise, mounts that fail to be unmounted (EBUSY) will be removed
from the children list anyway.
At this point, this just affects /proc/pid/mounts and /proc/pid/mountinfo.
PiperOrigin-RevId: 195267588
Change-Id: I79114483d73b90f9a7d764a7d513b5b2f251182e |
259,956 | 03.05.2018 13:43:20 | 25,200 | 18ebda3476f2e28101656d93a88107d587e0f1ca | Include Gold linker in requirements.
Updates | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -171,6 +171,7 @@ and Docker.\n* [Python 2.7][python] (See [bug #8](https://github.com/google/gvisor/issues/8)\nfor Python 3 support updates)\n* [Docker version 17.09.0 or greater][docker]\n+* Gold linker (e.g. `binutils-gold` package on Ubuntu)\n### Getting the source\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_generics/defs.bzl",
"new_path": "tools/go_generics/defs.bzl",
"diff": "@@ -39,28 +39,20 @@ Args:\nopt_consts: the list of constants in the template that can but aren't required to be specified.\ndeps: the list of dependencies.\n\"\"\"\n-\ngo_template = rule(\n+ implementation = _go_template_impl,\nattrs = {\n- \"srcs\": attr.label_list(\n- mandatory = True,\n- allow_files = True,\n- ),\n+ \"srcs\": attr.label_list(mandatory = True, allow_files = True),\n\"deps\": attr.label_list(allow_files = True),\n\"types\": attr.string_list(),\n\"opt_types\": attr.string_list(),\n\"consts\": attr.string_list(),\n\"opt_consts\": attr.string_list(),\n- \"_tool\": attr.label(\n- executable = True,\n- cfg = \"host\",\n- default = Label(\"//tools/go_generics:go_merge\"),\n- ),\n+ \"_tool\": attr.label(executable = True, cfg = \"host\", default = Label(\"//tools/go_generics:go_merge\")),\n},\noutputs = {\n\"out\": \"%{name}_template.go\",\n},\n- implementation = _go_template_impl,\n)\ndef _go_template_instance_impl(ctx):\n@@ -112,7 +104,7 @@ def _go_template_instance_impl(ctx):\n# TODO: How can we get the dependencies out?\nreturn struct(\n- files = depset([output])\n+ files = depset([output]),\n)\n\"\"\"\n@@ -128,13 +120,10 @@ Args:\nimports: the map from imports used in types/consts to their import paths.\npackage: the name of the package the instantiated template will be compiled into.\n\"\"\"\n-\ngo_template_instance = rule(\n+ implementation = _go_template_instance_impl,\nattrs = {\n- \"template\": attr.label(\n- mandatory = True,\n- providers = [\"types\"],\n- ),\n+ \"template\": attr.label(mandatory = True, providers = [\"types\"]),\n\"prefix\": attr.string(),\n\"suffix\": attr.string(),\n\"types\": attr.string_dict(),\n@@ -142,11 +131,6 @@ go_template_instance = rule(\n\"imports\": attr.string_dict(),\n\"package\": attr.string(mandatory = True),\n\"out\": attr.output(mandatory = True),\n- \"_tool\": attr.label(\n- executable = True,\n- cfg = \"host\",\n- default = Label(\"//tools/go_generics\"),\n- ),\n+ \"_tool\": attr.label(executable = True, cfg = \"host\", default = Label(\"//tools/go_generics\")),\n},\n- implementation = _go_template_instance_impl,\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_stateify/defs.bzl",
"new_path": "tools/go_stateify/defs.bzl",
"diff": "@@ -56,22 +56,14 @@ Args:\nout: the name of the generated file output. This must not conflict with any other files and must be added to the srcs of the relevant go_library.\npackage: the package name for the input sources.\n\"\"\"\n-\ngo_stateify = rule(\n+ implementation = _go_stateify_impl,\nattrs = {\n- \"srcs\": attr.label_list(\n- mandatory = True,\n- allow_files = True,\n- ),\n+ \"srcs\": attr.label_list(mandatory = True, allow_files = True),\n\"imports\": attr.string_list(mandatory = False),\n\"package\": attr.string(mandatory = True),\n\"out\": attr.output(mandatory = True),\n- \"_tool\": attr.label(\n- executable = True,\n- cfg = \"host\",\n- default = Label(\"//tools/go_stateify:stateify\"),\n- ),\n+ \"_tool\": attr.label(executable = True, cfg = \"host\", default = Label(\"//tools/go_stateify:stateify\")),\n\"_statepkg\": attr.string(default = \"gvisor.googlesource.com/gvisor/pkg/state\"),\n},\n- implementation = _go_stateify_impl,\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Include Gold linker in requirements.
Updates #26.
PiperOrigin-RevId: 195303940
Change-Id: I833cee55b5df6196ed90c1f8987c3c9c07204678 |
259,854 | 03.05.2018 16:25:39 | 25,200 | 58235b1840db01aa2ede311efa782eac60767722 | Clean up control message strace logging | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -463,7 +463,6 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\nvar h linux.ControlMessageHeader\nbinary.Unmarshal(buf[i:i+linux.SizeOfControlMessageHeader], usermem.ByteOrder, &h)\n- i += linux.SizeOfControlMessageHeader\nvar skipData bool\nlevel := \"SOL_SOCKET\"\n@@ -478,7 +477,7 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ntyp = fmt.Sprint(h.Type)\n}\n- if h.Length > uint64(len(buf)-i+linux.SizeOfControlMessageHeader) {\n+ if h.Length > uint64(len(buf)-i) {\nstrs = append(strs, fmt.Sprintf(\n\"{level=%s, type=%s, length=%d, content extends beyond buffer}\",\nlevel,\n@@ -488,12 +487,13 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\nbreak\n}\n+ i += linux.SizeOfControlMessageHeader\nwidth := t.Arch().Width()\nlength := int(h.Length) - linux.SizeOfControlMessageHeader\nif skipData {\nstrs = append(strs, fmt.Sprintf(\"{level=%s, type=%s, length=%d}\", level, typ, h.Length))\n- i += control.AlignUp(i+length, width)\n+ i += control.AlignUp(length, width)\ncontinue\n}\n@@ -518,8 +518,6 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\nstrings.Join(rights, \",\"),\n))\n- i += control.AlignUp(length, width)\n-\ncase linux.SCM_CREDENTIALS:\nif length < linux.SizeOfControlMessageCredentials {\nstrs = append(strs, fmt.Sprintf(\n@@ -528,7 +526,6 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ntyp,\nh.Length,\n))\n- i += control.AlignUp(length, width)\nbreak\n}\n@@ -545,8 +542,6 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ncreds.GID,\n))\n- i += control.AlignUp(length, width)\n-\ncase linux.SO_TIMESTAMP:\nif length < linux.SizeOfTimeval {\nstrs = append(strs, fmt.Sprintf(\n@@ -555,7 +550,6 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ntyp,\nh.Length,\n))\n- i += control.AlignUp(length, width)\nbreak\n}\n@@ -571,11 +565,10 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ntv.Usec,\n))\n- i += control.AlignUp(length, width)\n-\ndefault:\npanic(\"unreachable\")\n}\n+ i += control.AlignUp(length, width)\n}\nreturn fmt.Sprintf(\"%#x %s\", addr, strings.Join(strs, \", \"))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up control message strace logging
PiperOrigin-RevId: 195329972
Change-Id: I42f7d8800e6692c45ffa9683741f8de89f9a69bb |
259,992 | 03.05.2018 21:08:38 | 25,200 | c186ebb62a6005288d83feed0e43cca9f0577383 | Return error when child exits early | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/exec.go",
"new_path": "runsc/cmd/exec.go",
"diff": "@@ -123,6 +123,34 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// write the child's PID to the pid file. So when the container returns, the\n// child process will also return and signal containerd.\nif ex.detach {\n+ return ex.execAndWait(waitStatus)\n+ }\n+\n+ if ex.pidFile != \"\" {\n+ if err := ioutil.WriteFile(ex.pidFile, []byte(strconv.Itoa(os.Getpid())), 0644); err != nil {\n+ Fatalf(\"error writing pid file: %v\", err)\n+ }\n+ }\n+\n+ // Get the executable path, which is a bit tricky because we have to\n+ // inspect the environment PATH which is relative to the root path.\n+ // If the user is overriding environment variables, PATH may have been\n+ // overwritten.\n+ rootPath := s.Spec.Root.Path\n+ e.Filename, err = specutils.GetExecutablePath(e.Argv[0], rootPath, e.Envv)\n+ if err != nil {\n+ Fatalf(\"error getting executable path: %v\", err)\n+ }\n+\n+ ws, err := s.Execute(e)\n+ if err != nil {\n+ Fatalf(\"error getting processes for sandbox: %v\", err)\n+ }\n+ *waitStatus = ws\n+ return subcommands.ExitSuccess\n+}\n+\n+func (ex *Exec) execAndWait(waitStatus *syscall.WaitStatus) subcommands.ExitStatus {\nbinPath, err := specutils.BinPath()\nif err != nil {\nFatalf(\"error getting bin path: %v\", err)\n@@ -146,48 +174,23 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Wait for PID file to ensure that child process has started. Otherwise,\n// '--process' file is deleted as soon as this process returns and the child\n// may fail to read it.\n- sleepTime := 10 * time.Millisecond\n- for start := time.Now(); time.Now().Sub(start) < 10*time.Second; {\n+ ready := func() (bool, error) {\n_, err := os.Stat(ex.pidFile)\nif err == nil {\n- break\n+ // File appeared, we're done!\n+ return true, nil\n}\nif pe, ok := err.(*os.PathError); !ok || pe.Err != syscall.ENOENT {\n- Fatalf(\"unexpected error waiting for PID file, err: %v\", err)\n- }\n-\n- log.Infof(\"Waiting for PID file to be created...\")\n- time.Sleep(sleepTime)\n- sleepTime *= sleepTime * 2\n- if sleepTime > 1*time.Second {\n- sleepTime = 1 * time.Second\n- }\n- }\n- *waitStatus = 0\n- return subcommands.ExitSuccess\n- }\n-\n- if ex.pidFile != \"\" {\n- if err := ioutil.WriteFile(ex.pidFile, []byte(strconv.Itoa(os.Getpid())), 0644); err != nil {\n- Fatalf(\"error writing pid file: %v\", err)\n+ return false, err\n}\n+ // No file yet, continue to wait...\n+ return false, nil\n}\n-\n- // Get the executable path, which is a bit tricky because we have to\n- // inspect the environment PATH which is relative to the root path.\n- // If the user is overriding environment variables, PATH may have been\n- // overwritten.\n- rootPath := s.Spec.Root.Path\n- e.Filename, err = specutils.GetExecutablePath(e.Argv[0], rootPath, e.Envv)\n- if err != nil {\n- Fatalf(\"error getting executable path: %v\", err)\n+ if err := specutils.WaitForReady(cmd.Process.Pid, 10*time.Second, ready); err != nil {\n+ Fatalf(\"unexpected error waiting for PID file, err: %v\", err)\n}\n- ws, err := s.Execute(e)\n- if err != nil {\n- Fatalf(\"error getting processes for sandbox: %v\", err)\n- }\n- *waitStatus = ws\n+ *waitStatus = 0\nreturn subcommands.ExitSuccess\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -560,19 +560,20 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, binPath string, common\n// running, at which point the sandbox is in Created state.\nfunc (s *Sandbox) waitForCreated(timeout time.Duration) error {\nlog.Debugf(\"Waiting for sandbox %q creation\", s.ID)\n- tchan := time.After(timeout)\n- for {\n- select {\n- case <-tchan:\n- return fmt.Errorf(\"timed out waiting for sandbox control server\")\n- default:\n- if c, err := client.ConnectTo(boot.ControlSocketAddr(s.ID)); err == nil {\n+\n+ ready := func() (bool, error) {\n+ c, err := client.ConnectTo(boot.ControlSocketAddr(s.ID))\n+ if err != nil {\n+ return false, nil\n+ }\n// It's alive!\nc.Close()\n- return nil\n- }\n+ return true, nil\n}\n+ if err := specutils.WaitForReady(s.Pid, timeout, ready); err != nil {\n+ return fmt.Errorf(\"unexpected error waiting for sandbox %q, err: %v\", s.ID, err)\n}\n+ return nil\n}\n// Wait waits for the containerized process to exit, and returns its WaitStatus.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/BUILD",
"new_path": "runsc/specutils/BUILD",
"diff": "package(licenses = [\"notice\"]) # Apache 2.0\n-load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\")\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\", \"go_test\")\ngo_library(\nname = \"specutils\",\n@@ -16,3 +16,10 @@ go_library(\n\"@com_github_opencontainers_runtime-spec//specs-go:go_default_library\",\n],\n)\n+\n+go_test(\n+ name = \"specutils_test\",\n+ size = \"small\",\n+ srcs = [\"specutils_test.go\"],\n+ embed = [\":specutils\"],\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -23,6 +23,8 @@ import (\n\"os\"\n\"path/filepath\"\n\"strings\"\n+ \"syscall\"\n+ \"time\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n@@ -181,3 +183,33 @@ func BinPath() (string, error) {\n}\nreturn binPath, nil\n}\n+\n+// WaitForReady waits for a process to become ready. The process is ready when\n+// the 'ready' function returns true. It continues to wait if 'ready' returns\n+// false. It returns error on timeout, if the process stops or if 'ready' fails.\n+func WaitForReady(pid int, timeout time.Duration, ready func() (bool, error)) error {\n+ backoff := 1 * time.Millisecond\n+ for start := time.Now(); time.Now().Sub(start) < timeout; {\n+ if ok, err := ready(); err != nil {\n+ return err\n+ } else if ok {\n+ return nil\n+ }\n+\n+ // Check if the process is still running.\n+ var ws syscall.WaitStatus\n+ var ru syscall.Rusage\n+ child, err := syscall.Wait4(pid, &ws, syscall.WNOHANG, &ru)\n+ if err != nil || child == pid {\n+ return fmt.Errorf(\"process (%d) is not running, err: %v\", pid, err)\n+ }\n+\n+ // Process continues to run, backoff and retry.\n+ time.Sleep(backoff)\n+ backoff *= 2\n+ if backoff > 1*time.Second {\n+ backoff = 1 * time.Second\n+ }\n+ }\n+ return fmt.Errorf(\"timed out waiting for process (%d)\", pid)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/specutils/specutils_test.go",
"diff": "+// Copyright 2018 Google Inc.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package specutils\n+\n+import (\n+ \"fmt\"\n+ \"os/exec\"\n+ \"strings\"\n+ \"testing\"\n+ \"time\"\n+)\n+\n+func TestWaitForReadyHappy(t *testing.T) {\n+ cmd := exec.Command(\"/bin/sleep\", \"1000\")\n+ if err := cmd.Start(); err != nil {\n+ t.Fatalf(\"cmd.Start() failed, err: %v\", err)\n+ }\n+ defer cmd.Wait()\n+\n+ var count int\n+ err := WaitForReady(cmd.Process.Pid, 5*time.Second, func() (bool, error) {\n+ if count < 3 {\n+ count++\n+ return false, nil\n+ }\n+ return true, nil\n+ })\n+ if err != nil {\n+ t.Errorf(\"ProcessWaitReady got: %v, expected: nil\", err)\n+ }\n+ cmd.Process.Kill()\n+}\n+\n+func TestWaitForReadyFail(t *testing.T) {\n+ cmd := exec.Command(\"/bin/sleep\", \"1000\")\n+ if err := cmd.Start(); err != nil {\n+ t.Fatalf(\"cmd.Start() failed, err: %v\", err)\n+ }\n+ defer cmd.Wait()\n+\n+ var count int\n+ err := WaitForReady(cmd.Process.Pid, 5*time.Second, func() (bool, error) {\n+ if count < 3 {\n+ count++\n+ return false, nil\n+ }\n+ return false, fmt.Errorf(\"Fake error\")\n+ })\n+ if err == nil {\n+ t.Errorf(\"ProcessWaitReady got: nil, expected: error\")\n+ }\n+ cmd.Process.Kill()\n+}\n+\n+func TestWaitForReadyNotRunning(t *testing.T) {\n+ cmd := exec.Command(\"/bin/true\")\n+ if err := cmd.Start(); err != nil {\n+ t.Fatalf(\"cmd.Start() failed, err: %v\", err)\n+ }\n+ defer cmd.Wait()\n+\n+ err := WaitForReady(cmd.Process.Pid, 5*time.Second, func() (bool, error) {\n+ return false, nil\n+ })\n+ if !strings.Contains(err.Error(), \"not running\") {\n+ t.Errorf(\"ProcessWaitReady got: %v, expected: not running\", err)\n+ }\n+}\n+\n+func TestWaitForReadyTimeout(t *testing.T) {\n+ cmd := exec.Command(\"/bin/sleep\", \"1000\")\n+ if err := cmd.Start(); err != nil {\n+ t.Fatalf(\"cmd.Start() failed, err: %v\", err)\n+ }\n+ defer cmd.Wait()\n+\n+ err := WaitForReady(cmd.Process.Pid, 50*time.Millisecond, func() (bool, error) {\n+ return false, nil\n+ })\n+ if !strings.Contains(err.Error(), \"timed out\") {\n+ t.Errorf(\"ProcessWaitReady got: %v, expected: timed out\", err)\n+ }\n+ cmd.Process.Kill()\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return error when child exits early
PiperOrigin-RevId: 195365050
Change-Id: I8754dc7a3fc2975d422cae453762a455478a8e6a |
259,992 | 04.05.2018 01:23:43 | 25,200 | 7e82550bf7a383d0aa3b3c4c8107bc32816ca5d5 | Add github bug template | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/issue_template.md",
"diff": "+Before filling an issue, please consult our [FAQ](https://github.com/google/gvisor#faq--known-issues)\n+and check that the issue hasn't been [reported before](https://github.com/google/gvisor/issues).\n+\n+Enable [debug logs](https://github.com/google/gvisor#debugging), run your\n+repro, and attach the logs to the bug. Other useful information to include is:\n+- `docker version` or `docker info` if more relevant\n+- `uname -a`\n+- `git describe`\n+- Full docker command you ran\n+- Detailed repro steps\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add github bug template
PiperOrigin-RevId: 195382309
Change-Id: I3e50206d137bb15c0532282ffbc3508aa5ddeb28 |
259,992 | 04.05.2018 09:38:35 | 25,200 | c90fefc1161c58af34856aff7b7012f19f5d1f1b | Fix runsc capabilities
There was a typo and one new capability missing from the list | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/capability.go",
"new_path": "pkg/abi/linux/capability.go",
"diff": "@@ -32,7 +32,7 @@ const (\nCAP_SETPCAP = Capability(8)\nCAP_LINUX_IMMUTABLE = Capability(9)\nCAP_NET_BIND_SERVICE = Capability(10)\n- CAP_NET_BROAD_CAST = Capability(11)\n+ CAP_NET_BROADCAST = Capability(11)\nCAP_NET_ADMIN = Capability(12)\nCAP_NET_RAW = Capability(13)\nCAP_IPC_LOCK = Capability(14)\n@@ -58,9 +58,10 @@ const (\nCAP_SYSLOG = Capability(34)\nCAP_WAKE_ALARM = Capability(35)\nCAP_BLOCK_SUSPEND = Capability(36)\n+ CAP_AUDIT_READ = Capability(37)\n// MaxCapability is the highest-numbered capability.\n- MaxCapability = Capability(36) // CAP_BLOCK_SUSPEND as of 3.11\n+ MaxCapability = CAP_AUDIT_READ\n)\n// Ok returns true if cp is a supported capability.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/capability.go",
"new_path": "runsc/boot/capability.go",
"diff": "@@ -91,7 +91,7 @@ var capFromName = map[string]capability.Cap{\n\"CAP_SETPCAP\": capability.CAP_SETPCAP,\n\"CAP_LINUX_IMMUTABLE\": capability.CAP_LINUX_IMMUTABLE,\n\"CAP_NET_BIND_SERVICE\": capability.CAP_NET_BIND_SERVICE,\n- \"CAP_NET_BROAD_CAST\": capability.CAP_NET_BROADCAST,\n+ \"CAP_NET_BROADCAST\": capability.CAP_NET_BROADCAST,\n\"CAP_NET_ADMIN\": capability.CAP_NET_ADMIN,\n\"CAP_NET_RAW\": capability.CAP_NET_RAW,\n\"CAP_IPC_LOCK\": capability.CAP_IPC_LOCK,\n@@ -117,4 +117,5 @@ var capFromName = map[string]capability.Cap{\n\"CAP_SYSLOG\": capability.CAP_SYSLOG,\n\"CAP_WAKE_ALARM\": capability.CAP_WAKE_ALARM,\n\"CAP_BLOCK_SUSPEND\": capability.CAP_BLOCK_SUSPEND,\n+ \"CAP_AUDIT_READ\": capability.CAP_AUDIT_READ,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -129,7 +129,7 @@ var capFromName = map[string]linux.Capability{\n\"CAP_SETPCAP\": linux.CAP_SETPCAP,\n\"CAP_LINUX_IMMUTABLE\": linux.CAP_LINUX_IMMUTABLE,\n\"CAP_NET_BIND_SERVICE\": linux.CAP_NET_BIND_SERVICE,\n- \"CAP_NET_BROAD_CAST\": linux.CAP_NET_BROAD_CAST,\n+ \"CAP_NET_BROADCAST\": linux.CAP_NET_BROADCAST,\n\"CAP_NET_ADMIN\": linux.CAP_NET_ADMIN,\n\"CAP_NET_RAW\": linux.CAP_NET_RAW,\n\"CAP_IPC_LOCK\": linux.CAP_IPC_LOCK,\n@@ -155,6 +155,7 @@ var capFromName = map[string]linux.Capability{\n\"CAP_SYSLOG\": linux.CAP_SYSLOG,\n\"CAP_WAKE_ALARM\": linux.CAP_WAKE_ALARM,\n\"CAP_BLOCK_SUSPEND\": linux.CAP_BLOCK_SUSPEND,\n+ \"CAP_AUDIT_READ\": linux.CAP_AUDIT_READ,\n}\nfunc capsFromNames(names []string) (auth.CapabilitySet, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix runsc capabilities
There was a typo and one new capability missing from the list
PiperOrigin-RevId: 195427713
Change-Id: I6d9e1c6e77b48fe85ef10d9f54c70c8a7271f6e7 |
259,854 | 04.05.2018 11:25:36 | 25,200 | f94d90073f3b54a219c687894e9d7ce7f5c4efc4 | Add to the github issue template | [
{
"change_type": "MODIFY",
"old_path": ".github/issue_template.md",
"new_path": ".github/issue_template.md",
"diff": "Before filling an issue, please consult our [FAQ](https://github.com/google/gvisor#faq--known-issues)\nand check that the issue hasn't been [reported before](https://github.com/google/gvisor/issues).\n+If this is your first time compiling or running gVisor, please make sure that\n+your system meets the [minimum requirements](https://github.com/google/gvisor#requirements).\n+\n+If you believe you've found a security issue, please email\[email protected] rather than filing a bug.\n+\nEnable [debug logs](https://github.com/google/gvisor#debugging), run your\nrepro, and attach the logs to the bug. Other useful information to include is:\n- `docker version` or `docker info` if more relevant\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add to the github issue template
PiperOrigin-RevId: 195444658
Change-Id: I62d12405324f9c80ec572c65d76c5f320a9b549e |
259,881 | 04.05.2018 13:14:59 | 25,200 | 7bb10dc7a0499e20a37291d6f5fd105e6ae6fdbf | Disable stack protector in VDSO build
The VDSO has no hooks to handle stack protector failures.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "vdso/BUILD",
"new_path": "vdso/BUILD",
"diff": "@@ -26,6 +26,9 @@ genrule(\n\"-O2 \" +\n\"-std=c++11 \" +\n\"-fPIC \" +\n+ # Some toolchains enable stack protector by default. Disable it, the\n+ # VDSO has no hooks to handle failures.\n+ \"-fno-stack-protector \" +\n\"-fuse-ld=gold \" +\n\"-m64 \" +\n\"-shared \" +\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable stack protector in VDSO build
The VDSO has no hooks to handle stack protector failures.
Fixes #9
PiperOrigin-RevId: 195460989
Change-Id: Idf1d55bfee1126e551d7274b7f484e03bf440427 |
259,948 | 04.05.2018 13:55:06 | 25,200 | 0ce9c81b416494e3c3da793c278dfc767341fa6d | sentry: capture CPU usage metadata for save. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/state/BUILD",
"new_path": "pkg/sentry/state/BUILD",
"diff": "@@ -7,10 +7,12 @@ go_library(\nsrcs = [\n\"state.go\",\n\"state_metadata.go\",\n+ \"state_unsafe.go\",\n],\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/state\",\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/log\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/state/state.go",
"new_path": "pkg/sentry/state/state.go",
"diff": "@@ -27,6 +27,8 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/state/statefile\"\n)\n+var previousMetadata map[string]string\n+\n// ErrStateFile is returned when the state file cannot be opened.\ntype ErrStateFile struct {\nerr error\n@@ -103,11 +105,13 @@ type LoadOpts struct {\n// Load loads the given kernel, setting the provided platform and stack.\nfunc (opts LoadOpts) Load(k *kernel.Kernel, p platform.Platform, n inet.Stack) error {\n// Open the file.\n- r, _, err := statefile.NewReader(opts.Source, opts.Key)\n+ r, m, err := statefile.NewReader(opts.Source, opts.Key)\nif err != nil {\nreturn ErrStateFile{err}\n}\n+ previousMetadata = m\n+\n// Restore the Kernel object graph.\nreturn k.LoadFrom(r, p, n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/state/state_metadata.go",
"new_path": "pkg/sentry/state/state_metadata.go",
"diff": "@@ -17,13 +17,29 @@ package state\nimport (\n\"fmt\"\n\"time\"\n+\n+ \"gvisor.googlesource.com/gvisor/pkg/log\"\n)\n// The save metadata keys for timestamp.\nconst (\n+ cpuUsage = \"cpu_usage\"\nmetadataTimestamp = \"timestamp\"\n)\nfunc addSaveMetadata(m map[string]string) {\n+ t, err := cpuTime()\n+ if err != nil {\n+ log.Warningf(\"Error getting cpu time: %v\", err)\n+ }\n+ if previousMetadata != nil {\n+ p, err := time.ParseDuration(previousMetadata[cpuUsage])\n+ if err != nil {\n+ log.Warningf(\"Error parsing previous runs' cpu time: %v\", err)\n+ }\n+ t += p\n+ }\n+ m[cpuUsage] = t.String()\n+\nm[metadataTimestamp] = fmt.Sprintf(\"%v\", time.Now())\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/state/state_unsafe.go",
"diff": "+// Copyright 2018 Google Inc.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package state\n+\n+import (\n+ \"fmt\"\n+ \"syscall\"\n+ \"time\"\n+ \"unsafe\"\n+\n+ \"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+)\n+\n+func cpuTime() (time.Duration, error) {\n+ var ts syscall.Timespec\n+ _, _, errno := syscall.RawSyscall(syscall.SYS_CLOCK_GETTIME, uintptr(linux.CLOCK_PROCESS_CPUTIME_ID), uintptr(unsafe.Pointer(&ts)), 0)\n+ if errno != 0 {\n+ return 0, fmt.Errorf(\"failed calling clock_gettime(CLOCK_PROCESS_CPUTIME_ID): errno=%d\", errno)\n+ }\n+ return time.Duration(ts.Nano()), nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | sentry: capture CPU usage metadata for save.
PiperOrigin-RevId: 195466647
Change-Id: Ib5ca815f7b64a4881441e58567adedf344b206f1 |
259,891 | 04.05.2018 16:21:38 | 25,200 | d70787d340b3967fd691fbbd079dece329f7a65c | sentry: Adds the SIOCGIFNETMASK ioctl to epsocket. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -1109,7 +1109,20 @@ func (s *SocketOperations) interfaceIoctl(ctx context.Context, io usermem.IO, ar\ncase syscall.SIOCGIFNETMASK:\n// Gets the network mask of a device.\n- // TODO: Implement.\n+ for _, addr := range s.stack.InterfaceAddrs()[index] {\n+ // This ioctl is only compatible with AF_INET addresses.\n+ if addr.Family != linux.AF_INET {\n+ continue\n+ }\n+ // Populate ifr.ifr_netmask (type sockaddr).\n+ usermem.ByteOrder.PutUint16(ifr.Data[0:2], uint16(linux.AF_INET))\n+ usermem.ByteOrder.PutUint16(ifr.Data[2:4], 0)\n+ var mask uint32 = 0xffffffff << (32 - addr.PrefixLen)\n+ // Netmask is expected to be returned as a big endian\n+ // value.\n+ binary.BigEndian.PutUint32(ifr.Data[4:8], mask)\n+ break\n+ }\ndefault:\n// Not a valid call.\n"
}
] | Go | Apache License 2.0 | google/gvisor | sentry: Adds the SIOCGIFNETMASK ioctl to epsocket.
PiperOrigin-RevId: 195489319
Change-Id: I0841d41d042c6f91aa8d7f62c127213aa7953eac |
259,854 | 04.05.2018 23:19:13 | 25,200 | 268edf0e6230c9455972c3343125d416a71a8759 | Remove ineffectual code in sentry ELF loader | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/elf.go",
"new_path": "pkg/sentry/loader/elf.go",
"diff": "@@ -408,11 +408,8 @@ func loadParsedELF(ctx context.Context, m *mm.MemoryManager, f *fs.File, info el\npath := make([]byte, phdr.Filesz)\n_, err := readFull(ctx, f, usermem.BytesIOSequence(path), int64(phdr.Off))\nif err != nil {\n- ctx.Infof(\"Error reading PT_INTERP path: %v\", err)\n// If an interpreter was specified, it should exist.\n- if err == io.EOF || err == io.ErrUnexpectedEOF {\n- err = syserror.ENOEXEC\n- }\n+ ctx.Infof(\"Error reading PT_INTERP path: %v\", err)\nreturn loadedELF{}, syserror.ENOEXEC\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove ineffectual code in sentry ELF loader
PiperOrigin-RevId: 195517702
Change-Id: Id90309a6365cac06e68e8774aa79dc76ce1b11c7 |
259,881 | 05.05.2018 00:26:55 | 25,200 | ebae2191622122a9d2fb321be65089bbb228a1e6 | Note architecture and Linux version requirements | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -166,8 +166,11 @@ and Docker.\n### Requirements\n-gVisor currently can only build and run on Linux. In addition, the following\n-dependencies must be installed.\n+gVisor currently can only build and run on x86\\_64 Linux 3.17+. In addition,\n+gVisor only supports x86\\_64 binaries inside the sandbox (i.e., it cannot run\n+32-bit binaries).\n+\n+In addition, the following dependencies must be installed:\n* [git][git]\n* [Bazel][bazel]\n"
}
] | Go | Apache License 2.0 | google/gvisor | Note architecture and Linux version requirements
PiperOrigin-RevId: 195522238
Change-Id: I0107f856bea72ea6af8b196c1c13bafbc293ce95 |
259,854 | 05.05.2018 01:21:46 | 25,200 | f0a17bf9103be7127588ce016ff5b0ab367ce5e7 | Remove dead code in urpc | [
{
"change_type": "MODIFY",
"old_path": "pkg/urpc/urpc.go",
"new_path": "pkg/urpc/urpc.go",
"diff": "@@ -332,9 +332,6 @@ func (s *Server) clientBeginRequest(client *unet.Socket) bool {\n// Should not happen.\npanic(fmt.Sprintf(\"expected idle or closed, got %d\", state))\n}\n-\n- // Unreachable.\n- return false\n}\n// clientEndRequest ends a request.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove dead code in urpc
PiperOrigin-RevId: 195525267
Change-Id: I7a5ef31365cb0c55c462deb9bdbec092473ebc6b |
259,992 | 07.05.2018 11:49:47 | 25,200 | 2c21e4c32c1746d1c6353fdd7dd98bb333f03ae2 | Make bug template more readable in edit mode
When editing the bug, the rendered view of the tags don't show up. This format is easier to read. | [
{
"change_type": "MODIFY",
"old_path": ".github/issue_template.md",
"new_path": ".github/issue_template.md",
"diff": "-Before filling an issue, please consult our [FAQ](https://github.com/google/gvisor#faq--known-issues)\n-and check that the issue hasn't been [reported before](https://github.com/google/gvisor/issues).\n+Before filling an issue, please consult our FAQ: https://github.com/google/gvisor#faq--known-issues\n+Also check that the issue hasn't been reported before.\n-If this is your first time compiling or running gVisor, please make sure that\n-your system meets the [minimum requirements](https://github.com/google/gvisor#requirements).\n+If you have a question, please send e-mail to [email protected] rather than filing a bug.\nIf you believe you've found a security issue, please email\[email protected] rather than filing a bug.\n+If this is your first time compiling or running gVisor, please make sure that your system meets the minimum requirements: https://github.com/google/gvisor#requirements\n+\nEnable [debug logs](https://github.com/google/gvisor#debugging), run your\nrepro, and attach the logs to the bug. Other useful information to include is:\n- `docker version` or `docker info` if more relevant\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make bug template more readable in edit mode
When editing the bug, the rendered view of the tags don't show up. This format is easier to read.
PiperOrigin-RevId: 195697019
Change-Id: If9bb818b7ecd28bb87608a52b3343d488144ebfd |
259,854 | 07.05.2018 15:52:00 | 25,200 | 5666e35c43cadf834845359d009322e67f1e6a0d | Improve consistency of github templates | [
{
"change_type": "MODIFY",
"old_path": ".github/issue_template.md",
"new_path": ".github/issue_template.md",
"diff": "Before filling an issue, please consult our FAQ: https://github.com/google/gvisor#faq--known-issues\nAlso check that the issue hasn't been reported before.\n-If you have a question, please send e-mail to [email protected] rather than filing a bug.\n+If you have a question, please email [email protected] rather than filing a bug.\n-If you believe you've found a security issue, please email\[email protected] rather than filing a bug.\n+If you believe you've found a security issue, please email [email protected] rather than filing a bug.\nIf this is your first time compiling or running gVisor, please make sure that your system meets the minimum requirements: https://github.com/google/gvisor#requirements\n-Enable [debug logs](https://github.com/google/gvisor#debugging), run your\n-repro, and attach the logs to the bug. Other useful information to include is:\n+For all other issues, please attach debug logs. To get debug logs, follow the instructions here: https://github.com/google/gvisor#debugging\n+\n+Other useful information to include is:\n- `docker version` or `docker info` if more relevant\n- `uname -a`\n- `git describe`\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/pull_request_template.md",
"new_path": ".github/pull_request_template.md",
"diff": "Thanks for contributing to gVisor!\n-gVisor development happens on [Gerrit][gerrit] rather than GitHub, so we don't\n-accept pull requests here.\n+gVisor development happens on Gerrit rather than GitHub, so we don't accept pull requests here. Gerrit can be found here: https://gvisor-review.googlesource.com\n-Please see the [contributing guidelines][contrib] for more information.\n-\n-[contrib]: https://github.com/google/gvisor/blob/master/CONTRIBUTING.md\n-[gerrit]: https://gvisor-review.googlesource.com\n+Please see the contributing guidelines for more information: https://github.com/google/gvisor/blob/master/CONTRIBUTING.md\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve consistency of github templates
PiperOrigin-RevId: 195735915
Change-Id: If4dcd836c3cf9da7c314b95101b23f95ff0eb234 |
259,854 | 07.05.2018 16:08:03 | 25,200 | d5104a56e56ece50d3ec562edc31493516960c0c | Improve consistency in go_stateify file generation
This also fixes the go_vet warning:
error: Fprintln call ends with newline (vet) | [
{
"change_type": "MODIFY",
"old_path": "tools/go_stateify/main.go",
"new_path": "tools/go_stateify/main.go",
"diff": "@@ -222,9 +222,9 @@ func main() {\n}\n// Emit the package name.\n- fmt.Fprintf(outputFile, \"// automatically generated by stateify.\\n\\n\")\n+ fmt.Fprint(outputFile, \"// automatically generated by stateify.\\n\\n\")\nfmt.Fprintf(outputFile, \"package %s\\n\\n\", *pkg)\n- fmt.Fprintln(outputFile, \"import (\")\n+ fmt.Fprint(outputFile, \"import (\\n\")\nif *statePkg != \"\" {\nfmt.Fprintf(outputFile, \" \\\"%s\\\"\\n\", *statePkg)\n}\n@@ -233,7 +233,7 @@ func main() {\nfmt.Fprintf(outputFile, \" \\\"%s\\\"\\n\", i)\n}\n}\n- fmt.Fprintln(outputFile, \")\\n\")\n+ fmt.Fprint(outputFile, \")\\n\\n\")\nfiles := make([]*ast.File, 0, len(flag.Args()))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve consistency in go_stateify file generation
This also fixes the go_vet warning:
error: Fprintln call ends with newline (vet)
PiperOrigin-RevId: 195738471
Change-Id: Ic7a9df40eec1457ef03e6ee70872c497a676b53c |
260,011 | 07.05.2018 16:36:14 | 25,200 | a445b17933d38ee6f9cea9138c6197a07387b462 | tools/go_generics: fix typo in documentation of the type flag | [
{
"change_type": "MODIFY",
"old_path": "tools/go_generics/generics.go",
"new_path": "tools/go_generics/generics.go",
"diff": "//\n// would be renamed to:\n//\n-// fun f(arg *B)\n+// func f(arg *B)\n//\n// 2. Global type definitions and their method sets will be removed when they're\n// being renamed with -t. For example, if -t=A=B is passed in, the following\n"
}
] | Go | Apache License 2.0 | google/gvisor | tools/go_generics: fix typo in documentation of the type flag
PiperOrigin-RevId: 195742471
Change-Id: I114657f9238675da23461817ca542bdcb81312c2 |
259,854 | 08.05.2018 09:38:55 | 25,200 | d0d01a18963ed7cfc29e5b8334e30b1234b6048b | Fix format string type in test | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/fd_map_test.go",
"new_path": "pkg/sentry/kernel/fd_map_test.go",
"diff": "@@ -119,16 +119,18 @@ func TestDescriptorFlags(t *testing.T) {\nlimitSet := limits.NewLimitSet()\nlimitSet.Set(limits.NumberOfFiles, limits.Limit{maxFD, maxFD})\n- if err := f.NewFDAt(2, file, FDFlags{CloseOnExec: true}, limitSet); err != nil {\n+ origFlags := FDFlags{CloseOnExec: true}\n+\n+ if err := f.NewFDAt(2, file, origFlags, limitSet); err != nil {\nt.Fatalf(\"f.NewFDAt(2, r, FDFlags{}): got %v, wanted nil\", err)\n}\n- newFile, flags := f.GetDescriptor(2)\n+ newFile, newFlags := f.GetDescriptor(2)\nif newFile == nil {\nt.Fatalf(\"f.GetFile(2): got a %v, wanted nil\", newFile)\n}\n- if !flags.CloseOnExec {\n- t.Fatalf(\"new File flags %d don't match original %d\\n\", flags, 0)\n+ if newFlags != origFlags {\n+ t.Fatalf(\"new File flags %+v don't match original %+v\", newFlags, origFlags)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix format string type in test
PiperOrigin-RevId: 195831778
Change-Id: I413dc909cedc18fbf5320a4f75d876f1be133c6c |
259,854 | 08.05.2018 09:51:07 | 25,200 | b4765f782d91443ab0415dc00e727d783632e2ad | Fix warning: redundant if ...; err != nil check, just return error instead.
This warning is produced by golint. | [
{
"change_type": "MODIFY",
"old_path": "pkg/bpf/decoder.go",
"new_path": "pkg/bpf/decoder.go",
"diff": "@@ -161,10 +161,7 @@ func decodeAlu(inst linux.BPFInstruction, w *bytes.Buffer) error {\ndefault:\nreturn fmt.Errorf(\"invalid BPF ALU instruction: %v\", inst)\n}\n- if err := decodeSource(inst, w); err != nil {\n- return err\n- }\n- return nil\n+ return decodeSource(inst, w)\n}\nfunc decodeSource(inst linux.BPFInstruction, w *bytes.Buffer) error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/compressio/compressio.go",
"new_path": "pkg/compressio/compressio.go",
"diff": "@@ -184,10 +184,7 @@ func handleResult(r result, callback func(*chunk) error) error {\nif r.err != nil {\nreturn r.err\n}\n- if err := callback(r.chunk); err != nil {\n- return err\n- }\n- return nil\n+ return callback(r.chunk)\n}\n// schedule schedules the given buffers.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/local_server/local_server.go",
"new_path": "pkg/p9/local_server/local_server.go",
"diff": "@@ -246,11 +246,7 @@ func (l *local) Symlink(oldname string, newname string, _ p9.UID, _ p9.GID) (p9.\n//\n// Not properly implemented.\nfunc (l *local) Link(target p9.File, newname string) error {\n- if err := os.Link(target.(*local).path, path.Join(l.path, newname)); err != nil {\n- return err\n- }\n-\n- return nil\n+ return os.Link(target.(*local).path, path.Join(l.path, newname))\n}\n// Mknod implements p9.File.Mknod.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/pipe.go",
"new_path": "pkg/sentry/fs/fdpipe/pipe.go",
"diff": "@@ -90,10 +90,7 @@ func (p *pipeOperations) init() error {\nif err := syscall.SetNonblock(p.file.FD(), true); err != nil {\nreturn err\n}\n- if err := fdnotifier.AddFD(int32(p.file.FD()), &p.Queue); err != nil {\n- return err\n- }\n- return nil\n+ return fdnotifier.AddFD(int32(p.file.FD()), &p.Queue)\n}\n// EventRegister implements waiter.Waitable.EventRegister.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/fs_test.go",
"new_path": "pkg/sentry/fs/host/fs_test.go",
"diff": "@@ -141,11 +141,7 @@ func createTestDirs(ctx context.Context, t *testing.T, m *fs.MountNamespace) err\nreturn err\n}\n- if err := symlinks.CreateLink(ctx, r, \"/symlinks\", \"recursive\"); err != nil {\n- return err\n- }\n-\n- return nil\n+ return symlinks.CreateLink(ctx, r, \"/symlinks\", \"recursive\")\n}\n// allPaths returns a slice of all paths of entries visible in the rootfs.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket.go",
"new_path": "pkg/sentry/fs/host/socket.go",
"diff": "@@ -69,10 +69,7 @@ func (e *endpoint) init() error {\n}\ne.stype = unix.SockType(stype)\n- if err := fdnotifier.AddFD(int32(e.fd), &e.queue); err != nil {\n- return err\n- }\n- return nil\n+ return fdnotifier.AddFD(int32(e.fd), &e.queue)\n}\n// newEndpoint creates a new host endpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_signals.go",
"new_path": "pkg/sentry/kernel/task_signals.go",
"diff": "@@ -127,10 +127,7 @@ func (t *Task) dequeueSignalLocked() *arch.SignalInfo {\nif info := t.pendingSignals.dequeue(t.tr.SignalMask); info != nil {\nreturn info\n}\n- if info := t.tg.pendingSignals.dequeue(t.tr.SignalMask); info != nil {\n- return info\n- }\n- return nil\n+ return t.tg.pendingSignals.dequeue(t.tr.SignalMask)\n}\n// TakeSignal returns a pending signal not blocked by mask. Signal handlers are\n@@ -144,10 +141,7 @@ func (t *Task) TakeSignal(mask linux.SignalSet) *arch.SignalInfo {\nif info := t.pendingSignals.dequeue(mask); info != nil {\nreturn info\n}\n- if info := t.tg.pendingSignals.dequeue(mask); info != nil {\n- return info\n- }\n- return nil\n+ return t.tg.pendingSignals.dequeue(mask)\n}\n// discardSpecificLocked removes all instances of the given signal from all\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -460,14 +460,11 @@ func accessAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, resolve bool, m\ncreds: creds,\n}\n- if err := d.Inode.CheckPermission(ctx, fs.PermMask{\n+ return d.Inode.CheckPermission(ctx, fs.PermMask{\nRead: mode&rOK != 0,\nWrite: mode&wOK != 0,\nExecute: mode&xOK != 0,\n- }); err != nil {\n- return err\n- }\n- return nil\n+ })\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_demuxer.go",
"new_path": "pkg/tcpip/stack/transport_demuxer.go",
"diff": "@@ -158,9 +158,5 @@ func (d *transportDemuxer) findEndpointLocked(eps *transportEndpoints, vv *buffe\n// Try to find a match with only the local port.\nnid.LocalAddress = \"\"\n- if ep := eps.endpoints[nid]; ep != nil {\n- return ep\n- }\n-\n- return nil\n+ return eps.endpoints[nid]\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix warning: redundant if ...; err != nil check, just return error instead.
This warning is produced by golint.
PiperOrigin-RevId: 195833381
Change-Id: Idd6a7e57e3cfdf00819f2374b19fc113585dc1e1 |
259,854 | 08.05.2018 09:58:09 | 25,200 | 09c323910d7f28fec9e4c92e5faaa92bb63bd431 | Reword misleading log line | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/loader.go",
"new_path": "pkg/sentry/loader/loader.go",
"diff": "@@ -85,7 +85,7 @@ func openPath(ctx context.Context, mm *fs.MountNamespace, root, wd *fs.Dirent, m\n// No exec-ing directories, pipes, etc!\nif !fs.IsRegular(d.Inode.StableAttr) {\n- ctx.Infof(\"Error regularing %s: %v\", name, d.Inode.StableAttr)\n+ ctx.Infof(\"%s is not regular: %v\", name, d.Inode.StableAttr)\nreturn nil, nil, syserror.EACCES\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Reword misleading log line
PiperOrigin-RevId: 195834310
Change-Id: I8af748f75ab87ad1cd29c4c8904d07fd729ba6c9 |
259,948 | 08.05.2018 10:06:14 | 25,200 | fea624b37a90c0e1efc0c1e7ae7dda7b2d1a0050 | Sentry: always use "best speed" compression for save and remove the option. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/state/state.go",
"new_path": "pkg/sentry/state/state.go",
"diff": "@@ -50,11 +50,6 @@ type SaveOpts struct {\n// Metadata is save metadata.\nMetadata map[string]string\n- // CompressionLevel is the compression level to use.\n- //\n- // See statefile.NewWriter for details.\n- CompressionLevel int\n-\n// Callback is called prior to unpause, with any save error.\nCallback func(err error)\n}\n@@ -76,7 +71,7 @@ func (opts SaveOpts) Save(k *kernel.Kernel, w *watchdog.Watchdog) error {\naddSaveMetadata(opts.Metadata)\n// Open the statefile.\n- wc, err := statefile.NewWriter(opts.Destination, opts.Key, opts.Metadata, opts.CompressionLevel)\n+ wc, err := statefile.NewWriter(opts.Destination, opts.Key, opts.Metadata)\nif err != nil {\nerr = ErrStateFile{err}\n} else {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/statefile/statefile.go",
"new_path": "pkg/state/statefile/statefile.go",
"diff": "@@ -45,6 +45,7 @@ package statefile\nimport (\n\"bytes\"\n+ \"compress/flate\"\n\"crypto/hmac\"\n\"crypto/sha256\"\n\"encoding/json\"\n@@ -86,7 +87,7 @@ var ErrMetadataInvalid = fmt.Errorf(\"metadata invalid, can't start with _\")\n// NewWriter returns a state data writer for a statefile.\n//\n// Note that the returned WriteCloser must be closed.\n-func NewWriter(w io.Writer, key []byte, metadata map[string]string, compressionLevel int) (io.WriteCloser, error) {\n+func NewWriter(w io.Writer, key []byte, metadata map[string]string) (io.WriteCloser, error) {\nif metadata == nil {\nmetadata = make(map[string]string)\n}\n@@ -140,8 +141,11 @@ func NewWriter(w io.Writer, key []byte, metadata map[string]string, compressionL\nw = hashio.NewWriter(w, h)\n- // Wrap in compression.\n- return compressio.NewWriter(w, compressionChunkSize, compressionLevel)\n+ // Wrap in compression. We always use \"best speed\" mode here. When using\n+ // \"best compression\" mode, there is usually only a little gain in file\n+ // size reduction, which translate to even smaller gain in restore\n+ // latency reduction, while inccuring much more CPU usage at save time.\n+ return compressio.NewWriter(w, compressionChunkSize, flate.BestSpeed)\n}\n// MetadataUnsafe reads out the metadata from a state file without verifying any\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/statefile/statefile_test.go",
"new_path": "pkg/state/statefile/statefile_test.go",
"diff": "@@ -16,7 +16,6 @@ package statefile\nimport (\n\"bytes\"\n- \"compress/flate\"\ncrand \"crypto/rand\"\n\"encoding/base64\"\n\"io\"\n@@ -89,7 +88,7 @@ func TestStatefile(t *testing.T) {\nvar bufDecoded bytes.Buffer\n// Do all the writing.\n- w, err := NewWriter(&bufEncoded, key, c.metadata, flate.BestSpeed)\n+ w, err := NewWriter(&bufEncoded, key, c.metadata)\nif err != nil {\nt.Fatalf(\"error creating writer: got %v, expected nil\", err)\n}\n@@ -195,7 +194,7 @@ func benchmark(b *testing.B, size int, write bool, compressible bool) {\nvar stateBuf bytes.Buffer\nwriteState := func() {\nstateBuf.Reset()\n- w, err := NewWriter(&stateBuf, key, nil, flate.BestSpeed)\n+ w, err := NewWriter(&stateBuf, key, nil)\nif err != nil {\nb.Fatalf(\"error creating writer: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Sentry: always use "best speed" compression for save and remove the option.
PiperOrigin-RevId: 195835861
Change-Id: Ib696b1b571a6b061725a33c535cd7215fe518b97 |
259,992 | 08.05.2018 10:33:20 | 25,200 | e1b412d6609c848ff09356ead133b51cd0589731 | Error if container requires AppArmor, SELinux or seccomp
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -53,6 +53,22 @@ func validateID(id string) error {\nreturn nil\n}\n+func validateSpec(spec *specs.Spec) error {\n+ if spec.Process.SelinuxLabel != \"\" {\n+ return fmt.Errorf(\"SELinux is not supported: %s\", spec.Process.SelinuxLabel)\n+ }\n+\n+ // Docker uses AppArmor by default, so just log that it's being ignored.\n+ if spec.Process.ApparmorProfile != \"\" {\n+ log.Warningf(\"AppArmor profile %q is being ignored\", spec.Process.ApparmorProfile)\n+ }\n+ // TODO: Apply seccomp to application inside sandbox.\n+ if spec.Linux != nil && spec.Linux.Seccomp != nil {\n+ log.Warningf(\"Seccomp spec is being ignored\")\n+ }\n+ return nil\n+}\n+\n// Sandbox wraps a child sandbox process, and is responsible for saving and\n// loading sandbox metadata to disk.\n//\n@@ -110,6 +126,9 @@ func Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSo\nif err := validateID(id); err != nil {\nreturn nil, err\n}\n+ if err := validateSpec(spec); err != nil {\n+ return nil, err\n+ }\nsandboxRoot := filepath.Join(conf.RootDir, id)\nif exists(sandboxRoot) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox_test.go",
"new_path": "runsc/sandbox/sandbox_test.go",
"diff": "@@ -567,6 +567,28 @@ func TestConsoleSocket(t *testing.T) {\n}\n}\n+func TestSpecUnsupported(t *testing.T) {\n+ spec := newSpecWithArgs(\"/bin/true\")\n+ spec.Process.SelinuxLabel = \"somelabel\"\n+\n+ // These are normally set by docker and will just cause warnings to be logged.\n+ spec.Process.ApparmorProfile = \"someprofile\"\n+ spec.Linux = &specs.Linux{Seccomp: &specs.LinuxSeccomp{}}\n+\n+ rootDir, bundleDir, conf, err := setupSandbox(spec)\n+ if err != nil {\n+ t.Fatalf(\"error setting up sandbox: %v\", err)\n+ }\n+ defer os.RemoveAll(rootDir)\n+ defer os.RemoveAll(bundleDir)\n+\n+ id := uniqueSandboxID()\n+ _, err = sandbox.Create(id, spec, conf, bundleDir, \"\", \"\", nil)\n+ if err == nil || !strings.Contains(err.Error(), \"is not supported\") {\n+ t.Errorf(\"sandbox.Create() wrong error, got: %v, want: *is not supported, spec.Process: %+v\", err, spec.Process)\n+ }\n+}\n+\n// procListsEqual is used to check whether 2 Process lists are equal for all\n// implemented fields.\nfunc procListsEqual(got, want []*control.Process) bool {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Error if container requires AppArmor, SELinux or seccomp
Closes #35
PiperOrigin-RevId: 195840128
Change-Id: I31c1ad9b51ec53abb6f0b485d35622d4e9764b29 |
259,885 | 08.05.2018 11:25:40 | 25,200 | 3ac3ea1d6afea0b128112e6a46b8bf47b4b0e02a | Correct definition of SysV IPC structures. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/ipc.go",
"new_path": "pkg/abi/linux/ipc.go",
"diff": "package linux\n-// Control commands used with semctl. Source: //include/uapi/linux/ipc.h.\n+// Control commands used with semctl, shmctl, and msgctl. Source:\n+// include/uapi/linux/ipc.h.\nconst (\nIPC_RMID = 0\nIPC_SET = 1\n@@ -22,7 +23,7 @@ const (\nIPC_INFO = 3\n)\n-// resource get request flags. Source: //include/uapi/linux/ipc.h\n+// resource get request flags. Source: include/uapi/linux/ipc.h\nconst (\nIPC_CREAT = 00001000\nIPC_EXCL = 00002000\n@@ -31,7 +32,11 @@ const (\nconst IPC_PRIVATE = 0\n-// IPCPerm is equivalent to struct ipc_perm.\n+// In Linux, amd64 does not enable CONFIG_ARCH_WANT_IPC_PARSE_VERSION, so SysV\n+// IPC unconditionally uses the \"new\" 64-bit structures that are needed for\n+// features like 32-bit UIDs.\n+\n+// IPCPerm is equivalent to struct ipc64_perm.\ntype IPCPerm struct {\nKey uint32\nUID uint32\n@@ -42,6 +47,7 @@ type IPCPerm struct {\npad1 uint16\nSeq uint16\npad2 uint16\n- reserved1 uint32\n- reserved2 uint32\n+ pad3 uint32\n+ unused1 uint64\n+ unused2 uint64\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/sem.go",
"new_path": "pkg/abi/linux/sem.go",
"diff": "package linux\n-// semctl Command Definitions. Source: //include/uapi/linux/sem.h\n+// semctl Command Definitions. Source: include/uapi/linux/sem.h\nconst (\nGETPID = 11\nGETVAL = 12\n@@ -25,7 +25,7 @@ const (\nSETALL = 17\n)\n-// ipcs ctl cmds. Source: //include/uapi/linux/sem.h\n+// ipcs ctl cmds. Source: include/uapi/linux/sem.h\nconst (\nSEM_STAT = 18\nSEM_INFO = 19\n@@ -33,16 +33,14 @@ const (\nconst SEM_UNDO = 0x1000\n-// SemidDS is equivalent to struct semid_ds.\n+// SemidDS is equivalent to struct semid64_ds.\ntype SemidDS struct {\nSemPerm IPCPerm\nSemOTime TimeT\n- reserved1 uint32\nSemCTime TimeT\n- reserved2 uint32\n- SemNSems uint32\n- reserved3 uint32\n- reserved4 uint32\n+ SemNSems uint64\n+ unused3 uint64\n+ unused4 uint64\n}\n// Sembuf is equivalent to struct sembuf.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Correct definition of SysV IPC structures.
PiperOrigin-RevId: 195849066
Change-Id: If2146c7ce649522f86e661c5e52a9983345d6967 |
259,948 | 08.05.2018 11:36:11 | 25,200 | 174161013de22be6a42b02ee06611a9de9e20b18 | Capture restore file system corruption errors in exit error. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/pipe_state.go",
"new_path": "pkg/sentry/fs/fdpipe/pipe_state.go",
"diff": "@@ -63,7 +63,7 @@ func (p *pipeOperations) loadFlags(flags fs.FileFlags) {\n// afterLoad is invoked by stateify.\nfunc (p *pipeOperations) afterLoad() {\n- load := func() {\n+ load := func() error {\nif !p.flags.Read {\nreadPipeOperationsLoading.Wait()\n} else {\n@@ -75,14 +75,15 @@ func (p *pipeOperations) afterLoad() {\nWrite: p.flags.Write,\n})\nif err != nil {\n- panic(fmt.Sprintf(\"unable to open pipe %v: %v\", p, err))\n+ return fmt.Errorf(\"unable to open pipe %v: %v\", p, err)\n}\nif err := p.init(); err != nil {\n- panic(fmt.Sprintf(\"unable to initialize pipe %v: %v\", p, err))\n+ return fmt.Errorf(\"unable to initialize pipe %v: %v\", p, err)\n}\n+ return nil\n}\n// Do background opening of pipe ends. Note for write-only pipe ends we\n// have to do it asynchronously to avoid blocking the restore.\n- fs.Async(load)\n+ fs.Async(fs.CatchError(load))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fs.go",
"new_path": "pkg/sentry/fs/fs.go",
"diff": "@@ -55,11 +55,19 @@ package fs\nimport (\n\"sync\"\n+\n+ \"gvisor.googlesource.com/gvisor/pkg/log\"\n)\n-// work is a sync.WaitGroup that can be used to queue asynchronous operations\n-// via Do. Callers can use Barrier to ensure no operations are outstanding.\n-var work sync.WaitGroup\n+var (\n+ // work is a sync.WaitGroup that can be used to queue asynchronous\n+ // operations via Do. Callers can use Barrier to ensure no operations\n+ // are outstanding.\n+ work sync.WaitGroup\n+\n+ // asyncError is used to store up to one asynchronous execution error.\n+ asyncError = make(chan error, 1)\n+)\n// AsyncBarrier waits for all outstanding asynchronous work to complete.\nfunc AsyncBarrier() {\n@@ -75,6 +83,43 @@ func Async(f func()) {\n}()\n}\n+// AsyncErrorBarrier waits for all outstanding asynchronous work to complete, or\n+// the first async error to arrive. Other unfinished async executions will\n+// continue in the background. Other past and future async errors are ignored.\n+func AsyncErrorBarrier() error {\n+ wait := make(chan struct{}, 1)\n+ go func() { // S/R-SAFE: Does not touch persistent state.\n+ work.Wait()\n+ wait <- struct{}{}\n+ }()\n+ select {\n+ case <-wait:\n+ select {\n+ case err := <-asyncError:\n+ return err\n+ default:\n+ return nil\n+ }\n+ case err := <-asyncError:\n+ return err\n+ }\n+}\n+\n+// CatchError tries to capture the potential async error returned by the\n+// function. At most one async error will be captured globally so excessive\n+// errors will be dropped.\n+func CatchError(f func() error) func() {\n+ return func() {\n+ if err := f(); err != nil {\n+ select {\n+ case asyncError <- err:\n+ default:\n+ log.Warningf(\"excessive async error dropped: %v\", err)\n+ }\n+ }\n+ }\n+}\n+\n// ErrSaveRejection indicates a failed save due to unsupported file system state\n// such as dangling open fd, etc.\ntype ErrSaveRejection struct {\n@@ -86,3 +131,15 @@ type ErrSaveRejection struct {\nfunc (e ErrSaveRejection) Error() string {\nreturn \"save rejected due to unsupported file system state: \" + e.Err.Error()\n}\n+\n+// ErrCorruption indicates a failed restore due to external file system state in\n+// corruption.\n+type ErrCorruption struct {\n+ // Err is the wrapped error.\n+ Err error\n+}\n+\n+// Error returns a sensible description of the save rejection error.\n+func (e ErrCorruption) Error() string {\n+ return \"restore failed due to external file system state in corruption: \" + e.Err.Error()\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/file_state.go",
"new_path": "pkg/sentry/fs/gofer/file_state.go",
"diff": "package gofer\nimport (\n+ \"fmt\"\n+\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n)\n// afterLoad is invoked by stateify.\nfunc (f *fileOperations) afterLoad() {\n- load := func() {\n+ load := func() error {\nf.inodeOperations.fileState.waitForLoad()\n// Manually load the open handles.\n@@ -29,9 +31,10 @@ func (f *fileOperations) afterLoad() {\n// TODO: Context is not plumbed to save/restore.\nf.handles, err = newHandles(context.Background(), f.inodeOperations.fileState.file, f.flags)\nif err != nil {\n- panic(\"failed to re-open handle: \" + err.Error())\n+ return fmt.Errorf(\"failed to re-open handle: %v\", err)\n}\nf.inodeOperations.fileState.setHandlesForCachedIO(f.flags, f.handles)\n+ return nil\n}\n- fs.Async(load)\n+ fs.Async(fs.CatchError(load))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/inode_state.go",
"new_path": "pkg/sentry/fs/gofer/inode_state.go",
"diff": "package gofer\nimport (\n+ \"errors\"\n\"fmt\"\n\"strings\"\n@@ -83,7 +84,7 @@ func (i *inodeFileState) loadLoading(_ struct{}) {\n// afterLoad is invoked by stateify.\nfunc (i *inodeFileState) afterLoad() {\n- load := func() {\n+ load := func() error {\n// See comment on i.loading().\ndefer i.loading.Unlock()\n@@ -92,14 +93,14 @@ func (i *inodeFileState) afterLoad() {\nif !ok {\n// This should be impossible, see assertion in\n// beforeSave.\n- panic(fmt.Sprintf(\"failed to find path for inode number %d. Device %s contains %s\", i.sattr.InodeID, i.s.connID, fs.InodeMappings(i.s.inodeMappings)))\n+ return fmt.Errorf(\"failed to find path for inode number %d. Device %s contains %s\", i.sattr.InodeID, i.s.connID, fs.InodeMappings(i.s.inodeMappings))\n}\n// TODO: Context is not plumbed to save/restore.\nctx := &dummyClockContext{context.Background()}\nvar err error\n_, i.file, err = i.s.attach.walk(ctx, strings.Split(name, \"/\"))\nif err != nil {\n- panic(fmt.Sprintf(\"failed to walk to %q: %v\", name, err))\n+ return fmt.Errorf(\"failed to walk to %q: %v\", name, err)\n}\n// Remap the saved inode number into the gofer device using the\n@@ -107,10 +108,10 @@ func (i *inodeFileState) afterLoad() {\n// environment.\nqid, mask, attrs, err := i.file.getAttr(ctx, p9.AttrMaskAll())\nif err != nil {\n- panic(fmt.Sprintf(\"failed to get file attributes of %s: %v\", name, err))\n+ return fmt.Errorf(\"failed to get file attributes of %s: %v\", name, err)\n}\nif !mask.RDev {\n- panic(fmt.Sprintf(\"file %s lacks device\", name))\n+ return fs.ErrCorruption{fmt.Errorf(\"file %s lacks device\", name)}\n}\ni.key = device.MultiDeviceKey{\nDevice: attrs.RDev,\n@@ -118,24 +119,26 @@ func (i *inodeFileState) afterLoad() {\nInode: qid.Path,\n}\nif !goferDevice.Load(i.key, i.sattr.InodeID) {\n- panic(fmt.Sprintf(\"gofer device %s -> %d conflict in gofer device mappings: %s\", i.key, i.sattr.InodeID, goferDevice))\n+ return fs.ErrCorruption{fmt.Errorf(\"gofer device %s -> %d conflict in gofer device mappings: %s\", i.key, i.sattr.InodeID, goferDevice)}\n}\nif i.sattr.Type == fs.RegularFile {\nenv, ok := fs.CurrentRestoreEnvironment()\nif !ok {\n- panic(\"missing restore environment\")\n+ return errors.New(\"missing restore environment\")\n}\nuattr := unstable(ctx, mask, attrs, i.s.mounter, i.s.client)\nif env.ValidateFileSize && uattr.Size != i.savedUAttr.Size {\n- panic(fmt.Errorf(\"file size has changed for %s: previously %d, now %d\", i.s.inodeMappings[i.sattr.InodeID], i.savedUAttr.Size, uattr.Size))\n+ return fs.ErrCorruption{fmt.Errorf(\"file size has changed for %s: previously %d, now %d\", i.s.inodeMappings[i.sattr.InodeID], i.savedUAttr.Size, uattr.Size)}\n}\nif env.ValidateFileTimestamp && uattr.ModificationTime != i.savedUAttr.ModificationTime {\n- panic(fmt.Errorf(\"file modification time has changed for %s: previously %v, now %v\", i.s.inodeMappings[i.sattr.InodeID], i.savedUAttr.ModificationTime, uattr.ModificationTime))\n+ return fs.ErrCorruption{fmt.Errorf(\"file modification time has changed for %s: previously %v, now %v\", i.s.inodeMappings[i.sattr.InodeID], i.savedUAttr.ModificationTime, uattr.ModificationTime)}\n}\ni.savedUAttr = nil\n}\n+\n+ return nil\n}\n- fs.Async(load)\n+ fs.Async(fs.CatchError(load))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/inode_state.go",
"new_path": "pkg/sentry/fs/host/inode_state.go",
"diff": "@@ -59,7 +59,7 @@ func (i *inodeFileState) afterLoad() {\n// saved filesystem are no longer unique on this filesystem.\n// Since this violates the contract that filesystems cannot\n// change across save and restore, error out.\n- panic(fmt.Sprintf(\"host %s conflict in host device mappings: %s\", key, hostFileDevice))\n+ panic(fs.ErrCorruption{fmt.Errorf(\"host %s conflict in host device mappings: %s\", key, hostFileDevice)})\n}\nif !i.descriptor.donated && i.sattr.Type == fs.RegularFile {\n@@ -69,10 +69,10 @@ func (i *inodeFileState) afterLoad() {\n}\nuattr := unstableAttr(i.mops, &s)\nif env.ValidateFileSize && uattr.Size != i.savedUAttr.Size {\n- panic(fmt.Errorf(\"file size has changed for %s: previously %d, now %d\", i.mops.inodeMappings[i.sattr.InodeID], i.savedUAttr.Size, uattr.Size))\n+ panic(fs.ErrCorruption{fmt.Errorf(\"file size has changed for %s: previously %d, now %d\", i.mops.inodeMappings[i.sattr.InodeID], i.savedUAttr.Size, uattr.Size)})\n}\nif env.ValidateFileTimestamp && uattr.ModificationTime != i.savedUAttr.ModificationTime {\n- panic(fmt.Errorf(\"file modification time has changed for %s: previously %v, now %v\", i.mops.inodeMappings[i.sattr.InodeID], i.savedUAttr.ModificationTime, uattr.ModificationTime))\n+ panic(fs.ErrCorruption{fmt.Errorf(\"file modification time has changed for %s: previously %v, now %v\", i.mops.inodeMappings[i.sattr.InodeID], i.savedUAttr.ModificationTime, uattr.ModificationTime)})\n}\ni.savedUAttr = nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -418,7 +418,9 @@ func (k *Kernel) LoadFrom(r io.Reader, p platform.Platform, net inet.Stack) erro\n// Ensure that all pending asynchronous work is complete:\n// - namedpipe opening\n// - inode file opening\n- fs.AsyncBarrier()\n+ if err := fs.AsyncErrorBarrier(); err != nil {\n+ return err\n+ }\nlog.Infof(\"Overall load took [%s]\", time.Since(loadStart))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Capture restore file system corruption errors in exit error.
PiperOrigin-RevId: 195850822
Change-Id: I4d7bdd8fe129c5ed461b73e1d7458be2cf5680c2 |
259,885 | 08.05.2018 16:14:00 | 25,200 | 10a2cfc6a9216cb32e3a930016178d3c15ccc383 | Implement /proc/[pid]/statm. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -81,6 +81,7 @@ func newTaskDir(t *kernel.Task, msrc *fs.MountSource, pidns *kernel.PIDNamespace\n\"mounts\": seqfile.NewSeqFileInode(t, &mountsFile{t: t}, msrc),\n\"ns\": newNamespaceDir(t, msrc),\n\"stat\": newTaskStat(t, msrc, showSubtasks, pidns),\n+ \"statm\": newStatm(t, msrc),\n\"status\": newStatus(t, msrc, pidns),\n\"uid_map\": newUIDMap(t, msrc),\n}, fs.RootOwner, fs.FilePermsFromMode(0555))\n@@ -389,6 +390,40 @@ func (s *taskStatData) ReadSeqFileData(h seqfile.SeqHandle) ([]seqfile.SeqData,\nreturn []seqfile.SeqData{{Buf: buf.Bytes(), Handle: (*taskStatData)(nil)}}, 0\n}\n+// statmData implements seqfile.SeqSource for /proc/[pid]/statm.\n+type statmData struct {\n+ t *kernel.Task\n+}\n+\n+func newStatm(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ return newFile(seqfile.NewSeqFile(t, &statmData{t}), msrc, fs.SpecialFile, t)\n+}\n+\n+// NeedsUpdate implements seqfile.SeqSource.NeedsUpdate.\n+func (s *statmData) NeedsUpdate(generation int64) bool {\n+ return true\n+}\n+\n+// ReadSeqFileData implements seqfile.SeqSource.ReadSeqFileData.\n+func (s *statmData) ReadSeqFileData(h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+ if h != nil {\n+ return nil, 0\n+ }\n+\n+ var vss, rss uint64\n+ s.t.WithMuLocked(func(t *kernel.Task) {\n+ if mm := t.MemoryManager(); mm != nil {\n+ vss = mm.VirtualMemorySize()\n+ rss = mm.ResidentSetSize()\n+ }\n+ })\n+\n+ var buf bytes.Buffer\n+ fmt.Fprintf(&buf, \"%d %d 0 0 0 0 0\\n\", vss/usermem.PageSize, rss/usermem.PageSize)\n+\n+ return []seqfile.SeqData{{Buf: buf.Bytes(), Handle: (*statmData)(nil)}}, 0\n+}\n+\n// statusData implements seqfile.SeqSource for /proc/[pid]/status.\ntype statusData struct {\nt *kernel.Task\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement /proc/[pid]/statm.
PiperOrigin-RevId: 195893391
Change-Id: I645b7042d7f4f9dd54723afde3e5df0986e43160 |
259,948 | 08.05.2018 17:23:06 | 25,200 | ad278d69447ddca9c6923e5e830c12f1329438b9 | state: serialize string as bytes instead of protobuf string.
Protobuf strings have to be encoded or 7-bit ASCII. | [
{
"change_type": "MODIFY",
"old_path": "pkg/state/decode.go",
"new_path": "pkg/state/decode.go",
"diff": "@@ -335,7 +335,7 @@ func (ds *decodeState) decodeObject(os *objectState, obj reflect.Value, object *\ncase *pb.Object_BoolValue:\nobj.SetBool(x.BoolValue)\ncase *pb.Object_StringValue:\n- obj.SetString(x.StringValue)\n+ obj.SetString(string(x.StringValue))\ncase *pb.Object_Int64Value:\nobj.SetInt(x.Int64Value)\nif obj.Int() != x.Int64Value {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/encode.go",
"new_path": "pkg/state/encode.go",
"diff": "@@ -308,7 +308,7 @@ func (es *encodeState) encodeObject(obj reflect.Value, mapAsValue bool, format s\n}}}\n}\ncase reflect.String:\n- object = &pb.Object{Value: &pb.Object_StringValue{obj.String()}}\n+ object = &pb.Object{Value: &pb.Object_StringValue{[]byte(obj.String())}}\ncase reflect.Ptr:\nif obj.IsNil() {\n// Handled specially in decode; store as a nil value.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/object.proto",
"new_path": "pkg/state/object.proto",
"diff": "@@ -114,7 +114,7 @@ message Float32s {\nmessage Object {\noneof value {\nbool bool_value = 1;\n- string string_value = 2;\n+ bytes string_value = 2;\nint64 int64_value = 3;\nuint64 uint64_value = 4;\ndouble double_value = 5;\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/printer.go",
"new_path": "pkg/state/printer.go",
"diff": "@@ -30,7 +30,7 @@ func format(graph uint64, depth int, object *pb.Object, html bool) (string, bool\ncase *pb.Object_BoolValue:\nreturn fmt.Sprintf(\"%t\", x.BoolValue), x.BoolValue != false\ncase *pb.Object_StringValue:\n- return fmt.Sprintf(\"\\\"%s\\\"\", x.StringValue), x.StringValue != \"\"\n+ return fmt.Sprintf(\"\\\"%s\\\"\", string(x.StringValue)), len(x.StringValue) != 0\ncase *pb.Object_Int64Value:\nreturn fmt.Sprintf(\"%d\", x.Int64Value), x.Int64Value != 0\ncase *pb.Object_Uint64Value:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/state_test.go",
"new_path": "pkg/state/state_test.go",
"diff": "@@ -430,6 +430,7 @@ func TestTypes(t *testing.T) {\n\"\",\n\"foo\",\n\"bar\",\n+ \"\\xa0\",\n},\n},\n{\n"
}
] | Go | Apache License 2.0 | google/gvisor | state: serialize string as bytes instead of protobuf string.
Protobuf strings have to be UTF-8 encoded or 7-bit ASCII.
PiperOrigin-RevId: 195902557
Change-Id: I9800afd47ecfa6615e28a2cce7f2532f04f10763 |
259,992 | 09.05.2018 15:43:47 | 25,200 | 4453b56bd92c4ab9c0480dd99e80c65994711d33 | Increment link count in CreateHardlink
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/path.go",
"new_path": "pkg/sentry/fs/gofer/path.go",
"diff": "@@ -150,8 +150,10 @@ func (i *inodeOperations) CreateHardLink(ctx context.Context, _ *fs.Inode, targe\nif err := i.fileState.file.link(ctx, &targetOpts.fileState.file, newName); err != nil {\nreturn err\n}\n- // TODO: Don't increase link count because we can't properly accounts for links\n- // with gofers.\n+ if i.session().cachePolicy == cacheAll {\n+ // Increase link count.\n+ targetOpts.cachingInodeOps.IncLinks(ctx)\n+ }\ni.touchModificationTime(ctx)\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Increment link count in CreateHardlink
Closes #28
PiperOrigin-RevId: 196041391
Change-Id: I5d79f1735b9d72744e8bebc6897002b27df9aa7a |
259,992 | 10.05.2018 12:37:46 | 25,200 | 5a509c47a20e0b81b95bb4932e8b19dfc6a402e2 | Open file as read-write when mount points to a file
This is to allow files mapped directly, like /etc/hosts, to be writable.
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -98,7 +98,17 @@ func (a *attachPoint) Attach(appPath string) (p9.File, error) {\n}\nroot := filepath.Join(a.prefix, appPath)\n- f, err := os.OpenFile(root, openFlags|syscall.O_RDONLY, 0)\n+ fi, err := os.Stat(root)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ mode := syscall.O_RDWR\n+ if a.conf.ROMount || fi.IsDir() {\n+ mode = syscall.O_RDONLY\n+ }\n+\n+ f, err := os.OpenFile(root, mode|openFlags, 0)\nif err != nil {\nreturn nil, fmt.Errorf(\"unable to open file %q, err: %v\", root, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer_test.go",
"new_path": "runsc/fsgofer/fsgofer_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"io/ioutil\"\n\"os\"\n+ \"path\"\n\"syscall\"\n\"testing\"\n@@ -102,7 +103,7 @@ func setup(ft fileType) (string, string, error) {\nreturn \"\", \"\", fmt.Errorf(\"ioutil.TempDir() failed, err: %v\", err)\n}\n- // First attach with writable configuiration to setup tree.\n+ // First attach with writable configuration to setup tree.\na := NewAttachPoint(path, Config{})\nroot, err := a.Attach(\"/\")\nif err != nil {\n@@ -574,3 +575,50 @@ func TestReaddir(t *testing.T) {\n}\n})\n}\n+\n+// Test that attach point can be written to when it points to a file, e.g.\n+// /etc/hosts.\n+func TestAttachFile(t *testing.T) {\n+ conf := Config{ROMount: false}\n+ dir, err := ioutil.TempDir(\"\", \"root-\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed, err: %v\", err)\n+ }\n+ defer os.RemoveAll(dir)\n+\n+ path := path.Join(dir, \"test\")\n+ if _, err := os.Create(path); err != nil {\n+ t.Fatalf(\"os.Create(%q) failed, err: %v\", path, err)\n+ }\n+\n+ a := NewAttachPoint(path, conf)\n+ root, err := a.Attach(\"/\")\n+ if err != nil {\n+ t.Fatalf(\"Attach(%q) failed, err: %v\", \"/\", err)\n+ }\n+\n+ if _, _, _, err := root.Open(p9.ReadWrite); err != nil {\n+ t.Fatalf(\"Open(ReadWrite) failed, err: %v\", err)\n+ }\n+ defer root.Close()\n+\n+ b := []byte(\"foobar\")\n+ w, err := root.WriteAt(b, 0)\n+ if err != nil {\n+ t.Fatalf(\"Write() failed, err: %v\", err)\n+ }\n+ if w != len(b) {\n+ t.Fatalf(\"Write() was partial, got: %d, expected: %d\", w, len(b))\n+ }\n+ rBuf := make([]byte, len(b))\n+ r, err := root.ReadAt(rBuf, 0)\n+ if err != nil {\n+ t.Fatalf(\"ReadAt() failed, err: %v\", err)\n+ }\n+ if r != len(rBuf) {\n+ t.Fatalf(\"ReadAt() was partial, got: %d, expected: %d\", r, len(rBuf))\n+ }\n+ if string(rBuf) != \"foobar\" {\n+ t.Fatalf(\"ReadAt() wrong data, got: %s, expected: %s\", string(rBuf), \"foobar\")\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Open file as read-write when mount points to a file
This is to allow files mapped directly, like /etc/hosts, to be writable.
Closes #40
PiperOrigin-RevId: 196155920
Change-Id: Id2027e421cef5f94a0951c3e18b398a77c285bbd |
259,992 | 10.05.2018 12:46:27 | 25,200 | 31a4fefbe0a44377f75888284c9be0a3bec2a017 | Make cachePolicy int to avoid string comparison | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/fs.go",
"new_path": "pkg/sentry/fs/gofer/fs.go",
"diff": "@@ -57,20 +57,26 @@ const (\n)\n// cachePolicy is a 9p cache policy.\n-type cachePolicy string\n+type cachePolicy int\nconst (\n- // Use virtual file system cache.\n- cacheAll cachePolicy = \"fscache\"\n-\n// TODO: fully support cache=none.\n- cacheNone cachePolicy = \"none\"\n+ cacheNone cachePolicy = iota\n- // defaultCache is cacheAll. Note this diverges from the 9p Linux\n- // client whose default is \"none\". See TODO above.\n- defaultCache = cacheAll\n+ // Use virtual file system cache.\n+ cacheAll\n)\n+func parseCachePolicy(policy string) (cachePolicy, error) {\n+ switch policy {\n+ case \"fscache\":\n+ return cacheAll, nil\n+ case \"none\":\n+ return cacheNone, nil\n+ }\n+ return cacheNone, fmt.Errorf(\"unsupported cache mode: %s\", policy)\n+}\n+\n// defaultAname is the default attach name.\nconst defaultAname = \"/\"\n@@ -206,11 +212,12 @@ func options(data string) (opts, error) {\n// Parse the cache policy. Reject unsupported policies.\no.policy = cacheAll\n- if cp, ok := options[cacheKey]; ok {\n- if cachePolicy(cp) != cacheAll && cachePolicy(cp) != cacheNone {\n- return o, fmt.Errorf(\"unsupported cache mode: 'cache=%s'\", cp)\n+ if policy, ok := options[cacheKey]; ok {\n+ cp, err := parseCachePolicy(policy)\n+ if err != nil {\n+ return o, err\n}\n- o.policy = cachePolicy(cp)\n+ o.policy = cp\ndelete(options, cacheKey)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make cachePolicy int to avoid string comparison
PiperOrigin-RevId: 196157086
Change-Id: Ia7f7ffe1bf486b21ef8091e2e8ef9a9faf733dfc |
259,992 | 10.05.2018 17:12:21 | 25,200 | 7cff8489de2254cf355ec81cebc2338e0035f2df | Fix failure to rename directory
os.Rename validates that the target doesn't exist, which is different from
syscall.Rename which replace the target if both are directories. fsgofer needs
the syscall behavior. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -708,7 +708,7 @@ func (l *localFile) Rename(directory p9.File, name string) error {\n// TODO: change to renameat(2)\nparent := directory.(*localFile)\nnewPath := path.Join(parent.hostPath, name)\n- if err := os.Rename(l.hostPath, newPath); err != nil {\n+ if err := syscall.Rename(l.hostPath, newPath); err != nil {\nreturn extractErrno(err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix failure to rename directory
os.Rename validates that the target doesn't exist, which is different from
syscall.Rename which replace the target if both are directories. fsgofer needs
the syscall behavior.
PiperOrigin-RevId: 196194630
Change-Id: I87d08cad88b5ef310b245cd91647c4f5194159d8 |
259,885 | 11.05.2018 11:16:57 | 25,200 | 12c161f27865d0e389cd593c669bd740d7f24692 | Implement MAP_32BIT. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/mm.go",
"new_path": "pkg/abi/linux/mm.go",
"diff": "@@ -31,6 +31,7 @@ const (\nMAP_PRIVATE = 1 << 1\nMAP_FIXED = 1 << 4\nMAP_ANONYMOUS = 1 << 5\n+ MAP_32BIT = 1 << 6 // arch/x86/include/uapi/asm/mman.h\nMAP_GROWSDOWN = 1 << 8\nMAP_DENYWRITE = 1 << 11\nMAP_EXECUTABLE = 1 << 12\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/memmap/memmap.go",
"new_path": "pkg/sentry/memmap/memmap.go",
"diff": "@@ -266,6 +266,12 @@ type MMapOpts struct {\n// be replaced. If Unmap is true, Fixed must be true.\nUnmap bool\n+ // If Map32Bit is true, all addresses in the created mapping must fit in a\n+ // 32-bit integer. (Note that the \"end address\" of the mapping, i.e. the\n+ // address of the first byte *after* the mapping, need not fit in a 32-bit\n+ // integer.) Map32Bit is ignored if Fixed is true.\n+ Map32Bit bool\n+\n// Perms is the set of permissions to the applied to this mapping.\nPerms usermem.AccessType\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/vma.go",
"new_path": "pkg/sentry/mm/vma.go",
"diff": "@@ -37,6 +37,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\nAddr: opts.Addr,\nFixed: opts.Fixed,\nUnmap: opts.Unmap,\n+ Map32Bit: opts.Map32Bit,\n})\nif err != nil {\nreturn vmaIterator{}, usermem.AddrRange{}, err\n@@ -93,24 +94,40 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\n}\ntype findAvailableOpts struct {\n- // Addr is a suggested address. Addr must be page-aligned.\n- Addr usermem.Addr\n+ // These fields are equivalent to those in memmap.MMapOpts, except that:\n+ //\n+ // - Addr must be page-aligned.\n+ //\n+ // - Unmap allows existing guard pages in the returned range.\n- // Fixed is true if only the suggested address is acceptable.\n+ Addr usermem.Addr\nFixed bool\n-\n- // Unmap is true if existing vmas and guard pages may exist in the returned\n- // range.\nUnmap bool\n+ Map32Bit bool\n}\n+// map32Start/End are the bounds to which MAP_32BIT mappings are constrained,\n+// and are equivalent to Linux's MAP32_BASE and MAP32_MAX respectively.\n+const (\n+ map32Start = 0x40000000\n+ map32End = 0x80000000\n+)\n+\n// findAvailableLocked finds an allocatable range.\n//\n// Preconditions: mm.mappingMu must be locked.\nfunc (mm *MemoryManager) findAvailableLocked(length uint64, opts findAvailableOpts) (usermem.Addr, error) {\n+ if opts.Fixed {\n+ opts.Map32Bit = false\n+ }\n+ allowedAR := mm.applicationAddrRange()\n+ if opts.Map32Bit {\n+ allowedAR = allowedAR.Intersect(usermem.AddrRange{map32Start, map32End})\n+ }\n+\n// Does the provided suggestion work?\nif ar, ok := opts.Addr.ToRange(length); ok {\n- if mm.applicationAddrRange().IsSupersetOf(ar) {\n+ if allowedAR.IsSupersetOf(ar) {\nif opts.Unmap {\nreturn ar.Start, nil\n}\n@@ -132,6 +149,9 @@ func (mm *MemoryManager) findAvailableLocked(length uint64, opts findAvailableOp\nalignment = usermem.HugePageSize\n}\n+ if opts.Map32Bit {\n+ return mm.findLowestAvailableLocked(length, alignment, allowedAR)\n+ }\nif mm.layout.DefaultDirection == arch.MmapBottomUp {\nreturn mm.findLowestAvailableLocked(length, alignment, usermem.AddrRange{mm.layout.BottomUpBase, mm.layout.MaxAddr})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_mmap.go",
"new_path": "pkg/sentry/syscalls/linux/sys_mmap.go",
"diff": "@@ -45,6 +45,7 @@ func Mmap(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nprivate := flags&linux.MAP_PRIVATE != 0\nshared := flags&linux.MAP_SHARED != 0\nanon := flags&linux.MAP_ANONYMOUS != 0\n+ map32bit := flags&linux.MAP_32BIT != 0\n// Require exactly one of MAP_PRIVATE and MAP_SHARED.\nif private == shared {\n@@ -57,6 +58,7 @@ func Mmap(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nAddr: args[0].Pointer(),\nFixed: fixed,\nUnmap: fixed,\n+ Map32Bit: map32bit,\nPrivate: private,\nPerms: usermem.AccessType{\nRead: linux.PROT_READ&prot != 0,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement MAP_32BIT.
PiperOrigin-RevId: 196281052
Change-Id: Ie620a0f983a1bf2570d0003d4754611879335c1c |
259,881 | 11.05.2018 12:23:25 | 25,200 | 8deabbaae1fc45b042d551891080deef866dc0f8 | Remove error return from AddressSpace.Release() | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_usermem.go",
"new_path": "pkg/sentry/kernel/task_usermem.go",
"diff": "@@ -39,9 +39,7 @@ func (t *Task) Activate() {\n// Deactivate relinquishes the task's active address space.\nfunc (t *Task) Deactivate() {\nif mm := t.MemoryManager(); mm != nil {\n- if err := mm.Deactivate(); err != nil {\n- panic(\"unable to deactivate mm: \" + err.Error())\n- }\n+ mm.Deactivate()\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/address_space.go",
"new_path": "pkg/sentry/mm/address_space.go",
"diff": "@@ -114,12 +114,12 @@ func (mm *MemoryManager) Activate() error {\n}\n}\n-// Deactivate releases a release to the MemoryManager.\n-func (mm *MemoryManager) Deactivate() error {\n+// Deactivate releases a reference to the MemoryManager.\n+func (mm *MemoryManager) Deactivate() {\n// Fast path: this is not the last goroutine to deactivate the\n// MemoryManager.\nif atomicbitops.DecUnlessOneInt32(&mm.active) {\n- return nil\n+ return\n}\nmm.activeMu.Lock()\n@@ -128,26 +128,21 @@ func (mm *MemoryManager) Deactivate() error {\n// Still active?\nif atomic.AddInt32(&mm.active, -1) > 0 {\nmm.activeMu.Unlock()\n- return nil\n+ return\n}\n// Can we hold on to the address space?\nif !mm.p.CooperativelySchedulesAddressSpace() {\nmm.activeMu.Unlock()\n- return nil\n+ return\n}\n// Release the address space.\n- if err := mm.as.Release(); err != nil {\n- atomic.StoreInt32(&mm.active, 1)\n- mm.activeMu.Unlock()\n- return err\n- }\n+ mm.as.Release()\n// Lost it.\nmm.as = nil\nmm.activeMu.Unlock()\n- return nil\n}\n// mapASLocked maps addresses in ar into mm.as. If precommit is true, mappings\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/address_space.go",
"new_path": "pkg/sentry/platform/kvm/address_space.go",
"diff": "@@ -200,8 +200,7 @@ func (as *addressSpace) Unmap(addr usermem.Addr, length uint64) {\n}\n// Release releases the page tables.\n-func (as *addressSpace) Release() error {\n+func (as *addressSpace) Release() {\nas.Unmap(0, ^uint64(0))\nas.pageTables.Release()\n- return nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/platform.go",
"new_path": "pkg/sentry/platform/platform.go",
"diff": "@@ -205,7 +205,7 @@ type AddressSpace interface {\n// Release releases this address space. After releasing, a new AddressSpace\n// must be acquired via platform.NewAddressSpace().\n- Release() error\n+ Release()\n// AddressSpaceIO methods are supported iff the associated platform's\n// Platform.SupportsAddressSpaceIO() == true. AddressSpaces for which this\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess.go",
"diff": "@@ -242,14 +242,13 @@ func (s *subprocess) unmap() {\n// Therefore we simply unmap everything in the subprocess and return it to the\n// globalPool. This has the added benefit of reducing creation time for new\n// subprocesses.\n-func (s *subprocess) Release() error {\n+func (s *subprocess) Release() {\ngo func() { // S/R-SAFE: Platform.\ns.unmap()\nglobalPool.mu.Lock()\nglobalPool.available = append(globalPool.available, s)\nglobalPool.mu.Unlock()\n}()\n- return nil\n}\n// newThread creates a new traced thread.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove error return from AddressSpace.Release()
PiperOrigin-RevId: 196291289
Change-Id: Ie3487be029850b0b410b82416750853a6c4a2b00 |
259,948 | 11.05.2018 16:20:01 | 25,200 | 85fd5d40ff78f7b7fd473e5215daba84a28977f3 | netstack: release rcv lock after ping socket save is done. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/ping/endpoint.go",
"new_path": "pkg/tcpip/transport/ping/endpoint.go",
"diff": "@@ -52,7 +52,7 @@ type endpoint struct {\nrcvMu sync.Mutex `state:\"nosave\"`\nrcvReady bool\nrcvList pingPacketList\n- rcvBufSizeMax int\n+ rcvBufSizeMax int `state:\".(int)\"`\nrcvBufSize int\nrcvClosed bool\nrcvTimestamp bool\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/ping/endpoint_state.go",
"new_path": "pkg/tcpip/transport/ping/endpoint_state.go",
"diff": "@@ -29,9 +29,28 @@ func (p *pingPacket) loadData(data buffer.VectorisedView) {\n// beforeSave is invoked by stateify.\nfunc (e *endpoint) beforeSave() {\n// Stop incoming packets from being handled (and mutate endpoint state).\n+ // The lock will be released after savercvBufSizeMax(), which would have\n+ // saved e.rcvBufSizeMax and set it to 0 to continue blocking incoming\n+ // packets.\ne.rcvMu.Lock()\n}\n+// saveRcvBufSizeMax is invoked by stateify.\n+func (e *endpoint) saveRcvBufSizeMax() int {\n+ max := e.rcvBufSizeMax\n+ // Make sure no new packets will be handled regardless of the lock.\n+ e.rcvBufSizeMax = 0\n+ // Release the lock acquired in beforeSave() so regular endpoint closing\n+ // logic can proceed after save.\n+ e.rcvMu.Unlock()\n+ return max\n+}\n+\n+// loadRcvBufSizeMax is invoked by stateify.\n+func (e *endpoint) loadRcvBufSizeMax(max int) {\n+ e.rcvBufSizeMax = max\n+}\n+\n// afterLoad is invoked by stateify.\nfunc (e *endpoint) afterLoad() {\ne.stack = stack.StackFromEnv\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: release rcv lock after ping socket save is done.
PiperOrigin-RevId: 196324694
Change-Id: Ia3a48976433f21622eacb4a38fefe7143ca5e31b |
259,948 | 11.05.2018 16:27:50 | 25,200 | 987f7841a6ad8b77fe6a41cb70323517a5d2ccd1 | netstack: TCP connecting state endpoint save / restore support. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -31,6 +31,9 @@ import (\n// Error represents an error in the netstack error space. Using a special type\n// ensures that errors outside of this space are not accidentally introduced.\n+//\n+// Note: to support save / restore, it is important that all tcpip errors have\n+// distinct error messages.\ntype Error struct {\nstring\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -379,8 +379,8 @@ func (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) *tcpip.Error {\ne.handleListenSegment(ctx, s)\ns.decRef()\n}\n- e.drainDone <- struct{}{}\n- return nil\n+ close(e.drainDone)\n+ <-e.undrain\n}\ncase wakerForNewSegment:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -296,27 +296,31 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\nreturn nil\n}\n-// processSegments goes through the segment queue and processes up to\n-// maxSegmentsPerWake (if they're available).\n-func (h *handshake) processSegments() *tcpip.Error {\n- for i := 0; i < maxSegmentsPerWake; i++ {\n- s := h.ep.segmentQueue.dequeue()\n- if s == nil {\n- return nil\n- }\n-\n+func (h *handshake) handleSegment(s *segment) *tcpip.Error {\nh.sndWnd = s.window\nif !s.flagIsSet(flagSyn) && h.sndWndScale > 0 {\nh.sndWnd <<= uint8(h.sndWndScale)\n}\n- var err *tcpip.Error\nswitch h.state {\ncase handshakeSynRcvd:\n- err = h.synRcvdState(s)\n+ return h.synRcvdState(s)\ncase handshakeSynSent:\n- err = h.synSentState(s)\n+ return h.synSentState(s)\n}\n+ return nil\n+}\n+\n+// processSegments goes through the segment queue and processes up to\n+// maxSegmentsPerWake (if they're available).\n+func (h *handshake) processSegments() *tcpip.Error {\n+ for i := 0; i < maxSegmentsPerWake; i++ {\n+ s := h.ep.segmentQueue.dequeue()\n+ if s == nil {\n+ return nil\n+ }\n+\n+ err := h.handleSegment(s)\ns.decRef()\nif err != nil {\nreturn err\n@@ -364,6 +368,10 @@ func (h *handshake) resolveRoute() *tcpip.Error {\nh.ep.route.RemoveWaker(resolutionWaker)\nreturn tcpip.ErrAborted\n}\n+ if n¬ifyDrain != 0 {\n+ close(h.ep.drainDone)\n+ <-h.ep.undrain\n+ }\n}\n// Wait for notification.\n@@ -434,6 +442,20 @@ func (h *handshake) execute() *tcpip.Error {\nif n¬ifyClose != 0 {\nreturn tcpip.ErrAborted\n}\n+ if n¬ifyDrain != 0 {\n+ for s := h.ep.segmentQueue.dequeue(); s != nil; s = h.ep.segmentQueue.dequeue() {\n+ err := h.handleSegment(s)\n+ s.decRef()\n+ if err != nil {\n+ return err\n+ }\n+ if h.state == handshakeCompleted {\n+ return nil\n+ }\n+ }\n+ close(h.ep.drainDone)\n+ <-h.ep.undrain\n+ }\ncase wakerForNewSegment:\nif err := h.processSegments(); err != nil {\n@@ -833,7 +855,12 @@ func (e *endpoint) protocolMainLoop(passive bool) *tcpip.Error {\ne.mu.Lock()\ne.state = stateError\ne.hardError = err\n+ drained := e.drainDone != nil\ne.mu.Unlock()\n+ if drained {\n+ close(e.drainDone)\n+ <-e.undrain\n+ }\nreturn err\n}\n@@ -851,7 +878,12 @@ func (e *endpoint) protocolMainLoop(passive bool) *tcpip.Error {\n// Tell waiters that the endpoint is connected and writable.\ne.mu.Lock()\ne.state = stateConnected\n+ drained := e.drainDone != nil\ne.mu.Unlock()\n+ if drained {\n+ close(e.drainDone)\n+ <-e.undrain\n+ }\ne.waiterQueue.Notify(waiter.EventOut)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -74,7 +74,7 @@ type endpoint struct {\n// lastError represents the last error that the endpoint reported;\n// access to it is protected by the following mutex.\nlastErrorMu sync.Mutex `state:\"nosave\"`\n- lastError *tcpip.Error\n+ lastError *tcpip.Error `state:\".(string)\"`\n// The following fields are used to manage the receive queue. The\n// protocol goroutine adds ready-for-delivery segments to rcvList,\n@@ -92,7 +92,7 @@ type endpoint struct {\nmu sync.RWMutex `state:\"nosave\"`\nid stack.TransportEndpointID\nstate endpointState\n- isPortReserved bool\n+ isPortReserved bool `state:\"manual\"`\nisRegistered bool\nboundNICID tcpip.NICID\nroute stack.Route `state:\"manual\"`\n@@ -105,12 +105,12 @@ type endpoint struct {\n// protocols (e.g., IPv6 and IPv4) or a single different protocol (e.g.,\n// IPv4 when IPv6 endpoint is bound or connected to an IPv4 mapped\n// address).\n- effectiveNetProtos []tcpip.NetworkProtocolNumber\n+ effectiveNetProtos []tcpip.NetworkProtocolNumber `state:\"manual\"`\n// hardError is meaningful only when state is stateError, it stores the\n// error to be returned when read/write syscalls are called and the\n// endpoint is in this state.\n- hardError *tcpip.Error\n+ hardError *tcpip.Error `state:\".(string)\"`\n// workerRunning specifies if a worker goroutine is running.\nworkerRunning bool\n@@ -203,9 +203,15 @@ type endpoint struct {\n// The goroutine drain completion notification channel.\ndrainDone chan struct{} `state:\"nosave\"`\n+ // The goroutine undrain notification channel.\n+ undrain chan struct{} `state:\"nosave\"`\n+\n// probe if not nil is invoked on every received segment. It is passed\n// a copy of the current state of the endpoint.\nprobe stack.TCPProbeFunc `state:\"nosave\"`\n+\n+ // The following are only used to assist the restore run to re-connect.\n+ connectingAddress tcpip.Address\n}\nfunc newEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) *endpoint {\n@@ -786,6 +792,8 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n+ connectingAddr := addr.Addr\n+\nnetProto, err := e.checkV4Mapped(&addr)\nif err != nil {\nreturn err\n@@ -891,9 +899,10 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.route = r.Clone()\ne.boundNICID = nicid\ne.effectiveNetProtos = netProtos\n+ e.connectingAddress = connectingAddr\ne.workerRunning = true\n- go e.protocolMainLoop(false) // S/R-FIXME\n+ go e.protocolMainLoop(false) // S/R-SAFE: will be drained before save.\nreturn tcpip.ErrConnectStarted\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"diff": "@@ -6,6 +6,7 @@ package tcp\nimport (\n\"fmt\"\n+ \"sync\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n@@ -22,27 +23,43 @@ func (e ErrSaveRejection) Error() string {\nreturn \"save rejected due to unsupported endpoint state: \" + e.Err.Error()\n}\n+func (e *endpoint) drainSegmentLocked() {\n+ // Drain only up to once.\n+ if e.drainDone != nil {\n+ return\n+ }\n+\n+ e.drainDone = make(chan struct{})\n+ e.undrain = make(chan struct{})\n+ e.mu.Unlock()\n+\n+ e.notificationWaker.Assert()\n+ <-e.drainDone\n+\n+ e.mu.Lock()\n+}\n+\n// beforeSave is invoked by stateify.\nfunc (e *endpoint) beforeSave() {\n// Stop incoming packets.\ne.segmentQueue.setLimit(0)\n- e.mu.RLock()\n- defer e.mu.RUnlock()\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\nswitch e.state {\ncase stateInitial:\ncase stateBound:\ncase stateListen:\nif !e.segmentQueue.empty() {\n- e.mu.RUnlock()\n- e.drainDone = make(chan struct{}, 1)\n- e.notificationWaker.Assert()\n- <-e.drainDone\n- e.mu.RLock()\n+ e.drainSegmentLocked()\n}\ncase stateConnecting:\n- panic(ErrSaveRejection{fmt.Errorf(\"endpoint in connecting state upon save: local %v:%v, remote %v:%v\", e.id.LocalAddress, e.id.LocalPort, e.id.RemoteAddress, e.id.RemotePort)})\n+ e.drainSegmentLocked()\n+ if e.state != stateConnected {\n+ break\n+ }\n+ fallthrough\ncase stateConnected:\n// FIXME\npanic(ErrSaveRejection{fmt.Errorf(\"endpoint cannot be saved in connected state: local %v:%v, remote %v:%v\", e.id.LocalAddress, e.id.LocalPort, e.id.RemoteAddress, e.id.RemotePort)})\n@@ -56,41 +73,46 @@ func (e *endpoint) beforeSave() {\n// afterLoad is invoked by stateify.\nfunc (e *endpoint) afterLoad() {\ne.stack = stack.StackFromEnv\n+ e.segmentQueue.setLimit(2 * e.rcvBufSize)\n+ e.workMu.Init()\n- if e.state == stateListen {\n- e.state = stateBound\n- backlog := cap(e.acceptedChan)\n- e.acceptedChan = nil\n- defer func() {\n- if err := e.Listen(backlog); err != nil {\n- panic(\"endpoint listening failed: \" + err.String())\n+ state := e.state\n+ switch state {\n+ case stateInitial, stateBound, stateListen, stateConnecting:\n+ var ss SendBufferSizeOption\n+ if err := e.stack.TransportProtocolOption(ProtocolNumber, &ss); err == nil {\n+ if e.sndBufSize < ss.Min || e.sndBufSize > ss.Max {\n+ panic(fmt.Sprintf(\"endpoint.sndBufSize %d is outside the min and max allowed [%d, %d]\", e.sndBufSize, ss.Min, ss.Max))\n+ }\n+ if e.rcvBufSize < ss.Min || e.rcvBufSize > ss.Max {\n+ panic(fmt.Sprintf(\"endpoint.rcvBufSize %d is outside the min and max allowed [%d, %d]\", e.rcvBufSize, ss.Min, ss.Max))\n+ }\n}\n- }()\n}\n- if e.state == stateBound {\n+ switch state {\n+ case stateBound, stateListen, stateConnecting:\ne.state = stateInitial\n- defer func() {\nif err := e.Bind(tcpip.FullAddress{Addr: e.id.LocalAddress, Port: e.id.LocalPort}, nil); err != nil {\npanic(\"endpoint binding failed: \" + err.String())\n}\n- }()\n}\n- if e.state == stateInitial {\n- var ss SendBufferSizeOption\n- if err := e.stack.TransportProtocolOption(ProtocolNumber, &ss); err == nil {\n- if e.sndBufSize < ss.Min || e.sndBufSize > ss.Max {\n- panic(fmt.Sprintf(\"endpoint.sndBufSize %d is outside the min and max allowed [%d, %d]\", e.sndBufSize, ss.Min, ss.Max))\n+ switch state {\n+ case stateListen:\n+ backlog := cap(e.acceptedChan)\n+ e.acceptedChan = nil\n+ if err := e.Listen(backlog); err != nil {\n+ panic(\"endpoint listening failed: \" + err.String())\n}\n- if e.rcvBufSize < ss.Min || e.rcvBufSize > ss.Max {\n- panic(fmt.Sprintf(\"endpoint.rcvBufSize %d is outside the min and max allowed [%d, %d]\", e.rcvBufSize, ss.Min, ss.Max))\n}\n+\n+ switch state {\n+ case stateConnecting:\n+ if err := e.Connect(tcpip.FullAddress{NIC: e.boundNICID, Addr: e.connectingAddress, Port: e.id.RemotePort}); err != tcpip.ErrConnectStarted {\n+ panic(\"endpoint connecting failed: \" + err.String())\n}\n}\n-\n- e.segmentQueue.setLimit(2 * e.rcvBufSize)\n- e.workMu.Init()\n}\n// saveAcceptedChan is invoked by stateify.\n@@ -126,3 +148,96 @@ type endpointChan struct {\nbuffer []*endpoint\ncap int\n}\n+\n+// saveLastError is invoked by stateify.\n+func (e *endpoint) saveLastError() string {\n+ if e.lastError == nil {\n+ return \"\"\n+ }\n+\n+ return e.lastError.String()\n+}\n+\n+// loadLastError is invoked by stateify.\n+func (e *endpoint) loadLastError(s string) {\n+ if s == \"\" {\n+ return\n+ }\n+\n+ e.lastError = loadError(s)\n+}\n+\n+// saveHardError is invoked by stateify.\n+func (e *endpoint) saveHardError() string {\n+ if e.hardError == nil {\n+ return \"\"\n+ }\n+\n+ return e.hardError.String()\n+}\n+\n+// loadHardError is invoked by stateify.\n+func (e *endpoint) loadHardError(s string) {\n+ if s == \"\" {\n+ return\n+ }\n+\n+ e.hardError = loadError(s)\n+}\n+\n+var messageToError map[string]*tcpip.Error\n+\n+var populate sync.Once\n+\n+func loadError(s string) *tcpip.Error {\n+ populate.Do(func() {\n+ var errors = []*tcpip.Error{\n+ tcpip.ErrUnknownProtocol,\n+ tcpip.ErrUnknownNICID,\n+ tcpip.ErrUnknownProtocolOption,\n+ tcpip.ErrDuplicateNICID,\n+ tcpip.ErrDuplicateAddress,\n+ tcpip.ErrNoRoute,\n+ tcpip.ErrBadLinkEndpoint,\n+ tcpip.ErrAlreadyBound,\n+ tcpip.ErrInvalidEndpointState,\n+ tcpip.ErrAlreadyConnecting,\n+ tcpip.ErrAlreadyConnected,\n+ tcpip.ErrNoPortAvailable,\n+ tcpip.ErrPortInUse,\n+ tcpip.ErrBadLocalAddress,\n+ tcpip.ErrClosedForSend,\n+ tcpip.ErrClosedForReceive,\n+ tcpip.ErrWouldBlock,\n+ tcpip.ErrConnectionRefused,\n+ tcpip.ErrTimeout,\n+ tcpip.ErrAborted,\n+ tcpip.ErrConnectStarted,\n+ tcpip.ErrDestinationRequired,\n+ tcpip.ErrNotSupported,\n+ tcpip.ErrQueueSizeNotSupported,\n+ tcpip.ErrNotConnected,\n+ tcpip.ErrConnectionReset,\n+ tcpip.ErrConnectionAborted,\n+ tcpip.ErrNoSuchFile,\n+ tcpip.ErrInvalidOptionValue,\n+ tcpip.ErrNoLinkAddress,\n+ tcpip.ErrBadAddress,\n+ }\n+\n+ messageToError = make(map[string]*tcpip.Error)\n+ for _, e := range errors {\n+ if messageToError[e.String()] != nil {\n+ panic(\"tcpip errors with duplicated message: \" + e.String())\n+ }\n+ messageToError[e.String()] = e\n+ }\n+ })\n+\n+ e, ok := messageToError[s]\n+ if !ok {\n+ panic(\"unknown error message: \" + s)\n+ }\n+\n+ return e\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: TCP connecting state endpoint save / restore support.
PiperOrigin-RevId: 196325647
Change-Id: I850eb4a29b9c679da4db10eb164bbdf967690663 |
259,891 | 11.05.2018 17:18:56 | 25,200 | 08879266fef3a67fac1a77f1ea133c3ac75759dd | sentry: Adds canonical mode support. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/tty.go",
"new_path": "pkg/abi/linux/tty.go",
"diff": "package linux\n+import (\n+ \"unicode/utf8\"\n+)\n+\nconst (\n// NumControlCharacters is the number of control characters in Termios.\nNumControlCharacters = 19\n+ // disabledChar is used to indicate that a control character is\n+ // disabled.\n+ disabledChar = 0\n)\n// Termios is struct termios, defined in uapi/asm-generic/termbits.h.\n@@ -86,6 +93,27 @@ func (t *KernelTermios) FromTermios(term Termios) {\nt.ControlCharacters = term.ControlCharacters\n}\n+// IsTerminating returns whether c is a line terminating character.\n+func (t *KernelTermios) IsTerminating(c rune) bool {\n+ if t.IsEOF(c) {\n+ return true\n+ }\n+ switch byte(c) {\n+ case disabledChar:\n+ return false\n+ case '\\n', t.ControlCharacters[VEOL]:\n+ return true\n+ case t.ControlCharacters[VEOL2]:\n+ return t.LEnabled(IEXTEN)\n+ }\n+ return false\n+}\n+\n+// IsEOF returns whether c is the EOF character.\n+func (t *KernelTermios) IsEOF(c rune) bool {\n+ return utf8.RuneLen(c) == 1 && byte(c) == t.ControlCharacters[VEOF] && t.ControlCharacters[VEOF] != disabledChar\n+}\n+\n// Input flags.\nconst (\nIGNBRK = 0000001\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tty/line_discipline.go",
"new_path": "pkg/sentry/fs/tty/line_discipline.go",
"diff": "@@ -28,9 +28,90 @@ import (\n)\nconst (\n+ // canonMaxBytes is the number of bytes that fit into a single line of\n+ // terminal input in canonical mode. This corresponds to N_TTY_BUF_SIZE\n+ // in include/linux/tty.h.\n+ canonMaxBytes = 4096\n+\n+ // nonCanonMaxBytes is the maximum number of bytes that can be read at\n+ // a time in noncanonical mode.\n+ nonCanonMaxBytes = canonMaxBytes - 1\n+\nspacesPerTab = 8\n)\n+// queue represents one of the input or output queues between a pty master and\n+// slave. Bytes written to a queue are added to the read buffer until it is\n+// full, at which point they are written to the wait buffer. Bytes are\n+// processed (i.e. undergo termios transformations) as they are added to the\n+// read buffer. The read buffer is readable when its length is nonzero and\n+// readable is true.\n+type queue struct {\n+ waiter.Queue `state:\"nosave\"`\n+\n+ // readBuf is buffer of data ready to be read when readable is true.\n+ // This data has been processed.\n+ readBuf bytes.Buffer `state:\".([]byte)\"`\n+\n+ // waitBuf contains data that can't fit into readBuf. It is put here\n+ // until it can be loaded into the read buffer. waitBuf contains data\n+ // that hasn't been processed.\n+ waitBuf bytes.Buffer `state:\".([]byte)\"`\n+\n+ // readable indicates whether the read buffer can be read from. In\n+ // canonical mode, there can be an unterminated line in the read buffer,\n+ // so readable must be checked.\n+ readable bool\n+}\n+\n+// saveReadBuf is invoked by stateify.\n+func (q *queue) saveReadBuf() []byte {\n+ return append([]byte(nil), q.readBuf.Bytes()...)\n+}\n+\n+// loadReadBuf is invoked by stateify.\n+func (q *queue) loadReadBuf(b []byte) {\n+ q.readBuf.Write(b)\n+}\n+\n+// saveWaitBuf is invoked by stateify.\n+func (q *queue) saveWaitBuf() []byte {\n+ return append([]byte(nil), q.waitBuf.Bytes()...)\n+}\n+\n+// loadWaitBuf is invoked by stateify.\n+func (q *queue) loadWaitBuf(b []byte) {\n+ q.waitBuf.Write(b)\n+}\n+\n+// readReadiness returns whether q is ready to be read from.\n+func (q *queue) readReadiness(t *linux.KernelTermios) waiter.EventMask {\n+ if q.readBuf.Len() > 0 && q.readable {\n+ return waiter.EventIn\n+ }\n+ return waiter.EventMask(0)\n+}\n+\n+// writeReadiness returns whether q is ready to be written to.\n+func (q *queue) writeReadiness(t *linux.KernelTermios) waiter.EventMask {\n+ // Like Linux, we don't impose a maximum size on what can be enqueued.\n+ return waiter.EventOut\n+}\n+\n+// readableSize writes the number of readable bytes to userspace.\n+func (q *queue) readableSize(ctx context.Context, io usermem.IO, args arch.SyscallArguments) error {\n+ var size int32\n+ if q.readable {\n+ size = int32(q.readBuf.Len())\n+ }\n+\n+ _, err := usermem.CopyObjectOut(ctx, io, args[2].Pointer(), size, usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ })\n+ return err\n+\n+}\n+\n// lineDiscipline dictates how input and output are handled between the\n// pseudoterminal (pty) master and slave. It can be configured to alter I/O,\n// modify control characters (e.g. Ctrl-C for SIGINT), etc. The following man\n@@ -50,7 +131,7 @@ const (\n//\n// input from terminal +-------------+ input to process (e.g. bash)\n// +------------------------>| input queue |---------------------------+\n-// | +-------------+ |\n+// | (inputQueueWrite) +-------------+ (inputQueueRead) |\n// | |\n// | v\n// masterFD slaveFD\n@@ -58,7 +139,7 @@ const (\n// | |\n// | output to terminal +--------------+ output from process |\n// +------------------------| output queue |<--------------------------+\n-// +--------------+\n+// (outputQueueRead) +--------------+ (outputQueueWrite)\n//\n// Lock order:\n// inMu\n@@ -102,14 +183,25 @@ func (l *lineDiscipline) getTermios(ctx context.Context, io usermem.IO, args arc\n// setTermios sets a linux.Termios for the tty.\nfunc (l *lineDiscipline) setTermios(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+ l.inMu.Lock()\n+ defer l.inMu.Unlock()\nl.termiosMu.Lock()\ndefer l.termiosMu.Unlock()\n+ oldCanonEnabled := l.termios.LEnabled(linux.ICANON)\n// We must copy a Termios struct, not KernelTermios.\nvar t linux.Termios\n_, err := usermem.CopyObjectIn(ctx, io, args[2].Pointer(), &t, usermem.IOOpts{\nAddressSpaceActive: true,\n})\nl.termios.FromTermios(t)\n+\n+ // If canonical mode is turned off, move bytes from inQueue's wait\n+ // buffer to its read buffer. Anything already in the read buffer is\n+ // now readable.\n+ if oldCanonEnabled && !l.termios.LEnabled(linux.ICANON) {\n+ l.pushWaitBuf(&l.inQueue, transformInput)\n+ }\n+\nreturn 0, err\n}\n@@ -118,7 +210,9 @@ func (l *lineDiscipline) masterReadiness() waiter.EventMask {\ndefer l.inMu.Unlock()\nl.outMu.Lock()\ndefer l.outMu.Unlock()\n- return l.inQueue.writeReadiness() | l.outQueue.readReadiness()\n+ // We don't have to lock a termios because the default master termios\n+ // is immutable.\n+ return l.inQueue.writeReadiness(&linux.MasterTermios) | l.outQueue.readReadiness(&linux.MasterTermios)\n}\nfunc (l *lineDiscipline) slaveReadiness() waiter.EventMask {\n@@ -126,93 +220,97 @@ func (l *lineDiscipline) slaveReadiness() waiter.EventMask {\ndefer l.inMu.Unlock()\nl.outMu.Lock()\ndefer l.outMu.Unlock()\n- return l.outQueue.writeReadiness() | l.inQueue.readReadiness()\n-}\n-\n-// queue represents one of the input or output queues between a pty master and\n-// slave.\n-type queue struct {\n- waiter.Queue `state:\"nosave\"`\n- buf bytes.Buffer `state:\".([]byte)\"`\n-}\n-\n-// saveBuf is invoked by stateify.\n-func (q *queue) saveBuf() []byte {\n- return append([]byte(nil), q.buf.Bytes()...)\n-}\n-\n-// loadBuf is invoked by stateify.\n-func (q *queue) loadBuf(b []byte) {\n- q.buf.Write(b)\n-}\n-\n-// readReadiness returns whether q is ready to be read from.\n-//\n-// Preconditions: q's mutex must be held.\n-func (q *queue) readReadiness() waiter.EventMask {\n- ready := waiter.EventMask(0)\n- if q.buf.Len() > 0 {\n- ready |= waiter.EventIn\n- }\n- return ready\n+ l.termiosMu.Lock()\n+ defer l.termiosMu.Unlock()\n+ return l.outQueue.writeReadiness(&l.termios) | l.inQueue.readReadiness(&l.termios)\n}\n-// writeReadiness returns whether q is ready to be written to.\n-func (q *queue) writeReadiness() waiter.EventMask {\n- return waiter.EventOut\n+func (l *lineDiscipline) inputQueueReadSize(ctx context.Context, io usermem.IO, args arch.SyscallArguments) error {\n+ l.inMu.Lock()\n+ defer l.inMu.Unlock()\n+ return l.inQueue.readableSize(ctx, io, args)\n}\nfunc (l *lineDiscipline) inputQueueRead(ctx context.Context, dst usermem.IOSequence) (int64, error) {\nl.inMu.Lock()\ndefer l.inMu.Unlock()\n- return l.queueRead(ctx, dst, &l.inQueue)\n+ return l.queueRead(ctx, dst, &l.inQueue, transformInput)\n}\nfunc (l *lineDiscipline) inputQueueWrite(ctx context.Context, src usermem.IOSequence) (int64, error) {\nl.inMu.Lock()\ndefer l.inMu.Unlock()\n- return l.queueWrite(ctx, src, &l.inQueue, false)\n+ return l.queueWrite(ctx, src, &l.inQueue, transformInput)\n+}\n+\n+func (l *lineDiscipline) outputQueueReadSize(ctx context.Context, io usermem.IO, args arch.SyscallArguments) error {\n+ l.outMu.Lock()\n+ defer l.outMu.Unlock()\n+ return l.outQueue.readableSize(ctx, io, args)\n}\nfunc (l *lineDiscipline) outputQueueRead(ctx context.Context, dst usermem.IOSequence) (int64, error) {\nl.outMu.Lock()\ndefer l.outMu.Unlock()\n- return l.queueRead(ctx, dst, &l.outQueue)\n+ return l.queueRead(ctx, dst, &l.outQueue, transformOutput)\n}\nfunc (l *lineDiscipline) outputQueueWrite(ctx context.Context, src usermem.IOSequence) (int64, error) {\nl.outMu.Lock()\ndefer l.outMu.Unlock()\n- return l.queueWrite(ctx, src, &l.outQueue, true)\n+ return l.queueWrite(ctx, src, &l.outQueue, transformOutput)\n}\n// queueRead reads from q to userspace.\n//\n// Preconditions: q's lock must be held.\n-func (l *lineDiscipline) queueRead(ctx context.Context, dst usermem.IOSequence, q *queue) (int64, error) {\n- // Copy bytes out to user-space. queueRead doesn't have to do any\n- // processing or other extra work -- that's all taken care of when\n- // writing to a queue.\n- n, err := q.buf.WriteTo(dst.Writer(ctx))\n+func (l *lineDiscipline) queueRead(ctx context.Context, dst usermem.IOSequence, q *queue, f transform) (int64, error) {\n+ if !q.readable {\n+ return 0, syserror.ErrWouldBlock\n+ }\n+\n+ // Read out from the read buffer.\n+ n := canonMaxBytes\n+ if n > int(dst.NumBytes()) {\n+ n = int(dst.NumBytes())\n+ }\n+ if n > q.readBuf.Len() {\n+ n = q.readBuf.Len()\n+ }\n+ n, err := dst.Writer(ctx).Write(q.readBuf.Bytes()[:n])\n+ if err != nil {\n+ return 0, err\n+ }\n+ // Discard bytes read out.\n+ q.readBuf.Next(n)\n+\n+ // If we read everything, this queue is no longer readable.\n+ if q.readBuf.Len() == 0 {\n+ q.readable = false\n+ }\n+\n+ // Move data from the queue's wait buffer to its read buffer.\n+ l.termiosMu.Lock()\n+ defer l.termiosMu.Unlock()\n+ l.pushWaitBuf(q, f)\n// If state changed, notify any waiters. If nothing was available to\n// read, let the caller know we could block.\nif n > 0 {\nq.Notify(waiter.EventOut)\n- } else if err == nil {\n+ } else {\nreturn 0, syserror.ErrWouldBlock\n}\n- return int64(n), err\n+ return int64(n), nil\n}\n-// queueWrite writes to q from userspace. `output` is whether the queue being\n-// written to should be subject to output processing (i.e. whether it is the\n-// output queue).\n+// queueWrite writes to q from userspace. f is the function used to perform\n+// processing on data being written and write it to the read buffer.\n//\n// Precondition: q's lock must be held.\n-func (l *lineDiscipline) queueWrite(ctx context.Context, src usermem.IOSequence, q *queue, output bool) (int64, error) {\n+func (l *lineDiscipline) queueWrite(ctx context.Context, src usermem.IOSequence, q *queue, f transform) (int64, error) {\n// TODO: Use CopyInTo/safemem to avoid extra copying.\n- // Get the bytes to write from user-space.\n+ // Copy in the bytes to write from user-space.\nb := make([]byte, src.NumBytes())\nn, err := src.CopyIn(ctx, b)\nif err != nil {\n@@ -220,49 +318,69 @@ func (l *lineDiscipline) queueWrite(ctx context.Context, src usermem.IOSequence,\n}\nb = b[:n]\n+ // Write as much as possible to the read buffer.\n+ l.termiosMu.Lock()\n+ defer l.termiosMu.Unlock()\n+ n = f(l, q, b)\n+\n+ // Write remaining data to the wait buffer.\n+ nWaiting, _ := q.waitBuf.Write(b[n:])\n+\n// If state changed, notify any waiters. If we were unable to write\n// anything, let the caller know we could block.\nif n > 0 {\nq.Notify(waiter.EventIn)\n- } else {\n+ } else if nWaiting == 0 {\nreturn 0, syserror.ErrWouldBlock\n}\n-\n- // Optionally perform line discipline transformations depending on\n- // whether we're writing to the input queue or output queue.\n- var buf *bytes.Buffer\n- l.termiosMu.Lock()\n- if output {\n- buf = l.transformOutput(b)\n- } else {\n- buf = l.transformInput(b)\n+ return int64(n + nWaiting), nil\n}\n- l.termiosMu.Unlock()\n- // Enqueue buf at the end of the queue.\n- buf.WriteTo(&q.buf)\n- return int64(n), err\n+// pushWaitBuf fills the queue's read buffer with data from the wait buffer.\n+//\n+// Precondition: l.inMu and l.termiosMu must be held.\n+func (l *lineDiscipline) pushWaitBuf(q *queue, f transform) {\n+ // Remove bytes from the wait buffer and move them to the read buffer.\n+ n := f(l, q, q.waitBuf.Bytes())\n+ q.waitBuf.Next(n)\n+\n+ // If state changed, notify any waiters.\n+ if n > 0 {\n+ q.Notify(waiter.EventIn)\n+ }\n}\n+// transform functions require the passed in lineDiscipline's mutex to be held.\n+type transform func(*lineDiscipline, *queue, []byte) int\n+\n// transformOutput does output processing for one end of the pty. See\n// drivers/tty/n_tty.c:do_output_char for an analogous kernel function.\n//\n-// Precondition: l.termiosMu must be held.\n-func (l *lineDiscipline) transformOutput(buf []byte) *bytes.Buffer {\n+// Precondition: l.termiosMu and q's mutex must be held.\n+func transformOutput(l *lineDiscipline, q *queue, buf []byte) int {\n+ // transformOutput is effectively always in noncanonical mode, as the\n+ // master termios never has ICANON set.\n+\nif !l.termios.OEnabled(linux.OPOST) {\n- return bytes.NewBuffer(buf)\n+ n, _ := q.readBuf.Write(buf)\n+ if q.readBuf.Len() > 0 {\n+ q.readable = true\n+ }\n+ return n\n}\n- var ret bytes.Buffer\n+ var ret int\nfor len(buf) > 0 {\n- c := l.removeRune(&buf)\n+ c, size := l.peekRune(buf)\n+ ret += size\n+ buf = buf[size:]\nswitch c {\ncase '\\n':\nif l.termios.OEnabled(linux.ONLRET) {\nl.column = 0\n}\nif l.termios.OEnabled(linux.ONLCR) {\n- ret.Write([]byte{'\\r', '\\n'})\n+ q.readBuf.Write([]byte{'\\r', '\\n'})\ncontinue\n}\ncase '\\r':\n@@ -281,7 +399,7 @@ func (l *lineDiscipline) transformOutput(buf []byte) *bytes.Buffer {\nspaces := spacesPerTab - l.column%spacesPerTab\nif l.termios.OutputFlags&linux.TABDLY == linux.XTABS {\nl.column += spaces\n- ret.Write(bytes.Repeat([]byte{' '}, 8))\n+ q.readBuf.Write(bytes.Repeat([]byte{' '}, spacesPerTab))\ncontinue\n}\nl.column += spaces\n@@ -292,24 +410,40 @@ func (l *lineDiscipline) transformOutput(buf []byte) *bytes.Buffer {\ndefault:\nl.column++\n}\n- ret.WriteRune(c)\n+ q.readBuf.WriteRune(c)\n+ }\n+ if q.readBuf.Len() > 0 {\n+ q.readable = true\n}\n- return &ret\n+ return ret\n}\n-// transformInput does input processing for one end of the pty. Characters\n-// read are transformed according to flags set in the termios struct. See\n+// transformInput does input processing for one end of the pty. Characters read\n+// are transformed according to flags set in the termios struct. See\n// drivers/tty/n_tty.c:n_tty_receive_char_special for an analogous kernel\n// function.\n//\n-// Precondition: l.termiosMu must be held.\n-func (l *lineDiscipline) transformInput(buf []byte) *bytes.Buffer {\n- var ret bytes.Buffer\n- for len(buf) > 0 {\n- c := l.removeRune(&buf)\n+// Precondition: l.termiosMu and q's mutex must be held.\n+func transformInput(l *lineDiscipline, q *queue, buf []byte) int {\n+ // If there's a line waiting to be read in canonical mode, don't write\n+ // anything else to the read buffer.\n+ if l.termios.LEnabled(linux.ICANON) && q.readable {\n+ return 0\n+ }\n+\n+ maxBytes := nonCanonMaxBytes\n+ if l.termios.LEnabled(linux.ICANON) {\n+ maxBytes = canonMaxBytes\n+ }\n+\n+ var ret int\n+ for len(buf) > 0 && q.readBuf.Len() < canonMaxBytes {\n+ c, size := l.peekRune(buf)\nswitch c {\ncase '\\r':\nif l.termios.IEnabled(linux.IGNCR) {\n+ buf = buf[size:]\n+ ret += size\ncontinue\n}\nif l.termios.IEnabled(linux.ICRNL) {\n@@ -320,23 +454,63 @@ func (l *lineDiscipline) transformInput(buf []byte) *bytes.Buffer {\nc = '\\r'\n}\n}\n- ret.WriteRune(c)\n+\n+ // In canonical mode, we discard non-terminating characters\n+ // after the first 4095.\n+ if l.shouldDiscard(q, c) {\n+ buf = buf[size:]\n+ ret += size\n+ continue\n}\n- return &ret\n+\n+ // Stop if the buffer would be overfilled.\n+ if q.readBuf.Len()+size > maxBytes {\n+ break\n+ }\n+ buf = buf[size:]\n+ ret += size\n+\n+ // If we get EOF, make the buffer available for reading.\n+ if l.termios.LEnabled(linux.ICANON) && l.termios.IsEOF(c) {\n+ q.readable = true\n+ break\n+ }\n+\n+ q.readBuf.WriteRune(c)\n+\n+ // If we finish a line, make it available for reading.\n+ if l.termios.LEnabled(linux.ICANON) && l.termios.IsTerminating(c) {\n+ q.readable = true\n+ break\n+ }\n+ }\n+\n+ // In noncanonical mode, everything is readable.\n+ if !l.termios.LEnabled(linux.ICANON) && q.readBuf.Len() > 0 {\n+ q.readable = true\n+ }\n+\n+ return ret\n+}\n+\n+// shouldDiscard returns whether c should be discarded. In canonical mode, if\n+// too many bytes are enqueued, we keep reading input and discarding it until\n+// we find a terminating character. Signal/echo processing still occurs.\n+func (l *lineDiscipline) shouldDiscard(q *queue, c rune) bool {\n+ return l.termios.LEnabled(linux.ICANON) && q.readBuf.Len()+utf8.RuneLen(c) >= canonMaxBytes && !l.termios.IsTerminating(c)\n}\n-// removeRune removes and returns the first rune from the byte array. The\n-// buffer's length is updated accordingly.\n-func (l *lineDiscipline) removeRune(b *[]byte) rune {\n+// peekRune returns the first rune from the byte array depending on whether\n+// UTF8 is enabled.\n+func (l *lineDiscipline) peekRune(b []byte) (rune, int) {\nvar c rune\nvar size int\n// If UTF-8 support is enabled, runes might be multiple bytes.\nif l.termios.IEnabled(linux.IUTF8) {\n- c, size = utf8.DecodeRune(*b)\n+ c, size = utf8.DecodeRune(b)\n} else {\n- c = rune((*b)[0])\n+ c = rune(b[0])\nsize = 1\n}\n- *b = (*b)[size:]\n- return c\n+ return c, size\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tty/master.go",
"new_path": "pkg/sentry/fs/tty/master.go",
"diff": "@@ -148,6 +148,9 @@ func (mf *masterFileOperations) Write(ctx context.Context, _ *fs.File, src userm\n// Ioctl implements fs.FileOperations.Ioctl.\nfunc (mf *masterFileOperations) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nswitch args[1].Uint() {\n+ case linux.FIONREAD: // linux.FIONREAD == linux.TIOCINQ\n+ // Get the number of bytes in the output queue read buffer.\n+ return 0, mf.t.ld.outputQueueReadSize(ctx, io, args)\ncase linux.TCGETS:\n// N.B. TCGETS on the master actually returns the configuration\n// of the slave end.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tty/slave.go",
"new_path": "pkg/sentry/fs/tty/slave.go",
"diff": "@@ -133,6 +133,9 @@ func (sf *slaveFileOperations) Write(ctx context.Context, _ *fs.File, src userme\n// Ioctl implements fs.FileOperations.Ioctl.\nfunc (sf *slaveFileOperations) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nswitch args[1].Uint() {\n+ case linux.FIONREAD: // linux.FIONREAD == linux.TIOCINQ\n+ // Get the number of bytes in the input queue read buffer.\n+ return 0, sf.si.t.ld.inputQueueReadSize(ctx, io, args)\ncase linux.TCGETS:\nreturn sf.si.t.ld.getTermios(ctx, io, args)\ncase linux.TCSETS:\n"
}
] | Go | Apache License 2.0 | google/gvisor | sentry: Adds canonical mode support.
PiperOrigin-RevId: 196331627
Change-Id: Ifef4485f8202c52481af317cedd52d2ef48cea6a |
259,858 | 14.05.2018 20:26:35 | 25,200 | 17a0fa3af05dbb147cdd3d5ec898d31812a0ea66 | Ignore spurious KVM emulation failures. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -105,7 +105,11 @@ func bluepillHandler(context unsafe.Pointer) {\ncase _KVM_EXIT_IO:\nthrow(\"I/O\")\ncase _KVM_EXIT_INTERNAL_ERROR:\n- throw(\"internal error\")\n+ // An internal error is typically thrown when emulation\n+ // fails. This can occur via the MMIO path below (and\n+ // it might fail because we have multiple regions that\n+ // are not mapped). We would actually prefer that no\n+ // emulation occur, and don't mind at all if it fails.\ncase _KVM_EXIT_HYPERCALL:\nthrow(\"hypercall\")\ncase _KVM_EXIT_DEBUG:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ignore spurious KVM emulation failures.
PiperOrigin-RevId: 196609789
Change-Id: Ie261eea3b7fa05b6c348ca93e229de26cbd4dc7d |
259,858 | 14.05.2018 20:44:56 | 25,200 | 825e9ea8098d91e9770d27124717c08d1f5d2952 | Simplify KVM host map handling. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/address_space.go",
"new_path": "pkg/sentry/platform/kvm/address_space.go",
"diff": "@@ -46,6 +46,8 @@ type addressSpace struct {\ndirtySet sync.Map\n// files contains files mapped in the host address space.\n+ //\n+ // See host_map.go for more information.\nfiles hostMap\n}\n@@ -112,7 +114,8 @@ func (as *addressSpace) mapHostFile(addr usermem.Addr, fd int, fr platform.FileR\ninv := false\nfor _, m := range ms {\n// The host mapped slices are guaranteed to be aligned.\n- inv = inv || as.mapHost(addr, m, at)\n+ prev := as.mapHost(addr, m, at)\n+ inv = inv || prev\naddr += usermem.Addr(m.length)\n}\nif inv {\n@@ -157,10 +160,11 @@ func (as *addressSpace) mapFilemem(addr usermem.Addr, fr platform.FileRange, at\n_ = s[i] // Touch to commit.\n}\n}\n- inv = inv || as.mapHost(addr, hostMapEntry{\n+ prev := as.mapHost(addr, hostMapEntry{\naddr: reflect.ValueOf(&s[0]).Pointer(),\nlength: uintptr(len(s)),\n}, at)\n+ inv = inv || prev\naddr += usermem.Addr(len(s))\n}\nif inv {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/host_map.go",
"new_path": "pkg/sentry/platform/kvm/host_map.go",
"diff": "@@ -35,28 +35,48 @@ type hostMapEntry struct {\nlength uintptr\n}\n-func (hm *hostMap) forEachEntry(r usermem.AddrRange, fn func(offset uint64, m hostMapEntry)) {\n- for seg := hm.set.FindSegment(r.Start); seg.Ok() && seg.Start() < r.End; seg = seg.NextSegment() {\n- length := uintptr(seg.Range().Length())\n- segOffset := uint64(0) // Adjusted below.\n- if seg.End() > r.End {\n- length -= uintptr(seg.End() - r.End)\n- }\n- if seg.Start() < r.Start {\n- length -= uintptr(r.Start - seg.Start())\n+// forEach iterates over all mappings in the given range.\n+//\n+// Precondition: segFn and gapFn must be non-nil.\n+func (hm *hostMap) forEach(\n+ r usermem.AddrRange,\n+ segFn func(offset uint64, m hostMapEntry),\n+ gapFn func(offset uint64, length uintptr) (uintptr, bool)) {\n+\n+ seg, gap := hm.set.Find(r.Start)\n+ for {\n+ if seg.Ok() && seg.Start() < r.End {\n+ // A valid segment: pass information.\n+ overlap := seg.Range().Intersect(r)\n+ segOffset := uintptr(overlap.Start - seg.Start())\n+ mapOffset := uint64(overlap.Start - r.Start)\n+ segFn(mapOffset, hostMapEntry{\n+ addr: seg.Value() + segOffset,\n+ length: uintptr(overlap.Length()),\n+ })\n+ seg, gap = seg.NextNonEmpty()\n+ } else if gap.Ok() && gap.Start() < r.End {\n+ // A gap: pass gap information.\n+ overlap := gap.Range().Intersect(r)\n+ mapOffset := uint64(overlap.Start - r.Start)\n+ addr, ok := gapFn(mapOffset, uintptr(overlap.Length()))\n+ if ok {\n+ seg = hm.set.Insert(gap, overlap, addr)\n+ seg, gap = seg.NextNonEmpty()\n} else {\n- segOffset = uint64(seg.Start() - r.Start)\n+ seg = gap.NextSegment()\n+ gap = hostMapGapIterator{} // Invalid.\n+ }\n+ } else {\n+ // Terminal.\n+ break\n}\n- fn(segOffset, hostMapEntry{\n- addr: seg.Value(),\n- length: length,\n- })\n}\n}\nfunc (hm *hostMap) createMappings(r usermem.AddrRange, at usermem.AccessType, fd int, offset uint64) (ms []hostMapEntry, err error) {\n+ hm.forEach(r, func(mapOffset uint64, m hostMapEntry) {\n// Replace any existing mappings.\n- hm.forEachEntry(r, func(segOffset uint64, m hostMapEntry) {\n_, _, errno := syscall.RawSyscall6(\nsyscall.SYS_MMAP,\nm.addr,\n@@ -64,48 +84,40 @@ func (hm *hostMap) createMappings(r usermem.AddrRange, at usermem.AccessType, fd\nuintptr(at.Prot()),\nsyscall.MAP_FIXED|syscall.MAP_SHARED,\nuintptr(fd),\n- uintptr(offset+segOffset))\n+ uintptr(offset+mapOffset))\nif errno != 0 && err == nil {\nerr = errno\n}\n- })\n- if err != nil {\n- return nil, err\n- }\n-\n- // Add in necessary new mappings.\n- for gap := hm.set.FindGap(r.Start); gap.Ok() && gap.Start() < r.End; {\n- length := uintptr(gap.Range().Length())\n- gapOffset := uint64(0) // Adjusted below.\n- if gap.End() > r.End {\n- length -= uintptr(gap.End() - r.End)\n- }\n- if gap.Start() < r.Start {\n- length -= uintptr(r.Start - gap.Start())\n- } else {\n- gapOffset = uint64(gap.Start() - r.Start)\n- }\n-\n- // Map the host file memory.\n- hostAddr, _, errno := syscall.RawSyscall6(\n+ }, func(mapOffset uint64, length uintptr) (uintptr, bool) {\n+ // Create a new mapping.\n+ addr, _, errno := syscall.RawSyscall6(\nsyscall.SYS_MMAP,\n0,\nlength,\nuintptr(at.Prot()),\nsyscall.MAP_SHARED,\nuintptr(fd),\n- uintptr(offset+gapOffset))\n+ uintptr(offset+mapOffset))\nif errno != 0 {\n- return nil, errno\n+ err = errno\n+ return 0, false\n}\n-\n- // Insert into the host set and move to the next gap.\n- gap = hm.set.Insert(gap, gap.Range().Intersect(r), hostAddr).NextGap()\n+ return addr, true\n+ })\n+ if err != nil {\n+ return nil, err\n}\n- // Collect all slices.\n- hm.forEachEntry(r, func(_ uint64, m hostMapEntry) {\n+ // Collect all entries.\n+ //\n+ // We do this after the first iteration because some segments may have\n+ // been merged in the above, and we'll return the simplest form. This\n+ // also provides a basic sanity check in the form of no gaps.\n+ hm.forEach(r, func(_ uint64, m hostMapEntry) {\nms = append(ms, m)\n+ }, func(uint64, uintptr) (uintptr, bool) {\n+ // Should not happen: we just mapped this above.\n+ panic(\"unexpected gap\")\n})\nreturn ms, nil\n@@ -121,7 +133,7 @@ func (hm *hostMap) CreateMappings(r usermem.AddrRange, at usermem.AccessType, fd\nfunc (hm *hostMap) deleteMapping(r usermem.AddrRange) {\n// Remove all the existing mappings.\n- hm.forEachEntry(r, func(_ uint64, m hostMapEntry) {\n+ hm.forEach(r, func(_ uint64, m hostMapEntry) {\n_, _, errno := syscall.RawSyscall(\nsyscall.SYS_MUNMAP,\nm.addr,\n@@ -131,9 +143,13 @@ func (hm *hostMap) deleteMapping(r usermem.AddrRange) {\n// Should never happen.\npanic(fmt.Sprintf(\"unmap error: %v\", errno))\n}\n+ }, func(uint64, uintptr) (uintptr, bool) {\n+ // Sometimes deleteMapping will be called on a larger range\n+ // than physical mappings are defined. That's okay.\n+ return 0, false\n})\n- // Knock the range out.\n+ // Knock the entire range out.\nhm.set.RemoveRange(r)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify KVM host map handling.
PiperOrigin-RevId: 196611084
Change-Id: I6afa6b01e1dcd2aa9776dfc0f910874cc6b8d72c |
259,858 | 14.05.2018 21:13:28 | 25,200 | 2ab754cff7b2d45e1d59798562e47317aa480ecf | Make KVM system call first check. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"diff": "@@ -111,8 +111,11 @@ func (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetab\nvector = c.CPU.SwitchToUser(regs, fpState, pt, flags)\nexitsyscall()\n- // Free and clear.\nswitch vector {\n+ case ring0.Syscall, ring0.SyscallInt80:\n+ // Fast path: system call executed.\n+ return nil, usermem.NoAccess, nil\n+\ncase ring0.Debug, ring0.Breakpoint:\ninfo := &arch.SignalInfo{Signo: int32(syscall.SIGTRAP)}\nreturn info, usermem.AccessType{}, platform.ErrContextSignal\n@@ -158,10 +161,6 @@ func (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetab\nredpill() // Bail and reacqire.\nreturn nil, usermem.NoAccess, platform.ErrContextInterrupt\n- case ring0.Syscall, ring0.SyscallInt80:\n- // System call executed.\n- return nil, usermem.NoAccess, nil\n-\ndefault:\npanic(fmt.Sprintf(\"unexpected vector: 0x%x\", vector))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make KVM system call first check.
PiperOrigin-RevId: 196613447
Change-Id: Ib76902896798f072c3031b0c5cf7b433718928b7 |
259,858 | 14.05.2018 21:39:31 | 25,200 | ed02ac4f668ec41063cd51cbbd451baba9e9a6e7 | Disable INVPCID check; it's not used. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_amd64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/kvm_amd64_unsafe.go",
"diff": "@@ -27,7 +27,6 @@ import (\nvar (\nrunDataSize int\nhasGuestPCID bool\n- hasGuestINVPCID bool\npagetablesOpts pagetables.Opts\ncpuidSupported = cpuidEntries{nr: _KVM_NR_CPUID_ENTRIES}\n)\n@@ -74,16 +73,7 @@ func updateSystemValues(fd int) error {\nif entry.function == 1 && entry.index == 0 && entry.ecx&(1<<17) != 0 {\nhasGuestPCID = true // Found matching PCID in guest feature set.\n}\n- if entry.function == 7 && entry.index == 0 && entry.ebx&(1<<10) != 0 {\n- hasGuestINVPCID = true // Found matching INVPCID in guest feature set.\n}\n- }\n-\n- // A basic sanity check: ensure that we don't attempt to\n- // invpcid if guest PCIDs are not supported; it's not clear\n- // what the semantics of this would be (or why some CPU or\n- // hypervisor would export this particular combination).\n- hasGuestINVPCID = hasGuestPCID && hasGuestINVPCID\n// Set the pagetables to use PCID if it's available.\npagetablesOpts.EnablePCID = hasGuestPCID\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable INVPCID check; it's not used.
PiperOrigin-RevId: 196615029
Change-Id: Idfa383a9aee6a9397167a4231ce99d0b0e5b9912 |
259,992 | 15.05.2018 14:38:32 | 25,200 | 9889c29d6d26ba86b5e3590eac85bfb8393dd54e | Fix problem with sendfile(2) writing less data
When the amount of data read is more than the amount written, sendfile would not
adjust 'in file' position and would resume from the wrong location.
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -1929,8 +1929,16 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// If we don't have a provided offset.\n} else {\n// Send data using readv.\n+ inOff := inFile.Offset()\nr := &io.LimitedReader{R: &fs.FileReader{t, inFile}, N: count}\nn, err = io.Copy(w, r)\n+ inOff += n\n+ if inFile.Offset() != inOff {\n+ // Adjust file position in case more bytes were read than written.\n+ if _, err := inFile.Seek(t, fs.SeekSet, inOff); err != nil {\n+ return 0, nil, syserror.EIO\n+ }\n+ }\n}\n// We can only pass a single file to handleIOError, so pick inFile\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix problem with sendfile(2) writing less data
When the amount of data read is more than the amount written, sendfile would not
adjust 'in file' position and would resume from the wrong location.
Closes #33
PiperOrigin-RevId: 196731287
Change-Id: Ia219895dd765016ed9e571fd5b366963c99afb27 |
259,858 | 15.05.2018 18:33:19 | 25,200 | 310a99228b9254ad3c09ecdaa66e5747be4f46c5 | Simplify KVM state handling.
This also removes the dependency on tmutex. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/BUILD",
"new_path": "pkg/sentry/platform/kvm/BUILD",
"diff": "@@ -51,6 +51,7 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/atomicbitops\",\n\"//pkg/cpuid\",\n\"//pkg/log\",\n\"//pkg/sentry/arch\",\n@@ -63,7 +64,6 @@ go_library(\n\"//pkg/sentry/platform/safecopy\",\n\"//pkg/sentry/time\",\n\"//pkg/sentry/usermem\",\n- \"//pkg/tmutex\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/address_space.go",
"new_path": "pkg/sentry/platform/kvm/address_space.go",
"diff": "@@ -57,7 +57,7 @@ func (as *addressSpace) Invalidate() {\nc := key.(*vCPU)\nv := value.(*uint32)\natomic.StoreUint32(v, 0) // Invalidation required.\n- c.Bounce() // Force a kernel transition.\n+ c.BounceToKernel() // Force a kernel transition.\nreturn true // Keep iterating.\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -51,15 +51,13 @@ func bluepillHandler(context unsafe.Pointer) {\n// Increment the number of switches.\natomic.AddUint32(&c.switches, 1)\n- // Store vCPUGuest.\n- //\n- // This is fine even if we're not in guest mode yet. In this signal\n- // handler, we'll already have all the relevant signals blocked, so an\n- // interrupt is only deliverable when we actually execute the KVM_RUN.\n- //\n- // The state will be returned to vCPUReady by Phase2.\n- if state := atomic.SwapUintptr(&c.state, vCPUGuest); state != vCPUReady {\n- throw(\"vCPU not in ready state\")\n+ // Mark this as guest mode.\n+ switch atomic.SwapUint32(&c.state, vCPUGuest|vCPUUser) {\n+ case vCPUUser: // Expected case.\n+ case vCPUUser | vCPUWaiter:\n+ c.notify()\n+ default:\n+ throw(\"invalid state\")\n}\nfor {\n@@ -118,11 +116,12 @@ func bluepillHandler(context unsafe.Pointer) {\n// Copy out registers.\nbluepillArchExit(c, bluepillArchContext(context))\n- // Notify any waiters.\n- switch state := atomic.SwapUintptr(&c.state, vCPUReady); state {\n- case vCPUGuest:\n- case vCPUWaiter:\n- c.notify() // Safe from handler.\n+ // Return to the vCPUReady state; notify any waiters.\n+ user := atomic.LoadUint32(&c.state) & vCPUUser\n+ switch atomic.SwapUint32(&c.state, user) {\n+ case user | vCPUGuest: // Expected case.\n+ case user | vCPUGuest | vCPUWaiter:\n+ c.notify()\ndefault:\nthrow(\"invalid state\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_test.go",
"new_path": "pkg/sentry/platform/kvm/kvm_test.go",
"diff": "@@ -17,6 +17,7 @@ package kvm\nimport (\n\"math/rand\"\n\"reflect\"\n+ \"sync/atomic\"\n\"syscall\"\n\"testing\"\n\"time\"\n@@ -84,7 +85,7 @@ func bluepillTest(t testHarness, fn func(*vCPU)) {\nfunc TestKernelSyscall(t *testing.T) {\nbluepillTest(t, func(c *vCPU) {\nredpill() // Leave guest mode.\n- if got := c.State(); got != vCPUReady {\n+ if got := atomic.LoadUint32(&c.state); got != vCPUUser {\nt.Errorf(\"vCPU not in ready state: got %v\", got)\n}\n})\n@@ -102,7 +103,7 @@ func TestKernelFault(t *testing.T) {\nhostFault() // Ensure recovery works.\nbluepillTest(t, func(c *vCPU) {\nhostFault()\n- if got := c.State(); got != vCPUReady {\n+ if got := atomic.LoadUint32(&c.state); got != vCPUUser {\nt.Errorf(\"vCPU not in ready state: got %v\", got)\n}\n})\n@@ -229,7 +230,7 @@ func TestBounce(t *testing.T) {\napplicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\ngo func() {\ntime.Sleep(time.Millisecond)\n- c.Bounce()\n+ c.BounceToKernel()\n}()\nif _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextInterrupt {\nt.Errorf(\"application partial restore: got %v, wanted %v\", err, platform.ErrContextInterrupt)\n@@ -239,7 +240,7 @@ func TestBounce(t *testing.T) {\napplicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\ngo func() {\ntime.Sleep(time.Millisecond)\n- c.Bounce()\n+ c.BounceToKernel()\n}()\nif _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != platform.ErrContextInterrupt {\nt.Errorf(\"application full restore: got %v, wanted %v\", err, platform.ErrContextInterrupt)\n@@ -264,17 +265,15 @@ func TestBounceStress(t *testing.T) {\n// kernel is in various stages of the switch.\ngo func() {\nrandomSleep()\n- c.Bounce()\n+ c.BounceToKernel()\n}()\nrandomSleep()\n- // Execute the switch.\nif _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextInterrupt {\nt.Errorf(\"application partial restore: got %v, wanted %v\", err, platform.ErrContextInterrupt)\n}\n- // Simulate work.\n- c.Unlock()\n+ c.unlock()\nrandomSleep()\n- c.Lock()\n+ c.lock()\n}\nreturn false\n})\n@@ -289,8 +288,7 @@ func TestInvalidate(t *testing.T) {\n}\n// Unmap the page containing data & invalidate.\npt.Unmap(usermem.Addr(reflect.ValueOf(&data).Pointer() & ^uintptr(usermem.PageSize-1)), usermem.PageSize)\n- c.Invalidate() // Ensure invalidation.\n- if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextSignal {\n+ if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFlush); err != platform.ErrContextSignal {\nt.Errorf(\"application partial restore: got %v, wanted %v\", err, platform.ErrContextSignal)\n}\nreturn false\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -21,11 +21,11 @@ import (\n\"sync/atomic\"\n\"syscall\"\n+ \"gvisor.googlesource.com/gvisor/pkg/atomicbitops\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform/procid\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform/ring0\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform/ring0/pagetables\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n- \"gvisor.googlesource.com/gvisor/pkg/tmutex\"\n)\n// machine contains state associated with the VM as a whole.\n@@ -57,20 +57,19 @@ type machine struct {\n}\nconst (\n- // vCPUReady is the lock value for an available vCPU.\n- //\n- // Legal transitions: vCPUGuest (bluepill).\n- vCPUReady uintptr = iota\n+ // vCPUReady is an alias for all the below clear.\n+ vCPUReady uint32 = 0\n+\n+ // vCPUser indicates that the vCPU is in or about to enter user mode.\n+ vCPUUser uint32 = 1 << 0\n// vCPUGuest indicates the vCPU is in guest mode.\n- //\n- // Legal transition: vCPUReady (bluepill), vCPUWaiter (wait).\n- vCPUGuest\n+ vCPUGuest uint32 = 1 << 1\n- // vCPUWaiter indicates that the vCPU should be released.\n+ // vCPUWaiter indicates that there is a waiter.\n//\n- // Legal transition: vCPUReady (bluepill).\n- vCPUWaiter\n+ // If this is set, then notify must be called on any state transitions.\n+ vCPUWaiter uint32 = 1 << 2\n)\n// vCPU is a single KVM vCPU.\n@@ -93,17 +92,16 @@ type vCPU struct {\n// faults is a count of world faults (informational only).\nfaults uint32\n- // state is the vCPU state; all are described above.\n- state uintptr\n+ // state is the vCPU state.\n+ //\n+ // This is a bitmask of the three fields (vCPU*) described above.\n+ state uint32\n// runData for this vCPU.\nrunData *runData\n// machine associated with this vCPU.\nmachine *machine\n-\n- // mu applies across get/put; it does not protect the above.\n- mu tmutex.Mutex\n}\n// newMachine returns a new VM context.\n@@ -145,7 +143,6 @@ func newMachine(vm int, vCPUs int) (*machine, error) {\nfd: int(fd),\nmachine: m,\n}\n- c.mu.Init()\nc.CPU.Init(m.kernel)\nc.CPU.KernelSyscall = bluepillSyscall\nc.CPU.KernelException = bluepillException\n@@ -253,13 +250,10 @@ func (m *machine) Destroy() {\n// Ensure the vCPU is not still running in guest mode. This is\n// possible iff teardown has been done by other threads, and\n// somehow a single thread has not executed any system calls.\n- c.wait()\n+ c.BounceToHost()\n- // Teardown the vCPU itself.\n- switch state := c.State(); state {\n- case vCPUReady:\n- // Note that the runData may not be mapped if an error\n- // occurs during the middle of initialization.\n+ // Note that the runData may not be mapped if an error occurs\n+ // during the middle of initialization.\nif c.runData != nil {\nif err := unmapRunData(c.runData); err != nil {\npanic(fmt.Sprintf(\"error unmapping rundata: %v\", err))\n@@ -268,13 +262,6 @@ func (m *machine) Destroy() {\nif err := syscall.Close(int(c.fd)); err != nil {\npanic(fmt.Sprintf(\"error closing vCPU fd: %v\", err))\n}\n- case vCPUGuest, vCPUWaiter:\n- // Should never happen; waited above.\n- panic(\"vCPU disposed in guest state\")\n- default:\n- // Should never happen; not a valid state.\n- panic(fmt.Sprintf(\"vCPU in invalid state: %v\", state))\n- }\n}\n// Release host mappings.\n@@ -296,14 +283,19 @@ func (m *machine) Get() (*vCPU, error) {\nfor {\n// Check for an exact match.\n- if c := m.vCPUs[tid]; c != nil && c.mu.TryLock() {\n+ if c := m.vCPUs[tid]; c != nil {\n+ c.lock()\nm.mu.Unlock()\nreturn c, nil\n}\n// Scan for an available vCPU.\nfor origTID, c := range m.vCPUs {\n- if c.LockInState(vCPUReady) {\n+ // We can only steal a vCPU that is the vCPUReady\n+ // state. That is, it must not be heading to user mode\n+ // with some other thread, have a waiter registered, or\n+ // be in guest mode already.\n+ if atomic.CompareAndSwapUint32(&c.state, vCPUReady, vCPUUser) {\ndelete(m.vCPUs, origTID)\nm.vCPUs[tid] = c\nm.mu.Unlock()\n@@ -317,96 +309,151 @@ func (m *machine) Get() (*vCPU, error) {\n}\n}\n- // Everything is busy executing user code (locked).\n+ // Everything is already in guest mode.\n//\n- // We hold the pool lock here, so we should be able to kick something\n- // out of kernel mode and have it bounce into host mode when it tries\n- // to grab the vCPU again.\n+ // We hold the pool lock here, so we should be able to kick\n+ // something out of kernel mode and have it bounce into host\n+ // mode when it tries to grab the vCPU again.\nfor _, c := range m.vCPUs {\n- if c.State() != vCPUWaiter {\n- c.Bounce()\n- }\n+ c.BounceToHost()\n}\n- // Give other threads an opportunity to run.\n+ // Give other threads an opportunity to run. We don't yield the\n+ // pool lock above, so if they try to regrab the lock we will\n+ // serialize at this point. This is extreme, but we don't\n+ // expect to exhaust all vCPUs frequently.\nyield()\n}\n}\n// Put puts the current vCPU.\nfunc (m *machine) Put(c *vCPU) {\n- c.Unlock()\n+ c.unlock()\nruntime.UnlockOSThread()\n}\n-// State returns the current state.\n-func (c *vCPU) State() uintptr {\n- return atomic.LoadUintptr(&c.state)\n-}\n-\n-// Lock locks the vCPU.\n-func (c *vCPU) Lock() {\n- c.mu.Lock()\n-}\n-\n-// Invalidate invalidates caches.\n-func (c *vCPU) Invalidate() {\n+// lock marks the vCPU as in user mode.\n+//\n+// This should only be called directly when known to be safe, i.e. when\n+// the vCPU is owned by the current TID with no chance of theft.\n+//\n+//go:nosplit\n+func (c *vCPU) lock() {\n+ atomicbitops.OrUint32(&c.state, vCPUUser)\n}\n-// LockInState locks the vCPU if it is in the given state and TryLock succeeds.\n-func (c *vCPU) LockInState(state uintptr) bool {\n- if c.State() == state && c.mu.TryLock() {\n- if c.State() != state {\n- c.mu.Unlock()\n- return false\n- }\n- return true\n- }\n- return false\n+// unlock clears the vCPUUser bit.\n+//\n+//go:nosplit\n+func (c *vCPU) unlock() {\n+ if atomic.CompareAndSwapUint32(&c.state, vCPUUser|vCPUGuest, vCPUGuest) {\n+ // Happy path: no exits are forced, and we can continue\n+ // executing on our merry way with a single atomic access.\n+ return\n}\n-// Unlock unlocks the given vCPU.\n-func (c *vCPU) Unlock() {\n- // Ensure we're out of guest mode, if necessary.\n- if c.State() == vCPUWaiter {\n- redpill() // Force guest mode exit.\n+ // Clear the lock.\n+ origState := atomic.LoadUint32(&c.state)\n+ atomicbitops.AndUint32(&c.state, ^vCPUUser)\n+ switch origState {\n+ case vCPUUser:\n+ // Normal state.\n+ case vCPUUser | vCPUGuest | vCPUWaiter:\n+ // Force a transition: this must trigger a notification when we\n+ // return from guest mode.\n+ redpill()\n+ case vCPUUser | vCPUWaiter:\n+ // Waiting for the lock to be released; the responsibility is\n+ // on us to notify the waiter and clear the associated bit.\n+ atomicbitops.AndUint32(&c.state, ^vCPUWaiter)\n+ c.notify()\n+ default:\n+ panic(\"invalid state\")\n}\n- c.mu.Unlock()\n}\n// NotifyInterrupt implements interrupt.Receiver.NotifyInterrupt.\n+//\n+//go:nosplit\nfunc (c *vCPU) NotifyInterrupt() {\n- c.Bounce()\n+ c.BounceToKernel()\n}\n// pid is used below in bounce.\nvar pid = syscall.Getpid()\n-// Bounce ensures that the vCPU bounces back to the kernel.\n+// bounce forces a return to the kernel or to host mode.\n//\n-// In practice, this means returning EAGAIN from running user code. The vCPU\n-// will be unlocked and relock, and the kernel is guaranteed to check for\n-// interrupt notifications (e.g. injected via Notify) and invalidations.\n-func (c *vCPU) Bounce() {\n+// This effectively unwinds the state machine.\n+func (c *vCPU) bounce(forceGuestExit bool) {\nfor {\n- if c.mu.TryLock() {\n- // We know that the vCPU must be in the kernel already,\n- // because the lock was not acquired. We specifically\n- // don't want to call bounce in this case, because it's\n- // not necessary to knock the vCPU out of guest mode.\n- c.mu.Unlock()\n+ switch state := atomic.LoadUint32(&c.state); state {\n+ case vCPUReady, vCPUWaiter:\n+ // There is nothing to be done, we're already in the\n+ // kernel pre-acquisition. The Bounce criteria have\n+ // been satisfied.\n+ return\n+ case vCPUUser:\n+ // We need to register a waiter for the actual guest\n+ // transition. When the transition takes place, then we\n+ // can inject an interrupt to ensure a return to host\n+ // mode.\n+ atomic.CompareAndSwapUint32(&c.state, state, state|vCPUWaiter)\n+ case vCPUUser | vCPUWaiter:\n+ // Wait for the transition to guest mode. This should\n+ // come from the bluepill handler.\n+ c.waitUntilNot(state)\n+ case vCPUGuest, vCPUUser | vCPUGuest:\n+ if state == vCPUGuest && !forceGuestExit {\n+ // The vCPU is already not acquired, so there's\n+ // no need to do a fresh injection here.\nreturn\n}\n-\n- if state := c.State(); state == vCPUGuest || state == vCPUWaiter {\n- // We know that the vCPU was in guest mode, so a single signal\n- // interruption will guarantee that a transition takes place.\n- syscall.Tgkill(pid, int(atomic.LoadUint64(&c.tid)), bounceSignal)\n+ // The vCPU is in user or kernel mode. Attempt to\n+ // register a notification on change.\n+ if !atomic.CompareAndSwapUint32(&c.state, state, state|vCPUWaiter) {\n+ break // Retry.\n+ }\n+ for {\n+ // We need to spin here until the signal is\n+ // delivered, because Tgkill can return EAGAIN\n+ // under memory pressure. Since we already\n+ // marked ourselves as a waiter, we need to\n+ // ensure that a signal is actually delivered.\n+ if err := syscall.Tgkill(pid, int(atomic.LoadUint64(&c.tid)), bounceSignal); err == nil {\n+ break\n+ } else if err.(syscall.Errno) == syscall.EAGAIN {\n+ continue\n+ } else {\n+ // Nothing else should be returned by tgkill.\n+ panic(fmt.Sprintf(\"unexpected tgkill error: %v\", err))\n+ }\n+ }\n+ case vCPUGuest | vCPUWaiter, vCPUUser | vCPUGuest | vCPUWaiter:\n+ if state == vCPUGuest|vCPUWaiter && !forceGuestExit {\n+ // See above.\nreturn\n}\n+ // Wait for the transition. This again should happen\n+ // from the bluepill handler, but on the way out.\n+ c.waitUntilNot(state)\n+ default:\n+ // Should not happen: the above is exhaustive.\n+ panic(\"invalid state\")\n+ }\n+ }\n+}\n- // Someone holds the lock, but the vCPU is not yet transitioned\n- // into guest mode. It's in the critical section; give it time.\n- yield()\n+// BounceToKernel ensures that the vCPU bounces back to the kernel.\n+//\n+//go:nosplit\n+func (c *vCPU) BounceToKernel() {\n+ c.bounce(false)\n}\n+\n+// BounceToHost ensures that the vCPU is in host mode.\n+//\n+//go:nosplit\n+func (c *vCPU) BounceToHost() {\n+ c.bounce(true)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"diff": "@@ -158,7 +158,6 @@ func (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetab\nreturn info, usermem.AccessType{}, platform.ErrContextSignal\ncase ring0.Vector(bounce):\n- redpill() // Bail and reacqire.\nreturn nil, usermem.NoAccess, platform.ErrContextInterrupt\ndefault:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -16,7 +16,6 @@ package kvm\nimport (\n\"fmt\"\n- \"sync/atomic\"\n\"syscall\"\n\"unsafe\"\n@@ -69,7 +68,7 @@ func unmapRunData(r *runData) error {\nreturn nil\n}\n-// notify notifies that the vCPU has returned to host mode.\n+// notify notifies that the vCPU has transitioned modes.\n//\n// This may be called by a signal handler and therefore throws on error.\n//\n@@ -86,27 +85,20 @@ func (c *vCPU) notify() {\n}\n}\n-// wait waits for the vCPU to return to host mode.\n+// waitUntilNot waits for the vCPU to transition modes.\n+//\n+// The state should have been previously set to vCPUWaiter after performing an\n+// appropriate action to cause a transition (e.g. interrupt injection).\n//\n// This panics on error.\n-func (c *vCPU) wait() {\n- if !atomic.CompareAndSwapUintptr(&c.state, vCPUGuest, vCPUWaiter) {\n- return // Nothing to wait for.\n- }\n- for {\n+func (c *vCPU) waitUntilNot(state uint32) {\n_, _, errno := syscall.Syscall6(\nsyscall.SYS_FUTEX,\nuintptr(unsafe.Pointer(&c.state)),\nlinux.FUTEX_WAIT,\n- uintptr(vCPUWaiter), // Expected value.\n+ uintptr(state),\n0, 0, 0)\n- if errno == syscall.EINTR {\n- continue\n- } else if errno == syscall.EAGAIN {\n- break\n- } else if errno != 0 {\n+ if errno != 0 && errno != syscall.EINTR && errno != syscall.EAGAIN {\npanic(\"futex wait error\")\n}\n- break\n- }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify KVM state handling.
This also removes the dependency on tmutex.
PiperOrigin-RevId: 196764317
Change-Id: I523fb67454318e1a2ca9da3a08e63bfa3c1eeed3 |
259,858 | 15.05.2018 22:20:36 | 25,200 | 00adea3a3f0f3501809901bdac1a01c543d5e116 | Simplify KVM invalidation logic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/BUILD",
"new_path": "pkg/sentry/platform/kvm/BUILD",
"diff": "@@ -27,6 +27,7 @@ go_library(\nname = \"kvm\",\nsrcs = [\n\"address_space.go\",\n+ \"address_space_unsafe.go\",\n\"bluepill.go\",\n\"bluepill_amd64.go\",\n\"bluepill_amd64.s\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/address_space.go",
"new_path": "pkg/sentry/platform/kvm/address_space.go",
"diff": "@@ -16,8 +16,6 @@ package kvm\nimport (\n\"reflect\"\n- \"sync\"\n- \"sync/atomic\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform/filemem\"\n@@ -40,10 +38,10 @@ type addressSpace struct {\n// dirtySet is the set of dirty vCPUs.\n//\n- // The key is the vCPU, the value is a shared uint32 pointer that\n- // indicates whether or not the context is clean. A zero here indicates\n- // that the context should be cleaned prior to re-entry.\n- dirtySet sync.Map\n+ // These are actually vCPU pointers that are stored iff the vCPU is\n+ // dirty. If the vCPU is not dirty and requires invalidation, then a\n+ // nil value is stored here instead.\n+ dirtySet dirtySet\n// files contains files mapped in the host address space.\n//\n@@ -53,22 +51,22 @@ type addressSpace struct {\n// Invalidate interrupts all dirty contexts.\nfunc (as *addressSpace) Invalidate() {\n- as.dirtySet.Range(func(key, value interface{}) bool {\n- c := key.(*vCPU)\n- v := value.(*uint32)\n- atomic.StoreUint32(v, 0) // Invalidation required.\n+ for i := 0; i < as.dirtySet.size(); i++ {\n+ if c := as.dirtySet.swap(i, nil); c != nil && c.active.get() == as {\nc.BounceToKernel() // Force a kernel transition.\n- return true // Keep iterating.\n- })\n+ }\n+ }\n}\n// Touch adds the given vCPU to the dirty list.\n-func (as *addressSpace) Touch(c *vCPU) *uint32 {\n- value, ok := as.dirtySet.Load(c)\n- if !ok {\n- value, _ = as.dirtySet.LoadOrStore(c, new(uint32))\n+//\n+// The return value indicates whether a flush is required.\n+func (as *addressSpace) Touch(c *vCPU) bool {\n+ if old := as.dirtySet.swap(c.id, c); old == nil {\n+ return true // Flush is required.\n}\n- return value.(*uint32)\n+ // Already dirty: no flush required.\n+ return false\n}\nfunc (as *addressSpace) mapHost(addr usermem.Addr, m hostMapEntry, at usermem.AccessType) (inv bool) {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/kvm/address_space_unsafe.go",
"diff": "+// Copyright 2018 Google Inc.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package kvm\n+\n+import (\n+ \"sync/atomic\"\n+ \"unsafe\"\n+)\n+\n+// dirtySet tracks vCPUs for invalidation.\n+type dirtySet struct {\n+ vCPUs []unsafe.Pointer\n+}\n+\n+// makeDirtySet makes a new dirtySet.\n+func makeDirtySet(size int) dirtySet {\n+ return dirtySet{\n+ vCPUs: make([]unsafe.Pointer, size),\n+ }\n+}\n+\n+// size is the size of the set.\n+func (ds *dirtySet) size() int {\n+ return len(ds.vCPUs)\n+}\n+\n+// swap sets the given index and returns the previous value.\n+//\n+// The index is typically the id for a non-nil vCPU.\n+func (ds *dirtySet) swap(index int, c *vCPU) *vCPU {\n+ return (*vCPU)(atomic.SwapPointer(&ds.vCPUs[index], unsafe.Pointer(c)))\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/context.go",
"new_path": "pkg/sentry/platform/kvm/context.go",
"diff": "package kvm\nimport (\n- \"sync/atomic\"\n-\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform/interrupt\"\n@@ -54,10 +52,18 @@ func (c *context) Switch(as platform.AddressSpace, ac arch.Context, _ int32) (*a\nreturn nil, usermem.NoAccess, platform.ErrContextInterrupt\n}\n+ // Set the active address space.\n+ //\n+ // This must be done prior to the call to Touch below. If the address\n+ // space is invalidated between this line and the call below, we will\n+ // flag on entry anyways. When the active address space below is\n+ // cleared, it indicates that we don't need an explicit interrupt and\n+ // that the flush can occur naturally on the next user entry.\n+ cpu.active.set(localAS)\n+\n// Mark the address space as dirty.\nflags := ring0.Flags(0)\n- dirty := localAS.Touch(cpu)\n- if v := atomic.SwapUint32(dirty, 1); v == 0 {\n+ if localAS.Touch(cpu) {\nflags |= ring0.FlagFlush\n}\nif ac.FullRestore() {\n@@ -67,6 +73,9 @@ func (c *context) Switch(as platform.AddressSpace, ac arch.Context, _ int32) (*a\n// Take the blue pill.\nsi, at, err := cpu.SwitchToUser(regs, fp, localAS.pageTables, flags)\n+ // Clear the address space.\n+ cpu.active.set(nil)\n+\n// Release resources.\nc.machine.Put(cpu)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm.go",
"new_path": "pkg/sentry/platform/kvm/kvm.go",
"diff": "@@ -133,6 +133,7 @@ func (k *KVM) NewAddressSpace(_ interface{}) (platform.AddressSpace, <-chan stru\nfilemem: k.FileMem,\nmachine: k.machine,\npageTables: pageTables,\n+ dirtySet: makeDirtySet(len(k.machine.vCPUs)),\n}, nil, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -80,6 +80,9 @@ type vCPU struct {\n// by the bluepill code (see bluepill_amd64.s).\nring0.CPU\n+ // id is the vCPU id.\n+ id int\n+\n// fd is the vCPU fd.\nfd int\n@@ -102,6 +105,10 @@ type vCPU struct {\n// machine associated with this vCPU.\nmachine *machine\n+\n+ // active is the current addressSpace: this is set and read atomically,\n+ // it is used to elide unnecessary interrupts due to invalidations.\n+ active atomicAddressSpace\n}\n// newMachine returns a new VM context.\n@@ -140,6 +147,7 @@ func newMachine(vm int, vCPUs int) (*machine, error) {\nreturn nil, fmt.Errorf(\"error creating VCPU: %v\", errno)\n}\nc := &vCPU{\n+ id: id,\nfd: int(fd),\nmachine: m,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -16,6 +16,7 @@ package kvm\nimport (\n\"fmt\"\n+ \"sync/atomic\"\n\"syscall\"\n\"unsafe\"\n@@ -68,6 +69,28 @@ func unmapRunData(r *runData) error {\nreturn nil\n}\n+// atomicAddressSpace is an atomic address space pointer.\n+type atomicAddressSpace struct {\n+ pointer unsafe.Pointer\n+}\n+\n+// set sets the address space value.\n+//\n+//go:nosplit\n+func (a *atomicAddressSpace) set(as *addressSpace) {\n+ atomic.StorePointer(&a.pointer, unsafe.Pointer(as))\n+}\n+\n+// get gets the address space value.\n+//\n+// Note that this should be considered best-effort, and may have changed by the\n+// time this function returns.\n+//\n+//go:nosplit\n+func (a *atomicAddressSpace) get() *addressSpace {\n+ return (*addressSpace)(atomic.LoadPointer(&a.pointer))\n+}\n+\n// notify notifies that the vCPU has transitioned modes.\n//\n// This may be called by a signal handler and therefore throws on error.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify KVM invalidation logic.
PiperOrigin-RevId: 196780209
Change-Id: I89f39eec914ce54a7c6c4f28e1b6d5ff5a7dd38d |
259,858 | 15.05.2018 22:43:52 | 25,200 | 4b7e4f3d3612dde08a37a040d5be92c37cd0ee57 | Fix KVM EFAULT handling. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -61,8 +61,9 @@ func bluepillHandler(context unsafe.Pointer) {\n}\nfor {\n- _, _, errno := syscall.RawSyscall(syscall.SYS_IOCTL, uintptr(c.fd), _KVM_RUN, 0)\n- if errno == syscall.EINTR {\n+ switch _, _, errno := syscall.RawSyscall(syscall.SYS_IOCTL, uintptr(c.fd), _KVM_RUN, 0); errno {\n+ case 0: // Expected case.\n+ case syscall.EINTR:\n// First, we process whatever pending signal\n// interrupted KVM. Since we're in a signal handler\n// currently, all signals are masked and the signal\n@@ -93,7 +94,20 @@ func bluepillHandler(context unsafe.Pointer) {\n// Force injection below; the vCPU is ready.\nc.runData.exitReason = _KVM_EXIT_IRQ_WINDOW_OPEN\n}\n- } else if errno != 0 {\n+ case syscall.EFAULT:\n+ // If a fault is not serviceable due to the host\n+ // backing pages having page permissions, instead of an\n+ // MMIO exit we receive EFAULT from the run ioctl. We\n+ // always inject an NMI here since we may be in kernel\n+ // mode and have interrupts disabled.\n+ if _, _, errno := syscall.RawSyscall(\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_NMI, 0); errno != 0 {\n+ throw(\"NMI injection failed\")\n+ }\n+ continue // Rerun vCPU.\n+ default:\nthrow(\"run failed\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_const.go",
"new_path": "pkg/sentry/platform/kvm/kvm_const.go",
"diff": "@@ -24,6 +24,7 @@ const (\n_KVM_CREATE_VCPU = 0xae41\n_KVM_SET_TSS_ADDR = 0xae47\n_KVM_RUN = 0xae80\n+ _KVM_NMI = 0xae9a\n_KVM_INTERRUPT = 0x4004ae86\n_KVM_SET_MSRS = 0x4008ae89\n_KVM_SET_USER_MEMORY_REGION = 0x4020ae46\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"diff": "@@ -97,6 +97,29 @@ func (c *vCPU) initArchState() error {\nreturn c.setSystemTime()\n}\n+// fault generates an appropriate fault return.\n+//\n+//go:nosplit\n+func (c *vCPU) fault(signal int32) (*arch.SignalInfo, usermem.AccessType, error) {\n+ bluepill(c) // Probably no-op, but may not be.\n+ faultAddr := ring0.ReadCR2()\n+ code, user := c.ErrorCode()\n+ if !user {\n+ // The last fault serviced by this CPU was not a user\n+ // fault, so we can't reliably trust the faultAddr or\n+ // the code provided here. We need to re-execute.\n+ return nil, usermem.NoAccess, platform.ErrContextInterrupt\n+ }\n+ info := &arch.SignalInfo{Signo: signal}\n+ info.SetAddr(uint64(faultAddr))\n+ accessType := usermem.AccessType{\n+ Read: code&(1<<1) == 0,\n+ Write: code&(1<<1) != 0,\n+ Execute: code&(1<<4) != 0,\n+ }\n+ return info, accessType, platform.ErrContextSignal\n+}\n+\n// SwitchToUser unpacks architectural-details.\nfunc (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetables.PageTables, flags ring0.Flags) (*arch.SignalInfo, usermem.AccessType, error) {\n// See below.\n@@ -116,29 +139,13 @@ func (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetab\n// Fast path: system call executed.\nreturn nil, usermem.NoAccess, nil\n+ case ring0.PageFault:\n+ return c.fault(int32(syscall.SIGSEGV))\n+\ncase ring0.Debug, ring0.Breakpoint:\ninfo := &arch.SignalInfo{Signo: int32(syscall.SIGTRAP)}\nreturn info, usermem.AccessType{}, platform.ErrContextSignal\n- case ring0.PageFault:\n- bluepill(c) // Probably no-op, but may not be.\n- faultAddr := ring0.ReadCR2()\n- code, user := c.ErrorCode()\n- if !user {\n- // The last fault serviced by this CPU was not a user\n- // fault, so we can't reliably trust the faultAddr or\n- // the code provided here. We need to re-execute.\n- return nil, usermem.NoAccess, platform.ErrContextInterrupt\n- }\n- info := &arch.SignalInfo{Signo: int32(syscall.SIGSEGV)}\n- info.SetAddr(uint64(faultAddr))\n- accessType := usermem.AccessType{\n- Read: code&(1<<1) == 0,\n- Write: code&(1<<1) != 0,\n- Execute: code&(1<<4) != 0,\n- }\n- return info, accessType, platform.ErrContextSignal\n-\ncase ring0.GeneralProtectionFault:\nif !ring0.IsCanonical(regs.Rip) {\n// If the RIP is non-canonical, it's a SEGV.\n@@ -160,6 +167,14 @@ func (c *vCPU) SwitchToUser(regs *syscall.PtraceRegs, fpState *byte, pt *pagetab\ncase ring0.Vector(bounce):\nreturn nil, usermem.NoAccess, platform.ErrContextInterrupt\n+ case ring0.NMI:\n+ // An NMI is generated only when a fault is not servicable by\n+ // KVM itself, so we think some mapping is writeable but it's\n+ // really not. This could happen, e.g. if some file is\n+ // truncated (and would generate a SIGBUS) and we map it\n+ // directly into the instance.\n+ return c.fault(int32(syscall.SIGBUS))\n+\ndefault:\npanic(fmt.Sprintf(\"unexpected vector: 0x%x\", vector))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix KVM EFAULT handling.
PiperOrigin-RevId: 196781718
Change-Id: I889766eed871929cdc247c6b9aa634398adea9c9 |
260,013 | 16.05.2018 13:06:23 | 25,200 | f295e26b8abe395eaf1d4bee9a792a79b34d156f | Release mutex in BidirectionalConnect to avoid deadlock.
When doing a BidirectionalConnect we don't need to continue holding
the ConnectingEndpoint's mutex when creating the NewConnectedEndpoint
as it was held during the Connect. Additionally, we're not holding
the baseEndpoint mutex while Unregistering an event. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/socket.go",
"new_path": "pkg/sentry/fs/gofer/socket.go",
"diff": "@@ -79,26 +79,33 @@ func (e *endpoint) BidirectionalConnect(ce unix.ConnectingEndpoint, returnConnec\n// No lock ordering required as only the ConnectingEndpoint has a mutex.\nce.Lock()\n- defer ce.Unlock()\n// Check connecting state.\nif ce.Connected() {\n+ ce.Unlock()\nreturn tcpip.ErrAlreadyConnected\n}\nif ce.Listening() {\n+ ce.Unlock()\nreturn tcpip.ErrInvalidEndpointState\n}\nhostFile, err := e.file.Connect(cf)\nif err != nil {\n+ ce.Unlock()\nreturn tcpip.ErrConnectionRefused\n}\n- r, c, terr := host.NewConnectedEndpoint(hostFile, ce.WaiterQueue(), e.path)\n+ c, terr := host.NewConnectedEndpoint(hostFile, ce.WaiterQueue(), e.path)\nif terr != nil {\n+ ce.Unlock()\nreturn terr\n}\n- returnConnect(r, c)\n+\n+ returnConnect(c, c)\n+ ce.Unlock()\n+ c.Init()\n+\nreturn nil\n}\n@@ -109,14 +116,15 @@ func (e *endpoint) UnidirectionalConnect() (unix.ConnectedEndpoint, *tcpip.Error\nreturn nil, tcpip.ErrConnectionRefused\n}\n- r, c, terr := host.NewConnectedEndpoint(hostFile, &waiter.Queue{}, e.path)\n+ c, terr := host.NewConnectedEndpoint(hostFile, &waiter.Queue{}, e.path)\nif terr != nil {\nreturn nil, terr\n}\n+ c.Init()\n// We don't need the receiver.\n- r.CloseRecv()\n- r.Release()\n+ c.CloseRecv()\n+ c.Release()\nreturn c, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket.go",
"new_path": "pkg/sentry/fs/host/socket.go",
"diff": "@@ -286,26 +286,33 @@ func recvMsg(fd int, data [][]byte, numRights uintptr, peek bool, addr *tcpip.Fu\nreturn rl, ml, control.New(nil, nil, newSCMRights(fds)), nil\n}\n-// NewConnectedEndpoint creates a new unix.Receiver and unix.ConnectedEndpoint\n-// backed by a host FD that will pretend to be bound at a given sentry path.\n-func NewConnectedEndpoint(file *fd.FD, queue *waiter.Queue, path string) (unix.Receiver, unix.ConnectedEndpoint, *tcpip.Error) {\n- if err := fdnotifier.AddFD(int32(file.FD()), queue); err != nil {\n- return nil, nil, translateError(err)\n- }\n-\n- e := &connectedEndpoint{path: path, queue: queue, file: file}\n+// NewConnectedEndpoint creates a new ConnectedEndpoint backed by\n+// a host FD that will pretend to be bound at a given sentry path.\n+//\n+// The caller is responsible for calling Init(). Additionaly, Release needs\n+// to be called twice because host.ConnectedEndpoint is both a\n+// unix.Receiver and unix.ConnectedEndpoint.\n+func NewConnectedEndpoint(file *fd.FD, queue *waiter.Queue, path string) (*ConnectedEndpoint, *tcpip.Error) {\n+ e := &ConnectedEndpoint{path: path, queue: queue, file: file}\n// AtomicRefCounters start off with a single reference. We need two.\ne.ref.IncRef()\n- return e, e, nil\n+ return e, nil\n+}\n+\n+// Init will do initialization required without holding other locks.\n+func (c *ConnectedEndpoint) Init() {\n+ if err := fdnotifier.AddFD(int32(c.file.FD()), c.queue); err != nil {\n+ panic(err)\n+ }\n}\n-// connectedEndpoint is a host FD backed implementation of\n+// ConnectedEndpoint is a host FD backed implementation of\n// unix.ConnectedEndpoint and unix.Receiver.\n//\n-// connectedEndpoint does not support save/restore for now.\n-type connectedEndpoint struct {\n+// ConnectedEndpoint does not support save/restore for now.\n+type ConnectedEndpoint struct {\nqueue *waiter.Queue\npath string\n@@ -328,7 +335,7 @@ type connectedEndpoint struct {\n}\n// Send implements unix.ConnectedEndpoint.Send.\n-func (c *connectedEndpoint) Send(data [][]byte, controlMessages unix.ControlMessages, from tcpip.FullAddress) (uintptr, bool, *tcpip.Error) {\n+func (c *ConnectedEndpoint) Send(data [][]byte, controlMessages unix.ControlMessages, from tcpip.FullAddress) (uintptr, bool, *tcpip.Error) {\nc.mu.RLock()\ndefer c.mu.RUnlock()\nif c.writeClosed {\n@@ -341,20 +348,20 @@ func (c *connectedEndpoint) Send(data [][]byte, controlMessages unix.ControlMess\n}\n// SendNotify implements unix.ConnectedEndpoint.SendNotify.\n-func (c *connectedEndpoint) SendNotify() {}\n+func (c *ConnectedEndpoint) SendNotify() {}\n// CloseSend implements unix.ConnectedEndpoint.CloseSend.\n-func (c *connectedEndpoint) CloseSend() {\n+func (c *ConnectedEndpoint) CloseSend() {\nc.mu.Lock()\nc.writeClosed = true\nc.mu.Unlock()\n}\n// CloseNotify implements unix.ConnectedEndpoint.CloseNotify.\n-func (c *connectedEndpoint) CloseNotify() {}\n+func (c *ConnectedEndpoint) CloseNotify() {}\n// Writable implements unix.ConnectedEndpoint.Writable.\n-func (c *connectedEndpoint) Writable() bool {\n+func (c *ConnectedEndpoint) Writable() bool {\nc.mu.RLock()\ndefer c.mu.RUnlock()\nif c.writeClosed {\n@@ -364,18 +371,18 @@ func (c *connectedEndpoint) Writable() bool {\n}\n// Passcred implements unix.ConnectedEndpoint.Passcred.\n-func (c *connectedEndpoint) Passcred() bool {\n+func (c *ConnectedEndpoint) Passcred() bool {\n// We don't support credential passing for host sockets.\nreturn false\n}\n// GetLocalAddress implements unix.ConnectedEndpoint.GetLocalAddress.\n-func (c *connectedEndpoint) GetLocalAddress() (tcpip.FullAddress, *tcpip.Error) {\n+func (c *ConnectedEndpoint) GetLocalAddress() (tcpip.FullAddress, *tcpip.Error) {\nreturn tcpip.FullAddress{Addr: tcpip.Address(c.path)}, nil\n}\n// EventUpdate implements unix.ConnectedEndpoint.EventUpdate.\n-func (c *connectedEndpoint) EventUpdate() {\n+func (c *ConnectedEndpoint) EventUpdate() {\nc.mu.RLock()\ndefer c.mu.RUnlock()\nif c.file.FD() != -1 {\n@@ -384,7 +391,7 @@ func (c *connectedEndpoint) EventUpdate() {\n}\n// Recv implements unix.Receiver.Recv.\n-func (c *connectedEndpoint) Recv(data [][]byte, creds bool, numRights uintptr, peek bool) (uintptr, uintptr, unix.ControlMessages, tcpip.FullAddress, bool, *tcpip.Error) {\n+func (c *ConnectedEndpoint) Recv(data [][]byte, creds bool, numRights uintptr, peek bool) (uintptr, uintptr, unix.ControlMessages, tcpip.FullAddress, bool, *tcpip.Error) {\nc.mu.RLock()\ndefer c.mu.RUnlock()\nif c.readClosed {\n@@ -397,24 +404,24 @@ func (c *connectedEndpoint) Recv(data [][]byte, creds bool, numRights uintptr, p\n}\n// close releases all resources related to the endpoint.\n-func (c *connectedEndpoint) close() {\n+func (c *ConnectedEndpoint) close() {\nfdnotifier.RemoveFD(int32(c.file.FD()))\nc.file.Close()\nc.file = nil\n}\n// RecvNotify implements unix.Receiver.RecvNotify.\n-func (c *connectedEndpoint) RecvNotify() {}\n+func (c *ConnectedEndpoint) RecvNotify() {}\n// CloseRecv implements unix.Receiver.CloseRecv.\n-func (c *connectedEndpoint) CloseRecv() {\n+func (c *ConnectedEndpoint) CloseRecv() {\nc.mu.Lock()\nc.readClosed = true\nc.mu.Unlock()\n}\n// Readable implements unix.Receiver.Readable.\n-func (c *connectedEndpoint) Readable() bool {\n+func (c *ConnectedEndpoint) Readable() bool {\nc.mu.RLock()\ndefer c.mu.RUnlock()\nif c.readClosed {\n@@ -424,21 +431,21 @@ func (c *connectedEndpoint) Readable() bool {\n}\n// SendQueuedSize implements unix.Receiver.SendQueuedSize.\n-func (c *connectedEndpoint) SendQueuedSize() int64 {\n+func (c *ConnectedEndpoint) SendQueuedSize() int64 {\n// SendQueuedSize isn't supported for host sockets because we don't allow the\n// sentry to call ioctl(2).\nreturn -1\n}\n// RecvQueuedSize implements unix.Receiver.RecvQueuedSize.\n-func (c *connectedEndpoint) RecvQueuedSize() int64 {\n+func (c *ConnectedEndpoint) RecvQueuedSize() int64 {\n// RecvQueuedSize isn't supported for host sockets because we don't allow the\n// sentry to call ioctl(2).\nreturn -1\n}\n// SendMaxQueueSize implements unix.Receiver.SendMaxQueueSize.\n-func (c *connectedEndpoint) SendMaxQueueSize() int64 {\n+func (c *ConnectedEndpoint) SendMaxQueueSize() int64 {\nv, err := syscall.GetsockoptInt(c.file.FD(), syscall.SOL_SOCKET, syscall.SO_SNDBUF)\nif err != nil {\nreturn -1\n@@ -447,7 +454,7 @@ func (c *connectedEndpoint) SendMaxQueueSize() int64 {\n}\n// RecvMaxQueueSize implements unix.Receiver.RecvMaxQueueSize.\n-func (c *connectedEndpoint) RecvMaxQueueSize() int64 {\n+func (c *ConnectedEndpoint) RecvMaxQueueSize() int64 {\nv, err := syscall.GetsockoptInt(c.file.FD(), syscall.SOL_SOCKET, syscall.SO_RCVBUF)\nif err != nil {\nreturn -1\n@@ -456,7 +463,7 @@ func (c *connectedEndpoint) RecvMaxQueueSize() int64 {\n}\n// Release implements unix.ConnectedEndpoint.Release and unix.Receiver.Release.\n-func (c *connectedEndpoint) Release() {\n+func (c *ConnectedEndpoint) Release() {\nc.ref.DecRefWithDestructor(c.close)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket_test.go",
"new_path": "pkg/sentry/fs/host/socket_test.go",
"diff": "@@ -31,11 +31,11 @@ import (\n)\nvar (\n- // Make sure that connectedEndpoint implements unix.ConnectedEndpoint.\n- _ = unix.ConnectedEndpoint(new(connectedEndpoint))\n+ // Make sure that ConnectedEndpoint implements unix.ConnectedEndpoint.\n+ _ = unix.ConnectedEndpoint(new(ConnectedEndpoint))\n- // Make sure that connectedEndpoint implements unix.Receiver.\n- _ = unix.Receiver(new(connectedEndpoint))\n+ // Make sure that ConnectedEndpoint implements unix.Receiver.\n+ _ = unix.Receiver(new(ConnectedEndpoint))\n)\nfunc getFl(fd int) (uint32, error) {\n@@ -198,28 +198,28 @@ func TestListen(t *testing.T) {\n}\nfunc TestSend(t *testing.T) {\n- e := connectedEndpoint{writeClosed: true}\n+ e := ConnectedEndpoint{writeClosed: true}\nif _, _, err := e.Send(nil, unix.ControlMessages{}, tcpip.FullAddress{}); err != tcpip.ErrClosedForSend {\nt.Errorf(\"Got %#v.Send() = %v, want = %v\", e, err, tcpip.ErrClosedForSend)\n}\n}\nfunc TestRecv(t *testing.T) {\n- e := connectedEndpoint{readClosed: true}\n+ e := ConnectedEndpoint{readClosed: true}\nif _, _, _, _, _, err := e.Recv(nil, false, 0, false); err != tcpip.ErrClosedForReceive {\nt.Errorf(\"Got %#v.Recv() = %v, want = %v\", e, err, tcpip.ErrClosedForReceive)\n}\n}\nfunc TestPasscred(t *testing.T) {\n- e := connectedEndpoint{}\n+ e := ConnectedEndpoint{}\nif got, want := e.Passcred(), false; got != want {\nt.Errorf(\"Got %#v.Passcred() = %t, want = %t\", e, got, want)\n}\n}\nfunc TestGetLocalAddress(t *testing.T) {\n- e := connectedEndpoint{path: \"foo\"}\n+ e := ConnectedEndpoint{path: \"foo\"}\nwant := tcpip.FullAddress{Addr: tcpip.Address(\"foo\")}\nif got, err := e.GetLocalAddress(); err != nil || got != want {\nt.Errorf(\"Got %#v.GetLocalAddress() = %#v, %v, want = %#v, %v\", e, got, err, want, nil)\n@@ -227,7 +227,7 @@ func TestGetLocalAddress(t *testing.T) {\n}\nfunc TestQueuedSize(t *testing.T) {\n- e := connectedEndpoint{}\n+ e := ConnectedEndpoint{}\ntests := []struct {\nname string\nf func() int64\n@@ -244,14 +244,14 @@ func TestQueuedSize(t *testing.T) {\n}\nfunc TestReadable(t *testing.T) {\n- e := connectedEndpoint{readClosed: true}\n+ e := ConnectedEndpoint{readClosed: true}\nif got, want := e.Readable(), true; got != want {\nt.Errorf(\"Got %#v.Readable() = %t, want = %t\", e, got, want)\n}\n}\nfunc TestWritable(t *testing.T) {\n- e := connectedEndpoint{writeClosed: true}\n+ e := ConnectedEndpoint{writeClosed: true}\nif got, want := e.Writable(), true; got != want {\nt.Errorf(\"Got %#v.Writable() = %t, want = %t\", e, got, want)\n}\n@@ -262,8 +262,8 @@ func TestRelease(t *testing.T) {\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c := &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\n- want := &connectedEndpoint{queue: c.queue}\n+ c := &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\n+ want := &ConnectedEndpoint{queue: c.queue}\nwant.ref.DecRef()\nfdnotifier.AddFD(int32(c.file.FD()), nil)\nc.Release()\n@@ -275,119 +275,119 @@ func TestRelease(t *testing.T) {\nfunc TestClose(t *testing.T) {\ntype testCase struct {\nname string\n- cep *connectedEndpoint\n+ cep *ConnectedEndpoint\naddFD bool\nf func()\n- want *connectedEndpoint\n+ want *ConnectedEndpoint\n}\nvar tests []testCase\n- // nil is the value used by connectedEndpoint to indicate a closed file.\n+ // nil is the value used by ConnectedEndpoint to indicate a closed file.\n// Non-nil files are used to check if the file gets closed.\nf, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c := &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\n+ c := &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\ntests = append(tests, testCase{\nname: \"First CloseRecv\",\ncep: c,\naddFD: false,\nf: c.CloseRecv,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true}\ntests = append(tests, testCase{\nname: \"Second CloseRecv\",\ncep: c,\naddFD: false,\nf: c.CloseRecv,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f)}\ntests = append(tests, testCase{\nname: \"First CloseSend\",\ncep: c,\naddFD: false,\nf: c.CloseSend,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, writeClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), writeClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), writeClosed: true}\ntests = append(tests, testCase{\nname: \"Second CloseSend\",\ncep: c,\naddFD: false,\nf: c.CloseSend,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, writeClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), writeClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), writeClosed: true}\ntests = append(tests, testCase{\nname: \"CloseSend then CloseRecv\",\ncep: c,\naddFD: true,\nf: c.CloseRecv,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true}\ntests = append(tests, testCase{\nname: \"CloseRecv then CloseSend\",\ncep: c,\naddFD: true,\nf: c.CloseSend,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true, writeClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true, writeClosed: true}\ntests = append(tests, testCase{\nname: \"Full close then CloseRecv\",\ncep: c,\naddFD: false,\nf: c.CloseRecv,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n})\nf, err = syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, 0)\nif err != nil {\nt.Fatal(\"Creating socket:\", err)\n}\n- c = &connectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true, writeClosed: true}\n+ c = &ConnectedEndpoint{queue: &waiter.Queue{}, file: fd.New(f), readClosed: true, writeClosed: true}\ntests = append(tests, testCase{\nname: \"Full close then CloseSend\",\ncep: c,\naddFD: false,\nf: c.CloseSend,\n- want: &connectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n+ want: &ConnectedEndpoint{queue: c.queue, file: c.file, readClosed: true, writeClosed: true},\n})\nfor _, test := range tests {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/unix/unix.go",
"new_path": "pkg/tcpip/transport/unix/unix.go",
"diff": "@@ -677,8 +677,8 @@ type baseEndpoint struct {\n// EventRegister implements waiter.Waitable.EventRegister.\nfunc (e *baseEndpoint) EventRegister(we *waiter.Entry, mask waiter.EventMask) {\n- e.Lock()\ne.Queue.EventRegister(we, mask)\n+ e.Lock()\nif e.connected != nil {\ne.connected.EventUpdate()\n}\n@@ -687,8 +687,8 @@ func (e *baseEndpoint) EventRegister(we *waiter.Entry, mask waiter.EventMask) {\n// EventUnregister implements waiter.Waitable.EventUnregister.\nfunc (e *baseEndpoint) EventUnregister(we *waiter.Entry) {\n- e.Lock()\ne.Queue.EventUnregister(we)\n+ e.Lock()\nif e.connected != nil {\ne.connected.EventUpdate()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Release mutex in BidirectionalConnect to avoid deadlock.
When doing a BidirectionalConnect we don't need to continue holding
the ConnectingEndpoint's mutex when creating the NewConnectedEndpoint
as it was held during the Connect. Additionally, we're not holding
the baseEndpoint mutex while Unregistering an event.
PiperOrigin-RevId: 196875557
Change-Id: Ied4ceed89de883121c6cba81bc62aa3a8549b1e9 |
259,956 | 16.05.2018 14:53:57 | 25,200 | 8e1deb2ab8fb67da9a1f6521e31c5635ac587e71 | Fix another socket Dirent refcount. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/socket.go",
"new_path": "pkg/sentry/socket/rpcinet/socket.go",
"diff": "@@ -71,6 +71,7 @@ func newSocketFile(ctx context.Context, stack *Stack, family int, skType int, pr\nstack.notifier.AddFD(fd, &wq)\ndirent := socket.NewDirent(ctx, socketDevice)\n+ defer dirent.DecRef()\nreturn fs.NewFile(ctx, dirent, fs.FileFlags{Read: true, Write: true}, &socketOperations{\nwq: &wq,\nfd: fd,\n@@ -274,6 +275,7 @@ func (s *socketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\ns.notifier.AddFD(payload.Fd, &wq)\ndirent := socket.NewDirent(t, socketDevice)\n+ defer dirent.DecRef()\nfile := fs.NewFile(t, dirent, fs.FileFlags{Read: true, Write: true, NonBlocking: flags&linux.SOCK_NONBLOCK != 0}, &socketOperations{\nwq: &wq,\nfd: payload.Fd,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix another socket Dirent refcount.
PiperOrigin-RevId: 196893452
Change-Id: I5ea0f851fcabc5eac5859e61f15213323d996337 |
259,985 | 17.05.2018 15:37:19 | 25,200 | b904250b862c5c14da84e08b6a5400c7bf2458b0 | Fix capability check for sysv semaphores.
Capabilities for sysv sem operations were being checked against the
current task's user namespace. They should be checked against the user
namespace owning the ipc namespace for the sems instead, per
ipc/util.c:ipcperms(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/ipc_namespace.go",
"new_path": "pkg/sentry/kernel/ipc_namespace.go",
"diff": "@@ -33,7 +33,7 @@ type IPCNamespace struct {\nfunc NewIPCNamespace(userNS *auth.UserNamespace) *IPCNamespace {\nreturn &IPCNamespace{\nuserNS: userNS,\n- semaphores: semaphore.NewRegistry(),\n+ semaphores: semaphore.NewRegistry(userNS),\nshms: shm.NewRegistry(userNS),\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -43,6 +43,8 @@ const (\n// Registry maintains a set of semaphores that can be found by key or ID.\ntype Registry struct {\n+ // userNS owning the ipc name this registry belongs to. Immutable.\n+ userNS *auth.UserNamespace\n// mu protects all fields below.\nmu sync.Mutex `state:\"nosave\"`\nsemaphores map[int32]*Set\n@@ -51,6 +53,9 @@ type Registry struct {\n// Set represents a set of semaphores that can be operated atomically.\ntype Set struct {\n+ // registry owning this sem set. Immutable.\n+ registry *Registry\n+\n// Id is a handle that identifies the set.\nID int32\n@@ -90,8 +95,11 @@ type waiter struct {\n}\n// NewRegistry creates a new semaphore set registry.\n-func NewRegistry() *Registry {\n- return &Registry{semaphores: make(map[int32]*Set)}\n+func NewRegistry(userNS *auth.UserNamespace) *Registry {\n+ return &Registry{\n+ userNS: userNS,\n+ semaphores: make(map[int32]*Set),\n+ }\n}\n// FindOrCreate searches for a semaphore set that matches 'key'. If not found,\n@@ -175,6 +183,7 @@ func (r *Registry) RemoveID(id int32, creds *auth.Credentials) error {\nfunc (r *Registry) newSet(ctx context.Context, key int32, owner, creator fs.FileOwner, perms fs.FilePermissions, nsems int32) (*Set, error) {\nset := &Set{\n+ registry: r,\nkey: key,\nowner: owner,\ncreator: owner,\n@@ -415,7 +424,7 @@ func (s *Set) checkCredentials(creds *auth.Credentials) bool {\n}\nfunc (s *Set) checkCapability(creds *auth.Credentials) bool {\n- return creds.HasCapability(linux.CAP_IPC_OWNER) && creds.UserNamespace.MapFromKUID(s.owner.UID).Ok()\n+ return creds.HasCapabilityIn(linux.CAP_IPC_OWNER, s.registry.userNS) && creds.UserNamespace.MapFromKUID(s.owner.UID).Ok()\n}\nfunc (s *Set) checkPerms(creds *auth.Credentials, reqPerms fs.PermMask) bool {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore_test.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore_test.go",
"diff": "@@ -136,7 +136,7 @@ func TestNoWait(t *testing.T) {\nfunc TestUnregister(t *testing.T) {\nctx := contexttest.Context(t)\n- r := NewRegistry()\n+ r := NewRegistry(auth.NewRootUserNamespace())\nset, err := r.FindOrCreate(ctx, 123, 2, linux.FileMode(0x600), true, true, true)\nif err != nil {\nt.Fatalf(\"FindOrCreate() failed, err: %v\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix capability check for sysv semaphores.
Capabilities for sysv sem operations were being checked against the
current task's user namespace. They should be checked against the user
namespace owning the ipc namespace for the sems instead, per
ipc/util.c:ipcperms().
PiperOrigin-RevId: 197063111
Change-Id: Iba29486b316f2e01ee331dda4e48a6ab7960d589 |
259,881 | 17.05.2018 16:25:51 | 25,200 | b960559fdb9a22c986af11ba4e886ffb316a3574 | Cleanup docs
This brings the proc document more up-to-date. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/README.md",
"new_path": "pkg/sentry/fs/proc/README.md",
"diff": "@@ -11,15 +11,14 @@ inconsistency, please file a bug.\nThe following files are implemented:\n| File /proc/ | Content |\n-| :------------------------ | :----------------------------------------------- |\n+| :------------------------ | :---------------------------------------------------- |\n| [cpuinfo](#cpuinfo) | Info about the CPU |\n-| [filesystem](#filesystem) | Supported filesystems |\n+| [filesystems](#filesystems) | Supported filesystems |\n| [loadavg](#loadavg) | Load average of last 1, 5 & 15 minutes |\n| [meminfo](#meminfo) | Overall memory info |\n| [stat](#stat) | Overall kernel statistics |\n| [sys](#sys) | Change parameters within the kernel |\n-| [uptime](#uptime) | Wall clock since boot, combined idle time of all |\n-: : cpus :\n+| [uptime](#uptime) | Wall clock since boot, combined idle time of all cpus |\n| [version](#version) | Kernel version |\n### cpuinfo\n@@ -62,26 +61,20 @@ cache_alignment | Always 64\naddress sizes | Always 46 bits physical, 48 bits virtual\npower management | Always blank\n-Otherwise fields are derived from the SentryCPUIDSpec proto config.\n+Otherwise fields are derived from the sentry configuration.\n-### filesystem\n+### filesystems\n```bash\n-$ cat /proc/filesystem\n+$ cat /proc/filesystems\nnodev 9p\n+nodev devpts\nnodev devtmpfs\nnodev proc\n-nodev ramdiskfs\nnodev sysfs\nnodev tmpfs\n```\n-Notable divergences:\n-\n-Filesystem | Notes\n-:--------- | :--------------------------------------------------------\n-ramdiskfs | No Linux equivalent, see the SentryRamdiskFS proto config\n-\n### loadavg\n```bash\n@@ -166,10 +159,6 @@ DirectMap4k | Missing\nDirectMap2M | Missing\nDirectMap1G | Missing\n-See [Memory\n-Accounting](pkg/sentry/usage/g3doc/memory-accounting.md)\n-for general caveats.\n-\n### stat\n```bash\n@@ -237,18 +226,22 @@ Linux version 3.11.10 #1 SMP Fri Nov 29 10:47:50 PST 2013\nThe following files are implemented:\nFile /proc/PID | Content\n-:------------------ | :---------------------------------------------------\n+:---------------------- | :---------------------------------------------------\n[auxv](#auxv) | Copy of auxiliary vector for the process\n[cmdline](#cmdline) | Command line arguments\n[comm](#comm) | Command name associated with the process\n+[environ](#environ) | Process environment\n[exe](#exe) | Symlink to the process's executable\n[fd](#fd) | Directory containing links to open file descriptors\n[fdinfo](#fdinfo) | Information associated with open file descriptors\n[gid_map](#gid_map) | Mappings for group IDs inside the user namespace\n[io](#io) | IO statistics\n[maps](#maps) | Memory mappings (anon, executables, library files)\n+[mounts](#mounts) | Mounted filesystems\n+[mountinfo](#mountinfo) | Information about mounts\n[ns](#ns) | Directory containing info about supported namespaces\n[stat](#stat) | Process statistics\n+[statm](#statm) | Process memory statistics\n[status](#status) | Process status in human readable format\n[task](#task) | Directory containing info about running threads\n[uid_map](#uid_map) | Mappings for user IDs inside the user namespace\n@@ -265,6 +258,10 @@ TODO\nTODO\n+### environment\n+\n+TODO\n+\n### exe\nTODO\n@@ -291,6 +288,14 @@ TODO: add more detail.\nTODO\n+### mounts\n+\n+TODO\n+\n+### mountinfo\n+\n+TODO\n+\n### ns\nTODO\n@@ -302,9 +307,16 @@ num_threads, and exit_signal.\nTODO: add more detail.\n+### statm\n+\n+Only has data for vss and rss.\n+\n+TODO: add more detail.\n+\n### status\n-Statically created, most of the fields have no data.\n+Contains data for Name, State, Tgid, Pid, Ppid, TracerPid, FDSize, VmSize,\n+VmRSS, Threads, CapInh, CapPrm, CapEff, CapBnd, Seccomp.\nTODO: add more detail.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "// limitations under the License.\n// Package linux provides syscall tables for amd64 Linux.\n-//\n-// NOTE: Linux i386 support has been removed.\npackage linux\nimport (\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cleanup docs
This brings the proc document more up-to-date.
PiperOrigin-RevId: 197070161
Change-Id: Iae2cf9dc44e3e748a33f497bb95bd3c10d0c094a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.