You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2020/02/21 03:01:54 UTC

[skywalking-nginx-lua] branch master updated: Support extract logic and add segment ref concept.

This is an automated email from the ASF dual-hosted git repository.

wusheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/skywalking-nginx-lua.git


The following commit(s) were added to refs/heads/master by this push:
     new 318a910  Support extract logic and add segment ref concept.
318a910 is described below

commit 318a91039ab830274117deee1c206dd6a552cc95
Author: Wu Sheng <wu...@foxmail.com>
AuthorDate: Fri Feb 21 11:01:43 2020 +0800

    Support extract logic and add segment ref concept.
---
 LICENSE                                |  19 +++-
 README.md                              |   8 +-
 lib/skywalking/dependencies/base64.lua | 193 +++++++++++++++++++++++++++++++++
 lib/skywalking/segment_ref.lua         |  79 ++++++++++++++
 lib/skywalking/segment_ref_test.lua    |  45 ++++++++
 lib/skywalking/span.lua                |  53 ++++++++-
 lib/skywalking/span_test.lua           |  51 ++++++++-
 lib/skywalking/tracing_context.lua     |   9 +-
 lib/skywalking/util.lua                |  28 +++++
 licenses/LICENSE-base64.txt            |  39 +++++++
 10 files changed, 511 insertions(+), 13 deletions(-)

diff --git a/LICENSE b/LICENSE
index 9c8f3ea..21e1671 100644
--- a/LICENSE
+++ b/LICENSE
@@ -198,4 +198,21 @@
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
-   limitations under the License.
\ No newline at end of file
+   limitations under the License.
+
+=======================================================================
+Apache SkyWalking Nginx LUA Subcomponents:
+
+The Apache SkyWalking project contains subcomponents with separate copyright
+notices and license terms. Your use of the source code for the these
+subcomponents is subject to the terms and conditions of the following
+licenses.
+
+========================================================================
+MIT
+========================================================================
+
+The following components are provided under a MIT license. See project link for details.
+The text of each license is also included at licenses/LICENSE-[project].txt.
+
+    base64 dependencies/base64.lua https://github.com/iskolbin/lbase64 MIT
\ No newline at end of file
diff --git a/README.md b/README.md
index c9eedf1..c1c163c 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,6 @@ All HTTP 1.1 requests go through Nginx could be collected by this agent.
 # Setup Doc
 TODO
 
-# APIs
-
 # Set up dev env
 All codes in the `lib/skywalking` require the `*_test.lua` to do the UnitTest. To run that, you need to install
 - Lua 5.3
@@ -23,7 +21,11 @@ All codes in the `lib/skywalking` require the `*_test.lua` to do the UnitTest. T
 
 The following libs are required in runtime or test cases, please use `LuaRocks` to install them.
 - luaunit
-- luasocket
+
+# APIs
+This LUA tracing lib is originally designed for Nginx+LUA/OpenResty ecosystems. But we write it to support more complex cases.
+If you just use this in the Ngnix, [Setup Doc](#setup-doc) should be good enough.
+The following APIs are for developers or using this lib out of the Nginx case.
 
 
 # Download
diff --git a/lib/skywalking/dependencies/base64.lua b/lib/skywalking/dependencies/base64.lua
new file mode 100644
index 0000000..4aaa5bf
--- /dev/null
+++ b/lib/skywalking/dependencies/base64.lua
@@ -0,0 +1,193 @@
+--[[
+ base64 -- v1.5.1 public domain Lua base64 encoder/decoder
+ no warranty implied; use at your own risk
+ Needs bit32.extract function. If not present it's implemented using BitOp
+ or Lua 5.3 native bit operators. For Lua 5.1 fallbacks to pure Lua
+ implementation inspired by Rici Lake's post:
+   http://ricilake.blogspot.co.uk/2007/10/iterating-bits-in-lua.html
+ author: Ilya Kolbin (iskolbin@gmail.com)
+ url: github.com/iskolbin/lbase64
+ COMPATIBILITY
+ Lua 5.1, 5.2, 5.3, LuaJIT
+ LICENSE
+ See end of file for license information.
+--]]
+
+
+local base64 = {}
+
+local extract = _G.bit32 and _G.bit32.extract
+if not extract then
+	if _G.bit then
+		local shl, shr, band = _G.bit.lshift, _G.bit.rshift, _G.bit.band
+		extract = function( v, from, width )
+			return band( shr( v, from ), shl( 1, width ) - 1 )
+		end
+	elseif _G._VERSION >= "Lua 5.3" then
+		extract = load[[return function( v, from, width )
+			return ( v >> from ) & ((1 << width) - 1)
+		end]]()
+	else
+		extract = function( v, from, width )
+			local w = 0
+			local flag = 2^from
+			for i = 0, width-1 do
+				local flag2 = flag + flag
+				if v % flag2 >= flag then
+					w = w + 2^i
+				end
+				flag = flag2
+			end
+			return w
+		end
+	end
+end
+
+
+function base64.makeencoder( s62, s63, spad )
+	local encoder = {}
+	for b64code, char in pairs{[0]='A','B','C','D','E','F','G','H','I','J',
+		'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y',
+		'Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
+		'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2',
+		'3','4','5','6','7','8','9',s62 or '+',s63 or'/',spad or'='} do
+		encoder[b64code] = char:byte()
+	end
+	return encoder
+end
+
+function base64.makedecoder( s62, s63, spad )
+	local decoder = {}
+	for b64code, charcode in pairs( base64.makeencoder( s62, s63, spad )) do
+		decoder[charcode] = b64code
+	end
+	return decoder
+end
+
+local DEFAULT_ENCODER = base64.makeencoder()
+local DEFAULT_DECODER = base64.makedecoder()
+
+local char, concat = string.char, table.concat
+
+function base64.encode( str, encoder, usecaching )
+	encoder = encoder or DEFAULT_ENCODER
+	local t, k, n = {}, 1, #str
+	local lastn = n % 3
+	local cache = {}
+	for i = 1, n-lastn, 3 do
+		local a, b, c = str:byte( i, i+2 )
+		local v = a*0x10000 + b*0x100 + c
+		local s
+		if usecaching then
+			s = cache[v]
+			if not s then
+				s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
+				cache[v] = s
+			end
+		else
+			s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
+		end
+		t[k] = s
+		k = k + 1
+	end
+	if lastn == 2 then
+		local a, b = str:byte( n-1, n )
+		local v = a*0x10000 + b*0x100
+		t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[64])
+	elseif lastn == 1 then
+		local v = str:byte( n )*0x10000
+		t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[64], encoder[64])
+	end
+	return concat( t )
+end
+
+function base64.decode( b64, decoder, usecaching )
+	decoder = decoder or DEFAULT_DECODER
+	local pattern = '[^%w%+%/%=]'
+	if decoder then
+		local s62, s63
+		for charcode, b64code in pairs( decoder ) do
+			if b64code == 62 then s62 = charcode
+			elseif b64code == 63 then s63 = charcode
+			end
+		end
+		pattern = ('[^%%w%%%s%%%s%%=]'):format( char(s62), char(s63) )
+	end
+	b64 = b64:gsub( pattern, '' )
+	local cache = usecaching and {}
+	local t, k = {}, 1
+	local n = #b64
+	local padding = b64:sub(-2) == '==' and 2 or b64:sub(-1) == '=' and 1 or 0
+	for i = 1, padding > 0 and n-4 or n, 4 do
+		local a, b, c, d = b64:byte( i, i+3 )
+		local s
+		if usecaching then
+			local v0 = a*0x1000000 + b*0x10000 + c*0x100 + d
+			s = cache[v0]
+			if not s then
+				local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
+				s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
+				cache[v0] = s
+			end
+		else
+			local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
+			s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
+		end
+		t[k] = s
+		k = k + 1
+	end
+	if padding == 1 then
+		local a, b, c = b64:byte( n-3, n-1 )
+		local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40
+		t[k] = char( extract(v,16,8), extract(v,8,8))
+	elseif padding == 2 then
+		local a, b = b64:byte( n-3, n-2 )
+		local v = decoder[a]*0x40000 + decoder[b]*0x1000
+		t[k] = char( extract(v,16,8))
+	end
+	return concat( t )
+end
+
+return base64
+
+--[[
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2018 Ilya Kolbin
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+--]]
\ No newline at end of file
diff --git a/lib/skywalking/segment_ref.lua b/lib/skywalking/segment_ref.lua
new file mode 100644
index 0000000..1c83e83
--- /dev/null
+++ b/lib/skywalking/segment_ref.lua
@@ -0,0 +1,79 @@
+-- 
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+-- 
+--    http://www.apache.org/licenses/LICENSE-2.0
+-- 
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+-- 
+
+local Util = require('util')
+local Base64 = require('dependencies/base64')
+
+SegmentRef = {
+    -- There is no multiple-threads scenario in the LUA, no only hard coded as CROSS_PROCESS
+    type = 'CROSS_PROCESS',
+    trace_id,
+    segment_id,
+    span_id,
+    network_address,
+    network_address_id,
+    entry_service_instance_id,
+    parent_service_instance_id,
+    entry_endpoint_name,
+    entry_endpoint_id,
+    parent_endpoint_name,
+    parent_endpoint_id,
+}
+
+function SegmentRef:new()
+    local o = {}
+    setmetatable(o, self)
+    self.__index = self
+
+    return o
+end
+
+-- Deserialize value from the propagated context and initialize the SegmentRef
+function SegmentRef:fromSW6Value(value)
+    local parts = Util: split(value, '-')
+    if #parts ~= 9 then
+        return nil
+    end
+
+    self.trace_id = Util:formatID(Base64.decode(parts[2]))
+    self.segment_id = Util:formatID(Base64.decode(parts[3]))
+    self.span_id = tonumber(parts[4])
+    self.parent_service_instance_id = tonumber(parts[5])
+    self.entry_service_instance_id = tonumber(parts[6])
+    local peerStr = Base64.decode(parts[7])
+    if string.sub(peerStr, 1, 1) == '#' then
+        self.network_address = string.sub(peerStr, 2)
+    else
+        self.network_address_id = tonumber(peerStr)
+    end
+    local entryEndpointStr = Base64.decode(parts[8])
+    if string.sub(entryEndpointStr, 1, 1) == '#' then
+        self.entry_endpoint_name = string.sub(entryEndpointStr, 2)
+    else
+        self.entry_endpoint_id = tonumber(entryEndpointStr)
+    end
+    local parentEndpointStr = Base64.decode(parts[9])
+    if string.sub(parentEndpointStr, 1, 1) == '#' then
+        self.parent_endpoint_name = string.sub(parentEndpointStr, 2)
+    else
+        self.parent_endpoint_id = tonumber(parentEndpointStr)
+    end
+
+    return self
+end
+
+return SegmentRef
diff --git a/lib/skywalking/segment_ref_test.lua b/lib/skywalking/segment_ref_test.lua
new file mode 100644
index 0000000..5a62fa5
--- /dev/null
+++ b/lib/skywalking/segment_ref_test.lua
@@ -0,0 +1,45 @@
+-- 
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+-- 
+--    http://www.apache.org/licenses/LICENSE-2.0
+-- 
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+-- 
+
+
+local lu = require('luaunit')
+local SegmentRef = require('segment_ref')
+
+TestSegmentRef = {}
+    -- This test is originally from ContextCarrierV2HeaderTest in the Java agent.
+    function TestSegmentRef:testFromSW6Value()
+        local ref = SegmentRef:new():fromSW6Value('1-My40LjU=-MS4yLjM=-4-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWw=-MTIz')
+        lu.assertNotNil(ref)
+        lu.assertEquals(ref.trace_id, {3, 4, 5})
+        lu.assertEquals(ref.segment_id, {1, 2, 3})
+        lu.assertEquals(ref.span_id, 4)
+        lu.assertEquals(ref.parent_service_instance_id, 1)
+        lu.assertEquals(ref.entry_service_instance_id, 1)
+        lu.assertEquals(ref.network_address, '127.0.0.1:8080')
+        lu.assertEquals(ref.network_address_id, nil)
+        lu.assertEquals(ref.entry_endpoint_name, '/portal')
+        lu.assertEquals(ref.entry_endpoint_id, nil)
+        lu.assertEquals(ref.parent_endpoint_name, nil)
+        lu.assertEquals(ref.parent_endpoint_id, 123)
+
+        ref = SegmentRef:new():fromSW6Value('1-My40LjU=-MS')
+        lu.assertNil(ref)
+    end
+-- end TestSegmentRef
+
+
+os.exit( lu.LuaUnit.run() )
\ No newline at end of file
diff --git a/lib/skywalking/span.lua b/lib/skywalking/span.lua
index 207be6e..b2d00b3 100644
--- a/lib/skywalking/span.lua
+++ b/lib/skywalking/span.lua
@@ -18,6 +18,9 @@
 local spanLayer = require("span_layer")
 local Context = require("tracing_context")
 local Util = require('util')
+local SegmentRef = require("segment_ref")
+
+CONTEXT_CARRIER_KEY = 'sw6'
 
 Span = {
     span_id,
@@ -26,19 +29,58 @@ Span = {
     tags,
     logs,
     layer = spanLayer.NONE,
-    isEntry = false,
-    isExit = false,
+    is_entry = false,
+    is_exit = false,
     peer,
     start_time,
     end_time,
     error_occurred = false,
+    refs,
 }
 
--- Create an entry span, represent the HTTP incoming request.
-function Span:createEntrySpan(operationName, context, parent)
+-- Create an entry span. Represent the HTTP incoming request.
+-- @param contextCarrier, HTTP request header, which could carry the `sw6` context
+function Span:createEntrySpan(operationName, context, parent, contextCarrier)
+    local span = self:new(operationName, context, parent)
+    span.is_entry = true
+
+    if contextCarrier ~= nil then
+        local propagatedContext = contextCarrier[CONTEXT_CARRIER_KEY]
+        if propagatedContext ~= nil then
+            local ref = SegmentRef:new():fromSW6Value(propagatedContext)
+            if ref ~= nil then
+                -- If current trace id is generated by the context, in LUA case, mostly are yes
+                -- use the ref trace id to override it, in order to keep trace id consistently same.
+                if context.self_generated_trace_id == true then
+                    context.self_generated_trace_id = false
+                    context.trace_id = ref.trace_id
+                end
+                table.insert(span.refs, ref)
+            end
+        end
+    end
+
+    return span
+end
+
+-- Create an exit span. Represent the HTTP outgoing request.
+function Span:createExitSpan(operationName, context, parent, peer, contextCarrier)
     local span = self:new(operationName, context, parent)
-    span.isEntry = true
+    span.is_exit = true
+    span.peer = peer
+
+    if contextCarrier ~= nil then
+        -- if there is contextCarrier container, the Span will inject the value based on the current tracing context
+
+    end
+
+    return span
+end
 
+-- Create an local span. Local span is usually not used. 
+-- Typically, only one entry span and one exit span in the Nginx tracing segment.
+function Span:createLocalSpan(operationName, context, parent)
+    local span = self:new(operationName, context, parent) 
     return span
 end
 
@@ -61,6 +103,7 @@ function Span:new(operationName, context, parent)
 
     context.internal:addActive(o)
     o.start_time = Util.timestamp()
+    o.refs = {}
 
     return o
 end
diff --git a/lib/skywalking/span_test.lua b/lib/skywalking/span_test.lua
index 0523b63..7abad81 100644
--- a/lib/skywalking/span_test.lua
+++ b/lib/skywalking/span_test.lua
@@ -25,15 +25,60 @@ TestSpan = {}
         local context = TC:new()
         lu.assertNotNil(context)
 
-        local span1 = Span:createEntrySpan("operation_name", context, nil)
+        local span1 = Span:createEntrySpan("operation_name", context, nil, nil)
         lu.assertNotNil(span1)
-        lu.assertEquals(span1.isEntry, true)
-        lu.assertEquals(span1.isExit, false)
+        lu.assertEquals(span1.is_entry, true)
+        lu.assertEquals(span1.is_exit, false)
         lu.assertEquals(span1.layer, SpanLayer.NONE)
 
         lu.assertEquals(#(context.internal.active_spans), 1)
     end
 
+    function TestSpan:testNewEntryWithContextCarrier()
+        local context = TC:new()
+        lu.assertNotNil(context)
+
+        -- Typical header from the SkyWalking Java Agent test case
+        local header = {sw6='1-My40LjU=-MS4yLjM=-4-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWw=-MTIz'}
+
+        local span1 = Span:createEntrySpan("operation_name", context, nil, header)
+        lu.assertNotNil(span1)
+        lu.assertEquals(span1.is_entry, true)
+        lu.assertEquals(span1.is_exit, false)
+        lu.assertEquals(span1.layer, SpanLayer.NONE)
+        local ref = span1.refs[1]
+        lu.assertNotNil(ref)
+        lu.assertEquals(ref.trace_id, {3, 4, 5})
+        -- Context trace id will be overrided by the ref trace id
+        lu.assertEquals(context.trace_id, {3, 4, 5})
+        lu.assertEquals(ref.segment_id, {1, 2, 3})
+        lu.assertEquals(ref.span_id, 4)
+        lu.assertEquals(ref.parent_service_instance_id, 1)
+        lu.assertEquals(ref.entry_service_instance_id, 1)
+        lu.assertEquals(ref.network_address, '127.0.0.1:8080')
+        lu.assertEquals(ref.network_address_id, nil)
+        lu.assertEquals(ref.entry_endpoint_name, '/portal')
+        lu.assertEquals(ref.entry_endpoint_id, nil)
+        lu.assertEquals(ref.parent_endpoint_name, nil)
+        lu.assertEquals(ref.parent_endpoint_id, 123)
+
+        lu.assertEquals(#(context.internal.active_spans), 1)
+    end
+
+    function TestSpan:testNewExit()
+        local context = TC:new()
+        lu.assertNotNil(context)
+
+        local span1 = Span:createExitSpan("operation_name", context, nil, '127.0.0.1:80')
+        lu.assertNotNil(span1)
+        lu.assertEquals(span1.is_entry, false)
+        lu.assertEquals(span1.is_exit, true)
+        lu.assertEquals(span1.layer, SpanLayer.NONE)
+        lu.assertEquals(span1.peer, '127.0.0.1:80')
+
+        lu.assertEquals(#(context.internal.active_spans), 1)
+    end
+
     function TestSpan:testNew()
         local context = TC:new()
         lu.assertNotNil(context)
diff --git a/lib/skywalking/tracing_context.lua b/lib/skywalking/tracing_context.lua
index 1e122e2..4ce4204 100644
--- a/lib/skywalking/tracing_context.lua
+++ b/lib/skywalking/tracing_context.lua
@@ -19,6 +19,7 @@ local Util = require('util')
 
 TracingContext = {
     trace_id,
+    self_generated_trace_id,
     segment_id,
     is_noop = false,
 
@@ -30,7 +31,8 @@ function TracingContext:new()
     setmetatable(o, self)
     self.__index = self
 
-    o.trace_id = Util:newID();
+    o.trace_id = Util:newID()
+    o.self_generated_trace_id = true
     o.segment_id = o.trace_id
     o.internal = Internal:new()
     o.internal.owner = o
@@ -47,6 +49,8 @@ Internal = {
     span_id_seq,
     -- Owner means the Context instance holding this Internal object.
     owner,
+    -- The first created span.
+    first_span,
     -- Lists
     -- Created span and still active
     active_spans,
@@ -68,6 +72,9 @@ function Internal:new()
 end
 
 function Internal:addActive(span)
+    if first_span == nil then
+        first_span = span
+    end
     table.insert(self.active_spans, span)
     return self.owner
 end
diff --git a/lib/skywalking/util.lua b/lib/skywalking/util.lua
index ecabe7d..b5d4c96 100644
--- a/lib/skywalking/util.lua
+++ b/lib/skywalking/util.lua
@@ -25,6 +25,21 @@ function Util:newID()
     return {Util.timestamp(), math.random( 0, MAX_ID_PART2), math.random( 0, MAX_ID_PART3) + SEQ}
 end
 
+-- Format a trace/segment id into an array.
+-- An official ID should have three parts separated by '.' and each part of it is a number
+function Util:formatID(str) 
+    local parts = Util:split(str, '.')
+    if #parts ~= 3 then
+        return nil
+    end
+
+    parts[1] = tonumber(parts[1])
+    parts[2] = tonumber(parts[2])
+    parts[3] = tonumber(parts[3])
+
+    return parts
+end
+
 -- A simulation implementation of Java's System.currentTimeMillis() by following the SkyWalking protocol.
 -- Return the difference as string, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
 -- But in using os.clock(), I am not sure whether it is accurate enough.
@@ -39,5 +54,18 @@ function Util:timestamp()
     return os.time() * 1000 + b
 end
 
+-- Split the given string by the delimiter. The delimiter should be a literal string, such as '.', '-'
+function Util:split(str, delimiter)
+    local t = {}
+
+    for substr in string.gmatch(str, "[^".. delimiter.. "]*") do
+        if substr ~= nil and string.len(substr) > 0 then
+            table.insert(t,substr)
+        end
+    end
+
+    return t
+end
+
 
 return Util
\ No newline at end of file
diff --git a/licenses/LICENSE-base64.txt b/licenses/LICENSE-base64.txt
new file mode 100644
index 0000000..394693c
--- /dev/null
+++ b/licenses/LICENSE-base64.txt
@@ -0,0 +1,39 @@
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2018 Ilya Kolbin
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
\ No newline at end of file