forked from Normation/rudder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonResponseObjects.scala
1102 lines (1008 loc) · 41.5 KB
/
JsonResponseObjects.scala
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
/*
*************************************************************************************
* Copyright 2021 Normation SAS
*************************************************************************************
*
* This file is part of Rudder.
*
* Rudder is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In accordance with the terms of section 7 (7. Additional Terms.) of
* the GNU General Public License version 3, the copyright holders add
* the following Additional permissions:
* Notwithstanding to the terms of section 5 (5. Conveying Modified Source
* Versions) and 6 (6. Conveying Non-Source Forms.) of the GNU General
* Public License version 3, when you create a Related Module, this
* Related Module is not considered as a part of the work and may be
* distributed under the license agreement of your choice.
* A "Related Module" means a set of sources files including their
* documentation that, without modification of the Source Code, enables
* supplementary functions or services in addition to those offered by
* the Software.
*
* Rudder is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rudder. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************************
*/
package com.normation.rudder.apidata
import com.normation.GitVersion
import com.normation.GitVersion.RevisionInfo
import com.normation.cfclerk.domain.Technique
import com.normation.cfclerk.domain.TechniqueName
import com.normation.cfclerk.domain.TechniqueVersion
import com.normation.errors.*
import com.normation.inventory.domain.NodeId
import com.normation.rudder.apidata.JsonResponseObjects.JRPropertyHierarchy.JRPropertyHierarchyHtml
import com.normation.rudder.apidata.JsonResponseObjects.JRPropertyHierarchy.JRPropertyHierarchyJson
import com.normation.rudder.domain.nodes.NodeGroup
import com.normation.rudder.domain.nodes.NodeGroupCategoryId
import com.normation.rudder.domain.nodes.NodeGroupId
import com.normation.rudder.domain.policies.*
import com.normation.rudder.domain.properties.GenericProperty
import com.normation.rudder.domain.properties.GlobalParameter
import com.normation.rudder.domain.properties.GroupProperty
import com.normation.rudder.domain.properties.InheritMode
import com.normation.rudder.domain.properties.NodePropertyHierarchy
import com.normation.rudder.domain.properties.ParentProperty
import com.normation.rudder.domain.properties.PropertyProvider
import com.normation.rudder.domain.queries.CriterionLine
import com.normation.rudder.domain.queries.Query
import com.normation.rudder.domain.queries.QueryReturnType
import com.normation.rudder.domain.queries.ResultTransformation
import com.normation.rudder.domain.workflows.ChangeRequestId
import com.normation.rudder.hooks.Hooks
import com.normation.rudder.ncf.ResourceFile
import com.normation.rudder.ncf.TechniqueParameter
import com.normation.rudder.repository.FullActiveTechnique
import com.normation.rudder.repository.FullActiveTechniqueCategory
import com.normation.rudder.repository.FullNodeGroupCategory
import com.normation.rudder.rule.category.RuleCategory
import com.normation.rudder.rule.category.RuleCategoryId
import com.normation.rudder.services.queries.CmdbQueryParser
import com.normation.rudder.services.queries.StringCriterionLine
import com.normation.rudder.services.queries.StringQuery
import com.normation.utils.DateFormaterService
import com.softwaremill.quicklens.*
import com.typesafe.config.ConfigRenderOptions
import com.typesafe.config.ConfigValue
import io.scalaland.chimney.Transformer
import io.scalaland.chimney.dsl.*
import zio.*
import zio.Tag as _
import zio.json.*
import zio.json.DeriveJsonEncoder
import zio.json.internal.Write
import zio.syntax.*
/*
* This class deals with everything serialisation related for API.
* Change things with care! Everything must be versioned!
* Even changing a field name can lead to an API incompatible change and
* so will need a new API version number (and be sure that old behavior is kept
* for previous versions).
*/
// how to render parent properties in the returned json in node APIs
sealed trait RenderInheritedProperties
object RenderInheritedProperties {
case object HTML extends RenderInheritedProperties
case object JSON extends RenderInheritedProperties
}
// to avoid ambiguity with corresponding business objects, we use "JR" as a prfix
object JsonResponseObjects {
final case class JRActiveTechnique(
name: String,
versions: List[String]
)
object JRActiveTechnique {
def fromTechnique(activeTechnique: FullActiveTechnique): JRActiveTechnique = {
JRActiveTechnique(activeTechnique.techniqueName.value, activeTechnique.techniques.map(_._1.serialize).toList)
}
}
/*
* "sections": [
* {
* "section": {
* "name": "File to manage",
* "sections": [
* {
* "section": {
* "name": "Enforce content by section",
* "vars": [
* {
* "var": {
* "name": "GENERIC_FILE_CONTENT_SECTION_MANAGEMENT",
* "value": "false"
* }
* },
* {
* "var": {
* "name": "GENERIC_FILE_SECTION_CONTENT",
* "value": ""
* }
* },
* ],
* "vars": [ .... ]
* .....
*/
final case class JRDirectiveSectionVar(
name: String,
value: String
)
final case class JRDirectiveSection(
name: String, // we have one more "var" indirection level between a var and its details:
// { vars":[ { "var":{ "name": .... } }, { "var": { ... }} ]
vars: Option[
List[Map[String, JRDirectiveSectionVar]]
], // we have one more "section" indirection level between a section and its details:
// { sections":[ { "section":{ "name": .... } }, { "section": { ... }} ]
sections: Option[List[Map[String, JRDirectiveSection]]]
) {
// toMapVariable is just accumulating var by name in seq, see SectionVal.toMapVariables
def toMapVariables: Map[String, Seq[String]] = {
import scala.collection.mutable.Buffer
import scala.collection.mutable.Map
val res = Map[String, Buffer[String]]()
def recToMap(sec: JRDirectiveSection): Unit = {
sec.vars.foreach(_.foreach(_.foreach {
case (_, sectionVar) =>
res.getOrElseUpdate(sectionVar.name, Buffer()).append(sectionVar.value)
}))
sec.sections.foreach(_.foreach(_.foreach {
case (_, section) =>
recToMap(section)
}))
}
recToMap(this)
res.map { case (k, buf) => (k, buf.toSeq) }.toMap
}
}
// we have one more level between a directive section and a section
final case class JRDirectiveSectionHolder(
section: JRDirectiveSection
)
object JRDirectiveSection {
def fromSectionVal(name: String, sectionVal: SectionVal): JRDirectiveSection = {
JRDirectiveSection(
name = name,
sections = sectionVal.sections.toList.sortBy(_._1) match {
case Nil => None
case list => Some(list.flatMap { case (n, sections) => sections.map(s => Map("section" -> fromSectionVal(n, s))) })
},
vars = sectionVal.variables.toList.sortBy(_._1) match {
case Nil => None
case list => Some(list.map { case (n, v) => Map("var" -> JRDirectiveSectionVar(n, v)) })
}
)
}
}
final case class JRRevisionInfo(
revision: String,
date: String,
author: String,
message: String
)
object JRRevisionInfo {
def fromRevisionInfo(r: RevisionInfo): JRRevisionInfo = {
JRRevisionInfo(r.rev.value, DateFormaterService.serialize(r.date), r.author, r.message)
}
}
sealed trait JRTechnique {
def id: String
def name: String
def version: String
def source: String
}
final case class JRBuiltInTechnique(
name: String,
id: String,
version: String
) extends JRTechnique { val source = "builtin" }
final case class JRTechniqueParameter(
id: String,
name: String,
description: String,
mayBeEmpty: Boolean
)
object JRTechniqueParameter {
def from(param: TechniqueParameter): JRTechniqueParameter = {
JRTechniqueParameter(
param.id.value,
param.name,
param.description.getOrElse(""),
param.mayBeEmpty
)
}
}
final case class JRTechniqueResource(
path: String,
state: String
)
object JRTechniqueResource {
def from(resource: ResourceFile): JRTechniqueResource = {
JRTechniqueResource(
resource.path,
resource.state.value
)
}
}
final case class JRMethodCallValue(
name: String,
value: String
)
final case class JRReportingLogic(
name: String,
value: Option[String]
)
final case class JRDirective(
changeRequestId: Option[String],
id: String, // id is in format uid+rev
displayName: String,
shortDescription: String,
longDescription: String,
techniqueName: String,
techniqueVersion: String,
parameters: Map[String, JRDirectiveSection],
priority: Int,
enabled: Boolean,
system: Boolean,
policyMode: String,
tags: List[Map[String, String]]
) {
def toDirective(): IOResult[(TechniqueName, Directive)] = {
for {
i <- DirectiveId.parse(id).toIO
v <- TechniqueVersion.parse(techniqueVersion).toIO
// the Map is just for "section" -> ...
s <- parameters.get("section").notOptional("Root section entry 'section' is missing for directive parameters")
m <- PolicyMode.parseDefault(policyMode).toIO
} yield {
(
TechniqueName(techniqueName),
Directive(
i,
v,
s.toMapVariables,
displayName,
shortDescription,
m,
longDescription,
priority,
enabled,
system,
Tags.fromMaps(tags)
)
)
}
}
}
object JRDirective {
def empty(id: String): JRDirective = JRDirective(None, id, "", "", "", "", "", Map(), 5, false, false, "", List())
def fromDirective(technique: Technique, directive: Directive, crId: Option[ChangeRequestId]): JRDirective = {
directive
.into[JRDirective]
.enableBeanGetters
.withFieldConst(_.changeRequestId, crId.map(_.value.toString))
.withFieldComputed(_.id, _.id.serialize)
.withFieldRenamed(_.name, _.displayName)
.withFieldConst(_.techniqueName, technique.id.name.value)
.withFieldComputed(_.techniqueVersion, _.techniqueVersion.serialize)
.withFieldConst(
_.parameters,
Map(
"section" -> JRDirectiveSection.fromSectionVal(
SectionVal.ROOT_SECTION_NAME,
SectionVal.directiveValToSectionVal(technique.rootSection, directive.parameters)
)
)
)
.withFieldComputed(_.policyMode, _.policyMode.map(_.name).getOrElse("default"))
.withFieldComputed(_.tags, x => JRTags.fromTags(x.tags))
.transform
}
}
final case class JRDirectives(directives: List[JRDirective])
final case class JRDirectiveTreeCategory(
name: String,
description: String,
subCategories: List[JRDirectiveTreeCategory],
techniques: List[JRDirectiveTreeTechnique]
)
object JRDirectiveTreeCategory {
def fromActiveTechniqueCategory(technique: FullActiveTechniqueCategory): JRDirectiveTreeCategory = {
JRDirectiveTreeCategory(
technique.name,
technique.description,
technique.subCategories.map(fromActiveTechniqueCategory),
technique.activeTechniques.map(JRDirectiveTreeTechnique.fromActiveTechnique)
)
}
}
final case class JRDirectiveTreeTechnique(
id: String,
name: String,
directives: List[JRDirective]
)
object JRDirectiveTreeTechnique {
def fromActiveTechnique(technique: FullActiveTechnique): JRDirectiveTreeTechnique = {
JRDirectiveTreeTechnique(
technique.techniqueName.value,
technique.newestAvailableTechnique.map(_.name).getOrElse(technique.techniqueName.value),
technique.directives.flatMap { d =>
technique.techniques.get(d.techniqueVersion).map(t => JRDirective.fromDirective(t, d, None))
}
)
}
}
final case class JRApplicationStatus(
value: String,
details: Option[String]
)
final case class JRRule(
changeRequestId: Option[String] = None,
id: String, // id is in format uid+rev
displayName: String,
categoryId: String,
shortDescription: String,
longDescription: String,
directives: List[String], // directives ids
targets: List[JRRuleTarget],
enabled: Boolean,
system: Boolean,
tags: List[Map[String, String]],
policyMode: Option[String],
status: Option[JRApplicationStatus]
) {
def toRule(): IOResult[Rule] = {
for {
i <- RuleId.parse(id).toIO
d <- ZIO.foreach(directives)(DirectiveId.parse(_).toIO)
} yield Rule(
i,
displayName,
RuleCategoryId(categoryId),
targets.map(_.toRuleTarget).toSet,
d.toSet,
shortDescription,
longDescription,
enabled,
system,
Tags.fromMaps(tags)
)
}
}
object JRRule {
// create an empty json rule with just ID set
def empty(id: String): JRRule = JRRule(None, id, "", "", "", "", Nil, Nil, false, false, Nil, None, None)
// create from a rudder business rule
def fromRule(
rule: Rule,
crId: Option[ChangeRequestId],
policyMode: Option[String],
status: Option[(String, Option[String])]
): JRRule = {
rule
.into[JRRule]
.enableBeanGetters
.withFieldConst(_.changeRequestId, crId.map(_.value.toString))
.withFieldComputed(_.id, _.id.serialize)
.withFieldRenamed(_.name, _.displayName)
.withFieldComputed(_.categoryId, _.categoryId.value)
.withFieldComputed(_.directives, _.directiveIds.map(_.serialize).toList.sorted)
.withFieldComputed(_.targets, _.targets.toList.sortBy(_.target).map(t => JRRuleTarget(t)))
.withFieldRenamed(_.isEnabledStatus, _.enabled)
.withFieldComputed(_.tags, x => JRTags.fromTags(rule.tags))
.withFieldConst(_.policyMode, policyMode)
.withFieldConst(_.status, status.map(s => JRApplicationStatus(s._1, s._2)))
.transform
}
}
object JRTags {
def fromTags(tags: Tags): List[Map[String, String]] = {
tags.tags.toList.sortBy(_.name.value).map(t => Map((t.name.value, t.value.value)))
}
}
final case class JRRules(rules: List[JRRule])
sealed trait JRRuleTarget {
def toRuleTarget: RuleTarget
}
object JRRuleTarget {
def apply(t: RuleTarget): JRRuleTarget = {
def compose(x: TargetComposition): JRRuleTargetComposition = x match {
case TargetUnion(targets) => JRRuleTargetComposition.or(x.targets.toList.map(JRRuleTarget(_)))
case TargetIntersection(targets) => JRRuleTargetComposition.and(x.targets.toList.map(JRRuleTarget(_)))
}
t match {
case x: SimpleTarget => JRRuleTargetString(x)
case x: TargetComposition => compose(x)
case x: TargetExclusion => JRRuleTargetComposed(compose(x.includedTarget), compose(x.excludedTarget))
}
}
final case class JRRuleTargetString(r: SimpleTarget) extends JRRuleTarget {
override def toRuleTarget: RuleTarget = r
}
final case class JRRuleTargetComposed(
include: JRRuleTargetComposition,
exclude: JRRuleTargetComposition
) extends JRRuleTarget {
override def toRuleTarget: RuleTarget = TargetExclusion(include.toRuleTarget, exclude.toRuleTarget)
}
sealed trait JRRuleTargetComposition extends JRRuleTarget {
override def toRuleTarget: TargetComposition
}
object JRRuleTargetComposition {
final case class or(list: List[JRRuleTarget]) extends JRRuleTargetComposition {
override def toRuleTarget: TargetComposition = TargetUnion(list.map(_.toRuleTarget).toSet)
}
final case class and(list: List[JRRuleTarget]) extends JRRuleTargetComposition {
override def toRuleTarget: TargetComposition = TargetUnion(list.map(_.toRuleTarget).toSet)
}
}
implicit val transformer: Transformer[RuleTarget, JRRuleTarget] = apply _
}
final case class JRRuleTargetInfo(
id: JRRuleTarget,
@jsonField("displayName") name: String,
description: String,
@jsonField("enabled") isEnabled: Boolean,
target: JRRuleTarget
)
object JRRuleTargetInfo {
implicit val transformer: Transformer[RuleTargetInfo, JRRuleTargetInfo] =
Transformer.define[RuleTargetInfo, JRRuleTargetInfo].withFieldRenamed(_.target, _.id).buildTransformer
}
// CategoryKind is either JRRuleCategory or String (category id)
// RuleKind is either JRRule or String (rule id)
final case class JRFullRuleCategory(
id: String,
name: String,
description: String,
parent: Option[String],
categories: List[JRFullRuleCategory],
rules: List[JRRule]
)
object JRFullRuleCategory {
/*
* Prepare for json.
* Sort field by ID to keep diff easier.
*/
def fromCategory(
cat: RuleCategory,
allRules: Map[String, Seq[(Rule, Option[String], Option[(String, Option[String])])]],
parent: Option[String]
): JRFullRuleCategory = {
cat
.into[JRFullRuleCategory]
.withFieldConst(_.parent, parent)
.withFieldComputed(
_.categories,
_.childs.map(c => JRFullRuleCategory.fromCategory(c, allRules, Some(cat.id.value))).sortBy(_.id)
)
.withFieldConst(
_.rules,
allRules.get(cat.id.value).getOrElse(Nil).map { case (r, p, s) => JRRule.fromRule(r, None, p, s) }.toList.sortBy(_.id)
)
.transform
}
}
// when returning a root category, we have a "data":{"ruleCategories":{.... }}. Seems like a bug, though
final case class JRCategoriesRootEntryFull(ruleCategories: JRFullRuleCategory)
final case class JRCategoriesRootEntrySimple(ruleCategories: JRSimpleRuleCategory)
final case class JRCategoriesRootEntryInfo(ruleCategories: JRRuleCategoryInfo)
final case class JRSimpleRuleCategory(
id: String,
name: String,
description: String,
parent: String,
categories: List[String],
rules: List[String]
)
object JRSimpleRuleCategory {
def fromCategory(cat: RuleCategory, parent: String, rules: List[String]): JRSimpleRuleCategory = {
cat
.into[JRSimpleRuleCategory]
.withFieldComputed(_.id, _.id.value)
.withFieldConst(_.parent, parent)
.withFieldComputed(_.categories, _.childs.map(_.id.value).sorted)
.withFieldConst(_.rules, rules)
.transform
}
}
final case class JRRuleCategoryInfo(
id: String,
name: String,
description: String,
parent: Option[String],
categories: List[JRRuleCategoryInfo],
rules: List[JRRuleInfo]
)
object JRRuleCategoryInfo {
def fromCategory(
cat: RuleCategory,
allRules: Map[RuleCategoryId, Seq[Rule]],
parent: Option[String]
): JRRuleCategoryInfo = {
cat
.into[JRRuleCategoryInfo]
.withFieldConst(_.parent, parent)
.withFieldComputed(
_.categories,
_.childs.map(c => JRRuleCategoryInfo.fromCategory(c, allRules, Some(cat.id.value))).sortBy(_.id)
)
.withFieldConst(
_.rules,
allRules.get(cat.id).getOrElse(Nil).map(JRRuleInfo.fromRule).toList.sortBy(_.id)
)
.transform
}
}
final case class JRRuleInfo(
id: String,
displayName: String,
categoryId: String,
shortDescription: String,
longDescription: String,
enabled: Boolean,
tags: List[Map[String, String]]
)
object JRRuleInfo {
def fromRule(rule: Rule): JRRuleInfo = {
rule
.into[JRRuleInfo]
.enableBeanGetters
.withFieldComputed(_.id, _.id.serialize)
.withFieldRenamed(_.name, _.displayName)
.withFieldComputed(_.categoryId, _.categoryId.value)
.withFieldComputed(_.tags, x => JRTags.fromTags(rule.tags))
.transform
}
}
final case class JRGlobalParameter(
changeRequestId: Option[String] = None,
id: String,
value: ConfigValue,
description: String,
inheritMode: Option[InheritMode],
provider: Option[PropertyProvider]
)
object JRGlobalParameter {
import GenericProperty.*
def empty(name: String): JRGlobalParameter = JRGlobalParameter(None, name, "".toConfigValue, "", None, None)
def fromGlobalParameter(p: GlobalParameter, crId: Option[ChangeRequestId]): JRGlobalParameter = {
JRGlobalParameter(crId.map(_.value.toString), p.name, p.value, p.description, p.inheritMode, p.provider)
}
}
final case class JRPropertyHierarchyStatus(
hasChildTypeConflicts: Boolean,
fullHierarchy: List[JRParentPropertyDetails]
)
@jsonDiscriminator("kind") sealed trait JRParentPropertyDetails {
def valueType: String
}
object JRParentPropertyDetails {
@jsonHint("global")
final case class JRParentGlobalDetails(
valueType: String
) extends JRParentPropertyDetails
@jsonHint("group")
final case class JRParentGroupDetails(
name: String,
id: String,
valueType: String
) extends JRParentPropertyDetails
@jsonHint("node")
final case class JRParentNodeDetails(
name: String,
id: String,
valueType: String
) extends JRParentPropertyDetails
def fromParentProperty(p: ParentProperty): JRParentPropertyDetails = {
def serializeValueType(v: ConfigValue): String = v.valueType.name().toLowerCase().capitalize
p match {
case ParentProperty.Group(name, id, value) =>
JRParentGroupDetails(name, id.serialize, serializeValueType(value))
case ParentProperty.Node(name, id, value) =>
JRParentNodeDetails(name, id.value, serializeValueType(value))
case ParentProperty.Global(value) =>
JRParentGlobalDetails(serializeValueType(value))
}
}
}
// similar to JRGlobalParameter but s/id/name and no changeRequestId
final case class JRProperty(
name: String,
value: ConfigValue,
description: Option[String],
inheritMode: Option[InheritMode],
provider: Option[PropertyProvider],
hierarchy: Option[JRPropertyHierarchy],
hierarchyStatus: Option[JRPropertyHierarchyStatus],
origval: Option[ConfigValue]
)
object JRProperty {
def fromGroupProp(p: GroupProperty): JRProperty = {
val desc = if (p.description.trim.isEmpty) None else Some(p.description)
JRProperty(p.name, p.value, desc, p.inheritMode, p.provider, None, None, None)
}
def fromNodePropertyHierarchy(
prop: NodePropertyHierarchy,
hasChildTypeConflicts: Boolean,
fullHierarchy: List[ParentProperty],
renderInHtml: RenderInheritedProperties
): JRProperty = {
val (parents, origval) = prop.hierarchy.reverse match {
case Nil => (None, None)
case list =>
val parents = renderInHtml match {
case RenderInheritedProperties.HTML =>
JRPropertyHierarchyHtml(
list
.map(p =>
s"<p>from <b>${p.displayName}</b>:<pre>${p.value.render(ConfigRenderOptions.defaults().setOriginComments(false))}</pre></p>"
)
.mkString("")
)
case RenderInheritedProperties.JSON =>
JRPropertyHierarchyJson(list.map(JRParentProperty.fromParentProperty(_)))
}
(Some(parents), prop.hierarchy.headOption.map(_.value))
}
val hierarchyStatus = Some(
JRPropertyHierarchyStatus(
hasChildTypeConflicts,
fullHierarchy.map(JRParentPropertyDetails.fromParentProperty(_))
)
)
val desc = if (prop.prop.description.trim.isEmpty) None else Some(prop.prop.description)
JRProperty(
prop.prop.name,
prop.prop.value,
desc,
prop.prop.inheritMode,
prop.prop.provider,
parents,
hierarchyStatus,
origval
)
}
}
@jsonDiscriminator("kind") sealed trait JRParentProperty { def value: ConfigValue }
object JRParentProperty {
@jsonHint("global")
final case class JRParentGlobal(
value: ConfigValue
) extends JRParentProperty
@jsonHint("group")
final case class JRParentGroup(
name: String,
id: String,
value: ConfigValue
) extends JRParentProperty
def fromParentProperty(p: ParentProperty): JRParentProperty = {
p match {
case ParentProperty.Group(name, id, value) =>
JRParentGroup(name, id.serialize, value)
case _ =>
JRParentGlobal(p.value)
}
}
}
sealed trait JRPropertyHierarchy extends Product
object JRPropertyHierarchy {
final case class JRPropertyHierarchyHtml(html: String) extends JRPropertyHierarchy
final case class JRPropertyHierarchyJson(parents: List[JRParentProperty]) extends JRPropertyHierarchy
}
final case class JRGroupInheritedProperties(
groupId: String,
properties: List[JRProperty]
)
object JRGroupInheritedProperties {
def fromGroup(
groupId: NodeGroupId,
properties: List[
(NodePropertyHierarchy, List[ParentProperty], Boolean)
], // parent properties, child properties, has conflicts
renderInHtml: RenderInheritedProperties
): JRGroupInheritedProperties = {
JRGroupInheritedProperties(
groupId.serialize,
properties
.sortBy(_._1.prop.name)
.map {
case (parentProperties, childProperties, hasConflicts) =>
JRProperty.fromNodePropertyHierarchy(parentProperties, hasConflicts, childProperties, renderInHtml)
}
)
}
}
final case class JRCriterium(
objectType: String,
attribute: String,
comparator: String,
value: String
) {
def toStringCriterionLine: StringCriterionLine = StringCriterionLine(objectType, attribute, comparator, Some(value))
}
object JRCriterium {
def fromCriterium(c: CriterionLine): JRCriterium = {
c.into[JRCriterium]
.withFieldComputed(_.objectType, _.objectType.objectType)
.withFieldComputed(_.attribute, _.attribute.name)
.withFieldComputed(_.comparator, _.comparator.id)
.transform
}
}
final case class JRQuery(
select: String,
composition: String,
transform: Option[String],
where: List[JRCriterium]
)
object JRQuery {
def fromQuery(query: Query): JRQuery = {
JRQuery(
query.returnType.value,
query.composition.value,
query.transform match {
case ResultTransformation.Identity => None
case x => Some(x.value)
},
query.criteria.map(JRCriterium.fromCriterium(_))
)
}
}
final case class JRGroup(
changeRequestId: Option[String] = None,
id: String,
displayName: String,
description: String,
category: String,
query: Option[JRQuery],
nodeIds: List[String],
dynamic: Boolean,
enabled: Boolean,
groupClass: List[String],
properties: List[JRProperty],
target: String,
system: Boolean
) {
def toGroup(queryParser: CmdbQueryParser): IOResult[(NodeGroupCategoryId, NodeGroup)] = {
for {
i <- NodeGroupId.parse(id).toIO
q <- query match {
case None => None.succeed
case Some(q) =>
for {
t <- QueryReturnType(q.select).toIO
x <- queryParser
.parse(StringQuery(t, Some(q.composition), q.transform, q.where.map(_.toStringCriterionLine)))
.toIO
} yield Some(x)
}
} yield {
(
NodeGroupCategoryId(category),
NodeGroup(
i,
displayName,
description,
properties.map(p => GroupProperty(p.name, GitVersion.DEFAULT_REV, p.value, p.inheritMode, p.provider)),
q,
dynamic,
nodeIds.map(NodeId(_)).toSet,
enabled,
system
)
)
}
}
}
object JRGroup {
def empty(id: String): JRGroup = JRGroup(None, id, "", "", "", None, Nil, false, false, Nil, Nil, "", false)
def fromGroup(group: NodeGroup, catId: NodeGroupCategoryId, crId: Option[ChangeRequestId]): JRGroup = {
group
.into[JRGroup]
.enableBeanGetters
.withFieldConst(_.changeRequestId, crId.map(_.value.toString))
.withFieldComputed(_.id, _.id.serialize)
.withFieldRenamed(_.name, _.displayName)
.withFieldConst(_.category, catId.value)
.withFieldComputed(_.query, _.query.map(JRQuery.fromQuery(_)))
.withFieldComputed(_.nodeIds, _.serverList.toList.map(_.value).sorted)
.withFieldComputed(_.groupClass, x => List(x.id.serialize, x.name).map(RuleTarget.toCFEngineClassName _).sorted)
.withFieldComputed(_.properties, _.properties.map(JRProperty.fromGroupProp(_)))
.withFieldComputed(_.target, x => GroupTarget(x.id).target)
.withFieldComputed(_.system, _.isSystem)
.transform
}
}
/**
* Representation of a group category with bare minimum group information
*/
final case class JRGroupCategoryInfo(
id: String,
name: String,
description: String,
@jsonField("categories") subCategories: List[JRGroupCategoryInfo],
groups: List[JRGroupCategoryInfo.JRGroupInfo],
@jsonField("targets") targetInfos: List[JRRuleTargetInfo]
)
object JRGroupCategoryInfo {
final case class JRGroupInfo(
id: NodeGroupId,
displayName: String,
description: String,
category: Option[String],
dynamic: Boolean,
enabled: Boolean,
target: String
)
object JRGroupInfo {
def apply(nodeGroupCategory: NodeGroupCategoryId, fullGroupTarget: FullGroupTarget): JRGroupInfo = {
JRGroupInfo(
fullGroupTarget.nodeGroup.id,
fullGroupTarget.nodeGroup.name,
fullGroupTarget.nodeGroup.description,
Some(nodeGroupCategory.value),
fullGroupTarget.nodeGroup.isDynamic,
fullGroupTarget.nodeGroup.isEnabled,
fullGroupTarget.target.target
)
}
}
implicit lazy val transformer: Transformer[FullNodeGroupCategory, JRGroupCategoryInfo] = {
Transformer
.define[FullNodeGroupCategory, JRGroupCategoryInfo]
.withFieldComputed(
_.groups,
_.allCategories.toList.flatMap {
case (catId, groups) =>
groups.allGroups.values.map(JRGroupInfo(catId, _))
}
)
.withFieldComputed(_.targetInfos, _.targetInfos.map(_.toTargetInfo.transformInto[JRRuleTargetInfo]))
.buildTransformer
}
}
final case class JRRuleNodesDirectives(
id: String, // id is in format uid+rev
numberOfNodes: Int,
numberOfDirectives: Int
)
object JRRuleNodesDirectives {
// create an empty json rule with just ID set
def empty(id: String): JRRuleNodesDirectives = JRRuleNodesDirectives(id, 0, 0)
// create from a rudder business rule
def fromData(ruleId: RuleId, nodesCount: Int, directivesCount: Int): JRRuleNodesDirectives = {
JRRuleNodesDirectives(ruleId.serialize, nodesCount, directivesCount)
}
}
final case class JRHooks(
basePath: String,
hooksFile: List[String]
)
object JRHooks {
def fromHook(hook: Hooks): JRHooks = {
hook
.into[JRHooks]
.withFieldConst(_.basePath, hook.basePath)
.withFieldConst(_.hooksFile, hook.hooksFile.map(_._1))
.transform
}
}
}
//////////////////////////// zio-json encoders ////////////////////////////
trait RudderJsonEncoders {
import JsonResponseObjects.*
import JsonResponseObjects.JRRuleTarget.*
implicit lazy val stringTargetEnc: JsonEncoder[JRRuleTargetString] = JsonEncoder[String].contramap(_.r.target)
implicit lazy val andTargetEnc: JsonEncoder[JRRuleTargetComposition.or] = JsonEncoder[List[JRRuleTarget]].contramap(_.list)
implicit lazy val orTargetEnc: JsonEncoder[JRRuleTargetComposition.and] = JsonEncoder[List[JRRuleTarget]].contramap(_.list)
implicit lazy val comp1TargetEnc: JsonEncoder[JRRuleTargetComposed] = DeriveJsonEncoder.gen
implicit lazy val comp2TargetEnc: JsonEncoder[JRRuleTargetComposition] = DeriveJsonEncoder.gen
implicit lazy val targetEncoder: JsonEncoder[JRRuleTarget] = new JsonEncoder[JRRuleTarget] {
override def unsafeEncode(a: JRRuleTarget, indent: Option[Int], out: Write): Unit = {
a match {
case x: JRRuleTargetString => stringTargetEnc.unsafeEncode(x, indent, out)
case x: JRRuleTargetComposed => comp1TargetEnc.unsafeEncode(x, indent, out)
case x: JRRuleTargetComposition => comp2TargetEnc.unsafeEncode(x, indent, out)
}
}
}
implicit val ruleTargetInfoEncoder: JsonEncoder[JRRuleTargetInfo] = DeriveJsonEncoder.gen[JRRuleTargetInfo]
implicit val ruleIdEncoder: JsonEncoder[RuleId] = JsonEncoder[String].contramap(_.serialize)
implicit val groupIdEncoder: JsonEncoder[NodeGroupId] = JsonEncoder[String].contramap(_.serialize)
implicit val applicationStatusEncoder: JsonEncoder[JRApplicationStatus] = DeriveJsonEncoder.gen