Class: CPEE::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/cpee/controller.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, opts) ⇒ Controller

Returns a new instance of Controller.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
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/cpee/controller.rb', line 55

def initialize(id,opts)
  @directory = opts[:instances] + "/#{id}/"
  @id = id
  @events = {}
  @votes = {}
  @votes_results = {}
  @communication = {}
  @callbacks = {}
  @instance = EmptyWorkflow.new(self,opts[:url])
  @positions = []
  @thread = nil
  @mutex = Mutex.new
  @opts = opts

  @properties = Riddl::Utils::Properties::Backend.new( 
    {
      :inactive => opts[:properties_schema_inactive],
      :active   => opts[:properties_schema_active],
      :finished => opts[:properties_schema_finished]
    },
    @directory + '/properties.xml',
    opts[:properties_init]
  )
  @notifications =  Riddl::Utils::Notifications::Producer::Backend.new(
    opts[:topics],
    @directory + '/notifications/'
  )

  @notifications.subscriptions.keys.each do |key|
    self.unserialize_notifications!(:cre,key)
  end
  unless ['stopped','ready','finished'].include?(@properties.data.find("string(/p:properties/p:state)"))
    @properties.modify do |doc|
      doc.find("/p:properties/p:state").first.text = 'stopped'
    end  
  end
  unserialize_handlerwrapper!
  unserialize_dataelements!
  unserialize_endpoints!
  unserialize_dsl!
  unserialize_positions!
end

Instance Attribute Details

#callbacksObject (readonly)

Returns the value of attribute callbacks.



101
102
103
# File 'lib/cpee/controller.rb', line 101

def callbacks
  @callbacks
end

#idObject (readonly)

Returns the value of attribute id.



98
99
100
# File 'lib/cpee/controller.rb', line 98

def id
  @id
end

#mutexObject (readonly)

Returns the value of attribute mutex.



102
103
104
# File 'lib/cpee/controller.rb', line 102

def mutex
  @mutex
end

#notificationsObject (readonly)

Returns the value of attribute notifications.



100
101
102
# File 'lib/cpee/controller.rb', line 100

def notifications
  @notifications
end

#propertiesObject (readonly)

Returns the value of attribute properties.



99
100
101
# File 'lib/cpee/controller.rb', line 99

def properties
  @properties
end

Instance Method Details

#add_ws(key, socket) ⇒ Object

}}}



482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/cpee/controller.rb', line 482

def add_ws(key,socket)# {{{
  @communication[key] = socket
  @events.each do |a|
    if a[1].has_key?(key)
      a[1][key] = socket
    end  
  end
  @votes.each do |a|
    if a[1].has_key?(key)
      a[1][key] = socket
    end  
  end
end

#call_vote(what, content = {}) ⇒ Object

}}}



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/cpee/controller.rb', line 419

def call_vote(what,content={})# {{{
  voteid = Digest::MD5.hexdigest(Kernel::rand().to_s)
  item = @votes[what]
  if item && item.length > 0
    continue = WEEL::Continue.new
    @votes_results[voteid] = []
    inum = 0
    item.each do |key,url|
      if url.class == String
        inum += 1
      elsif url.class == Riddl::Utils::Notifications::Producer::WS
        inum += 1 unless url.closed?
      end  
    end

    item.each do |key,url|

      Thread.new(key,url,content.dup) do |k,u,c|
        callback = Digest::MD5.hexdigest(Kernel::rand().to_s)
        c['callback'] = callback
        notf = build_notification(k,what,c,'vote',callback)
        if u.class == String
          client = Riddl::Client.new(u)
          params = notf.map{|ke,va|Riddl::Parameter::Simple.new(ke,va)}
          @mutex.synchronize do
            status, result, headers = client.post params
            if headers["CPEE_CALLBACK"] && headers["CPEE_CALLBACK"] == 'true'
              @callbacks[callback] = Callback.new("vote #{notf.find{|a,b| a == 'notification'}[1]}", self, :vote_callback, what, k, :http, continue, voteid, callback, inum)
            else
              vote_callback(result,continue,voteid,callback, inum)
            end
          end  
        elsif u.class == Riddl::Utils::Notifications::Producer::WS
          @callbacks[callback] = Callback.new("vote #{notf.find{|a,b| a == 'notification'}[1]}", self, :vote_callback, what, k, :ws, continue, voteid, callback, inum)
          e = XML::Smart::string("<vote/>")
          notf.each do |ke,va|
            e.root.add(ke,va)
          end
          u.send(e.to_s)
        end
      end

    end
    continue.wait

    !@votes_results.delete(voteid).include?(false)
  else  
    true
  end
end

#del_ws(key) ⇒ Object

}}}



496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/cpee/controller.rb', line 496

def del_ws(key)# {{{
  @communication[key] = nil
  @events.each do |a|
    if a[1].has_key?(key)
      a[1][key] = nil
    end  
  end
  @votes.each do |a|
    if a[1].has_key?(key)
      a[1][key] = nil
    end
  end
end

#instance_urlObject



104
105
106
# File 'lib/cpee/controller.rb', line 104

def instance_url 
  "#{@opts[:url]}/#{@id}"
end

#notify(what, content = {}) ⇒ Object

}}}



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/cpee/controller.rb', line 398

def notify(what,content={})# {{{
  item = @events[what]
  if item
    item.each do |ke,ur|
      Thread.new(ke,ur) do |key,url|
        ev = build_notification(key,what,content,'event')
        if url.class == String
          client = Riddl::Client.new(url,nil,:xmpp => @opts[:xmpp])
          client.post ev.map{|k,v|Riddl::Parameter::Simple.new(k,v)} rescue nil
        elsif url.class == Riddl::Utils::Notifications::Producer::WS
          e = XML::Smart::string("<event/>")
          ev.each do |k,v|
            e.root.add(k,v)
          end
          url.send(e.to_s) rescue nil
        end  
      end
    end
  end
end

#serialize_dataelements!Object

}}}



141
142
143
144
145
146
147
148
149
# File 'lib/cpee/controller.rb', line 141

def serialize_dataelements! #{{{
  @properties.modify do |doc|
    node = doc.find("/p:properties/p:dataelements").first
    node.children.delete_all!
    @instance.data.each do |k,v|
      node.add(k.to_s,ValueHelper::generate(v))
    end
  end
end

#serialize_endpoints!Object

}}}



150
151
152
153
154
155
156
157
158
# File 'lib/cpee/controller.rb', line 150

def serialize_endpoints! #{{{
  @properties.modify do |doc|
    node = doc.find("/p:properties/p:endpoints").first
    node.children.delete_all!
    @instance.endpoints.each do |k,v|
      node.add(k.to_s,v)
    end
  end
end

#serialize_positions!Object

}}}



170
171
172
173
174
175
176
177
178
179
# File 'lib/cpee/controller.rb', line 170

def serialize_positions! # {{{
  @properties.modify do |doc|
    pos = doc.find("/p:properties/p:positions").first
    pos.children.delete_all!
    @positions = @instance.positions
    @instance.positions.each do |p|
      pos.add("#{p.position}",[p.detail,p.passthrough].compact.join(';'))
    end
  end
end

#serialize_state!Object

}}}



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cpee/controller.rb', line 159

def serialize_state! # {{{
  @properties.activate_schema(:finished) if @instance.state == :finished
  @properties.activate_schema(:inactive) if @instance.state == :stopped || @instance.state == :ready
  @properties.activate_schema(:active)   if @instance.state == :running || @instance.state == :simulating
  if [:finished, :stopped, :ready].include?(@instance.state)
    @properties.modify do |doc|
      node = doc.find("/p:properties/p:state").first
      node.text = @instance.state
    end 
  end  
end

#serialize_status!Object

}}}



180
181
182
183
184
185
186
187
# File 'lib/cpee/controller.rb', line 180

def serialize_status! #{{{
  @properties.modify do |doc|
    node = doc.find("/p:properties/p:status/p:id").first
    node.text = @instance.status.id
    node = doc.find("/p:properties/p:status/p:message").first
    node.text = @instance.status.message
  end
end

#simObject

{{{



111
112
113
114
# File 'lib/cpee/controller.rb', line 111

def sim # {{{
  @thread.join if !@thread.nil? && @thread.alive?
  @thread = @instance.sim
end

#startObject

}}}



116
117
118
119
120
121
122
# File 'lib/cpee/controller.rb', line 116

def start # {{{
  @thread.join if !@thread.nil? && @thread.alive?
  unless @positions.empty?
    @instance.search(@positions)
  end
  @thread = @instance.start
end

#stopObject

}}}



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/cpee/controller.rb', line 124

def stop # {{{
  t = @instance.stop
  t.run
  @callbacks.delete_if do |k,c| 
    # only remove vote_callbacks, the other stuff is removed by
    # the instance stopping cleanup
    if c.method == :vote_callback
      c.callback(nil)
      true
    else  
      false
    end
  end  
  @thread.join if !@thread.nil? && @thread.alive?
  @callback = [] # everything should be empty now
end

#unserialize_dataelements!Object

}}}



253
254
255
256
257
258
# File 'lib/cpee/controller.rb', line 253

def unserialize_dataelements! #{{{
    @instance.data.clear
    @properties.data.find("/p:properties/p:dataelements/p:*").each do |e|
      @instance.data[e.qname.to_sym] = ValueHelper::parse(e.text)
    end
end

#unserialize_description!Object

}}}



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
396
# File 'lib/cpee/controller.rb', line 310

def unserialize_description! #{{{
  dsl = nil
  nots = []
  @properties.modify do |doc|
    dsl   = doc.find("/p:properties/p:dsl").first
    dslx  = doc.find("/p:properties/p:dslx").first
    desc  = doc.find("/p:properties/p:description").first
    tdesc = doc.find("/p:properties/p:transformation/p:description").first
    tdata = doc.find("/p:properties/p:transformation/p:dataelements").first
    tendp = doc.find("/p:properties/p:transformation/p:endpoints").first

    ### description transformation, including dslx to dsl
    addit = if tdesc.attributes['type'] == 'copy' || tdesc.empty?
      desc.children.first.to_doc.root
    elsif tdesc.attributes['type'] == 'rest' && !tdesc.empty?
      srv = Riddl::Client.interface(tdesc.text,@opts[:transformation_service],:xmpp => @opts[:xmpp])
      status, res = srv.post [
        Riddl::Parameter::Complex.new("description","text/xml",desc.children.first.dump),
        Riddl::Parameter::Simple.new("type","description")
      ]
      XML::Smart::string(res[0].value.read).root if status == 200
    elsif tdesc.attributes['type'] == 'xslt' && !tdesc.empty?
      trans = XML::Smart::open_unprotected(tdesc.text)
      desc.children.first.to_doc.transform_with(trans).root
    else
      nil
    end
    unless addit.nil?
      dslx.children.delete_all!
      dslx.add addit
      trans = XML::Smart::open_unprotected(@opts[:transformation_dslx])
      dsl.text = dslx.to_doc.transform_with(trans)
      @instance.description = dsl.text
    end

    ### dataelements extraction
    addit = if tdata.attributes['type'] == 'rest' && !tdata.empty?
      srv = Riddl::Client.interface(tdata.text,@opts[:transformation_service],:xmpp => @opts[:xmpp])
      status, res = srv.post [ 
        Riddl::Parameter::Complex.new("description","text/xml",desc.children.first.dump),
        Riddl::Parameter::Simple.new("type","dataelements")
      ]
      res
    elsif tdata.attributes['type'] == 'xslt' && !tdata.empty?
      trans = XML::Smart::open_unprotected(tdata.text)
      desc.children.first.to_doc.transform_with(trans)
    else
      nil
    end  
    unless addit.nil?
      node = doc.find("/p:properties/p:dataelements").first
      node.children.delete_all!
      @instance.data.clear
      addit.each_slice(2).each do |k,v|
        @instance.data[k.value.to_sym] = ValueHelper::parse(v.value)
        node.add(k.value,ValueHelper::generate(v.value))
      end  
      nots << ["properties/dataelements/change", {:instance => instance_url, :changed => JSON::generate(@instance.data)}]
    end  

    ### enpoints extraction
    addit = if tendp.attributes['type'] == 'rest' && !tdata.empty?
      srv = Riddl::Client.interface(tendp.text,@opts[:transformation_service],:xmpp => @opts[:xmpp])
      status, res = srv.post [ 
        Riddl::Parameter::Complex.new("description","text/xml",desc.children.first.dump),
        Riddl::Parameter::Simple.new("type","endpoints")
      ]
      res
    elsif tendp.attributes['type'] == 'xslt' && !tdata.empty?
      trans = XML::Smart::open_unprotected(tendp.text)
      desc.children.first.to_doc.transform_with(trans)
    else
      nil
    end  
    unless addit.nil?
      node = doc.find("/p:properties/p:endpoints").first
      node.children.delete_all!
      @instance.endpoints.clear
      addit.each_slice(2).each do |k,v|
        @instance.endpoints[k.value.to_sym] = ValueHelper::parse(v.value)
        node.add(k.value,ValueHelper::generate(v.value))
      end  
      nots << ["properties/endpoints/change", {:instance => instance_url, :changed => JSON::generate(@instance.endpoints)}]
    end  
  end
  nots
end

#unserialize_dsl!Object

}}}



307
308
309
# File 'lib/cpee/controller.rb', line 307

def unserialize_dsl! #{{{
  @instance.description = @properties.data.find("string(/p:properties/p:dsl)")
end

#unserialize_endpoints!Object

}}}



259
260
261
262
263
264
# File 'lib/cpee/controller.rb', line 259

def unserialize_endpoints! #{{{
    @instance.endpoints.clear
    @properties.data.find("/p:properties/p:endpoints/p:*").each do |e|
      @instance.endpoints[e.qname.to_sym] = e.text
    end
end

#unserialize_handlerwrapper!Object

}}}



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/cpee/controller.rb', line 285

def unserialize_handlerwrapper! #{{{
  hw = nil
  begin
    hw = eval(@properties.data.find("string(/p:properties/p:handlerwrapper)"))
    @instance.handlerwrapper = hw
  rescue => e  
    @instance.handlerwrapper = DefaultHandlerWrapper
  end  
  if hw != @instance.handlerwrapper
    @properties.modify do |doc|
      node = doc.find("/p:properties/p:handlerwrapper").first
      node.text = @instance.handlerwrapper.to_s
    end 
  end
end

#unserialize_notifications!(op, key) ⇒ Object

}}}



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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/cpee/controller.rb', line 189

def unserialize_notifications!(op,key)# {{{
  case op
    when :del
      @communication.delete(key)
      @events.each do |eve,keys|
        keys.delete_if{|k,v| key == k}
      end  
      @votes.each do |eve,keys|
        keys.delete_if do |k,v|
          if key == k
            @callbacks.each{|voteid,cb|cb.delete_if!(eve,k)}
            true
          end  
        end
      end  
    when :upd 
      if @notifications.subscriptions[key]
        url = @communication[key]
        evs = []
        vos = []
        @events.each { |e,v| evs << e }
        @votes.each { |e,v| vos << e }
        @notifications.subscriptions[key].view do |doc|
          turl = doc.find('string(/n:subscription/@url)') 
          url = turl == '' ? url : turl
          @communication[key] = url
          doc.find('/n:subscription/n:topic').each do |t|
            t.find('n:event').each do |e|
              @events["#{t.attributes['id']}/#{e}"] ||= {}
              @events["#{t.attributes['id']}/#{e}"][key] = url
              evs.delete("#{t.attributes['id']}/#{e}")
            end
            t.find('n:vote').each do |e|
              @votes["#{t.attributes['id']}/#{e}"] ||= {}
              @votes["#{t.attributes['id']}/#{e}"][key] = url
              vos.delete("#{t.attributes['id']}/#{e}")
            end
          end
        end
        evs.each { |e| @votes[e].delete(key) }
        vos.each do |e| 
          @callbacks.each{|voteid,cb|cb.delete_if!(e,key)}
          @votes[e].delete(key)
        end  
      end  
    when :cre
      @notifications.subscriptions[key].view do |doc|
        turl = doc.find('string(/n:subscription/@url)') 
        url = turl == '' ? nil : turl
        @communication[key] = url
        doc.find('/n:subscription/n:topic').each do |t|
          t.find('n:event').each do |e|
            @events["#{t.attributes['id']}/#{e}"] ||= {}
            @events["#{t.attributes['id']}/#{e}"][key] = (url == "" ? nil : url)
          end
          t.find('n:vote').each do |e|
            @votes["#{t.attributes['id']}/#{e}"] ||= {}
            @votes["#{t.attributes['id']}/#{e}"][key] = url
          end
        end
      end  
  end    
end

#unserialize_positions!Object

}}}



300
301
302
303
304
305
306
# File 'lib/cpee/controller.rb', line 300

def unserialize_positions! #{{{
  @positions = []
  @properties.data.find("/p:properties/p:positions/p:*").each do |e|
    val = e.text.split(';')
    @positions << ::WEEL::Position.new(e.qname.to_s.to_sym,val[0].to_sym,val[1])
  end
end

#unserialize_state!Object

}}}



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/cpee/controller.rb', line 265

def unserialize_state! #{{{ 
  state = @properties.data.find("string(/p:properties/p:state)")
  if call_vote("properties/state/change", :instance => @id, :newstate => state)
    case state
      when 'stopping'
        stop
      when 'running'
        start
      when 'simulating'  
        sim
    end
  else
    if node = @properties.data.find("/p:properties/p:state").first
      case state
        when 'stopping'; node.text = 'running'
        when 'running'; node.text = 'stopped'
      end
    end
  end
end

#vote_callback(result, continue, voteid, callback, num) ⇒ Object

}}}



470
471
472
473
474
475
476
477
478
479
480
# File 'lib/cpee/controller.rb', line 470

def vote_callback(result,continue,voteid,callback,num)# {{{
  @callbacks.delete(callback)
  if result == :DELETE
    @votes_results[voteid] << true
  else
    @votes_results[voteid] << (result && result[0] && result[0].value == 'true')
  end  
  if (num == @votes_results[voteid].length)
    continue.continue
  end  
end

#xmppObject



107
108
109
# File 'lib/cpee/controller.rb', line 107

def xmpp 
  @opts[:xmpp]
end