/
package.rb
1262 lines (1079 loc) · 40.4 KB
/
package.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
158
159
160
161
162
163
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
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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 i*-
require_dependency 'api_exception'
require 'builder/xchar'
require 'rexml/document'
require_dependency 'has_relationships'
class Package < ActiveRecord::Base
include FlagHelper
include CanRenderModel
include ForbidsAnonymousUsers
include HasRelationships
has_many :relationships, dependent: :destroy, inverse_of: :package
include HasRatings
include HasAttributes
class PackageError < StandardError; end
class CycleError < APIException
setup 'cycle_error'
end
class DeleteError < APIException
attr_accessor :packages
setup 'delete_error'
end
class SaveError < APIException
setup 'package_save_error'
end
class WritePermissionError < APIException
setup 'package_write_permission_error'
end
class UnknownObjectError < APIException
setup 'unknown_package', 404, 'Unknown package'
end
class ReadAccessError < UnknownObjectError; end
class ReadSourceAccessError < APIException
setup 'source_access_no_permission', 403, 'Source Access not allowed'
end
class IllegalFileName < APIException; setup 'invalid_file_name_error'; end
class PutFileNoPermission < APIException; setup 403; end
belongs_to :project, inverse_of: :packages
delegate :name, to: :project, prefix: true
attr_reader :commit_opts
attr_writer :commit_opts
after_initialize do
@commit_opts = {}
end
has_many :messages, :as => :db_object, dependent: :delete_all
has_many :taggings, :as => :taggable, dependent: :delete_all
has_many :tags, :through => :taggings
has_many :flags, -> { order(:position) }, dependent: :delete_all, inverse_of: :package
belongs_to :develpackage, :class_name => 'Package', :foreign_key => 'develpackage_id'
has_many :develpackages, :class_name => 'Package', :foreign_key => 'develpackage_id'
has_many :attribs, :dependent => :destroy, foreign_key: :package_id
has_many :package_kinds, dependent: :delete_all
has_many :package_issues, dependent: :delete_all # defined in sources
has_many :issues, through: :package_issues
has_many :products, :dependent => :destroy
has_many :channels, :dependent => :destroy, foreign_key: :package_id
has_many :comments, :dependent => :destroy, inverse_of: :package, class_name: 'CommentPackage'
has_many :binary_releases, dependent: :delete_all, :foreign_key => 'release_package_id'
before_destroy :check_devel_packages, prepend: true
before_destroy :delete_on_backend
before_destroy :revoke_requests
before_destroy :update_project_for_product
before_destroy :remove_linked_packages
before_destroy :delete_cache_lines
after_save :write_to_backend
before_update :update_activity
after_rollback :reset_cache
# The default scope is necessary to exclude the forbidden projects.
# It's necessary to write it as a nested Active Record query for performance reasons
# which will produce a query like:
# WHERE (`packages`.`id` NOT IN (SELECT `packages`.`id` FROM `packages` WHERE packages.project_id in (0))
# This is faster than
# default_scope { where('packages.project_id not in (?)', Relationship.forbidden_project_ids) }
# which would produce a query like
# WHERE (packages.project_id not in (0))
# because we assumes that there are more allowed projects than forbidden ones.
default_scope {
where.not(id: Package.where(project_id: Relationship.forbidden_project_ids))
}
scope :order_by_name, -> { order('LOWER(name)') }
# rubocop:disable Metrics/LineLength
scope :dirty_backend_package, -> { joins('left outer join backend_packages on backend_packages.package_id = packages.id').where('backend_packages.package_id is null') }
# rubocop:enable Metrics/LineLength
validates :name, presence: true, length: { maximum: 200 }
validates :title, length: { maximum: 250 }
validate :valid_name
has_one :backend_package, foreign_key: :package_id, dependent: :destroy, inverse_of: :package
has_one :token, foreign_key: :package_id, dependent: :destroy
has_many :tokens, dependent: :destroy, inverse_of: :package
def self.check_access?(dbpkg = self)
return false if dbpkg.nil?
return false unless dbpkg.class == Package
return Project.check_access?(dbpkg.project)
end
def self.check_cache(project, package, opts)
@key = { 'get_by_project_and_name' => 1, package: package, opts: opts }
@key[:user] = User.current.cache_key if User.current
# the cache is only valid if the user, prj and pkg didn't change
if project.is_a? Project
@key[:project] = project.id
else
@key[:project] = project
end
pid, old_pkg_time, old_prj_time = Rails.cache.read(@key)
if pid
pkg=Package.where(id: pid).includes(:project).first
return pkg if pkg && pkg.updated_at == old_pkg_time && pkg.project.updated_at == old_prj_time
Rails.cache.delete(@key) # outdated anyway
end
return nil
end
def self.internal_get_project(project)
if project.is_a? Project
prj = project
else
return nil if Project.is_remote_project?(project)
prj = Project.get_by_name(project)
end
raise UnknownObjectError, "#{project}/#{package}" unless prj
prj
end
# returns an object of package or raises an exception
# should be always used when a project is required
# in case you don't access sources or build logs in any way use
# use_source: false to skip check for sourceaccess permissions
# function returns a nil object in case the package is on remote instance
def self.get_by_project_and_name(project, package, opts = {})
opts = { use_source: true, follow_project_links: true, check_update_project: false }.merge(opts)
pkg = check_cache(project, package, opts)
return pkg if pkg
prj = internal_get_project(project)
return nil unless prj # remote prjs
if pkg.nil? and opts[:follow_project_links]
pkg = prj.find_package(package, opts[:check_update_project])
elsif pkg.nil?
pkg = prj.update_instance.packages.find_by_name(package) if opts[:check_update_project]
pkg = prj.packages.find_by_name(package) if pkg.nil?
end
if pkg.nil? and opts[:follow_project_links]
# in case we link to a remote project we need to assume that the
# backend may be able to find it even when we don't have the package local
prj.expand_all_projects.each do |p|
return nil unless p.is_a? Project
end
end
raise UnknownObjectError, "#{project}/#{package}" unless pkg
raise ReadAccessError, "#{project}/#{package}" unless check_access?(pkg)
pkg.check_source_access! if opts[:use_source]
Rails.cache.write(@key, [pkg.id, pkg.updated_at, prj.updated_at])
pkg
end
def self.get_by_project_and_name!(project, package, opts = {})
pkg = get_by_project_and_name(project, package, opts)
raise UnknownObjectError, "#{project}/#{package}" unless pkg
pkg
end
# to check existens of a project (local or remote)
def self.exists_by_project_and_name(project, package, opts = {})
opts = { follow_project_links: true, allow_remote_packages: false }.merge(opts)
begin
prj = Project.get_by_name(project)
rescue Project::UnknownObjectError
return false
end
unless prj.is_a? Project
return opts[:allow_remote_packages] && self.exists_on_backend?(package, project)
end
prj.exists_package?(package, opts)
end
def self.exists_on_backend?(package, project)
begin
answer = Suse::Backend.get(Package.source_path(project, package))
return true if answer
rescue ActiveXML::Transport::Error
# ignored
end
false
end
def self.find_by_project_and_name(project, package)
Package.where(name: package.to_s, projects: { name: project }).includes(:project).first
end
def self.find_by_attribute_type(attrib_type, package = nil)
# One sql statement is faster than a ruby loop
# attribute match in package or project
sql =<<-END_SQL
SELECT pack.*
FROM packages pack
LEFT OUTER JOIN attribs attr ON pack.id = attr.package_id
LEFT OUTER JOIN attribs attrprj ON pack.project_id = attrprj.project_id
WHERE ( attr.attrib_type_id = ? or attrprj.attrib_type_id = ? )
END_SQL
if package
sql += ' AND pack.name = ? GROUP by pack.id'
ret = Package.find_by_sql [sql, attrib_type.id.to_s, attrib_type.id.to_s, package]
ret.each do |dbpkg|
ret.delete(dbpkg) unless Package.check_access?(dbpkg)
end
return ret
end
sql += ' GROUP by pack.id'
ret = Package.find_by_sql [sql, attrib_type.id.to_s, attrib_type.id.to_s]
ret.each do |dbpkg|
ret.delete(dbpkg) unless Package.check_access?(dbpkg)
end
ret
end
def self.find_by_attribute_type_and_value(attrib_type, value, package = nil)
# One sql statement is faster than a ruby loop
sql =<<-END_SQL
SELECT pack.*
FROM packages pack
LEFT OUTER JOIN attribs attr ON pack.id = attr.package_id
LEFT OUTER JOIN attrib_values val ON attr.id = val.attrib_id
WHERE attr.attrib_type_id = ? AND val.value = ?
END_SQL
if package
sql += ' AND pack.name = ?'
ret = Package.find_by_sql [sql, attrib_type.id.to_s, value.to_s, package]
ret.each do |dbpkg|
ret.delete(dbpkg) unless Package.check_access?(dbpkg)
end
return ret
end
sql += ' GROUP by pack.id'
ret = Package.find_by_sql [sql, attrib_type.id.to_s, value.to_s]
ret.each do |dbpkg|
ret.delete(dbpkg) unless Package.check_access?(dbpkg)
end
ret
end
def check_source_access?
if self.disabled_for?('sourceaccess', nil, nil) or self.project.disabled_for?('sourceaccess', nil, nil)
unless User.current && User.current.can_source_access?(self)
return false
end
end
return true
end
def check_source_access!
if !self.check_source_access?
be_not_nobody!
raise ReadSourceAccessError, "#{self.project.name}/#{self.name}"
end
end
def is_locked?
return true if flags.find_by_flag_and_status 'lock', 'enable'
return self.project.is_locked?
end
def check_write_access!(ignoreLock = nil)
return if Rails.env.test? and User.current.nil? # for unit tests
# test _product permissions if any other _product: subcontainer is used
obj = self
obj = self.project.packages.where(:name => "_product").first if self.name =~ /\A_product:\w[-+\w\.]*\z/
unless User.current.can_modify_package? obj, ignoreLock
raise WritePermissionError, "No permission to modify package '#{self.name}' for user '#{User.current.login}'"
end
end
def check_devel_packages
if develpackages.any?
develpackages.each do |package|
# We only care about packages in foreign projects
if package.project.name != self.project.name
self.errors.add(:base, "used as devel package by #{package.project.name}/#{package.name}")
end
end
return false if self.errors.any?
end
true
end
# NOTE: this is no permission check, should it be added ?
def can_be_deleted?
# check if other packages have me as devel package
packs = self.develpackages.to_a
unless packs.empty?
msg = packs.map { |p| p.project.name + '/' + p.name }.join(', ')
de = DeleteError.new "Package is used by following packages as devel package: #{msg}"
de.packages = packs
raise de
end
end
def find_project_local_linking_packages
find_linking_packages(1)
end
def find_linking_packages(project_local = nil)
path = "/search/package/id?match=(linkinfo/@package=\"#{CGI.escape(self.name)}\"+and+linkinfo/@project=\"#{CGI.escape(self.project.name)}\""
path += "+and+@project=\"#{CGI.escape(self.project.name)}\"" if project_local
path += ')'
answer = Suse::Backend.post path, nil
data = REXML::Document.new(answer.body)
result = []
data.elements.each('collection/package') do |e|
p = Package.find_by_project_and_name(e.attributes['project'], e.attributes['name'])
if p.nil?
logger.error "read permission or data inconsistency, backend delivered package as linked package " +
"where no database object exists: #{e.attributes['project']} / #{e.attributes['name']}"
else
result << p
end
end
result
end
def update_project_for_product
if name == '_product'
project.update_product_autopackages
end
end
def private_set_package_kind(dir)
kinds = Package.detect_package_kinds(dir)
self.package_kinds.each do |pk|
if kinds.include? pk.kind
kinds.delete(pk.kind)
else
pk.delete
end
end
kinds.each do |k|
self.package_kinds.create :kind => k
end
end
def sources_changed(opts = {})
dir_xml = opts[:dir_xml]
update_activity
# mark the backend infos "dirty"
BackendPackage.where(package_id: self.id).delete_all
if dir_xml
dir_xml = dir_xml.body if dir_xml.is_a? Net::HTTPSuccess
else
dir_xml = source_file(nil)
end
private_set_package_kind Xmlhash.parse(dir_xml)
update_project_for_product
if opts[:wait_for_update]
self.update_if_dirty
else
retries=10
begin
self.delay.update_if_dirty
rescue ActiveRecord::StatementInvalid
# mysql lock errors in delayed job handling... we need to retry
retries = retries - 1
retry if retries > 0
end
end
end
def self.source_path(project, package, file = nil, opts = {})
path = "/source/#{URI.escape(project)}/#{URI.escape(package)}"
path += "/#{URI.escape(file)}" unless file.blank?
path += '?' + opts.to_query unless opts.blank?
path
end
def source_path(file = nil, opts = {})
Package.source_path(self.project.name, self.name, file, opts)
end
def source_file(file, opts = {})
Suse::Backend.get(source_path(file, opts)).body
end
# Reads the source file and converts it into an ActiveXML::Node
def source_file_to_axml(file, opts = {})
ActiveXML::Node.new(self.source_file(file, opts))
end
def self.dir_hash(project, package, opts = {})
begin
directory = Suse::Backend.get(source_path(project, package, nil, opts)).body
Xmlhash.parse(directory)
rescue ActiveXML::Transport::Error => e
Xmlhash::XMLHash.new error: e.summary
end
end
def dir_hash(opts = {})
Package.dir_hash(self.project.name, self.name, opts)
end
def is_patchinfo?
is_of_kind? :patchinfo
end
def is_link?
is_of_kind? :link
end
def is_channel?
is_of_kind? :channel
end
def is_product?
is_of_kind? :product
end
def is_of_kind? kind
self.package_kinds.where(kind: kind).exists?
end
def update_issue_list
current_issues = {}
if self.is_patchinfo?
xml = Patchinfo.new.read_patchinfo_xmlhash(self)
xml.elements('issue') do |i|
begin
current_issues['kept'] ||= []
current_issues['kept'] << Issue.find_or_create_by_name_and_tracker(i['id'], i['tracker'])
rescue IssueTracker::NotFoundError => e
# if the issue is invalid, we ignore it
Rails.logger.debug e
end
end
else
# onlyissues backend call gets the issues from .changes files
current_issues = find_changed_issues
end
# fast sync our relations
PackageIssue.sync_relations(self, current_issues)
end
def parse_issues_xml(query, force_state = nil)
begin
answer = Suse::Backend.post(self.source_path(nil, query), nil)
rescue ActiveXML::Transport::Error => e
Rails.logger.debug "failed to parse issues: #{e.inspect}"
return {}
end
xml = Xmlhash.parse(answer.body)
# collect all issues and put them into an hash
issues = {}
xml.get('issues').elements('issue') do |i|
issues[i['tracker']] ||= {}
issues[i['tracker']][i['name']] = force_state || i['state']
end
issues
end
def find_changed_issues
# no expand=1, so only branches are tracked
query = { cmd: :diff, orev: 0, onlyissues: 1, linkrev: :base, view: :xml }
issue_change = parse_issues_xml(query, 'kept')
# issues introduced by local changes
if self.is_link?
query = { cmd: :linkdiff, onlyissues: 1, linkrev: :base, view: :xml }
new = parse_issues_xml(query)
(issue_change.keys + new.keys).uniq.each do |key|
issue_change[key] ||= {}
issue_change[key].merge!(new[key]) if new[key]
issue_change['kept'].delete(new[key]) if issue_change['kept'] and key != 'kept'
end
end
myissues = {}
Issue.transaction do
# update existing issues
self.issues.each do |issue|
next unless issue_change[issue.issue_tracker.name]
next unless issue_change[issue.issue_tracker.name][issue.name]
state = issue_change[issue.issue_tracker.name][issue.name]
myissues[state] ||= []
myissues[state] << issue
issue_change[issue.issue_tracker.name].delete(issue.name)
end
issue_change.keys.each do |tracker|
t=IssueTracker.find_by_name tracker
# create new issues
issue_change[tracker].keys.each do |name|
issue = t.issues.find_by_name(name) || t.issues.create(name: name)
state = issue_change[tracker][name]
myissues[state] ||= []
myissues[state] << issue
end
end
end
myissues
end
def update_channel_list
if self.is_channel?
xml = Suse::Backend.get(self.source_path('_channel'))
self.channels.first_or_create.update_from_xml(xml.body.to_s)
else
self.channels.destroy_all
end
end
def update_product_list
# short cut to ensure that no products are left over
unless self.is_product?
self.products.destroy_all
return
end
# hash existing entries
old = Hash.new
self.products.each { |p| old[p.name] = p }
Product.transaction do
begin
xml = Xmlhash.parse(Suse::Backend.get(self.source_path(nil, view: :products)).body)
rescue
return
end
xml.elements('productdefinition') do |pd|
pd.elements('products') do |ps|
ps.elements('product') do |p|
product = Product.find_or_create_by_name_and_package(p['name'], self)
product = product.first unless product.class == Product
product.update_from_xml(xml)
product.save!
old.delete(product.name)
end
end
end
# drop old entries
self.products.destroy(old.values)
end
end
def self.detect_package_kinds(directory)
raise ArgumentError.new 'neh!' if directory.has_key? 'time'
ret = []
directory.elements('entry') do |e|
%w{patchinfo aggregate link channel}.each do |kind|
if e['name'] == '_' + kind
ret << kind
end
end
if e['name'] =~ /.product$/
ret << 'product'
end
# further types my be spec, dsc, kiwi in future
end
ret.uniq
end
# delivers only a defined devel package
def find_devel_package
pkg = self.resolve_devel_package
return nil if pkg == self
pkg
end
# delivers always a package
def resolve_devel_package
pkg = self
prj_name = pkg.project.name
processed = {}
if pkg == pkg.develpackage
raise CycleError.new 'Package defines itself as devel package'
end
while (pkg.develpackage or pkg.project.develproject)
#logger.debug "resolve_devel_package #{pkg.inspect}"
# cycle detection
str = prj_name+'/'+pkg.name
if processed[str]
processed.keys.each do |key|
str = str + ' -- ' + key
end
raise CycleError.new "There is a cycle in devel definition at #{str}"
end
processed[str] = 1
# get project and package name
if pkg.develpackage
# A package has a devel package definition
pkg = pkg.develpackage
prj_name = pkg.project.name
else
# Take project wide devel project definitions into account
prj = pkg.project.develproject
prj_name = prj.name
pkg = prj.packages.get_by_name(pkg.name)
if pkg.nil?
return nil
end
end
if pkg.id == self.id
pkg = self
end
end
#logger.debug "WORKED - #{pkg.inspect}"
return pkg
end
def update_from_xml(xmlhash)
check_write_access!
Package.transaction do
self.title = xmlhash.value('title')
self.description = xmlhash.value('description')
self.bcntsynctag = xmlhash.value('bcntsynctag')
#--- devel project ---#
self.develpackage = nil
devel = xmlhash['devel']
if devel
prj_name = devel['project'] || xmlhash['project']
pkg_name = devel['package'] || xmlhash['name']
develprj = Project.find_by_name(prj_name)
unless develprj
raise SaveError, "value of develproject has to be a existing project (project '#{prj_name}' does not exist)"
end
develpkg = develprj.packages.find_by_name(pkg_name)
unless develpkg
raise SaveError, "value of develpackage has to be a existing package (package '#{pkg_name}' does not exist)"
end
self.develpackage = develpkg
end
#--- end devel project ---#
# just for cycle detection
self.resolve_devel_package
update_relationships_from_xml(xmlhash)
#---begin enable / disable flags ---#
update_all_flags(xmlhash)
#--- update url ---#
self.url = xmlhash.value('url')
#--- end update url ---#
save!
end
end
# for the HasAttributes mixing
def attribute_url
self.source_path('_attribute')
end
def store(opts = {})
# no write access check here, since this operation may will disable this permission ...
self.commit_opts = opts if opts
save!
end
def destroy_without_backend_write
self.commit_opts = { no_backend_write: 1 }
destroy
end
def reset_cache
Rails.cache.delete('xml_package_%d' % id) if id
end
def write_to_backend
reset_cache
#--- write through to backend ---#
if CONFIG['global_write_through']
query = { user: User.current ? User.current.login : User.nobody_login }
query[:comment] = @commit_opts[:comment] unless @commit_opts[:comment].blank?
query[:requestid] = @commit_opts[:requestid] unless @commit_opts[:requestid].blank?
Suse::Backend.put_source(self.source_path('_meta', query), to_axml)
logger.tagged('backend_sync') { logger.debug "Saved Package #{self.project.name}/#{self.name}" }
else
logger.tagged('backend_sync') { logger.warn "Not saving Package #{self.project.name}/#{self.name}, global_write_through is off" }
end
@commit_opts = {}
end
def delete_on_backend
# not really packages...
# everything below _product:
return true if name =~ /\A_product:\w[-+\w\.]*\z/
return true if is_product?
return true if is_channel?
return true if is_patchinfo?
return true if name == '_project'
if CONFIG['global_write_through'] && !@commit_opts[:no_backend_write]
path = source_path
path << Suse::Backend.build_query_from_hash({ user: User.current.login, comment: commit_opts[:comment], requestid: commit_opts[:request]},
[:user, :comment, :requestid])
Suse::Backend.delete path
logger.tagged('backend_sync') { logger.debug "Deleted Package #{self.project.name}/#{self.name}" }
else
if @commit_opts[:no_backend_write]
logger.tagged('backend_sync') { logger.warn "Not deleting Package #{self.project.name}/#{self.name}, backend_write is off " }
else
logger.tagged('backend_sync') { logger.warn "Not deleting Package #{self.project.name}/#{self.name}, global_write_through is off" }
end
end
end
def to_axml_id
return "<package project='#{::Builder::XChar.encode(project.name)}' name='#{::Builder::XChar.encode(name)}'/>\n"
end
def to_axml(_opts = {})
Rails.cache.fetch('xml_package_%d' % self.id) do
# CanRenderModel
render_xml
end
end
def self.activity_algorithm
# this is the algorithm (sql) we use for calculating activity of packages
# we use Time.now.to_i instead of UNIX_TIMESTAMP() so we can test with frozen ruby time
'( packages.activity_index * ' +
"POWER( 2.3276, (UNIX_TIMESTAMP(packages.updated_at) - #{Time.now.to_i})/10000000 ) " +
') as activity_value'
end
before_validation(on: :create) do
# it lives but is new
self.activity_index = 20
end
def activity
package = Package.find_by_sql("SELECT packages.*, #{Package.activity_algorithm} " +
"FROM `packages` WHERE id = #{self.id} LIMIT 1")
return package.shift.activity_value.to_f
end
# is called before_update
def update_activity
# the value we add to the activity, when the object gets updated
addon = 10 * (Time.now.to_f - self.updated_at_was.to_f) / 86400
addon = 10 if addon > 10
new_activity = activity + addon
new_activity = 100 if new_activity > 100
# rails 3 only - rails 4 is reported to name it update_columns
self.update_column(:activity_index, new_activity)
# we need to update the timestamp manually to avoid the activity_algorithm to run away
self.update_column(:updated_at, Time.now)
# just for beauty - and only saved if we save it for other reasons
self.update_counter += 1
end
def expand_flags
return project.expand_flags(self)
end
def open_requests_with_package_as_source_or_target
rel = BsRequest.where(state: [:new, :review, :declined]).joins(:bs_request_actions)
# rubocop:disable Metrics/LineLength
rel = rel.where('(bs_request_actions.source_project = ? and bs_request_actions.source_package = ?) or (bs_request_actions.target_project = ? and bs_request_actions.target_package = ?)', self.project.name, self.name, self.project.name, self.name)
# rubocop:enable Metrics/LineLength
return BsRequest.where(id: rel.select('bs_requests.id').map { |r| r.id })
end
def open_requests_with_by_package_review
rel = BsRequest.where(state: [:new, :review])
rel = rel.joins(:reviews).where("reviews.state = 'new' and reviews.by_project = ? and reviews.by_package = ? ", self.project.name, self.name)
return BsRequest.where(id: rel.select('bs_requests.id').map { |r| r.id })
end
def linkinfo
dir_hash['linkinfo']
end
def rev
dir_hash['rev']
end
def channels
update_if_dirty
super
end
def services
the_services = Service.find(project: self.project.name, package: self.name)
the_services ||= Service.new(project: self.project.name, package: self.name)
the_services
end
def build_result(repository, view = [])
Buildresult.find(project: self.project, package: self, repository: repository, view: view)
end
# first package in link chain outside of my project
def origin_container
# no link, so I am origin
return self unless self.dir_hash
# link target package name is more important, since local name could be
# extended. for example in maintenance incident projects.
li = self.dir_hash['linkinfo']
return self unless li
# from external project, so it is my origin
prj = Project.get_by_name(li['project'])
pkg = prj.find_package(li['package'])
return pkg if self.project != prj
# broken or remote link, aborting
return nil if pkg.nil?
# local link, go one step deeper
return pkg.origin_container
end
# last package in link chain in my project
def local_origin_container
# no link, so I am origin
return self unless self.dir_hash
# link target package name is more important, since local name could be
# extended. for example in maintenance incident projects.
li = self.dir_hash['linkinfo']
return self unless li
# links to external project, so I am origin
return self if li['project'] != self.project.name
# local link, go one step deeper
prj = Project.get_by_name(li['project'])
pkg = prj.find_package(li['package'])
# broken or remote link, aborting
return nil if pkg.nil?
return pkg.local_origin_container
end
def is_local_link?
# no link
return false unless self.dir_hash
li = self.dir_hash['linkinfo']
return false unless li
# linking to my project?
return li['project'] == self.project.name
end
def modify_channel(mode = nil)
raise InvalidParameterError unless [:add_disabled, :enable_all].include? mode
channel = self.channels.first
return unless channel
channel.add_channel_repos_to_project(self, mode)
end
def add_channels(mode = nil)
raise InvalidParameterError unless [nil, :add_disabled, :skip_disabled, :enable_all].include? mode
return if self.is_channel?
opkg = self.origin_container
# remote or broken link?
return if opkg.nil?
# Update projects are usually used in _channels
project_name = opkg.project.update_instance.name
# not my link target, so it does not qualify for my code streastream
return unless self.linkinfo and project_name == self.linkinfo['project']
# main package
ChannelBinary.find_by_project_and_package(project_name, opkg.name).each do |cb|
_add_channel(mode, cb, "Listed in #{project_name} #{opkg.name}")
end
# and all possible existing local links
if opkg.project.is_maintenance_release? and opkg.is_link?
opkg = opkg.project.packages.find_by_name opkg.linkinfo["package"]
end
opkg.find_project_local_linking_packages.each do |p|
name = p.name
# strip incident suffix in update release projects
name.gsub!(/\.[^\.]*$/, '') if opkg.project.is_maintenance_release?
ChannelBinary.find_by_project_and_package(project_name, name).each do |cb|
_add_channel(mode, cb, "Listed in #{project_name} #{name}")
end
end
self.project.store
end
def _add_channel(mode, channel_binary, message)
return if mode == :skip_disabled and not channel_binary.channel_binary_list.channel.is_active?
cpkg = channel_binary.create_channel_package_into(self.project, message)
return unless cpkg
return if mode.nil? and not channel_binary.channel_binary_list.channel.is_active?
cpkg.channels.first.add_channel_repos_to_project(cpkg, mode)
end
private :_add_channel
def update_instance(namespace = 'OBS', name = 'UpdateProject')
# check if a newer instance exists in a defined update project
self.project.update_instance(namespace, name).find_package(self.name)
end
def developed_packages
packages = []
candidates = Package.where(develpackage_id: self).load
candidates.each do |candidate|
packages << candidate unless candidate.linkinfo
end
return packages
end
def self.valid_name?(name)
return false unless name.kind_of? String
# this length check is duplicated but useful for other uses for this function
return false if name.length > 200 || name.blank?
return true if name =~ /\A_product:\w[-+\w\.]*\z/
# obsolete, just for backward compatibility
return true if name =~ /\A_patchinfo:\w[-+\w\.]*\z/
return false if name =~ %r{[ \/:\000-\037]}
if name =~ %r{^[_\.]} && !%w(_product _pattern _project _patchinfo).include?(name)
return false
end
return name =~ /\A\w[-+\w\.]*\z/
end
def valid_name
errors.add(:name, 'is illegal') unless Package.valid_name?(self.name)
end
def branch_from(origin_project, origin_package, rev = nil, missingok = nil, comment = nil, linkrev = nil)
myparam = { cmd: "branch",
noservice: "1",
oproject: origin_project,
opackage: origin_package,
user: User.current.login
}
myparam[:orev] = rev if rev and not rev.empty?
myparam[:olinkrev] = linkrev if linkrev and not linkrev.empty?
myparam[:missingok] = '1' if missingok
myparam[:comment] = comment if comment
path = self.source_path + Suse::Backend.build_query_from_hash(myparam, [:cmd, :oproject, :opackage, :user, :comment, :orev, :missingok])
# branch sources in backend
Suse::Backend.post path, nil
end
# just make sure the backend_package is there
def update_if_dirty
self.backend_package
end
def linking_packages
::Package.joins(:backend_package).where(backend_packages: { links_to_id: self.id })
end
def backend_package
bp = super
# if it's there, it's supposed to be fine
return bp if bp
update_backendinfo