libs/core: util.lua optimize get() and set() accessors of threadlocals
[project/luci.git] / libs / core / luasrc / util.lua
1 --[[
2 LuCI - Utility library
3
4 Description:
5 Several common useful Lua functions
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 local io = require "io"
28 local math = require "math"
29 local table = require "table"
30 local debug = require "debug"
31 local ldebug = require "luci.debug"
32 local string = require "string"
33 local coroutine = require "coroutine"
34
35 local getmetatable, setmetatable = getmetatable, setmetatable
36 local rawget, rawset, unpack = rawget, rawset, unpack
37 local tostring, type, assert = tostring, type, assert
38 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
39 local require, pcall, xpcall = require, pcall, xpcall
40 local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
41
42 --- LuCI utility functions.
43 module "luci.util"
44
45 --
46 -- Pythonic string formatting extension
47 --
48 getmetatable("").__mod = function(a, b)
49 if not b then
50 return a
51 elseif type(b) == "table" then
52 return a:format(unpack(b))
53 else
54 return a:format(b)
55 end
56 end
57
58
59 --
60 -- Class helper routines
61 --
62
63 -- Instantiates a class
64 local function _instantiate(class, ...)
65 local inst = setmetatable({}, {__index = class})
66
67 if inst.__init__ then
68 inst:__init__(...)
69 end
70
71 return inst
72 end
73
74 --- Create a Class object (Python-style object model).
75 -- The class object can be instantiated by calling itself.
76 -- Any class functions or shared parameters can be attached to this object.
77 -- Attaching a table to the class object makes this table shared between
78 -- all instances of this class. For object parameters use the __init__ function.
79 -- Classes can inherit member functions and values from a base class.
80 -- Class can be instantiated by calling them. All parameters will be passed
81 -- to the __init__ function of this class - if such a function exists.
82 -- The __init__ function must be used to set any object parameters that are not shared
83 -- with other objects of this class. Any return values will be ignored.
84 -- @param base The base class to inherit from (optional)
85 -- @return A class object
86 -- @see instanceof
87 -- @see clone
88 function class(base)
89 return setmetatable({}, {
90 __call = _instantiate,
91 __index = base
92 })
93 end
94
95 --- Test whether the given object is an instance of the given class.
96 -- @param object Object instance
97 -- @param class Class object to test against
98 -- @return Boolean indicating whether the object is an instance
99 -- @see class
100 -- @see clone
101 function instanceof(object, class)
102 local meta = getmetatable(object)
103 while meta and meta.__index do
104 if meta.__index == class then
105 return true
106 end
107 meta = getmetatable(meta.__index)
108 end
109 return false
110 end
111
112
113 --
114 -- Scope manipulation routines
115 --
116
117 --- Create a new or get an already existing thread local store associated with
118 -- the current active coroutine. A thread local store is private a table object
119 -- whose values can't be accessed from outside of the running coroutine.
120 -- @return Table value representing the corresponding thread local store
121 function threadlocal()
122 local tbl = {}
123
124 local function get(self, key)
125 local t = rawget(self, coxpt[coroutine.running()] or coroutine.running() or 0)
126 return t and t[key]
127 end
128
129 local function set(self, key, value)
130 local c = coxpt[coroutine.running()] or coroutine.running() or 0
131 if not rawget(self, c) then
132 rawset(self, c, { [key] = value })
133 else
134 rawget(self, c)[key] = value
135 end
136 end
137
138 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
139
140 return tbl
141 end
142
143
144 --
145 -- Debugging routines
146 --
147
148 --- Write given object to stderr.
149 -- @param obj Value to write to stderr
150 -- @return Boolean indicating whether the write operation was successful
151 function perror(obj)
152 return io.stderr:write(tostring(obj) .. "\n")
153 end
154
155 --- Recursively dumps a table to stdout, useful for testing and debugging.
156 -- @param t Table value to dump
157 -- @param maxdepth Maximum depth
158 -- @return Always nil
159 function dumptable(t, maxdepth, i, seen)
160 i = i or 0
161 seen = seen or setmetatable({}, {__mode="k"})
162
163 for k,v in pairs(t) do
164 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
165 if type(v) == "table" and (not maxdepth or i < maxdepth) then
166 if not seen[v] then
167 seen[v] = true
168 dumptable(v, maxdepth, i+1, seen)
169 else
170 perror(string.rep("\t", i) .. "*** RECURSION ***")
171 end
172 end
173 end
174 end
175
176
177 --
178 -- String and data manipulation routines
179 --
180
181 --- Escapes all occurrences of the given character in given string.
182 -- @param s String value containing unescaped characters
183 -- @param c String value with character to escape (optional, defaults to "\")
184 -- @return String value with each occurrence of character escaped with "\"
185 function escape(s, c)
186 c = c or "\\"
187 return s:gsub(c, "\\" .. c)
188 end
189
190 --- Create valid XML PCDATA from given string.
191 -- @param value String value containing the data to escape
192 -- @return String value containing the escaped data
193 local function _pcdata_repl(c)
194 local i = string.byte(c)
195
196 if ( i >= 0x00 and i <= 0x08 ) or ( i >= 0x0B and i <= 0x0C ) or
197 ( i >= 0x0E and i <= 0x1F ) or ( i == 0x7F )
198 then
199 return ""
200
201 elseif ( i == 0x26 ) or ( i == 0x27 ) or ( i == 0x22 ) or
202 ( i == 0x3C ) or ( i == 0x3E )
203 then
204 return string.format("&#%i;", i)
205 end
206
207 return c
208 end
209
210 function pcdata(value)
211 return value and tostring(value):gsub("[&\"'<>%c]", _pcdata_repl)
212 end
213
214 --- Strip HTML tags from given string.
215 -- @param value String containing the HTML text
216 -- @return String with HTML tags stripped of
217 function striptags(s)
218 return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
219 end
220
221 --- Splits given string on a defined separator sequence and return a table
222 -- containing the resulting substrings. The optional max parameter specifies
223 -- the number of bytes to process, regardless of the actual length of the given
224 -- string. The optional last parameter, regex, specifies whether the separator
225 -- sequence is interpreted as regular expression.
226 -- @param str String value containing the data to split up
227 -- @param pat String with separator pattern (optional, defaults to "\n")
228 -- @param max Maximum times to split (optional)
229 -- @param regex Boolean indicating whether to interpret the separator
230 -- pattern as regular expression (optional, default is false)
231 -- @return Table containing the resulting substrings
232 function split(str, pat, max, regex)
233 pat = pat or "\n"
234 max = max or #str
235
236 local t = {}
237 local c = 1
238
239 if #str == 0 then
240 return {""}
241 end
242
243 if #pat == 0 then
244 return nil
245 end
246
247 if max == 0 then
248 return str
249 end
250
251 repeat
252 local s, e = str:find(pat, c, not regex)
253 max = max - 1
254 if s and max < 0 then
255 t[#t+1] = str:sub(c)
256 else
257 t[#t+1] = str:sub(c, s and s - 1)
258 end
259 c = e and e + 1 or #str + 1
260 until not s or max < 0
261
262 return t
263 end
264
265 --- Remove leading and trailing whitespace from given string value.
266 -- @param str String value containing whitespace padded data
267 -- @return String value with leading and trailing space removed
268 function trim(str)
269 return (str:gsub("^%s*(.-)%s*$", "%1"))
270 end
271
272 --- Count the occurences of given substring in given string.
273 -- @param str String to search in
274 -- @param pattern String containing pattern to find
275 -- @return Number of found occurences
276 function cmatch(str, pat)
277 local count = 0
278 for _ in str:gmatch(pat) do count = count + 1 end
279 return count
280 end
281
282 --- Parse certain units from the given string and return the canonical integer
283 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
284 -- Recognized units are:
285 -- o "y" - one year (60*60*24*366)
286 -- o "m" - one month (60*60*24*31)
287 -- o "w" - one week (60*60*24*7)
288 -- o "d" - one day (60*60*24)
289 -- o "h" - one hour (60*60)
290 -- o "min" - one minute (60)
291 -- o "kb" - one kilobyte (1024)
292 -- o "mb" - one megabyte (1024*1024)
293 -- o "gb" - one gigabyte (1024*1024*1024)
294 -- o "kib" - one si kilobyte (1000)
295 -- o "mib" - one si megabyte (1000*1000)
296 -- o "gib" - one si gigabyte (1000*1000*1000)
297 -- @param ustr String containing a numerical value with trailing unit
298 -- @return Number containing the canonical value
299 function parse_units(ustr)
300
301 local val = 0
302
303 -- unit map
304 local map = {
305 -- date stuff
306 y = 60 * 60 * 24 * 366,
307 m = 60 * 60 * 24 * 31,
308 w = 60 * 60 * 24 * 7,
309 d = 60 * 60 * 24,
310 h = 60 * 60,
311 min = 60,
312
313 -- storage sizes
314 kb = 1024,
315 mb = 1024 * 1024,
316 gb = 1024 * 1024 * 1024,
317
318 -- storage sizes (si)
319 kib = 1000,
320 mib = 1000 * 1000,
321 gib = 1000 * 1000 * 1000
322 }
323
324 -- parse input string
325 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
326
327 local num = spec:gsub("[^0-9%.]+$","")
328 local spn = spec:gsub("^[0-9%.]+", "")
329
330 if map[spn] or map[spn:sub(1,1)] then
331 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
332 else
333 val = val + num
334 end
335 end
336
337
338 return val
339 end
340
341 -- also register functions above in the central string class for convenience
342 string.escape = escape
343 string.pcdata = pcdata
344 string.striptags = striptags
345 string.split = split
346 string.trim = trim
347 string.cmatch = cmatch
348 string.parse_units = parse_units
349
350
351 --- Appends numerically indexed tables or single objects to a given table.
352 -- @param src Target table
353 -- @param ... Objects to insert
354 -- @return Target table
355 function append(src, ...)
356 for i, a in ipairs({...}) do
357 if type(a) == "table" then
358 for j, v in ipairs(a) do
359 src[#src+1] = v
360 end
361 else
362 src[#src+1] = a
363 end
364 end
365 return src
366 end
367
368 --- Combines two or more numerically indexed tables and single objects into one table.
369 -- @param tbl1 Table value to combine
370 -- @param tbl2 Table value to combine
371 -- @param ... More tables to combine
372 -- @return Table value containing all values of given tables
373 function combine(...)
374 return append({}, ...)
375 end
376
377 --- Checks whether the given table contains the given value.
378 -- @param table Table value
379 -- @param value Value to search within the given table
380 -- @return Boolean indicating whether the given value occurs within table
381 function contains(table, value)
382 for k, v in pairs(table) do
383 if value == v then
384 return k
385 end
386 end
387 return false
388 end
389
390 --- Update values in given table with the values from the second given table.
391 -- Both table are - in fact - merged together.
392 -- @param t Table which should be updated
393 -- @param updates Table containing the values to update
394 -- @return Always nil
395 function update(t, updates)
396 for k, v in pairs(updates) do
397 t[k] = v
398 end
399 end
400
401 --- Retrieve all keys of given associative table.
402 -- @param t Table to extract keys from
403 -- @return Sorted table containing the keys
404 function keys(t)
405 local keys = { }
406 if t then
407 for k, _ in kspairs(t) do
408 keys[#keys+1] = k
409 end
410 end
411 return keys
412 end
413
414 --- Clones the given object and return it's copy.
415 -- @param object Table value to clone
416 -- @param deep Boolean indicating whether to do recursive cloning
417 -- @return Cloned table value
418 function clone(object, deep)
419 local copy = {}
420
421 for k, v in pairs(object) do
422 if deep and type(v) == "table" then
423 v = clone(v, deep)
424 end
425 copy[k] = v
426 end
427
428 return setmetatable(copy, getmetatable(object))
429 end
430
431
432 --- Create a dynamic table which automatically creates subtables.
433 -- @return Dynamic Table
434 function dtable()
435 return setmetatable({}, { __index =
436 function(tbl, key)
437 return rawget(tbl, key)
438 or rawget(rawset(tbl, key, dtable()), key)
439 end
440 })
441 end
442
443
444 -- Serialize the contents of a table value.
445 function _serialize_table(t, seen)
446 assert(not seen[t], "Recursion detected.")
447 seen[t] = true
448
449 local data = ""
450 local idata = ""
451 local ilen = 0
452
453 for k, v in pairs(t) do
454 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
455 k = serialize_data(k, seen)
456 v = serialize_data(v, seen)
457 data = data .. ( #data > 0 and ", " or "" ) ..
458 '[' .. k .. '] = ' .. v
459 elseif k > ilen then
460 ilen = k
461 end
462 end
463
464 for i = 1, ilen do
465 local v = serialize_data(t[i], seen)
466 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
467 end
468
469 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
470 end
471
472 --- Recursively serialize given data to lua code, suitable for restoring
473 -- with loadstring().
474 -- @param val Value containing the data to serialize
475 -- @return String value containing the serialized code
476 -- @see restore_data
477 -- @see get_bytecode
478 function serialize_data(val, seen)
479 seen = seen or setmetatable({}, {__mode="k"})
480
481 if val == nil then
482 return "nil"
483 elseif type(val) == "number" then
484 return val
485 elseif type(val) == "string" then
486 return "%q" % val
487 elseif type(val) == "boolean" then
488 return val and "true" or "false"
489 elseif type(val) == "function" then
490 return "loadstring(%q)" % get_bytecode(val)
491 elseif type(val) == "table" then
492 return "{ " .. _serialize_table(val, seen) .. " }"
493 else
494 return '"[unhandled data type:' .. type(val) .. ']"'
495 end
496 end
497
498 --- Restore data previously serialized with serialize_data().
499 -- @param str String containing the data to restore
500 -- @return Value containing the restored data structure
501 -- @see serialize_data
502 -- @see get_bytecode
503 function restore_data(str)
504 return loadstring("return " .. str)()
505 end
506
507
508 --
509 -- Byte code manipulation routines
510 --
511
512 --- Return the current runtime bytecode of the given data. The byte code
513 -- will be stripped before it is returned.
514 -- @param val Value to return as bytecode
515 -- @return String value containing the bytecode of the given data
516 function get_bytecode(val)
517 local code
518
519 if type(val) == "function" then
520 code = string.dump(val)
521 else
522 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
523 end
524
525 return code and strip_bytecode(code)
526 end
527
528 --- Strips unnescessary lua bytecode from given string. Information like line
529 -- numbers and debugging numbers will be discarded. Original version by
530 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
531 -- @param code String value containing the original lua byte code
532 -- @return String value containing the stripped lua byte code
533 function strip_bytecode(code)
534 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
535 local subint
536 if endian == 1 then
537 subint = function(code, i, l)
538 local val = 0
539 for n = l, 1, -1 do
540 val = val * 256 + code:byte(i + n - 1)
541 end
542 return val, i + l
543 end
544 else
545 subint = function(code, i, l)
546 local val = 0
547 for n = 1, l, 1 do
548 val = val * 256 + code:byte(i + n - 1)
549 end
550 return val, i + l
551 end
552 end
553
554 local function strip_function(code)
555 local count, offset = subint(code, 1, size)
556 local stripped = { string.rep("\0", size) }
557 local dirty = offset + count
558 offset = offset + count + int * 2 + 4
559 offset = offset + int + subint(code, offset, int) * ins
560 count, offset = subint(code, offset, int)
561 for n = 1, count do
562 local t
563 t, offset = subint(code, offset, 1)
564 if t == 1 then
565 offset = offset + 1
566 elseif t == 4 then
567 offset = offset + size + subint(code, offset, size)
568 elseif t == 3 then
569 offset = offset + num
570 elseif t == 254 or t == 9 then
571 offset = offset + lnum
572 end
573 end
574 count, offset = subint(code, offset, int)
575 stripped[#stripped+1] = code:sub(dirty, offset - 1)
576 for n = 1, count do
577 local proto, off = strip_function(code:sub(offset, -1))
578 stripped[#stripped+1] = proto
579 offset = offset + off - 1
580 end
581 offset = offset + subint(code, offset, int) * int + int
582 count, offset = subint(code, offset, int)
583 for n = 1, count do
584 offset = offset + subint(code, offset, size) + size + int * 2
585 end
586 count, offset = subint(code, offset, int)
587 for n = 1, count do
588 offset = offset + subint(code, offset, size) + size
589 end
590 stripped[#stripped+1] = string.rep("\0", int * 3)
591 return table.concat(stripped), offset
592 end
593
594 return code:sub(1,12) .. strip_function(code:sub(13,-1))
595 end
596
597
598 --
599 -- Sorting iterator functions
600 --
601
602 function _sortiter( t, f )
603 local keys = { }
604
605 for k, v in pairs(t) do
606 keys[#keys+1] = k
607 end
608
609 local _pos = 0
610
611 table.sort( keys, f )
612
613 return function()
614 _pos = _pos + 1
615 if _pos <= #keys then
616 return keys[_pos], t[keys[_pos]]
617 end
618 end
619 end
620
621 --- Return a key, value iterator which returns the values sorted according to
622 -- the provided callback function.
623 -- @param t The table to iterate
624 -- @param f A callback function to decide the order of elements
625 -- @return Function value containing the corresponding iterator
626 function spairs(t,f)
627 return _sortiter( t, f )
628 end
629
630 --- Return a key, value iterator for the given table.
631 -- The table pairs are sorted by key.
632 -- @param t The table to iterate
633 -- @return Function value containing the corresponding iterator
634 function kspairs(t)
635 return _sortiter( t )
636 end
637
638 --- Return a key, value iterator for the given table.
639 -- The table pairs are sorted by value.
640 -- @param t The table to iterate
641 -- @return Function value containing the corresponding iterator
642 function vspairs(t)
643 return _sortiter( t, function (a,b) return t[a] < t[b] end )
644 end
645
646
647 --
648 -- System utility functions
649 --
650
651 --- Test whether the current system is operating in big endian mode.
652 -- @return Boolean value indicating whether system is big endian
653 function bigendian()
654 return string.byte(string.dump(function() end), 7) == 0
655 end
656
657 --- Execute given commandline and gather stdout.
658 -- @param command String containing command to execute
659 -- @return String containing the command's stdout
660 function exec(command)
661 local pp = io.popen(command)
662 local data = pp:read("*a")
663 pp:close()
664
665 return data
666 end
667
668 --- Return a line-buffered iterator over the output of given command.
669 -- @param command String containing the command to execute
670 -- @return Iterator
671 function execi(command)
672 local pp = io.popen(command)
673
674 return pp and function()
675 local line = pp:read()
676
677 if not line then
678 pp:close()
679 end
680
681 return line
682 end
683 end
684
685 -- Deprecated
686 function execl(command)
687 local pp = io.popen(command)
688 local line = ""
689 local data = {}
690
691 while true do
692 line = pp:read()
693 if (line == nil) then break end
694 data[#data+1] = line
695 end
696 pp:close()
697
698 return data
699 end
700
701 --- Returns the absolute path to LuCI base directory.
702 -- @return String containing the directory path
703 function libpath()
704 return require "nixio.fs".dirname(ldebug.__file__)
705 end
706
707
708 --
709 -- Coroutine safe xpcall and pcall versions modified for Luci
710 -- original version:
711 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
712 --
713 -- Copyright © 2005 Kepler Project.
714 -- Permission is hereby granted, free of charge, to any person obtaining a
715 -- copy of this software and associated documentation files (the "Software"),
716 -- to deal in the Software without restriction, including without limitation
717 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
718 -- and/or sell copies of the Software, and to permit persons to whom the
719 -- Software is furnished to do so, subject to the following conditions:
720 --
721 -- The above copyright notice and this permission notice shall be
722 -- included in all copies or substantial portions of the Software.
723 --
724 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
725 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
726 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
727 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
728 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
729 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
730 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
731
732 local performResume, handleReturnValue
733 local oldpcall, oldxpcall = pcall, xpcall
734 coxpt = {}
735 setmetatable(coxpt, {__mode = "kv"})
736
737 -- Identity function for copcall
738 local function copcall_id(trace, ...)
739 return ...
740 end
741
742 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
743 -- @param f Lua function to be called protected
744 -- @param err Custom error handler
745 -- @param ... Parameters passed to the function
746 -- @return A boolean whether the function call succeeded and the return
747 -- values of either the function or the error handler
748 function coxpcall(f, err, ...)
749 local res, co = oldpcall(coroutine.create, f)
750 if not res then
751 local params = {...}
752 local newf = function() return f(unpack(params)) end
753 co = coroutine.create(newf)
754 end
755 local c = coroutine.running()
756 coxpt[co] = coxpt[c] or c or 0
757
758 return performResume(err, co, ...)
759 end
760
761 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
762 -- @param f Lua function to be called protected
763 -- @param ... Parameters passed to the function
764 -- @return A boolean whether the function call succeeded and the returns
765 -- values of the function or the error object
766 function copcall(f, ...)
767 return coxpcall(f, copcall_id, ...)
768 end
769
770 -- Handle return value of protected call
771 function handleReturnValue(err, co, status, ...)
772 if not status then
773 return false, err(debug.traceback(co, (...)), ...)
774 end
775 if coroutine.status(co) == 'suspended' then
776 return performResume(err, co, coroutine.yield(...))
777 else
778 return true, ...
779 end
780 end
781
782 -- Resume execution of protected function call
783 function performResume(err, co, ...)
784 if get_memory_limit and get_memory_limit() > 0 and
785 collectgarbage("count") > (get_memory_limit() * 0.8)
786 then
787 collectgarbage("collect")
788 end
789
790 return handleReturnValue(err, co, coroutine.resume(co, ...))
791 end