Class: NewRelic::TransactionSample::Segment

Inherits:
Object
  • Object
show all
Defined in:
lib/new_relic/transaction_sample.rb

Direct Known Subclasses

CompositeSegment, FakeSegment, SummarySegment

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timestamp, metric_name, segment_id) ⇒ Segment

Returns a new instance of Segment.



35
36
37
38
39
# File 'lib/new_relic/transaction_sample.rb', line 35

def initialize(timestamp, metric_name, segment_id)
  @entry_timestamp = timestamp
  @metric_name = metric_name || '<unknown>'
  @segment_id = segment_id || object_id
end

Instance Attribute Details

#entry_timestampObject (readonly)

Returns the value of attribute entry_timestamp.



27
28
29
# File 'lib/new_relic/transaction_sample.rb', line 27

def 
  @entry_timestamp
end

#exit_timestampObject (readonly)

The exit timestamp will be relative except for the outermost sample which will have a timestamp.



30
31
32
# File 'lib/new_relic/transaction_sample.rb', line 30

def exit_timestamp
  @exit_timestamp
end

#metric_nameObject (readonly)

Returns the value of attribute metric_name.



32
33
34
# File 'lib/new_relic/transaction_sample.rb', line 32

def metric_name
  @metric_name
end

#parent_segmentObject

Returns the value of attribute parent_segment.



31
32
33
# File 'lib/new_relic/transaction_sample.rb', line 31

def parent_segment
  @parent_segment
end

#segment_idObject (readonly)

Returns the value of attribute segment_id.



33
34
35
# File 'lib/new_relic/transaction_sample.rb', line 33

def segment_id
  @segment_id
end

Class Method Details

.from_json(json, id_generator) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/new_relic/transaction_sample.rb', line 69

def self.from_json(json, id_generator)
  json = ActiveSupport::JSON.decode(json) if json.is_a?(String)
  if json.is_a?(Array)
     = json[0].to_f / 1000
    exit_timestamp = json[1].to_f / 1000
    metric_name = json[2]
    params = json[3]
    called_segments = json[4]
  else
     = json["entry_timestamp"].to_f
    exit_timestamp = json["exit_timestamp"].to_f
    metric_name =  json["metric_name"]       
    params = json["params"]
    
    called_segments = json["called_segments"]
  end
  segment = Segment.new(, metric_name, id_generator.next_id)
  segment.end_trace exit_timestamp
  if params
    segment.send :params=, HashWithIndifferentAccess.new(params)
  end
  if called_segments
    called_segments.each do |child|
      segment.add_called_segment(self.from_json(child, id_generator))
    end
  end
  segment
end

Instance Method Details

#[](key) ⇒ Object



179
180
181
# File 'lib/new_relic/transaction_sample.rb', line 179

def [](key)
  params[key]
end

#[]=(key, value) ⇒ Object



173
174
175
176
177
# File 'lib/new_relic/transaction_sample.rb', line 173

def []=(key, value)
  # only create a parameters field if a parameter is set; this will save
  # bandwidth etc as most segments have no parameters
  params[key] = value
end

#add_called_segment(s) ⇒ Object



45
46
47
48
49
# File 'lib/new_relic/transaction_sample.rb', line 45

def add_called_segment(s)
  @called_segments ||= []
  @called_segments << s
  s.parent_segment = self
end

#called_segmentsObject



130
131
132
# File 'lib/new_relic/transaction_sample.rb', line 130

def called_segments
  @called_segments || EMPTY_ARRAY
end

#called_segments=(segments) ⇒ Object



263
264
265
# File 'lib/new_relic/transaction_sample.rb', line 263

def called_segments=(segments)
  @called_segments = segments
end

#count_segmentsObject



151
152
153
154
155
# File 'lib/new_relic/transaction_sample.rb', line 151

def count_segments
  count = 1
  @called_segments.each { | seg | count  += seg.count_segments } if @called_segments
  count
end

#durationObject

return the total duration of this segment



135
136
137
# File 'lib/new_relic/transaction_sample.rb', line 135

def duration
  (@exit_timestamp - @entry_timestamp).to_f
end

#each_segment(&block) ⇒ Object

call the provided block for this segment and each of the called segments



189
190
191
192
193
194
195
196
197
# File 'lib/new_relic/transaction_sample.rb', line 189

def each_segment(&block)
  block.call self
  
  if @called_segments
    @called_segments.each do |segment|
      segment.each_segment(&block)
    end
  end
end

#end_trace(timestamp) ⇒ Object



41
42
43
# File 'lib/new_relic/transaction_sample.rb', line 41

def end_trace(timestamp)
  @exit_timestamp = timestamp
end

#exclusive_durationObject

return the duration of this segment without including the time in the called segments



141
142
143
144
145
146
147
148
149
150
# File 'lib/new_relic/transaction_sample.rb', line 141

def exclusive_duration
  d = duration
  
  if @called_segments
    @called_segments.each do |segment|
      d -= segment.duration
    end
  end
  d
end

#explain_sqlObject

perform this in the runtime environment of a managed application, to explain the sql statement(s) executed within a segment of a transaction sample. returns an array of explanations (which is an array rows consisting of an array of strings for each column returned by the the explain query) Note this happens only for statements whose execution time exceeds a threshold (e.g. 500ms) and only within the slowest transaction in a report period, selected for shipment to RPM



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/new_relic/transaction_sample.rb', line 214

def explain_sql        
  sql = params[:sql]
  return nil unless sql && params[:connection_config]
  statements = sql.split(";\n")
  explanations = []
  statements.each do |statement|
    if statement.split($;, 2)[0].upcase == 'SELECT'
      explain_resultset = []
      begin
        connection = NewRelic::TransactionSample.get_connection(params[:connection_config])    
        if connection
          # The resultset type varies for different drivers.  Only thing you can count on is
          # that it implements each.  Also: can't use select_rows because the native postgres
          # driver doesn't know that method.
          explain_resultset = connection.execute("EXPLAIN #{statement}") if connection
          rows = []
          # Note: we can't use map.
          # Note: have to convert from native column element types to string so we can
          # serialize.  Esp. for postgresql.
          # Can't use map.  Suck it up.
          if explain_resultset.respond_to?(:each)
            explain_resultset.each { | row | rows << row.map(&:to_s) }
          else
            rows << [ explain_resultset ]
          end
          explanations << rows
          # sleep for a very short period of time in order to yield to the main thread
          # this is because a remote database call will likely hang the VM
          sleep 0.05
        end
      rescue => e
        handle_exception_in_explain(e)
      end
    end
  end

  explanations
end

#find_segment(id) ⇒ Object



199
200
201
202
203
204
205
206
# File 'lib/new_relic/transaction_sample.rb', line 199

def find_segment(id)
  return self if @segment_id == id
  called_segments.each do |segment|
    found = segment.find_segment(id)
    return found if found
  end
  nil
end

#handle_exception_in_explain(e) ⇒ Object



253
254
255
256
257
258
# File 'lib/new_relic/transaction_sample.rb', line 253

def handle_exception_in_explain(e)
  x = 1 # this is here so that code coverage knows we've entered this block
  # swallow failed attempts to run an explain.  One example of a failure is the
  # connection for the sql statement is to a different db than the default connection
  # specified in AR::Base
end

#obfuscated_sqlObject

swallow failed attempts to run an explain. One example of a failure is the connection for the sql statement is to a different db than the default connection specified in AR::Base



259
260
261
# File 'lib/new_relic/transaction_sample.rb', line 259

def obfuscated_sql
  TransactionSample.obfuscate_sql(params[:sql])
end

#paramsObject



183
184
185
# File 'lib/new_relic/transaction_sample.rb', line 183

def params
  @params ||= {}
end

#path_stringObject



98
99
100
# File 'lib/new_relic/transaction_sample.rb', line 98

def path_string
  "#{metric_name}[#{called_segments.collect {|segment| segment.path_string }.join('')}]"
end

#to_debug_str(depth) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/new_relic/transaction_sample.rb', line 109

def to_debug_str(depth)
  tab = "  " * depth 
  s = tab.clone
  s << ">> #{'%3i ms' % (@entry_timestamp*1000)} [#{self.class.name.split("::").last}] #{metric_name} \n"
  unless params.empty?
    params.each do |k,v|
      s << "#{tab}    -#{'%-16s' % k}: #{v.to_s[0..80]}\n"
    end
  end
  called_segments.each do |cs|
    s << cs.to_debug_str(depth + 1)
  end
  s << tab + "<< "
  s << case @exit_timestamp
    when nil then ' n/a'
    when Numeric then '%3i ms' % (@exit_timestamp*1000)
    else @exit_timestamp.to_s
  end
  s << " #{metric_name}\n"
end

#to_jsonObject



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/new_relic/transaction_sample.rb', line 55

def to_json
  map = {:entry_timestamp => @entry_timestamp,
    :exit_timestamp => @exit_timestamp,
    :metric_name => @metric_name,
    :segment_id => @segment_id}
  if @called_segments && !@called_segments.empty?
    map[:called_segments] = @called_segments
  end
  if @params && !@params.empty?
    map[:params] = @params
  end
  map.to_json
end

#to_sObject



51
52
53
# File 'lib/new_relic/transaction_sample.rb', line 51

def to_s
  to_debug_str(0)
end

#to_s_compactObject



101
102
103
104
105
106
107
108
# File 'lib/new_relic/transaction_sample.rb', line 101

def to_s_compact
  str = ""
  str << metric_name
  if called_segments.any?
    str << "{#{called_segments.map { | cs | cs.to_s_compact }.join(",")}}"
  end
  str
end

#truncate(max) ⇒ Object

Walk through the tree and truncate the segments



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/new_relic/transaction_sample.rb', line 157

def truncate(max)
  return max unless @called_segments
  i = 0
  @called_segments.each do | segment |
    max = segment.truncate(max)
    max -= 1
    if max <= 0
      @called_segments = @called_segments[0..i]
      break
    else
      i += 1
    end
  end
  max
end