Module: CPEE::Logging

Defined in:
lib/cpee-logging-xes-yaml/tools.rb,
lib/cpee-logging-xes-yaml/logging.rb

Defined Under Namespace

Classes: Handler, Overview, Subscription, Subscriptions, Topics

Constant Summary collapse

SERVER =
File.expand_path(File.join(__dir__,'logging.xml'))

Class Method Summary collapse

Class Method Details

.doc(opts, topic, event_name, payload) ⇒ Object



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 233

def self::doc(opts,topic,event_name,payload)
  notification = JSON.parse(payload)
  instance = notification['instance-uuid']
  return unless instance

  log_dir = opts[:log_dir]

  instancenr = notification['instance']
  content = notification['content']
  activity = content['activity']
  activity = nil if activity == '' || activity&.strip == ''
  eid = content['eid']
  eid = nil if eid == '' || eid&.strip == ''
  parameters = content['parameters']
  receiving = content['received']

  if content['dslx']
    CPEE::Logging::extract_probes(File.join(log_dir,instance),content['dslx'])
    CPEE::Logging::extract_annotations(File.join(log_dir,instance),content['dslx']).each do |k,v|
      so = JSON.parse(notification.to_json)
      so['content'].delete('dslx')
      so['content'].delete('dsl')
      so['content'].delete('description')
      so['content']['annotation'] = v
      so['content']['activity'] = k
      so['topic'] = 'annotation'
      so['name'] = 'change'
      EM.defer do
        self::notify(opts,'annotation','change',so.to_json)
      end
    end
  end

  if topic == 'dataelements' && event_name == 'change'
    if content['changed']&.any?
      CPEE::Logging::persist_values(File.join(log_dir,instance + '.data.json'),content['values'])
    end
  end

  event = {}
  event['concept:instance'] = instancenr
  event['concept:name'] = content['label'] if content['label']
  if content['endpoint']
    event['concept:endpoint'] = content['endpoint']
  end
  event['id:id'] = (activity.nil? && eid.nil?) ? 'ex-ante' : (activity || eid)
  event['cpee:activity'] = activity unless activity.nil?
  event['cpee:activity_uuid'] = content['activity-uuid'] if content['activity-uuid']
  event['cpee:instance'] = instance
  case event_name
    when 'calling'
      event['lifecycle:transition'] = 'start'
    when 'done'
      event['lifecycle:transition'] = 'complete'
    else
      event['lifecycle:transition'] = 'unknown'
  end
  event['cpee:lifecycle:transition'] = "#{topic}/#{event_name}"
  event['cpee:state'] = content['state'] if content['state']
  event['cpee:description'] = content['dslx'] if content['dslx']
  event['cpee:change_uuid'] = content['change_uuid'] if content['change_uuid']
  event['cpee:exposition'] = content['exposition'] if content['exposition']
  if topic == 'gateway' && event_name == 'decide'
    event['data'] = { 'condition' => content['code'], 'result' => content['condition'] }
  end
  unless parameters['arguments']&.nil?
    event['data'] = parameters['arguments']
  end if parameters
  if content['changed']&.any?
    event['data'] = content['values'].map do |k,v|
      { 'name' => k, 'value' => v }
    end

    fname = File.join(log_dir,instance + '_' + event['id:id'] + '.probe')
    dname = File.join(log_dir,instance + '.data.json')

    # Handle intrinsic data probes
    if File.exist?(fname)
      rs = WEEL::ReadStructure.new(File.exist?(dname) ? CPEE::Logging::load_values(dname) : {},{},{},{})
      XML::Smart::open_unprotected(fname) do |doc|
        doc.register_namespace 'd', 'http://cpee.org/ns/description/1.0'
        doc.find('//d:probe[d:extractor_type="intrinsic"]').each do |p|
          pid    = p.find('string(d:id)')
          source = p.find('string(d:source)')
          val = CPEE::Logging::extract_val(rs,p.find('string(d:extractor_code)'),pid,nil) rescue nil
          # Do not add datastream entries if the dataprobes return nil
          if val != nil
            event['stream:datastream'] ||= []
            CPEE::Logging::merge_val(event['stream:datastream'],val,pid,source)
          end
        end
      end
      if event['stream:datastream'] && event['stream:datastream'].any?
        EM.defer do
          self::notify(
            opts,
            'stream',
            'extraction',
            notification.merge(
              'topic'=>'stream',
              'name'=>'extraction',
              'datastream'=>event['stream:datastream']
            ).to_json
          )
        end
      end
    end
  end
  # Handle extrinsic data probes
  if topic == 'activity' && event_name == 'receiving' && receiving && !receiving.empty?
    fname = File.join(log_dir,instance + '_' + event['id:id'] + '.probe')
    dname = File.join(log_dir,instance + '.data.json')

    if File.exist?(fname)
      te = event.dup

      rs = WEEL::ReadStructure.new(File.exist?(dname) ? CPEE::Logging::load_values(dname) : {},{},{},{})
      XML::Smart::open_unprotected(fname) do |doc|
        doc.register_namespace 'd', 'http://cpee.org/ns/description/1.0'
        if doc.find('//d:probe/d:extractor_type[.="extrinsic"]').any?
          rc = CPEE::Logging::extract_result(receiving)
          doc.find('//d:probe[d:extractor_type="extrinsic"]').each do |p|
            pid = p.find('string(d:id)')
            te['stream:datastream'] ||= []
            val = CPEE::Logging::extract_val(rs,p.find('string(d:extractor_code)'),pid,rc) rescue nil
            if not val.nil?
              # Do not add datastream entries if the dataprobes return nil
              CPEE::Logging::merge_val(te['stream:datastream'],val,pid,p.find('string(d:source)'))
            end
          end
        end
      end
      if te['stream:datastream'] && te['stream:datastream'].any?
        te['cpee:lifecycle:transition'] = 'stream/data'
        File.open(File.join(log_dir,instance+'.xes.yaml'),'a') do |f|
          f << {'event' => te}.to_yaml
        end
        EM.defer do
          self::notify(
            opts,
            'stream',
            'extraction',
            notification.merge(
              'topic'=>'stream',
              'name'=>'extraction',
              'datastream'=>te['stream:datastream']
            ).to_json
          )
        end
      end
    end
  end
  if receiving && !receiving.empty?
    event['data'] = receiving
  end
  if content['data'] && !content['data'].empty?
    event['data'] = content['data']
  end
  event['time:timestamp']= notification['timestamp'] || Time.now.xmlschema(4)
  File.open(File.join(log_dir,instance+'.xes.yaml'),'a') do |f|
    f << {'event' => event}.to_yaml
  end
end

.extract_annotations(where, xml) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 129

def self::extract_annotations(where,xml)
  ret = {}
  XML::Smart::string(xml) do |doc|
    doc.register_namespace 'd', 'http://cpee.org/ns/description/1.0'
    doc.find('/d:description | //d:call | //d:manipulate').each do |c|
      tid = c.attributes['id'] || 'complex'
      fname = where + '_' + tid + '.anno'
      nset = if tid == 'complex'
        c.find('d:*[starts-with(name(),"_")]')
      else
        c.find('d:annotations')
      end
      nset.each do |p|
        anno = p.dump
        ret[tid] ||= []
        ret[tid] << anno
      end
      if ret[tid]
        if ret[tid].length > 1
          ret[tid] = "<annotations xmlns=\"http://cpee.org/ns/description/1.0\">\n" +
            ret[tid].join("\n") + "\n" +
            '</annotations>'
        else
          ret[tid] = ret[tid][0]
        end
        hash = Digest::SHA1.hexdigest(ret[tid])
        if !File.exist?(fname) || File.read(fname) !=  hash
          File.write(fname,hash)
        end
      end
    end
  end
  ret
end

.extract_probes(where, xml) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 117

def self::extract_probes(where,xml)
  XML::Smart::string(xml) do |doc|
    doc.register_namespace 'd', 'http://cpee.org/ns/description/1.0'
    doc.find('//d:call | //d:manipulate').each do |c|
      File.unlink(where + '_' + c.attributes['id'] + '.probe') rescue nil
      c.find('d:annotations/d:_context_data_analysis/d:probes[d:probe]').each do |p|
        File.write(where + '_' + c.attributes['id'] + '.probe', p.dump)
      end
    end
  end
end

.extract_result(result) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 164

def self::extract_result(result)
  ret = result.map do |res|
    if res['mimetype'].nil?
      res['value']
    elsif res['mimetype'] == 'application/json'
      JSON::parse(res['data'])
    elsif res['mimetype'] == 'application/xml' || res['mimetype'] == 'text/xml'
      XML::Smart::string(res['data']) rescue nil
    elsif res['mimetype'] == 'text/yaml'
      YAML::load(res['data']) rescue nil
    elsif res['mimetype'] == 'text/plain'
      t = res['data']
      if t.start_with?('<?xml version=')
        t = XML::Smart::string(t)
      else
        t = t.to_f if t == t.to_f.to_s
        t = t.to_i if t == t.to_i.to_s
      end
      t
    elsif res['mimetype'] == 'text/html'
      t = res['data']
      t = t.to_f if t == t.to_f.to_s
      t = t.to_i if t == t.to_i.to_s
      t
    else
      res['data']
    end
  end
  ret.length == 1 ? ret[0] : ret
end

.extract_val(rs, code, pid, result) ⇒ Object



195
196
197
198
199
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 195

def self::extract_val(rs,code,pid,result)
  rs.instance_eval(code,'probe',1)
rescue => e
  e.backtrace[0].gsub(/(\w+):(\d+):in.*/,'Probe ' + pid + ' Line \2: ') + e.message
end

.forward(opts, topic, event_name, payload) ⇒ Object



225
226
227
228
229
230
231
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 225

def self::forward(opts,topic,event_name,payload)
  if topic == 'state' && event_name == 'change'
    self::notify(opts,topic,event_name,payload)
  elsif topic == 'gateway' && event_name == 'join'
    self::notify(opts,topic,event_name,payload)
  end
end

.implementation(opts) ⇒ Object

}}}



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/cpee-logging-xes-yaml/logging.rb', line 116

def self::implementation(opts)
  opts[:log_dir]           ||= File.expand_path(File.join(__dir__,'logs'))
  opts[:notifications_dir] ||= File.expand_path(File.join(__dir__,'notifications'))
  opts[:template]          ||= File.expand_path(File.join(__dir__,'template.xes_yaml'))
  opts[:topics]            ||= File.expand_path(File.join(__dir__,'topics.xml'))
  opts[:subscriptions]     =  {}

  Dir.glob(File.join(opts[:notifications_dir],'*','subscription.xml')).each do |f|
    XML::Smart::open_unprotected(f) do |doc|
      doc.register_namespace :p, 'http://riddl.org/ns/common-patterns/notifications-producer/2.0'
      doc.find('/p:subscription/p:topic').each do |t|
        t.find('p:event').each do |e|
          opts[:subscriptions][t.attributes['id']+'/'+e.text] ||= []
          opts[:subscriptions][t.attributes['id']+'/'+e.text] << doc.root.attributes['url']
        end
      end
    end
  end

  Proc.new do
    interface 'events' do
      run Handler, opts if post 'event'
    end
    interface 'notifications' do
      on resource "notifications" do
        run Overview if get
        on resource "topics" do
          run Topics, opts if get
        end
        on resource "subscriptions" do
          run Subscriptions, opts if get
          run CreateSubscription, opts if post 'create_subscription'
          on resource do
            run Subscription, opts if get
            run UpdateSubscription, opts if put 'change_subscription'
            run DeleteSubscription, opts if delete
          end
        end
      end
    end
  end
end

.load_values(where) ⇒ Object



215
216
217
218
219
220
221
222
223
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 215

def self::load_values(where)
  ret = nil
  File.open(where,'r') do |f|
    f.flock(File::LOCK_SH)
    ret = JSON::load(f)
    f.flock(File::LOCK_UN)
  end
  ret
end

.merge_val(target, val, tid, tso) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 98

def self::merge_val(target,val,tid,tso)
  if val.is_a? Stream
    val.source = tso if val.source.nil?
    target.push *val.to_list
  else
    tp = nil
    if val.is_a? StreamPoint
      tp = val
      tp.id = tid if tp.id.nil?
      tp.source = tso if tp.source.nil?
    else
      tp = StreamPoint.new(tid)
      tp.source =  tso
      tp.value = val
    end
    target << { 'stream:point' => tp.to_h }
  end
end

.notify(opts, topic, event_name, payload) ⇒ Object

Forward event to subscriptions



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 80

def self::notify(opts,topic,event_name,payload)
  opts[:subscriptions].each do |e,urls|
    if e == topic + '/' + event_name
      urls.each do |url|
        EM.defer do
          client = Riddl::Client.new(url)
          client.post [
            Riddl::Parameter::Simple::new('type','event'),
            Riddl::Parameter::Simple::new('topic',topic),
            Riddl::Parameter::Simple::new('event',event_name),
            Riddl::Parameter::Complex::new('notification','application/json',payload)
          ]
        end
      end
    end
  end
end

.persist_values(where, values) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/cpee-logging-xes-yaml/tools.rb', line 201

def self::persist_values(where,values)
  unless File.exist?(where)
    File.write(where,'{}')
  end
  f = File.open(where,'r+')
  f.flock(File::LOCK_EX)
  json = JSON::load(f) || {}
  json.merge!(values)
  f.rewind
  f.truncate(0)
  f.write(JSON.generate(json))
  f.flock(File::LOCK_UN)
  f.close
end